utils

package
v1.41.3 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2023 License: MIT Imports: 57 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 (
	Pg13Image = "supabase/postgres:13.3.0"
	Pg14Image = "supabase/postgres:14.1.0.89"
	Pg15Image = "supabase/postgres:15.1.0.52"
	// Append to ServiceImages when adding new dependencies below
	KongImage        = "library/kong:2.8.1"
	InbucketImage    = "inbucket/inbucket:3.0.3"
	PostgrestImage   = "postgrest/postgrest:v10.1.2"
	DifferImage      = "supabase/pgadmin-schema-diff:cli-0.0.5"
	MigraImage       = "djrobstep/migra:3.0.1621480950"
	PgmetaImage      = "supabase/postgres-meta:v0.60.7"
	StudioImage      = "supabase/studio:20230228-029c7bd"
	DenoRelayImage   = "supabase/deno-relay:v1.6.0"
	ImageProxyImage  = "darthsim/imgproxy:v3.8.0"
	EdgeRuntimeImage = "supabase/edge-runtime:v1.1.1"
	// Update initial schemas in internal/utils/templates/initial_schemas when
	// updating any one of these.
	GotrueImage   = "supabase/gotrue:v2.51.4"
	RealtimeImage = "supabase/realtime:v2.6.0"
	StorageImage  = "supabase/storage-api:v0.29.1"
	// Should be kept in-sync with DenoRelayImage
	DenoVersion = "1.30.3"
)
View Source
const (
	// https://dba.stackexchange.com/a/11895
	// Args: dbname
	TerminateDbSqlFmt = `` /* 244-byte string literal not displayed */

	AnonKey        = "" /* 153-byte string literal not displayed */
	ServiceRoleKey = "" /* 164-byte string literal not displayed */
	JWTSecret      = "super-secret-jwt-token-with-at-least-32-characters-long"
	AccessTokenKey = "access-token"
)

Variables

View Source
var (
	DbImage     string
	NetId       string
	DbId        string
	KongId      string
	GotrueId    string
	InbucketId  string
	RealtimeId  string
	RestId      string
	StorageId   string
	ImgProxyId  string
	DifferId    string
	PgmetaId    string
	StudioId    string
	DenoRelayId string

	InitialSchemaSql string
	//go:embed templates/initial_schemas/13.sql
	InitialSchemaPg13Sql string
	//go:embed templates/initial_schemas/14.sql
	InitialSchemaPg14Sql string
	//go:embed templates/initial_schemas/15.sql
	InitialSchemaPg15Sql string
)
View Source
var (
	Containers []string
	Volumes    []string
)

Used by unit tests NOTE: There's a risk of data race with reads & writes from `DockerRun` and reads from `DockerRemoveAll`, but since they're expected to be run on the same thread, this is fine.

View Source
var (
	CmdSuggestion 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

	AccessTokenPattern = regexp.MustCompile(`^sbp_[a-f0-9]{40}$`)
	ProjectRefPattern  = regexp.MustCompile(`^[a-z]{20}$`)
	PostgresUrlPattern = regexp.MustCompile(`^postgres(?:ql)?:\/\/postgres:(.*)@(.+)\/postgres$`)
	MigrateFilePattern = regexp.MustCompile(`^([0-9]+)_.*\.sql$`)
	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
	SystemSchemas = []string{
		"information_schema",
		"pg_*",

		"cron",
		"graphql",
		"graphql_public",
		"net",
		"pgsodium",
		"pgsodium_masks",
		"pgtle",
		"repack",
		"tiger",
		"tiger_data",
		"timescaledb_*",
		"_timescaledb_*",
		"topology",
		"vault",
	}
	InternalSchemas = append([]string{
		"auth",
		"extensions",
		"pgbouncer",
		"realtime",
		"_realtime",
		"storage",
		"supabase_functions",
		"supabase_migrations",
	}, SystemSchemas...)
	ReservedRoles = []string{
		"anon",
		"authenticated",
		"authenticator",
		"dashboard_user",
		"pgbouncer",
		"postgres",
		"service_role",
		"supabase_admin",
		"supabase_auth_admin",
		"supabase_functions_admin",
		"supabase_replication_admin",
		"supabase_storage_admin",
	}

	SupabaseDirPath       = "supabase"
	ConfigPath            = filepath.Join(SupabaseDirPath, "config.toml")
	ProjectRefPath        = filepath.Join(SupabaseDirPath, ".temp", "project-ref")
	RemoteDbPath          = filepath.Join(SupabaseDirPath, ".temp", "remote-db-url")
	CurrBranchPath        = filepath.Join(SupabaseDirPath, ".branches", "_current_branch")
	MigrationsDir         = filepath.Join(SupabaseDirPath, "migrations")
	FunctionsDir          = filepath.Join(SupabaseDirPath, "functions")
	FallbackImportMapPath = filepath.Join(FunctionsDir, "import_map.json")
	DbTestsDir            = filepath.Join(SupabaseDirPath, "tests")
	SeedDataPath          = filepath.Join(SupabaseDirPath, "seed.sql")
	CustomRolesPath       = filepath.Join(SupabaseDirPath, "roles.sql")
)
View Source
var Config config
View Source
var (
	DNSResolver = EnumFlag{
		Allowed: []string{DNS_GO_NATIVE, DNS_OVER_HTTPS},
		Value:   DNS_GO_NATIVE,
	}
)
View Source
var (
	DenoPathOverride string
)

