From 2bc0c20c5788807c7e77233e6fb28906277f82dd Mon Sep 17 00:00:00 2001 From: Qiao Han Date: Tue, 14 Oct 2025 11:03:16 +0800 Subject: [PATCH 1/2] chore: modernise golang code --- cmd/root.go | 4 ++-- internal/db/branch/switch_/switch__test.go | 6 +++--- internal/db/lint/lint_test.go | 18 +++++++++--------- internal/db/pull/pull_test.go | 6 +++--- internal/db/reset/reset_test.go | 4 ++-- internal/hostnames/common_test.go | 4 ++-- internal/init/init.go | 2 +- internal/link/link_test.go | 8 ++++---- internal/migration/down/down_test.go | 4 ++-- internal/migration/list/list_test.go | 4 ++-- internal/migration/up/up_test.go | 20 ++++++++++---------- internal/postgresConfig/update/update.go | 2 +- internal/sso/create/create.go | 8 ++++---- internal/sso/internal/saml/files_test.go | 8 ++++---- internal/sso/update/update.go | 8 ++++---- internal/start/start_test.go | 2 +- internal/storage/ls/ls_test.go | 2 +- internal/utils/connect.go | 2 +- internal/utils/container_output.go | 8 ++------ internal/utils/docker.go | 2 +- internal/utils/flags/db_url.go | 2 +- internal/utils/output_test.go | 20 ++++++++++---------- internal/utils/prompt.go | 5 +---- internal/utils/slice.go | 9 +++------ 24 files changed, 74 insertions(+), 84 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 8329cd86c..5a1072284 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -260,7 +260,7 @@ func GetRootCmd() *cobra.Command { func addSentryScope(scope *sentry.Scope) { serviceImages := utils.Config.GetServiceImages() - imageToVersion := make(map[string]interface{}, len(serviceImages)) + imageToVersion := make(map[string]any, len(serviceImages)) for _, image := range serviceImages { parts := strings.Split(image, ":") // Bypasses sentry's IP sanitization rule, ie. 15.1.0.147 @@ -271,7 +271,7 @@ func addSentryScope(scope *sentry.Scope) { } } scope.SetContext("Services", imageToVersion) - scope.SetContext("Config", map[string]interface{}{ + scope.SetContext("Config", map[string]any{ "Image Registry": utils.GetRegistry(), "Project ID": flags.ProjectRef, }) diff --git a/internal/db/branch/switch_/switch__test.go b/internal/db/branch/switch_/switch__test.go index 3eca45cd1..f0e51d521 100644 --- a/internal/db/branch/switch_/switch__test.go +++ b/internal/db/branch/switch_/switch__test.go @@ -48,7 +48,7 @@ func TestSwitchCommand(t *testing.T) { Query(reset.TERMINATE_BACKENDS). Reply("SELECT 1"). Query(reset.COUNT_REPLICATION_SLOTS). - Reply("SELECT 1", []interface{}{0}). + Reply("SELECT 1", []any{0}). Query("ALTER DATABASE postgres RENAME TO main;"). Reply("ALTER DATABASE"). Query("ALTER DATABASE " + branch + " RENAME TO postgres;"). @@ -237,7 +237,7 @@ func TestSwitchDatabase(t *testing.T) { Query(reset.TERMINATE_BACKENDS). Reply("SELECT 1"). Query(reset.COUNT_REPLICATION_SLOTS). - Reply("SELECT 1", []interface{}{0}). + Reply("SELECT 1", []any{0}). Query("ALTER DATABASE postgres RENAME TO main;"). ReplyError(pgerrcode.DuplicateDatabase, `database "main" already exists`) // Setup mock docker @@ -267,7 +267,7 @@ func TestSwitchDatabase(t *testing.T) { Query(reset.TERMINATE_BACKENDS). Reply("SELECT 1"). Query(reset.COUNT_REPLICATION_SLOTS). - Reply("SELECT 1", []interface{}{0}). + Reply("SELECT 1", []any{0}). Query("ALTER DATABASE postgres RENAME TO main;"). Reply("ALTER DATABASE"). Query("ALTER DATABASE target RENAME TO postgres;"). diff --git a/internal/db/lint/lint_test.go b/internal/db/lint/lint_test.go index e8f4bc9a0..f43b2086d 100644 --- a/internal/db/lint/lint_test.go +++ b/internal/db/lint/lint_test.go @@ -62,7 +62,7 @@ func TestLintCommand(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"f1", string(data)}). + Reply("SELECT 1", []any{"f1", string(data)}). Query("rollback").Reply("ROLLBACK") // Run test err = Run(context.Background(), []string{"public"}, "warning", "none", dbConfig, fsys, conn.Intercept) @@ -117,8 +117,8 @@ func TestLintDatabase(t *testing.T) { Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). Reply("SELECT 2", - []interface{}{"f1", string(r1)}, - []interface{}{"f2", string(r2)}, + []any{"f1", string(r1)}, + []any{"f2", string(r2)}, ). Query("rollback").Reply("ROLLBACK") // Run test @@ -158,9 +158,9 @@ func TestLintDatabase(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"where_clause", string(r1)}). + Reply("SELECT 1", []any{"where_clause", string(r1)}). Query(checkSchemaScript, "private"). - Reply("SELECT 1", []interface{}{"f2", string(r2)}). + Reply("SELECT 1", []any{"f2", string(r2)}). Query("rollback").Reply("ROLLBACK") // Run test result, err := LintDatabase(context.Background(), conn.MockClient(t), []string{"public", "private"}) @@ -191,7 +191,7 @@ func TestLintDatabase(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"f1", "malformed"}). + Reply("SELECT 1", []any{"f1", "malformed"}). Query("rollback").Reply("ROLLBACK") // Run test _, err := LintDatabase(context.Background(), conn.MockClient(t), []string{"public"}) @@ -253,7 +253,7 @@ func TestPrintResult(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"f1", `{"function":"22751","issues":[{"level":"warning","message":"test warning"}]}`}). + Reply("SELECT 1", []any{"f1", `{"function":"22751","issues":[{"level":"warning","message":"test warning"}]}`}). Query("rollback").Reply("ROLLBACK") // Run test err := Run(context.Background(), []string{"public"}, "warning", "warning", dbConfig, fsys, conn.Intercept) @@ -271,7 +271,7 @@ func TestPrintResult(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"f1", `{"function":"22751","issues":[{"level":"error","message":"test error"}]}`}). + Reply("SELECT 1", []any{"f1", `{"function":"22751","issues":[{"level":"error","message":"test error"}]}`}). Query("rollback").Reply("ROLLBACK") // Run test err := Run(context.Background(), []string{"public"}, "warning", "error", dbConfig, fsys, conn.Intercept) @@ -289,7 +289,7 @@ func TestPrintResult(t *testing.T) { Query(ENABLE_PGSQL_CHECK). Reply("CREATE EXTENSION"). Query(checkSchemaScript, "public"). - Reply("SELECT 1", []interface{}{"f1", `{"function":"22751","issues":[{"level":"error","message":"test error"}]}`}). + Reply("SELECT 1", []any{"f1", `{"function":"22751","issues":[{"level":"error","message":"test error"}]}`}). Query("rollback").Reply("ROLLBACK") // Run test err := Run(context.Background(), []string{"public"}, "warning", "none", dbConfig, fsys, conn.Intercept) diff --git a/internal/db/pull/pull_test.go b/internal/db/pull/pull_test.go index 8161f51e1..293448156 100644 --- a/internal/db/pull/pull_test.go +++ b/internal/db/pull/pull_test.go @@ -92,7 +92,7 @@ func TestPullSchema(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"0"}). + Reply("SELECT 1", []any{"0"}). Query(migration.ListSchemas, migration.ManagedSchemas). ReplyError(pgerrcode.DuplicateTable, `relation "test" already exists`) // Run test @@ -116,7 +116,7 @@ func TestPullSchema(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"0"}) + Reply("SELECT 1", []any{"0"}) // Run test err := run(context.Background(), []string{"public"}, "", conn.MockClient(t), fsys) // Check error @@ -167,7 +167,7 @@ func TestSyncRemote(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"20220727064247"}) + Reply("SELECT 1", []any{"20220727064247"}) // Run test err := assertRemoteInSync(context.Background(), conn.MockClient(t), fsys) // Check error diff --git a/internal/db/reset/reset_test.go b/internal/db/reset/reset_test.go index 23454d070..9eeb0f150 100644 --- a/internal/db/reset/reset_test.go +++ b/internal/db/reset/reset_test.go @@ -206,7 +206,7 @@ func TestRecreateDatabase(t *testing.T) { Query(TERMINATE_BACKENDS). Reply("SELECT 1"). Query(COUNT_REPLICATION_SLOTS). - Reply("SELECT 1", []interface{}{0}). + Reply("SELECT 1", []any{0}). Query("DROP DATABASE IF EXISTS postgres WITH (FORCE)"). Reply("DROP DATABASE"). Query("CREATE DATABASE postgres WITH OWNER postgres"). @@ -269,7 +269,7 @@ func TestRecreateDatabase(t *testing.T) { Query(TERMINATE_BACKENDS). Reply("SELECT 1"). Query(COUNT_REPLICATION_SLOTS). - Reply("SELECT 1", []interface{}{0}). + Reply("SELECT 1", []any{0}). Query("DROP DATABASE IF EXISTS postgres WITH (FORCE)"). ReplyError(pgerrcode.ObjectInUse, `database "postgres" is used by an active logical replication slot`). Query("CREATE DATABASE postgres WITH OWNER postgres"). diff --git a/internal/hostnames/common_test.go b/internal/hostnames/common_test.go index e46e202ab..2c3755c7c 100644 --- a/internal/hostnames/common_test.go +++ b/internal/hostnames/common_test.go @@ -19,7 +19,7 @@ func TestVerifyCNAME(t *testing.T) { MatchParam("type", "5"). MatchHeader("accept", "application/dns-json"). Reply(http.StatusOK). - JSON(&map[string]interface{}{"Answer": []map[string]interface{}{ + JSON(&map[string]any{"Answer": []map[string]any{ { "Type": 5, "Data": "foobarbaz.supabase.co.", }, @@ -36,7 +36,7 @@ func TestVerifyCNAMEFailures(t *testing.T) { MatchParam("type", "5"). MatchHeader("accept", "application/dns-json"). Reply(http.StatusOK). - JSON(&map[string]interface{}{"Answer": []map[string]interface{}{ + JSON(&map[string]any{"Answer": []map[string]any{ { "Type": 28, "Data": "127.0.0.1", }, diff --git a/internal/init/init.go b/internal/init/init.go index 72241a0e0..4bb18581b 100644 --- a/internal/init/init.go +++ b/internal/init/init.go @@ -99,7 +99,7 @@ func updateGitIgnore(ignorePath string, fsys afero.Fs) error { return nil } -type VSCodeSettings map[string]interface{} +type VSCodeSettings map[string]any func loadUserSettings(path string, fsys afero.Fs) (VSCodeSettings, error) { data, err := afero.ReadFile(fsys, path) diff --git a/internal/link/link_test.go b/internal/link/link_test.go index 686f12d46..8b473d9de 100644 --- a/internal/link/link_test.go +++ b/internal/link/link_test.go @@ -50,7 +50,7 @@ func TestLinkCommand(t *testing.T) { conn.Query(utils.SET_SESSION_ROLE). Reply("SET ROLE"). Query(GET_LATEST_STORAGE_MIGRATION). - Reply("SELECT 1", []interface{}{"custom-metadata"}) + Reply("SELECT 1", []any{"custom-metadata"}) helper.MockMigrationHistory(conn) helper.MockSeedHistory(conn) // Flush pending mocks after test execution @@ -200,7 +200,7 @@ func TestLinkCommand(t *testing.T) { conn.Query(utils.SET_SESSION_ROLE). Reply("SET ROLE"). Query(GET_LATEST_STORAGE_MIGRATION). - Reply("SELECT 1", []interface{}{"custom-metadata"}) + Reply("SELECT 1", []any{"custom-metadata"}) helper.MockMigrationHistory(conn) helper.MockSeedHistory(conn) // Flush pending mocks after test execution @@ -423,7 +423,7 @@ func TestLinkDatabase(t *testing.T) { }) defer conn.Close(t) conn.Query(GET_LATEST_STORAGE_MIGRATION). - Reply("SELECT 1", []interface{}{"custom-metadata"}) + Reply("SELECT 1", []any{"custom-metadata"}) helper.MockMigrationHistory(conn) helper.MockSeedHistory(conn) // Run test @@ -446,7 +446,7 @@ func TestLinkDatabase(t *testing.T) { }) defer conn.Close(t) conn.Query(GET_LATEST_STORAGE_MIGRATION). - Reply("SELECT 1", []interface{}{"custom-metadata"}) + Reply("SELECT 1", []any{"custom-metadata"}) helper.MockMigrationHistory(conn) helper.MockSeedHistory(conn) // Run test diff --git a/internal/migration/down/down_test.go b/internal/migration/down/down_test.go index 79eacf2a0..89d9ff66d 100644 --- a/internal/migration/down/down_test.go +++ b/internal/migration/down/down_test.go @@ -40,7 +40,7 @@ func TestMigrationsDown(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 2", []interface{}{"20221201000000"}, []interface{}{"20221201000001"}) + Reply("SELECT 2", []any{"20221201000000"}, []any{"20221201000001"}) // Run test err := Run(context.Background(), 1, dbConfig, fsys, conn.Intercept) // Check error @@ -54,7 +54,7 @@ func TestMigrationsDown(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 2", []interface{}{"20221201000000"}, []interface{}{"20221201000001"}) + Reply("SELECT 2", []any{"20221201000000"}, []any{"20221201000001"}) // Run test err := Run(context.Background(), 2, dbConfig, fsys, conn.Intercept) // Check error diff --git a/internal/migration/list/list_test.go b/internal/migration/list/list_test.go index b23fa4a2d..9744174df 100644 --- a/internal/migration/list/list_test.go +++ b/internal/migration/list/list_test.go @@ -71,7 +71,7 @@ func TestRemoteMigrations(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"20220727064247"}) + Reply("SELECT 1", []any{"20220727064247"}) // Run test versions, err := loadRemoteVersions(context.Background(), dbConfig, conn.Intercept) // Check error @@ -104,7 +104,7 @@ func TestRemoteMigrations(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{}) + Reply("SELECT 1", []any{}) // Run test _, err := loadRemoteVersions(context.Background(), dbConfig, conn.Intercept) // Check error diff --git a/internal/migration/up/up_test.go b/internal/migration/up/up_test.go index ea41680bc..85669d709 100644 --- a/internal/migration/up/up_test.go +++ b/internal/migration/up/up_test.go @@ -32,7 +32,7 @@ func TestPendingMigrations(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 2", []interface{}{"20221201000000"}, []interface{}{"20221201000001"}) + Reply("SELECT 2", []any{"20221201000000"}, []any{"20221201000001"}) // Run test pending, err := GetPendingMigrations(context.Background(), false, conn.MockClient(t), fsys) // Check error @@ -61,7 +61,7 @@ func TestPendingMigrations(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"0"}) + Reply("SELECT 1", []any{"0"}) // Run test _, err := GetPendingMigrations(context.Background(), false, conn.MockClient(t), fsys) // Check error @@ -81,7 +81,7 @@ func TestPendingMigrations(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 1", []interface{}{"1"}) + Reply("SELECT 1", []any{"1"}) // Run test _, err := GetPendingMigrations(context.Background(), false, conn.MockClient(t), fsys) // Check error @@ -106,7 +106,7 @@ func TestIgnoreVersionMismatch(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 2", []interface{}{"20221201000000"}, []interface{}{"20221201000002"}) + Reply("SELECT 2", []any{"20221201000000"}, []any{"20221201000002"}) // Run test pending, err := GetPendingMigrations(context.Background(), true, conn.MockClient(t), fsys) // Check error @@ -130,7 +130,7 @@ func TestIgnoreVersionMismatch(t *testing.T) { conn := pgtest.NewConn() defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). - Reply("SELECT 2", []interface{}{"20221201000002"}, []interface{}{"20221201000004"}) + Reply("SELECT 2", []any{"20221201000002"}, []any{"20221201000004"}) // Run test _, err := GetPendingMigrations(context.Background(), true, conn.MockClient(t), fsys) // Check error @@ -153,11 +153,11 @@ func TestIgnoreVersionMismatch(t *testing.T) { defer conn.Close(t) conn.Query(migration.LIST_MIGRATION_VERSION). Reply("SELECT 5", - []interface{}{"20221201000000"}, - []interface{}{"20221201000001"}, - []interface{}{"20221201000002"}, - []interface{}{"20221201000003"}, - []interface{}{"20221201000004"}, + []any{"20221201000000"}, + []any{"20221201000001"}, + []any{"20221201000002"}, + []any{"20221201000003"}, + []any{"20221201000004"}, ) // Run test _, err := GetPendingMigrations(context.Background(), true, conn.MockClient(t), fsys) diff --git a/internal/postgresConfig/update/update.go b/internal/postgresConfig/update/update.go index f031b3378..4d7e42087 100644 --- a/internal/postgresConfig/update/update.go +++ b/internal/postgresConfig/update/update.go @@ -25,7 +25,7 @@ func Run(ctx context.Context, projectRef string, values []string, replaceOverrid newConfigOverrides[splits[0]] = splits[1] } // 2. If not in replace mode, retrieve current overrides - finalOverrides := make(map[string]interface{}) + finalOverrides := make(map[string]any) { if !replaceOverrides { config, err := get.GetCurrentPostgresConfig(ctx, projectRef) diff --git a/internal/sso/create/create.go b/internal/sso/create/create.go index 83cadd5fb..15dea6cc7 100644 --- a/internal/sso/create/create.go +++ b/internal/sso/create/create.go @@ -51,10 +51,10 @@ func Run(ctx context.Context, params RunParams) error { if params.AttributeMapping != "" { body.AttributeMapping = &struct { Keys map[string]struct { - Array *bool "json:\"array,omitempty\"" - Default *interface{} "json:\"default,omitempty\"" - Name *string "json:\"name,omitempty\"" - Names *[]string "json:\"names,omitempty\"" + Array *bool "json:\"array,omitempty\"" + Default *any "json:\"default,omitempty\"" + Name *string "json:\"name,omitempty\"" + Names *[]string "json:\"names,omitempty\"" } "json:\"keys\"" }{} if err := saml.ReadAttributeMappingFile(Fs, params.AttributeMapping, body.AttributeMapping); err != nil { diff --git a/internal/sso/internal/saml/files_test.go b/internal/sso/internal/saml/files_test.go index 320f2df13..cc5c59b85 100644 --- a/internal/sso/internal/saml/files_test.go +++ b/internal/sso/internal/saml/files_test.go @@ -33,10 +33,10 @@ func TestReadAttributeMappingFile(t *testing.T) { body := api.CreateProviderBody{ AttributeMapping: &struct { Keys map[string]struct { - Array *bool "json:\"array,omitempty\"" - Default *interface{} "json:\"default,omitempty\"" - Name *string "json:\"name,omitempty\"" - Names *[]string "json:\"names,omitempty\"" + Array *bool "json:\"array,omitempty\"" + Default *any "json:\"default,omitempty\"" + Name *string "json:\"name,omitempty\"" + Names *[]string "json:\"names,omitempty\"" } "json:\"keys\"" }{}, } diff --git a/internal/sso/update/update.go b/internal/sso/update/update.go index f92357c70..316a1360b 100644 --- a/internal/sso/update/update.go +++ b/internal/sso/update/update.go @@ -71,10 +71,10 @@ func Run(ctx context.Context, params RunParams) error { if params.AttributeMapping != "" { body.AttributeMapping = &struct { Keys map[string]struct { - Array *bool "json:\"array,omitempty\"" - Default *interface{} "json:\"default,omitempty\"" - Name *string "json:\"name,omitempty\"" - Names *[]string "json:\"names,omitempty\"" + Array *bool "json:\"array,omitempty\"" + Default *any "json:\"default,omitempty\"" + Name *string "json:\"name,omitempty\"" + Names *[]string "json:\"names,omitempty\"" } "json:\"keys\"" }{} if err := saml.ReadAttributeMappingFile(Fs, params.AttributeMapping, body.AttributeMapping); err != nil { diff --git a/internal/start/start_test.go b/internal/start/start_test.go index 99df75378..5e4e578db 100644 --- a/internal/start/start_test.go +++ b/internal/start/start_test.go @@ -268,7 +268,7 @@ func TestFormatMapForEnvConfig(t *testing.T) { if len(output.Bytes()) > 0 { t.Error("No values should be expected when empty map is provided") } - for i := 0; i < 4; i++ { + for i := range 4 { output.Reset() input[keys[i]] = values[i] formatMapForEnvConfig(input, &output) diff --git a/internal/storage/ls/ls_test.go b/internal/storage/ls/ls_test.go index 27c388f5f..e32c5b845 100644 --- a/internal/storage/ls/ls_test.go +++ b/internal/storage/ls/ls_test.go @@ -185,7 +185,7 @@ func TestListStoragePaths(t *testing.T) { defer gock.OffAll() expected := make([]string, storage.PAGE_LIMIT) resp := make([]storage.ObjectResponse, storage.PAGE_LIMIT) - for i := 0; i < len(resp); i++ { + for i := range resp { resp[i] = storage.ObjectResponse{Name: fmt.Sprintf("dir_%d", i)} expected[i] = resp[i].Name + "/" } diff --git a/internal/utils/connect.go b/internal/utils/connect.go index 1527a020d..3223bb032 100644 --- a/internal/utils/connect.go +++ b/internal/utils/connect.go @@ -59,7 +59,7 @@ func GetPoolerConfig(projectRef string) *pgconn.Config { } // Verify that the pooler username matches the database host being connected to if _, ref, found := strings.Cut(poolerConfig.User, "."); !found { - for _, option := range strings.Split(poolerConfig.RuntimeParams["options"], ",") { + for option := range strings.SplitSeq(poolerConfig.RuntimeParams["options"], ",") { key, value, found := strings.Cut(option, "=") if found && key == "reference" && value != projectRef { fmt.Fprintln(logger, "Pooler options does not match project ref:", projectRef) diff --git a/internal/utils/container_output.go b/internal/utils/container_output.go index ccbbab033..bd3e19d1f 100644 --- a/internal/utils/container_output.go +++ b/internal/utils/container_output.go @@ -8,6 +8,7 @@ import ( "io" "os" "regexp" + "slices" "strconv" "strings" @@ -178,12 +179,7 @@ func ProcessDiffOutput(diffBytes []byte) ([]byte, error) { } isSchemaIgnored := func(schema string) bool { - for _, s := range InternalSchemas { - if s == schema { - return true - } - } - return false + return slices.Contains(InternalSchemas, schema) } if isSchemaIgnored(diffEntry.GroupName) || diff --git a/internal/utils/docker.go b/internal/utils/docker.go index 7e908649e..6da0d5aa6 100644 --- a/internal/utils/docker.go +++ b/internal/utils/docker.go @@ -224,7 +224,7 @@ var timeUnit = time.Second func DockerImagePullWithRetry(ctx context.Context, image string, retries int) error { err := DockerImagePull(ctx, image, os.Stderr) - for i := 0; i < retries; i++ { + for i := range retries { if err == nil || errors.Is(ctx.Err(), context.Canceled) { break } diff --git a/internal/utils/flags/db_url.go b/internal/utils/flags/db_url.go index 152900ba2..35bdc836d 100644 --- a/internal/utils/flags/db_url.go +++ b/internal/utils/flags/db_url.go @@ -202,7 +202,7 @@ func PromptPassword(stdin *os.File) string { charset := string(config.LowerUpperLettersDigits.ToChar()) charset = strings.ReplaceAll(charset, ":", "") maxRange := big.NewInt(int64(len(charset))) - for i := 0; i < PASSWORD_LENGTH; i++ { + for range PASSWORD_LENGTH { random, err := rand.Int(rand.Reader, maxRange) if err != nil { fmt.Fprintln(os.Stderr, "Failed to randomise password:", err) diff --git a/internal/utils/output_test.go b/internal/utils/output_test.go index daaa947c1..a04be2536 100644 --- a/internal/utils/output_test.go +++ b/internal/utils/output_test.go @@ -34,9 +34,9 @@ func TestEncodeOutput(t *testing.T) { }) t.Run("encodes json format", func(t *testing.T) { - input := map[string]interface{}{ + input := map[string]any{ "name": "test", - "config": map[string]interface{}{ + "config": map[string]any{ "port": 5432, "enabled": true, }, @@ -56,9 +56,9 @@ func TestEncodeOutput(t *testing.T) { }) t.Run("encodes yaml format", func(t *testing.T) { - input := map[string]interface{}{ + input := map[string]any{ "name": "test", - "config": map[string]interface{}{ + "config": map[string]any{ "port": 5432, "enabled": true, }, @@ -75,9 +75,9 @@ name: test }) t.Run("encodes toml format", func(t *testing.T) { - input := map[string]interface{}{ + input := map[string]any{ "name": "test", - "config": map[string]interface{}{ + "config": map[string]any{ "port": 5432, "enabled": true, }, @@ -101,9 +101,9 @@ name: test }) t.Run("handles complex nested structures", func(t *testing.T) { - input := map[string]interface{}{ - "database": map[string]interface{}{ - "connections": []map[string]interface{}{ + input := map[string]any{ + "database": map[string]any{ + "connections": []map[string]any{ { "host": "localhost", "port": 5432, @@ -113,7 +113,7 @@ name: test "port": 6543, }, }, - "settings": map[string]interface{}{ + "settings": map[string]any{ "max_connections": 100, "ssl_enabled": true, }, diff --git a/internal/utils/prompt.go b/internal/utils/prompt.go index 5589f49d6..3e121f092 100644 --- a/internal/utils/prompt.go +++ b/internal/utils/prompt.go @@ -113,10 +113,7 @@ func PromptChoice(ctx context.Context, title string, items []PromptItem, opts .. listItems = append(listItems, v) } // Create list model - height := len(listItems) * 4 - if height > 14 { - height = 14 - } + height := min(len(listItems)*4, 14) l := list.New(listItems, itemDelegate{}, 0, height) l.Title = title l.SetShowStatusBar(false) diff --git a/internal/utils/slice.go b/internal/utils/slice.go index 3d036c19d..574f30cc0 100644 --- a/internal/utils/slice.go +++ b/internal/utils/slice.go @@ -1,12 +1,9 @@ package utils +import "slices" + func SliceContains[T comparable](s []T, e T) bool { - for _, a := range s { - if a == e { - return true - } - } - return false + return slices.Contains(s, e) } func SliceEqual[T comparable](a, b []T) bool { From 62a05d28d279822479f1e20ac86ea3be06215989 Mon Sep 17 00:00:00 2001 From: Qiao Han Date: Tue, 14 Oct 2025 11:04:51 +0800 Subject: [PATCH 2/2] chore: prefer native slices package --- cmd/start.go | 3 ++- internal/db/pull/pull.go | 3 ++- internal/start/start.go | 3 ++- internal/status/status.go | 11 ++++++----- internal/utils/enum.go | 3 ++- internal/utils/slice.go | 18 ------------------ internal/utils/slice_test.go | 35 ----------------------------------- pkg/config/auth.go | 7 ++++--- pkg/config/config.go | 9 +++++---- pkg/config/db.go | 5 +++-- pkg/config/utils.go | 9 --------- 11 files changed, 26 insertions(+), 80 deletions(-) diff --git a/cmd/start.go b/cmd/start.go index a7af80e0c..bd1cc1f8a 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -3,6 +3,7 @@ package cmd import ( "fmt" "os" + "slices" "sort" "strings" @@ -18,7 +19,7 @@ func validateExcludedContainers(excludedContainers []string) { var invalidContainers []string for _, e := range excludedContainers { - if !utils.SliceContains(validContainers, e) { + if !slices.Contains(validContainers, e) { invalidContainers = append(invalidContainers, e) } } diff --git a/internal/db/pull/pull.go b/internal/db/pull/pull.go index feffe2ce2..9c822971b 100644 --- a/internal/db/pull/pull.go +++ b/internal/db/pull/pull.go @@ -7,6 +7,7 @@ import ( "math" "os" "path/filepath" + "slices" "strconv" "strings" @@ -120,7 +121,7 @@ func diffRemoteSchema(ctx context.Context, schema []string, path string, config func diffUserSchemas(ctx context.Context, schema []string, path string, config pgconn.Config, fsys afero.Fs) error { var managed, user []string for _, s := range schema { - if utils.SliceContains(managedSchemas, s) { + if slices.Contains(managedSchemas, s) { managed = append(managed, s) } else { user = append(user, s) diff --git a/internal/start/start.go b/internal/start/start.go index 1176eaa56..47f8b5c37 100644 --- a/internal/start/start.go +++ b/internal/start/start.go @@ -10,6 +10,7 @@ import ( "os" "path" "path/filepath" + "slices" "strconv" "strings" "text/template" @@ -1152,7 +1153,7 @@ EOF } fmt.Fprintln(os.Stderr, "Waiting for health checks...") - if utils.NoBackupVolume && utils.SliceContains(started, utils.StorageId) { + if utils.NoBackupVolume && slices.Contains(started, utils.StorageId) { if err := start.WaitForHealthyService(ctx, serviceTimeout, utils.StorageId); err != nil { return err } diff --git a/internal/status/status.go b/internal/status/status.go index 4ed7afde2..ee087062b 100644 --- a/internal/status/status.go +++ b/internal/status/status.go @@ -11,6 +11,7 @@ import ( "net/url" "os" "reflect" + "slices" "strings" "sync" "time" @@ -48,11 +49,11 @@ func (c *CustomName) toValues(exclude ...string) map[string]string { c.DbURL: fmt.Sprintf("postgresql://%s@%s:%d/postgres", url.UserPassword("postgres", utils.Config.Db.Password), utils.Config.Hostname, utils.Config.Db.Port), } - apiEnabled := utils.Config.Api.Enabled && !utils.SliceContains(exclude, utils.RestId) && !utils.SliceContains(exclude, utils.ShortContainerImageName(utils.Config.Api.Image)) - studioEnabled := utils.Config.Studio.Enabled && !utils.SliceContains(exclude, utils.StudioId) && !utils.SliceContains(exclude, utils.ShortContainerImageName(utils.Config.Studio.Image)) - authEnabled := utils.Config.Auth.Enabled && !utils.SliceContains(exclude, utils.GotrueId) && !utils.SliceContains(exclude, utils.ShortContainerImageName(utils.Config.Auth.Image)) - inbucketEnabled := utils.Config.Inbucket.Enabled && !utils.SliceContains(exclude, utils.InbucketId) && !utils.SliceContains(exclude, utils.ShortContainerImageName(utils.Config.Inbucket.Image)) - storageEnabled := utils.Config.Storage.Enabled && !utils.SliceContains(exclude, utils.StorageId) && !utils.SliceContains(exclude, utils.ShortContainerImageName(utils.Config.Storage.Image)) + apiEnabled := utils.Config.Api.Enabled && !slices.Contains(exclude, utils.RestId) && !slices.Contains(exclude, utils.ShortContainerImageName(utils.Config.Api.Image)) + studioEnabled := utils.Config.Studio.Enabled && !slices.Contains(exclude, utils.StudioId) && !slices.Contains(exclude, utils.ShortContainerImageName(utils.Config.Studio.Image)) + authEnabled := utils.Config.Auth.Enabled && !slices.Contains(exclude, utils.GotrueId) && !slices.Contains(exclude, utils.ShortContainerImageName(utils.Config.Auth.Image)) + inbucketEnabled := utils.Config.Inbucket.Enabled && !slices.Contains(exclude, utils.InbucketId) && !slices.Contains(exclude, utils.ShortContainerImageName(utils.Config.Inbucket.Image)) + storageEnabled := utils.Config.Storage.Enabled && !slices.Contains(exclude, utils.StorageId) && !slices.Contains(exclude, utils.ShortContainerImageName(utils.Config.Storage.Image)) if apiEnabled { values[c.ApiURL] = utils.Config.Api.ExternalUrl diff --git a/internal/utils/enum.go b/internal/utils/enum.go index 6d800d6a0..06cac719d 100644 --- a/internal/utils/enum.go +++ b/internal/utils/enum.go @@ -2,6 +2,7 @@ package utils import ( "fmt" + "slices" "strings" "github.com/go-errors/errors" @@ -18,7 +19,7 @@ func (a EnumFlag) String() string { } func (a *EnumFlag) Set(p string) error { - if !SliceContains(a.Allowed, p) { + if !slices.Contains(a.Allowed, p) { return errors.Errorf("must be one of [ %s ]", strings.Join(a.Allowed, " | ")) } a.Value = p diff --git a/internal/utils/slice.go b/internal/utils/slice.go index 574f30cc0..9babf6c59 100644 --- a/internal/utils/slice.go +++ b/internal/utils/slice.go @@ -1,23 +1,5 @@ package utils -import "slices" - -func SliceContains[T comparable](s []T, e T) bool { - return slices.Contains(s, e) -} - -func SliceEqual[T comparable](a, b []T) bool { - if len(a) != len(b) { - return false - } - for i, v := range a { - if v != b[i] { - return false - } - } - return true -} - func RemoveDuplicates[T comparable](slice []T) (result []T) { set := make(map[T]struct{}) for _, item := range slice { diff --git a/internal/utils/slice_test.go b/internal/utils/slice_test.go index 47bdea171..3c2a3e957 100644 --- a/internal/utils/slice_test.go +++ b/internal/utils/slice_test.go @@ -6,41 +6,6 @@ import ( "github.com/stretchr/testify/assert" ) -func TestSliceEqual(t *testing.T) { - t.Run("different slices", func(t *testing.T) { - assert.False(t, SliceEqual([]string{"a"}, []string{"b"})) - }) - - t.Run("different lengths", func(t *testing.T) { - assert.False(t, SliceEqual([]string{"a"}, []string{"a", "b"})) - assert.False(t, SliceEqual([]string{"a", "b"}, []string{"a"})) - }) - - t.Run("equal slices", func(t *testing.T) { - assert.True(t, SliceEqual([]string{"a", "b"}, []string{"a", "b"})) - assert.True(t, SliceEqual([]int{1, 2, 3}, []int{1, 2, 3})) - }) - - t.Run("empty slices", func(t *testing.T) { - assert.True(t, SliceEqual([]string{}, []string{})) - }) -} - -func TestSliceContains(t *testing.T) { - t.Run("not contains element", func(t *testing.T) { - assert.False(t, SliceContains([]string{"a"}, "b")) - }) - - t.Run("contains element", func(t *testing.T) { - assert.True(t, SliceContains([]string{"a", "b", "c"}, "b")) - assert.True(t, SliceContains([]int{1, 2, 3}, 2)) - }) - - t.Run("empty slice", func(t *testing.T) { - assert.False(t, SliceContains([]string{}, "a")) - }) -} - func TestRemoveDuplicates(t *testing.T) { t.Run("string slice", func(t *testing.T) { input := []string{"a", "b", "a", "c", "b", "d"} diff --git a/pkg/config/auth.go b/pkg/config/auth.go index c8f017a5c..82fc0eef7 100644 --- a/pkg/config/auth.go +++ b/pkg/config/auth.go @@ -1,6 +1,7 @@ package config import ( + "slices" "strconv" "strings" "time" @@ -24,7 +25,7 @@ const ( func (r *PasswordRequirements) UnmarshalText(text []byte) error { allowed := []PasswordRequirements{NoRequirements, LettersDigits, LowerUpperLettersDigits, LowerUpperLettersDigitsSymbols} - if *r = PasswordRequirements(text); !sliceContains(allowed, *r) { + if *r = PasswordRequirements(text); !slices.Contains(allowed, *r) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -63,7 +64,7 @@ const ( func (p *CaptchaProvider) UnmarshalText(text []byte) error { allowed := []CaptchaProvider{HCaptchaProvider, TurnstileProvider} - if *p = CaptchaProvider(text); !sliceContains(allowed, *p) { + if *p = CaptchaProvider(text); !slices.Contains(allowed, *p) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -78,7 +79,7 @@ const ( func (p *Algorithm) UnmarshalText(text []byte) error { allowed := []Algorithm{AlgRS256, AlgES256} - if *p = Algorithm(text); !sliceContains(allowed, *p) { + if *p = Algorithm(text); !slices.Contains(allowed, *p) { return errors.Errorf("must be one of %v", allowed) } return nil diff --git a/pkg/config/config.go b/pkg/config/config.go index ea49a76ca..915327e41 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -17,6 +17,7 @@ import ( "path" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" @@ -58,7 +59,7 @@ const ( func (b *LogflareBackend) UnmarshalText(text []byte) error { allowed := []LogflareBackend{LogflarePostgres, LogflareBigQuery} - if *b = LogflareBackend(text); !sliceContains(allowed, *b) { + if *b = LogflareBackend(text); !slices.Contains(allowed, *b) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -73,7 +74,7 @@ const ( func (f *AddressFamily) UnmarshalText(text []byte) error { allowed := []AddressFamily{AddressIPv6, AddressIPv4} - if *f = AddressFamily(text); !sliceContains(allowed, *f) { + if *f = AddressFamily(text); !slices.Contains(allowed, *f) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -88,7 +89,7 @@ const ( func (p *RequestPolicy) UnmarshalText(text []byte) error { allowed := []RequestPolicy{PolicyPerWorker, PolicyOneshot} - if *p = RequestPolicy(text); !sliceContains(allowed, *p) { + if *p = RequestPolicy(text); !slices.Contains(allowed, *p) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -1133,7 +1134,7 @@ func (e external) validate() (err error) { if provider.ClientId == "" { return errors.Errorf("Missing required field in config: auth.external.%s.client_id", ext) } - if !sliceContains([]string{"apple", "google"}, ext) && len(provider.Secret.Value) == 0 { + if !slices.Contains([]string{"apple", "google"}, ext) && len(provider.Secret.Value) == 0 { return errors.Errorf("Missing required field in config: auth.external.%s.secret", ext) } if err := assertEnvLoaded(provider.ClientId); err != nil { diff --git a/pkg/config/db.go b/pkg/config/db.go index 740dabf53..b2b947667 100644 --- a/pkg/config/db.go +++ b/pkg/config/db.go @@ -2,6 +2,7 @@ package config import ( "bytes" + "slices" "github.com/go-errors/errors" v1API "github.com/supabase/cli/pkg/api" @@ -18,7 +19,7 @@ const ( func (m *PoolMode) UnmarshalText(text []byte) error { allowed := []PoolMode{TransactionMode, SessionMode} - if *m = PoolMode(text); !sliceContains(allowed, *m) { + if *m = PoolMode(text); !slices.Contains(allowed, *m) { return errors.Errorf("must be one of %v", allowed) } return nil @@ -34,7 +35,7 @@ const ( func (r *SessionReplicationRole) UnmarshalText(text []byte) error { allowed := []SessionReplicationRole{SessionReplicationRoleOrigin, SessionReplicationRoleReplica, SessionReplicationRoleLocal} - if *r = SessionReplicationRole(text); !sliceContains(allowed, *r) { + if *r = SessionReplicationRole(text); !slices.Contains(allowed, *r) { return errors.Errorf("must be one of %v", allowed) } return nil diff --git a/pkg/config/utils.go b/pkg/config/utils.go index e4a77aef4..b8ddeeb4d 100644 --- a/pkg/config/utils.go +++ b/pkg/config/utils.go @@ -72,15 +72,6 @@ func NewPathBuilder(configPath string) pathBuilder { } } -func sliceContains[T comparable](s []T, e T) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - func replaceImageTag(image string, tag string) string { index := strings.IndexByte(image, ':') return image[:index+1] + strings.TrimSpace(tag)