Skip to content

Commit

Permalink
Merge branch 'develop' into bump-er-1-45-2
Browse files Browse the repository at this point in the history
  • Loading branch information
laktek authored Apr 22, 2024
2 parents 6aaafb4 + 8a29e72 commit be47ecd
Show file tree
Hide file tree
Showing 33 changed files with 456 additions and 215 deletions.
2 changes: 1 addition & 1 deletion cmd/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var (
RunE: func(cmd *cobra.Command, args []string) error {
if !viper.IsSet("WORKDIR") {
title := fmt.Sprintf("Enter a directory to bootstrap your project (or leave blank to use %s): ", utils.Bold(utils.CurrentDirAbs))
workdir, err := utils.PromptText(title, os.Stdin)
workdir, err := utils.NewConsole().PromptText(title)
if err != nil {
return err
}
Expand Down
98 changes: 89 additions & 9 deletions cmd/branches.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package cmd

import (
"context"
"fmt"
"os"
"sort"

"github.com/go-errors/errors"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/supabase/cli/internal/branches/create"
Expand All @@ -11,7 +15,9 @@ import (
"github.com/supabase/cli/internal/branches/get"
"github.com/supabase/cli/internal/branches/list"
"github.com/supabase/cli/internal/branches/update"
"github.com/supabase/cli/internal/gen/keys"
"github.com/supabase/cli/internal/utils"
"github.com/supabase/cli/internal/utils/flags"
"github.com/supabase/cli/pkg/api"
)

Expand Down Expand Up @@ -44,18 +50,29 @@ var (
Use: "list",
Short: "List all preview branches",
Long: "List all preview branches of the linked project.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return list.Run(cmd.Context(), afero.NewOsFs())
},
}

branchId string

branchGetCmd = &cobra.Command{
Use: "get <branch-id>",
Use: "get [branch-id]",
Short: "Retrieve details of a preview branch",
Long: "Retrieve details of the specified preview branch.",
Args: cobra.ExactArgs(1),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return get.Run(cmd.Context(), args[0])
ctx := cmd.Context()
if len(args) == 0 {
if err := promptBranchId(ctx, flags.ProjectRef); err != nil {
return err
}
} else {
branchId = args[0]
}
return get.Run(ctx, branchId)
},
}

Expand All @@ -64,7 +81,7 @@ var (
resetOnPush bool

branchUpdateCmd = &cobra.Command{
Use: "update <branch-id>",
Use: "update [branch-id]",
Short: "Update a preview branch",
Long: "Update a preview branch by its ID.",
Args: cobra.ExactArgs(1),
Expand All @@ -79,17 +96,33 @@ var (
if cmd.Flags().Changed("reset-on-push") {
body.ResetOnPush = &resetOnPush
}
return update.Run(cmd.Context(), args[0], body, afero.NewOsFs())
ctx := cmd.Context()
if len(args) == 0 {
if err := promptBranchId(ctx, flags.ProjectRef); err != nil {
return err
}
} else {
branchId = args[0]
}
return update.Run(cmd.Context(), branchId, body, afero.NewOsFs())
},
}

branchDeleteCmd = &cobra.Command{
Use: "delete <branch-id>",
Use: "delete [branch-id]",
Short: "Delete a preview branch",
Long: "Delete a preview branch by its ID.",
Args: cobra.ExactArgs(1),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return delete.Run(cmd.Context(), args[0])
ctx := cmd.Context()
if len(args) == 0 {
if err := promptBranchId(ctx, flags.ProjectRef); err != nil {
return err
}
} else {
branchId = args[0]
}
return delete.Run(ctx, branchId)
},
}

Expand All @@ -104,7 +137,8 @@ var (
)

func init() {
branchesCmd.AddCommand(branchCreateCmd)
branchFlags := branchesCmd.PersistentFlags()
branchFlags.StringVar(&flags.ProjectRef, "project-ref", "", "Project ref of the Supabase project.")
// Setup enum flags
i := 0
for k := range utils.FlyRegions {
Expand All @@ -114,6 +148,7 @@ func init() {
sort.Strings(branchRegion.Allowed)
createFlags := branchCreateCmd.Flags()
createFlags.Var(&branchRegion, "region", "Select a region to deploy the branch database.")
branchesCmd.AddCommand(branchCreateCmd)
branchesCmd.AddCommand(branchListCmd)
branchesCmd.AddCommand(branchGetCmd)
updateFlags := branchUpdateCmd.Flags()
Expand All @@ -125,3 +160,48 @@ func init() {
branchesCmd.AddCommand(branchDisableCmd)
rootCmd.AddCommand(branchesCmd)
}

func promptBranchId(ctx context.Context, ref string) error {
resp, err := utils.GetSupabase().GetBranchesWithResponse(ctx, ref)
if err != nil {
return errors.Errorf("failed to list preview branches: %w", err)
}
if resp.JSON200 == nil {
return errors.New("Unexpected error listing preview branches: " + string(resp.Body))
}
console := utils.NewConsole()
if !console.IsTTY {
// Fallback to current git branch on GHA
gitBranch := keys.GetGitBranch(afero.NewOsFs())
title := "Enter the name of your branch: "
if len(gitBranch) > 0 {
title = fmt.Sprintf("%-2s (or leave blank to use %s): ", title, utils.Aqua(gitBranch))
}
if name, err := console.PromptText(title); err != nil {
return err
} else if len(name) > 0 {
gitBranch = name
}
for _, branch := range *resp.JSON200 {
if branch.Name == gitBranch {
branchId = branch.Id
return nil
}
}
return errors.Errorf("Branch not found: %s", gitBranch)
}
items := make([]utils.PromptItem, len(*resp.JSON200))
for i, branch := range *resp.JSON200 {
items[i] = utils.PromptItem{
Summary: branch.Name,
Details: branch.Id,
}
}
title := "Select a branch:"
choice, err := utils.PromptChoice(ctx, title, items)
if err == nil {
branchId = choice.Details
fmt.Fprintln(os.Stderr, "Selected branch ID:", branchId)
}
return err
}
6 changes: 1 addition & 5 deletions cmd/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@ var (
Use: "logout",
Short: "Log out and delete access tokens locally",
RunE: func(cmd *cobra.Command, args []string) error {
params := logout.RunParams{
Fsys: afero.NewOsFs(),
DefaultAnswer: false,
}
return logout.Run(cmd.Context(), os.Stdout, params)
return logout.Run(cmd.Context(), os.Stdout, afero.NewOsFs())
},
}
)
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ require (
github.com/charmbracelet/lipgloss v0.10.0
github.com/containers/common v0.58.2
github.com/deepmap/oapi-codegen v1.16.2
github.com/docker/cli v26.0.1+incompatible
github.com/docker/docker v26.0.1+incompatible
github.com/docker/cli v26.0.2+incompatible
github.com/docker/docker v26.0.2+incompatible
github.com/docker/go-connections v0.5.0
github.com/docker/go-units v0.5.0
github.com/getsentry/sentry-go v0.27.0
Expand Down Expand Up @@ -323,7 +323,7 @@ require (
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect
golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f // indirect
golang.org/x/net v0.22.0 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
12 changes: 6 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,13 @@ github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E
github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/dnephin/pflag v1.0.7 h1:oxONGlWxhmUct0YzKTgrpQv9AUA1wtPBn7zuSjJqptk=
github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE=
github.com/docker/cli v26.0.1+incompatible h1:eZDuplk2jYqgUkNLDYwTBxqmY9cM3yHnmN6OIUEjL3U=
github.com/docker/cli v26.0.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/cli v26.0.2+incompatible h1:4C4U8ZqrlNDe/R1U1zFFX+YsCFiVUicJqo4WVdInJas=
github.com/docker/cli v26.0.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v26.0.1+incompatible h1:t39Hm6lpXuXtgkF0dm1t9a5HkbUfdGy6XbWexmGr+hA=
github.com/docker/docker v26.0.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker v26.0.2+incompatible h1:yGVmKUFGgcxA6PXWAokO0sQL22BrQ67cgVjko8tGdXE=
github.com/docker/docker v26.0.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker-credential-helpers v0.8.1 h1:j/eKUktUltBtMzKqmfLB0PAgqYyMHOp5vfsD1807oKo=
github.com/docker/docker-credential-helpers v0.8.1/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M=
github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c h1:lzqkGL9b3znc+ZUgi7FlLnqjQhcXxkNM/quxIjBVMD0=
Expand Down Expand Up @@ -1188,8 +1188,8 @@ golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
Expand Down
2 changes: 1 addition & 1 deletion internal/bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func Run(ctx context.Context, starter StarterTemplate, fsys afero.Fs, options ..
return errors.Errorf("failed to read workdir: %w", err)
} else if !empty {
title := fmt.Sprintf("Do you want to overwrite existing files in %s directory?", utils.Bold(workdir))
if !utils.PromptYesNo(title, true, os.Stdin) {
if !utils.NewConsole().PromptYesNo(title, true) {
return context.Canceled
}
}
Expand Down
12 changes: 6 additions & 6 deletions internal/branches/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ import (
)

func Run(ctx context.Context, name, region string, fsys afero.Fs) error {
ref, err := flags.LoadProjectRef(fsys)
if err != nil {
return err
}
gitBranch := keys.GetGitBranchOrDefault("", fsys)
if len(name) == 0 {
if len(name) == 0 && len(gitBranch) > 0 {
title := fmt.Sprintf("Do you want to create a branch named %s?", utils.Aqua(gitBranch))
if shouldCreate := utils.NewConsole().PromptYesNo(title, true); !shouldCreate {
return context.Canceled
}
name = gitBranch
}

resp, err := utils.GetSupabase().CreateBranchWithResponse(ctx, ref, api.CreateBranchJSONRequestBody{
resp, err := utils.GetSupabase().CreateBranchWithResponse(ctx, flags.ProjectRef, api.CreateBranchJSONRequestBody{
BranchName: name,
GitBranch: &gitBranch,
Region: &region,
Expand Down
30 changes: 9 additions & 21 deletions internal/branches/create/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,32 @@ import (
"context"
"net"
"net/http"
"os"
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/supabase/cli/internal/testing/apitest"
"github.com/supabase/cli/internal/testing/fstest"
"github.com/supabase/cli/internal/utils"
"github.com/supabase/cli/internal/utils/flags"
"github.com/supabase/cli/pkg/api"
"gopkg.in/h2non/gock.v1"
)

func TestCreateCommand(t *testing.T) {
// Setup valid project ref
flags.ProjectRef = apitest.RandomProjectRef()

t.Run("creates preview branch", func(t *testing.T) {
// Setup valid project ref
ref := apitest.RandomProjectRef()
// Setup valid access token
token := apitest.RandomAccessToken(t)
t.Setenv("SUPABASE_ACCESS_TOKEN", string(token))
// Setup in-memory fs
fsys := afero.NewMemMapFs()
require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
// Setup mock api
defer gock.OffAll()
gock.New(utils.DefaultApiHost).
Post("/v1/projects/" + ref + "/branches").
Post("/v1/projects/" + flags.ProjectRef + "/branches").
Reply(http.StatusCreated).
JSON(api.BranchResponse{
Id: "test-uuid",
Expand All @@ -41,24 +40,14 @@ func TestCreateCommand(t *testing.T) {
assert.NoError(t, err)
})

t.Run("throws error on permission denied", func(t *testing.T) {
// Setup in-memory fs
fsys := &fstest.OpenErrorFs{DenyPath: utils.ProjectRefPath}
// Run test
err := Run(context.Background(), "branch", "region", fsys)
// Check error
assert.ErrorIs(t, err, os.ErrPermission)
})

t.Run("throws error on network disconnected", func(t *testing.T) {
ref := apitest.RandomProjectRef()
// Setup in-memory fs
fsys := afero.NewMemMapFs()
require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(flags.ProjectRef), 0644))
// Setup mock api
defer gock.OffAll()
gock.New(utils.DefaultApiHost).
Post("/v1/projects/" + ref + "/branches").
Post("/v1/projects/" + flags.ProjectRef + "/branches").
ReplyError(net.ErrClosed)
// Run test
err := Run(context.Background(), "", "sin", fsys)
Expand All @@ -67,14 +56,13 @@ func TestCreateCommand(t *testing.T) {
})

t.Run("throws error on service unavailable", func(t *testing.T) {
ref := apitest.RandomProjectRef()
// Setup in-memory fs
fsys := afero.NewMemMapFs()
require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(ref), 0644))
require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(flags.ProjectRef), 0644))
// Setup mock api
defer gock.OffAll()
gock.New(utils.DefaultApiHost).
Post("/v1/projects/" + ref + "/branches").
Post("/v1/projects/" + flags.ProjectRef + "/branches").
Reply(http.StatusServiceUnavailable)
// Run test
err := Run(context.Background(), "", "sin", fsys)
Expand Down
8 changes: 2 additions & 6 deletions internal/branches/disable/disable.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,13 @@ import (
)

func Run(ctx context.Context, fsys afero.Fs) error {
ref, err := flags.LoadProjectRef(fsys)
if err != nil {
return err
}
resp, err := utils.GetSupabase().DisableBranchWithResponse(ctx, ref)
resp, err := utils.GetSupabase().DisableBranchWithResponse(ctx, flags.ProjectRef)
if err != nil {
return errors.Errorf("failed to disable preview branching: %w", err)
}
if resp.StatusCode() != http.StatusOK {
return errors.New("Unexpected error disabling preview branching: " + string(resp.Body))
}
fmt.Println("Disabled preview branching for project:", ref)
fmt.Println("Disabled preview branching for project:", flags.ProjectRef)
return nil
}
8 changes: 2 additions & 6 deletions internal/branches/list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ import (
)

func Run(ctx context.Context, fsys afero.Fs) error {
ref, err := flags.LoadProjectRef(fsys)
if err != nil {
return err
}
resp, err := utils.GetSupabase().GetBranchesWithResponse(ctx, ref)
resp, err := utils.GetSupabase().GetBranchesWithResponse(ctx, flags.ProjectRef)
if err != nil {
return errors.Errorf("failed to list preview branches: %w", err)
}
Expand All @@ -27,7 +23,7 @@ func Run(ctx context.Context, fsys afero.Fs) error {
}

table := `|ID|NAME|DEFAULT|GIT BRANCH|RESET ON PUSH|STATUS|CREATED AT (UTC)|UPDATED AT (UTC)|
|-|-|-|-|-|-|-|
|-|-|-|-|-|-|-|-|
`
for _, branch := range *resp.JSON200 {
gitBranch := " "
Expand Down
Loading

0 comments on commit be47ecd

Please sign in to comment.