Used by unit tests

View Source
var Docker = NewDocker()

TODO: refactor to initialise lazily

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)",
}
View Source
var Version string

Passed from `-ldflags`: https://stackoverflow.com/q/11354518.

Functions

func Aqua added in v0.15.6

func Aqua(str string) string

For commands & names.

func AssertDockerIsRunning

func AssertDockerIsRunning(ctx context.Context) error

func AssertIsLinkedFS added in v0.32.0

func AssertIsLinkedFS(fsys afero.Fs) error

func AssertSupabaseCliIsSetUpFS added in v0.32.0

func AssertSupabaseCliIsSetUpFS(fsys afero.Fs) error

func AssertSupabaseDbIsRunning added in v0.33.1

func AssertSupabaseDbIsRunning() error

func Bold added in v0.15.6

func Bold(str string) string

For paths & filenames.

func ConnectByUrl added in v1.28.0

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

func ConnectLocalPostgres added in v1.17.4

func ConnectLocalPostgres(ctx context.Context, host string, port uint, database string, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

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

func ConnectRemotePostgres added in v1.17.4

func ConnectRemotePostgres(ctx context.Context, username, password, database, host string, options ...func(*pgx.ConnConfig)) (*pgx.Conn, error)

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

func DockerAddFile added in v0.28.2

func DockerAddFile(ctx context.Context, container string, fileName string, content []byte) error

func DockerExec

func DockerExec(ctx context.Context, container string, cmd []string) (io.Reader, error)

func DockerExecOnce added in v0.37.0

func DockerExecOnce(ctx context.Context, container 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 DockerImagePull added in v1.26.9

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

func DockerImagePullWithRetry added in v1.5.2

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

func DockerNetworkCreateIfNotExists added in v1.16.0

func DockerNetworkCreateIfNotExists(ctx context.Context, networkId string) error

func DockerPullImageIfNotCached added in v0.37.0

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

func DockerRemove added in v1.27.1

func DockerRemove(containerId string)

func DockerRemoveAll

func DockerRemoveAll(ctx context.Context)

func DockerRunOnce added in v0.37.0

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 DockerRunOnceWithStream added in v1.27.2

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

func DockerStart added in v1.11.2

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

func DockerStop added in v1.11.2

func DockerStop(containerID string)

func FallbackLookupIP added in v1.41.0

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

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

func GetCurrentBranchFS added in v0.32.0

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

func GetCurrentTimestamp

func GetCurrentTimestamp() string

func GetDenoPath added in v1.4.7

func GetDenoPath() (string, error)

func GetGitRoot added in v0.8.0

func GetGitRoot(fsys afero.Fs) (*string, error)

func GetProjectRoot added in v1.8.2

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

If the `os.Getwd()` is within a supabase project, this will return the root of the given project as the current working directory. Otherwise, the `os.Getwd()` is kept as is.

func GetRegistryAuth added in v1.16.2

func GetRegistryAuth() string

func GetRegistryImageUrl added in v1.0.1

func GetRegistryImageUrl(imageName string) string

func GetSupabase added in v0.38.5

func GetSupabase() *supabase.ClientWithResponses

func GetSupabaseAPIHost added in v0.31.1

func GetSupabaseAPIHost() string

func GetSupabaseDashboardURL added in v0.31.1

func GetSupabaseDashboardURL() string

func GetSupabaseDbHost added in v1.4.10

func GetSupabaseDbHost(projectRef string) string

func GetSupabaseHost added in v1.10.0

func GetSupabaseHost(projectRef string) string

func InitConfig added in v1.38.1

func InitConfig(projectId string, fsys afero.Fs) error

func InstallOrUpgradeDeno added in v0.19.0

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

func IsBranchNameReserved added in v0.13.0

func IsBranchNameReserved(branch string) bool

func LoadAccessToken added in v0.20.0

func LoadAccessToken() (string, error)

func LoadAccessTokenFS added in v0.31.0

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

func LoadConfig

func LoadConfig() error

func LoadConfigFS added in v0.32.0

func LoadConfigFS(fsys afero.Fs) error

func LoadProjectRef added in v0.38.0

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

func MkdirIfNotExist added in v0.19.0

func MkdirIfNotExist(path string) error

func MkdirIfNotExistFS added in v0.31.0

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

func NewDocker added in v0.37.0

func NewDocker() *client.Client

func NewError added in v0.18.0

func NewError(s string) error

TODO: Make all errors use this.

func ProcessDiffOutput added in v0.9.0

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

func ProcessDiffProgress added in v1.27.2

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

func ProcessPsqlOutput added in v0.10.0

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

func ProcessPullOutput added in v0.9.0

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

func ResolveCNAME added in v1.10.0

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

func RunProgram added in v1.27.2

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

func ShortContainerImageName added in v1.19.0

func ShortContainerImageName(imageName string) string

func ValidateFunctionSlug added in v0.20.6

func ValidateFunctionSlug(slug string) error

func WaitAll added in v1.31.1

func WaitAll(containers []string, exec func(container string))

func WithTraceContext added in v1.4.1

func WithTraceContext(ctx context.Context) context.Context

func WriteConfig added in v0.18.2

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

Types

type DenoScriptDir added in v1.34.0

type DenoScriptDir struct {
	ExtractPath string
	BuildPath   string
}

func CopyDenoScripts added in v1.34.0

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 added in v1.41.1

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

type DiffDependencies added in v0.13.0

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 added in v1.27.2

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

func NewDiffStream added in v1.27.2

func NewDiffStream(p Program) *DiffStream

func (DiffStream) Collect added in v1.27.2

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

func (DiffStream) Stderr added in v1.27.2

func (c DiffStream) Stderr() io.Writer

func (DiffStream) Stdout added in v1.27.2

func (c DiffStream) Stdout() io.Writer

type EnumFlag added in v0.39.0

type EnumFlag struct {
	Allowed []string
	Value   string
}

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

func (*EnumFlag) Set added in v0.39.0

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

func (EnumFlag) String added in v0.39.0

func (a EnumFlag) String() string

func (*EnumFlag) Type added in v0.39.0

func (a *EnumFlag) Type() string

type Program added in v0.17.1

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 added in v0.17.1

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

type ProgressMsg added in v0.9.0

type ProgressMsg *float64

type PromptItem added in v0.39.0

type PromptItem struct {
	Summary string
	Details string
}

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

func PromptChoice added in v0.39.0

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

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

func (PromptItem) Description added in v0.39.0

func (i PromptItem) Description() string

func (PromptItem) FilterValue added in v0.39.0

func (i PromptItem) FilterValue() string

func (PromptItem) Title added in v0.39.0

func (i PromptItem) Title() string

type PsqlMsg added in v0.10.0

type PsqlMsg *string

type StatusMsg added in v0.9.0

type StatusMsg string

type StatusWriter added in v1.28.0

type StatusWriter struct {
	Program
}

func (StatusWriter) Write added in v1.28.0

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