github.com/supabase/cli@v1.168.1/internal/utils/flags/project_ref.go (about) 1 package flags 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "os" 8 9 "github.com/go-errors/errors" 10 "github.com/spf13/afero" 11 "github.com/spf13/viper" 12 "github.com/supabase/cli/internal/utils" 13 "golang.org/x/term" 14 ) 15 16 var ProjectRef string 17 18 func ParseProjectRef(ctx context.Context, fsys afero.Fs) error { 19 // Flag takes highest precedence 20 if len(ProjectRef) == 0 { 21 ProjectRef = viper.GetString("PROJECT_ID") 22 } 23 if len(ProjectRef) > 0 { 24 return utils.AssertProjectRefIsValid(ProjectRef) 25 } 26 // Followed by linked ref file 27 if _, err := LoadProjectRef(fsys); !errors.Is(err, utils.ErrNotLinked) { 28 return err 29 } 30 // Prompt as the last resort 31 if term.IsTerminal(int(os.Stdin.Fd())) { 32 return PromptProjectRef(ctx, "Select a project:") 33 } 34 return errors.New(utils.ErrNotLinked) 35 } 36 37 func PromptProjectRef(ctx context.Context, title string) error { 38 resp, err := utils.GetSupabase().GetProjectsWithResponse(ctx) 39 if err != nil { 40 return errors.Errorf("failed to retrieve projects: %w", err) 41 } 42 if resp.JSON200 == nil { 43 return errors.New("Unexpected error retrieving projects: " + string(resp.Body)) 44 } 45 items := make([]utils.PromptItem, len(*resp.JSON200)) 46 for i, project := range *resp.JSON200 { 47 items[i] = utils.PromptItem{ 48 Summary: project.Id, 49 Details: fmt.Sprintf("name: %s, org: %s, region: %s", project.Name, project.OrganizationId, project.Region), 50 } 51 } 52 choice, err := utils.PromptChoice(ctx, title, items) 53 if err != nil { 54 return err 55 } 56 ProjectRef = choice.Summary 57 fmt.Fprintln(os.Stderr, "Selected project:", ProjectRef) 58 return nil 59 } 60 61 func LoadProjectRef(fsys afero.Fs) (string, error) { 62 projectRefBytes, err := afero.ReadFile(fsys, utils.ProjectRefPath) 63 if errors.Is(err, os.ErrNotExist) { 64 return "", errors.New(utils.ErrNotLinked) 65 } else if err != nil { 66 return "", errors.Errorf("failed to load project ref: %w", err) 67 } 68 ProjectRef = string(bytes.TrimSpace(projectRefBytes)) 69 if err := utils.AssertProjectRefIsValid(ProjectRef); err != nil { 70 return "", err 71 } 72 return ProjectRef, nil 73 }