utils

package
v2.0.5-0...-bd0d250 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2024 License: MIT Imports: 71 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DNS_GO_NATIVE  = "native"
	DNS_OVER_HTTPS = "https"
)
View Source
const (
	DefaultApiHost = "https://api.supabase.com"
	// DEPRECATED
	DeprecatedApiHost = "https://api.supabase.io"
)
View Source
const (
	// Legacy bundle options
	DockerDenoDir  = "/home/deno"
	DockerEszipDir = "/root/eszips"
	DenoVersion    = "1.30.3"
)
View Source
const (
	DinDHost        = "host.docker.internal"
	CliProjectLabel = "com.supabase.cli.project"
)
View Source
const (
	OutputEnv    = "env"
	OutputJson   = "json"
	OutputPretty = "pretty"
	OutputToml   = "toml"
	OutputYaml   = "yaml"

	// OutputMetadata is used with certain SSO commands only.
	OutputMetadata = "metadata"
)
View Source
const (
	CLI_OWNER = "supabase"
	CLI_REPO  = "cli"
)
View Source
const AccessTokenKey = "access-token"
View Source
const SuggestDebugFlag = "Try rerunning the command with --debug to troubleshoot the error."

Variables

View Source
var (
	AccessTokenPattern = regexp.MustCompile(`^sbp_(oauth_)?[a-f0-9]{40}$`)
	ErrInvalidToken    = errors.New("Invalid access token format. Must be like `sbp_0102...1920`.")
	ErrMissingToken    = errors.Errorf("Access token not provided. Supply an access token by running %s or setting the SUPABASE_ACCESS_TOKEN environment variable.", Aqua("supabase login"))
	ErrNotLoggedIn     = errors.New("You were not logged in, nothing to do.")
)
View Source
var (
	NetId         string
	DbId          string
	ConfigId      string
	KongId        string
	GotrueId      string
	InbucketId    string
	RealtimeId    string
	RestId        string
	StorageId     string
	ImgProxyId    string
	DifferId      string
	PgmetaId      string
	StudioId      string
	EdgeRuntimeId string
	LogflareId    string
	VectorId      string
	PoolerId      string

	DbAliases          = []string{"db", "db.supabase.internal"}
	KongAliases        = []string{"kong", "api.supabase.internal"}
	GotrueAliases      = []string{"auth"}
	InbucketAliases    = []string{"inbucket"}
	RealtimeAliases    = []string{"realtime", Config.Realtime.TenantId}
	RestAliases        = []string{"rest"}
	StorageAliases     = []string{"storage"}
	ImgProxyAliases    = []string{"imgproxy"}
	PgmetaAliases      = []string{"pg_meta"}
	StudioAliases      = []string{"studio"}
	EdgeRuntimeAliases = []string{"edge_runtime"}
	LogflareAliases    = []string{"analytics"}
	VectorAliases      = []string{"vector"}
	PoolerAliases      = []string{"pooler"}

	//go:embed templates/initial_schemas/13.sql
	InitialSchemaPg13Sql string
	//go:embed templates/initial_schemas/14.sql
	InitialSchemaPg14Sql string
)
View Source
var (
	Version   string
	SentryDsn string
)

Assigned using `-ldflags` https://stackoverflow.com/q/11354518

View Source
var (
	CmdSuggestion string
	CurrentDirAbs string

	// pg_dumpall --globals-only --no-role-passwords --dbname $DB_URL \
	// | sed '/^CREATE ROLE postgres;/d' \
	// | sed '/^ALTER ROLE postgres WITH /d' \
	// | sed "/^ALTER ROLE .* WITH .* LOGIN /s/;$/ PASSWORD 'postgres';/"
	//go:embed templates/globals.sql
	GlobalsSql string

	ProjectRefPattern  = regexp.MustCompile(`^[a-z]{20}$`)
	UUIDPattern        = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
	ProjectHostPattern = regexp.MustCompile(`^(db\.)([a-z]{20})\.supabase\.(co|red)$`)
	BranchNamePattern  = regexp.MustCompile(`[[:word:]-]+`)
	FuncSlugPattern    = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]*$`)
	ImageNamePattern   = regexp.MustCompile(`\/(.*):`)

	// These schemas are ignored from db diff and db dump
	PgSchemas = []string{
		"information_schema",
		"pg_*",
	}
	// Initialised by postgres image and owned by postgres role
	InternalSchemas = append([]string{
		"_analytics",
		"_realtime",
		"_supavisor",
		"auth",
		"extensions",
		"pgbouncer",
		"realtime",
		"storage",
		"supabase_functions",
		"supabase_migrations",

		"cron",
		"dbdev",
		"graphql",
		"graphql_public",
		"net",
		"pgsodium",
		"pgsodium_masks",
		"pgtle",
		"repack",
		"tiger",
		"tiger_data",
		"timescaledb_*",
		"_timescaledb_*",
		"topology",
		"vault",
	}, PgSchemas...)
	ReservedRoles = []string{
		"anon",
		"authenticated",
		"authenticator",
		"dashboard_user",
		"pgbouncer",
		"postgres",
		"service_role",
		"supabase_admin",
		"supabase_auth_admin",
		"supabase_functions_admin",
		"supabase_read_only_user",
		"supabase_realtime_admin",
		"supabase_replication_admin",
		"supabase_storage_admin",

		"pgsodium_keyholder",
		"pgsodium_keyiduser",
		"pgsodium_keymaker",
		"pgtle_admin",
	}
	AllowedConfigs = []string{

		"pgaudit.*",
		"pgrst.*",
		"session_replication_role",
		"statement_timeout",
		"track_io_timing",
	}

	SupabaseDirPath       = "supabase"
	ConfigPath            = filepath.Join(SupabaseDirPath, "config.toml")
	GitIgnorePath         = filepath.Join(SupabaseDirPath, ".gitignore")
	TempDir               = filepath.Join(SupabaseDirPath, ".temp")
	ImportMapsDir         = filepath.Join(TempDir, "import_maps")
	ProjectRefPath        = filepath.Join(TempDir, "project-ref")
	PoolerUrlPath         = filepath.Join(TempDir, "pooler-url")
	PostgresVersionPath   = filepath.Join(TempDir, "postgres-version")
	GotrueVersionPath     = filepath.Join(TempDir, "gotrue-version")
	RestVersionPath       = filepath.Join(TempDir, "rest-version")
	StorageVersionPath    = filepath.Join(TempDir, "storage-version")
	StudioVersionPath     = filepath.Join(TempDir, "studio-version")
	PgmetaVersionPath     = filepath.Join(TempDir, "pgmeta-version")
	PoolerVersionPath     = filepath.Join(TempDir, "pooler-version")
	RealtimeVersionPath   = filepath.Join(TempDir, "realtime-version")
	CliVersionPath        = filepath.Join(TempDir, "cli-latest")
	CurrBranchPath        = filepath.Join(SupabaseDirPath, ".branches", "_current_branch")
	SchemasDir            = filepath.Join(SupabaseDirPath, "schemas")
	MigrationsDir         = filepath.Join(SupabaseDirPath, "migrations")
	FunctionsDir          = filepath.Join(SupabaseDirPath, "functions")
	FallbackImportMapPath = filepath.Join(FunctionsDir, "import_map.json")
	FallbackEnvFilePath   = filepath.Join(FunctionsDir, ".env")
	DbTestsDir            = filepath.Join(SupabaseDirPath, "tests")
	CustomRolesPath       = filepath.Join(SupabaseDirPath, "roles.sql")

	ErrNotLinked   = errors.Errorf("Cannot find project ref. Have you run %s?", Aqua("supabase link"))
	ErrInvalidRef  = errors.New("Invalid project ref format. Must be like `abcdefghijklmnopqrst`.")
	ErrInvalidSlug = errors.New("Invalid Function name. Must start with at least one letter, and only include alphanumeric characters, underscores, and hyphens. (^[A-Za-z][A-Za-z0-9_-]*$)")
	ErrNotRunning  = errors.Errorf("%s is not running.", Aqua("supabase start"))
)
View Source
var (
	OutputDefaultAllowed = []string{
		OutputPretty,
		OutputJson,
		OutputToml,
		OutputYaml,
	}

	OutputFormat = EnumFlag{
		Allowed: OutputDefaultAllowed,
		Value:   OutputPretty,
	}
)
View Source
var (
	DNSResolver = EnumFlag{
		Allowed: []string{DNS_GO_NATIVE, DNS_OVER_HTTPS},
		Value:   DNS_GO_NATIVE,
	}
)
View Source
var (

	// Used by unit tests
	DenoPathOverride string
)
View Source
var Docker = NewDocker()
View Source
var NoBackupVolume = false

NoBackupVolume TODO: encapsulate this state in a class

View Source
var RegionMap = map[string]string{
	"ap-northeast-1": "Northeast Asia (Tokyo)",
	"ap-northeast-2": "Northeast Asia (Seoul)",
	"ap-south-1":     "South Asia (Mumbai)",
	"ap-southeast-1": "Southeast Asia (Singapore)",
	"ap-southeast-2": "Oceania (Sydney)",
	"ca-central-1":   "Canada (Central)",
	"eu-central-1":   "Central EU (Frankfurt)",
	"eu-west-1":      "West EU (Ireland)",
	"eu-west-2":      "West EU (London)",
	"eu-west-3":      "West EU (Paris)",
	"sa-east-1":      "South America (São Paulo)",
	"us-east-1":      "East US (North Virginia)",
	"us-west-1":      "West US (North California)",
	"us-west-2":      "West US (Oregon)",
}

Functions

func Aqua

func Aqua(str string) string

For commands & names.

func AssertProjectRefIsValid

func AssertProjectRefIsValid(projectRef string) error

func AssertServiceIsRunning

func AssertServiceIsRunning(ctx context.Context, containerId string) error

func AssertSupabaseCliIsSetUpFS

func AssertSupabaseCliIsSetUpFS(fsys afero.Fs) error

func AssertSupabaseDbIsRunning

func AssertSupabaseDbIsRunning() error

func Bold

func Bold(str string) string

For paths & filenames.

func ChangeWorkDir

func ChangeWorkDir(fsys afero.Fs) error

func CliProjectFilter

func CliProjectFilter(projectId string) filters.Args

func ConnectByConfig

func ConnectByConfig(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

func ConnectByConfigStream

func ConnectByConfigStream(ctx context.Context, config pgconn.Config, w io.Writer, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

func ConnectByUrl

func ConnectByUrl(ctx context.Context, url string, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

func ConnectLocalPostgres

func ConnectLocalPostgres(ctx context.Context, config pgconn.Config, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

Connnect to local Postgres with optimised settings. The caller is responsible for closing the connection returned.

func DeleteAccessToken

func DeleteAccessToken(fsys afero.Fs) error

func DockerExecOnce

func DockerExecOnce(ctx context.Context, containerId string, env []string, cmd []string) (string, error)

Exec a command once inside a container, returning stdout and throwing error on non-zero exit code.

func DockerExecOnceWithStream

func DockerExecOnceWithStream(ctx context.Context, containerId, workdir string, env, cmd []string, stdout, stderr io.Writer) error

func DockerImagePull

func DockerImagePull(ctx context.Context, imageTag string, w io.Writer) error

func DockerImagePullWithRetry

func DockerImagePullWithRetry(ctx context.Context, image string, retries int) error

func DockerNetworkCreateIfNotExists

func DockerNetworkCreateIfNotExists(ctx context.Context, mode container.NetworkMode, labels map[string]string) error

func DockerPullImageIfNotCached

func DockerPullImageIfNotCached(ctx context.Context, imageName string) error

func DockerRemove

func DockerRemove(containerId string)

func DockerRemoveAll

func DockerRemoveAll(ctx context.Context, w io.Writer, projectId string) error

func DockerRunJob

func DockerRunJob(ctx context.Context, job DockerJob, stdout, stderr io.Writer) error

func DockerRunOnce

func DockerRunOnce(ctx context.Context, image string, env []string, cmd []string) (string, error)

Runs a container image exactly once, returning stdout and throwing error on non-zero exit code.

func DockerRunOnceWithConfig

func DockerRunOnceWithConfig(ctx context.Context, config container.Config, hostConfig container.HostConfig, networkingConfig network.NetworkingConfig, containerName string, stdout, stderr io.Writer) error

func DockerRunOnceWithStream

func DockerRunOnceWithStream(ctx context.Context, image string, env, cmd []string, stdout, stderr io.Writer) error

func DockerStart

func DockerStart(ctx context.Context, config container.Config, hostConfig container.HostConfig, networkingConfig network.NetworkingConfig, containerName string) (string, error)

func DockerStreamLogs

func DockerStreamLogs(ctx context.Context, containerId string, stdout, stderr io.Writer) error

func DockerStreamLogsOnce

func DockerStreamLogsOnce(ctx context.Context, containerId string, stdout, stderr io.Writer) error

func EncodeOutput

func EncodeOutput(format string, w io.Writer, value any) error

func FallbackLookupIP

func FallbackLookupIP(ctx context.Context, host string) ([]string, error)

Performs DNS lookup via HTTPS, in case firewall blocks native netgo resolver.

func FormatTimestamp

func FormatTimestamp(timestamp string) string

func FormatTimestampVersion

func FormatTimestampVersion(timestamp string) string

func GetApiUrl

func GetApiUrl(path string) string

func GetCurrentBranchFS

func GetCurrentBranchFS(fsys afero.Fs) (string, error)

func GetCurrentTimestamp

func GetCurrentTimestamp() string

func GetDebugLogger

func GetDebugLogger() io.Writer

func GetDenoPath

func GetDenoPath() (string, error)

func GetDockerIds

func GetDockerIds() []string

func GetGitHubClient

func GetGitHubClient(ctx context.Context) *github.Client

func GetHostname

func GetHostname() string

func GetId

func GetId(name string) string

func GetLatestRelease

func GetLatestRelease(ctx context.Context) (string, error)

func GetPoolerConfig

func GetPoolerConfig(projectRef string) *pgconn.Config

func GetRegistry

func GetRegistry() string

func GetRegistryAuth

func GetRegistryAuth() string

func GetRegistryImageUrl

func GetRegistryImageUrl(imageName string) string

func GetSupabase

func GetSupabase() *supabase.ClientWithResponses

func GetSupabaseAPIHost

func GetSupabaseAPIHost() string

func GetSupabaseDashboardURL

func GetSupabaseDashboardURL() string

func GetSupabaseDbHost

func GetSupabaseDbHost(projectRef string) string

func GetSupabaseHost

func GetSupabaseHost(projectRef string) string

func InitConfig

func InitConfig(params InitParams, fsys afero.Fs) error

func InstallOrUpgradeDeno

func InstallOrUpgradeDeno(ctx context.Context, fsys afero.Fs) error

func IsBranchNameReserved

func IsBranchNameReserved(branch string) bool

func IsGitRepo

func IsGitRepo() bool

func IsLocalDatabase

func IsLocalDatabase(config pgconn.Config) bool

func LoadAccessToken

func LoadAccessToken() (string, error)

func LoadAccessTokenFS

func LoadAccessTokenFS(fsys afero.Fs) (string, error)

func LoadConfigFS

func LoadConfigFS(fsys afero.Fs) error

func MkdirIfNotExist

func MkdirIfNotExist(path string) error

func MkdirIfNotExistFS

func MkdirIfNotExistFS(fsys afero.Fs, path string) error

func NewDocker

func NewDocker() *client.Client

func NewRootFS

func NewRootFS(fsys afero.Fs) fs.FS

func ProcessDiffOutput

func ProcessDiffOutput(diffBytes []byte) ([]byte, error)

func ProcessDiffProgress

func ProcessDiffProgress(p Program, out io.Reader) error

func ProcessPsqlOutput

func ProcessPsqlOutput(out io.Reader, p Program) error

func ProcessPullOutput

func ProcessPullOutput(out io.ReadCloser, p Program) error

func Red

func Red(str string) string

For errors.

func RemoveDuplicates

func RemoveDuplicates[T comparable](slice []T) (result []T)

func ResolveCNAME

func ResolveCNAME(ctx context.Context, host string) (string, error)

func RunProgram

func RunProgram(ctx context.Context, f func(p Program, ctx context.Context) error) error

func SaveAccessToken

func SaveAccessToken(accessToken string, fsys afero.Fs) error

func ShortContainerImageName

func ShortContainerImageName(imageName string) string

func SliceContains

func SliceContains[T comparable](s []T, e T) bool

func SliceEqual

func SliceEqual[T comparable](a, b []T) bool

func ToDockerPath

func ToDockerPath(absHostPath string) string

func ToPostgresURL

func ToPostgresURL(config pgconn.Config) string

func ToRealtimeEnv

func ToRealtimeEnv(addr config.AddressFamily) string

func UpdateDockerIds

func UpdateDockerIds()

func ValidateFunctionSlug

func ValidateFunctionSlug(slug string) error

func WaitAll

func WaitAll[T any](containers []T, exec func(container T) error) []error

func WithTraceContext

func WithTraceContext(ctx context.Context) context.Context

func WriteConfig

func WriteConfig(fsys afero.Fs, _test bool) error

func WriteFile

func WriteFile(path string, contents []byte, fsys afero.Fs) error

func Yellow

func Yellow(str string) string

Types

type Console

type Console struct {
	IsTTY bool
	// contains filtered or unexported fields
}

func NewConsole

func NewConsole() *Console

func (*Console) PromptText

func (c *Console) PromptText(ctx context.Context, label string) (string, error)

PromptText asks for input using the label.

func (*Console) PromptYesNo

func (c *Console) PromptYesNo(ctx context.Context, label string, def bool) (bool, error)

PromptYesNo asks yes/no questions using the label.

func (*Console) ReadLine

func (c *Console) ReadLine(ctx context.Context) string

type DenoScriptDir

type DenoScriptDir struct {
	ExtractPath string
	BuildPath   string
}

func CopyDenoScripts

func CopyDenoScripts(ctx context.Context, fsys afero.Fs) (*DenoScriptDir, error)

Copy Deno scripts needed for function deploy and downloads, returning a DenoScriptDir struct or an error.

type DialContextFunc

type DialContextFunc func(context.Context, string, string) (net.Conn, error)

type DiffDependencies

type DiffDependencies struct {
	Type string `json:"type"`
}

type DiffEntry

type DiffEntry struct {
	Type             string             `json:"type"`
	Status           string             `json:"status"`
	DiffDdl          string             `json:"diff_ddl"`
	GroupName        string             `json:"group_name"`
	Dependencies     []DiffDependencies `json:"dependencies"`
	SourceSchemaName *string            `json:"source_schema_name"`
}

type DiffStream

type DiffStream struct {
	// contains filtered or unexported fields
}

func NewDiffStream

func NewDiffStream(p Program) *DiffStream

func (DiffStream) Collect

func (c DiffStream) Collect() ([]byte, error)

func (DiffStream) Stderr

func (c DiffStream) Stderr() io.Writer

func (DiffStream) Stdout

func (c DiffStream) Stdout() io.Writer

type DockerJob

type DockerJob struct {
	Image string
	Env   []string
	Cmd   []string
}

type EnumFlag

type EnumFlag struct {
	Allowed []string
	Value   string
}

Ref: https://github.com/spf13/pflag/issues/236#issuecomment-931600452

func (*EnumFlag) Set

func (a *EnumFlag) Set(p string) error

func (EnumFlag) String

func (a EnumFlag) String() string

func (*EnumFlag) Type

func (a *EnumFlag) Type() string

type ImportMap

type ImportMap struct {
	Imports map[string]string            `json:"imports"`
	Scopes  map[string]map[string]string `json:"scopes"`
}

func NewImportMap

func NewImportMap(absJsonPath string, fsys afero.Fs) (*ImportMap, error)

func (*ImportMap) BindHostModules

func (m *ImportMap) BindHostModules() []string

type InitParams

type InitParams struct {
	ProjectId   string
	UseOrioleDB bool
	Overwrite   bool
}

type Program

type Program interface {
	Start() error
	Send(msg tea.Msg)
	Quit()
}

An interface describing the parts of BubbleTea's Program that we actually use.

func NewProgram

func NewProgram(model tea.Model, opts ...tea.ProgramOption) Program

type ProgressMsg

type ProgressMsg *float64

type PromptItem

type PromptItem struct {
	Summary string
	Details string
	Index   int
}

PromptItem is exposed as prompt input, empty summary + details will be excluded.

func PromptChoice

func PromptChoice(ctx context.Context, title string, items []PromptItem, opts ...tea.ProgramOption) (PromptItem, error)

Prompt user to choose from a list of items, returns the chosen index.

func (PromptItem) Description

func (i PromptItem) Description() string

func (PromptItem) FilterValue

func (i PromptItem) FilterValue() string

func (PromptItem) Title

func (i PromptItem) Title() string

type PsqlMsg

type PsqlMsg *string

type StatusMsg

type StatusMsg string

type StatusWriter

type StatusWriter struct {
	Program
}

func (StatusWriter) Write

func (t StatusWriter) Write(p []byte) (int, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL