diff --git a/internal/bootstrap/bootstrap.go b/internal/bootstrap/bootstrap.go index 8a07e2530..5bbaec0a1 100644 --- a/internal/bootstrap/bootstrap.go +++ b/internal/bootstrap/bootstrap.go @@ -100,7 +100,7 @@ func Run(ctx context.Context, starter StarterTemplate, fsys afero.Fs, options .. return err } link.LinkServices(ctx, flags.ProjectRef, tenant.NewApiKey(keys).Anon, false, fsys) - if err := utils.WriteFile(utils.ProjectRefPath, []byte(flags.ProjectRef), fsys); err != nil { + if err := utils.WriteFile(utils.Paths.ProjectRefPath, []byte(flags.ProjectRef), fsys); err != nil { return err } // 5. Wait for project healthy diff --git a/internal/branches/create/create_test.go b/internal/branches/create/create_test.go index 60dbfc527..7f934d5e2 100644 --- a/internal/branches/create/create_test.go +++ b/internal/branches/create/create_test.go @@ -47,7 +47,7 @@ func TestCreateCommand(t *testing.T) { t.Run("throws error on network disconnected", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(flags.ProjectRef), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(flags.ProjectRef), 0644)) // Setup mock api defer gock.OffAll() gock.New(utils.DefaultApiHost). @@ -64,7 +64,7 @@ func TestCreateCommand(t *testing.T) { t.Run("throws error on service unavailable", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(flags.ProjectRef), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(flags.ProjectRef), 0644)) // Setup mock api defer gock.OffAll() gock.New(utils.DefaultApiHost). diff --git a/internal/config/push/push_test.go b/internal/config/push/push_test.go index 5af8fb273..9043f3f57 100644 --- a/internal/config/push/push_test.go +++ b/internal/config/push/push_test.go @@ -23,7 +23,7 @@ func TestPushConfig(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, utils.WriteFile(utils.ConfigPath, []byte("malformed"), fsys)) + require.NoError(t, utils.WriteFile(utils.Paths.ConfigPath, []byte("malformed"), fsys)) // Run test err := Run(context.Background(), "", fsys) // Check error diff --git a/internal/db/branch/create/create.go b/internal/db/branch/create/create.go index 550128376..dbb9c6806 100644 --- a/internal/db/branch/create/create.go +++ b/internal/db/branch/create/create.go @@ -30,7 +30,7 @@ func Run(branch string, fsys afero.Fs) error { return err } - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) if err := assertNewBranchIsValid(branchPath, fsys); err != nil { return nil } diff --git a/internal/db/branch/delete/delete.go b/internal/db/branch/delete/delete.go index ea14cd34d..c033bcd6c 100644 --- a/internal/db/branch/delete/delete.go +++ b/internal/db/branch/delete/delete.go @@ -46,7 +46,7 @@ func deleteBranchDir(branch string, fsys afero.Fs) error { return errors.New("Cannot delete branch " + utils.Aqua(branch) + ": branch name is reserved.") } - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) if _, err := afero.ReadDir(fsys, branchPath); err != nil { return errors.New("Branch " + utils.Aqua(branch) + " does not exist.") } diff --git a/internal/db/branch/delete/delete_test.go b/internal/db/branch/delete/delete_test.go index 76957e246..6d03e14fd 100644 --- a/internal/db/branch/delete/delete_test.go +++ b/internal/db/branch/delete/delete_test.go @@ -17,7 +17,7 @@ func TestBranchDir(t *testing.T) { t.Run("removes a branch directory", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(filepath.Dir(utils.CurrBranchPath), "test-branch") + path := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), "test-branch") require.NoError(t, fsys.Mkdir(path, 0755)) // Run test assert.NoError(t, deleteBranchDir("test-branch", fsys)) @@ -30,7 +30,7 @@ func TestBranchDir(t *testing.T) { t.Run("branch is current", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.CurrBranchPath, []byte("main"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.CurrBranchPath, []byte("main"), 0644)) // Run test assert.Error(t, deleteBranchDir("main", fsys)) }) @@ -46,7 +46,7 @@ func TestBranchDir(t *testing.T) { t.Run("branch permission denied", func(t *testing.T) { // Setup read-only fs fsys := afero.NewMemMapFs() - path := filepath.Join(filepath.Dir(utils.CurrBranchPath), "test-branch") + path := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), "test-branch") require.NoError(t, fsys.Mkdir(path, 0755)) // Run test assert.Error(t, deleteBranchDir("test-branch", afero.NewReadOnlyFs(fsys))) diff --git a/internal/db/branch/list/list.go b/internal/db/branch/list/list.go index b1037ac1b..66b6f0969 100644 --- a/internal/db/branch/list/list.go +++ b/internal/db/branch/list/list.go @@ -12,7 +12,7 @@ import ( ) func Run(fsys afero.Fs, out io.Writer) error { - branches, err := afero.ReadDir(fsys, filepath.Dir(utils.CurrBranchPath)) + branches, err := afero.ReadDir(fsys, filepath.Dir(utils.Paths.CurrBranchPath)) if errors.Is(err, os.ErrNotExist) { return nil } else if err != nil { @@ -21,7 +21,7 @@ func Run(fsys afero.Fs, out io.Writer) error { currBranch, _ := utils.GetCurrentBranchFS(fsys) for _, branch := range branches { - if branch.Name() == filepath.Base(utils.CurrBranchPath) { + if branch.Name() == filepath.Base(utils.Paths.CurrBranchPath) { continue } diff --git a/internal/db/branch/list/list_test.go b/internal/db/branch/list/list_test.go index 24e34d5e5..303076f44 100644 --- a/internal/db/branch/list/list_test.go +++ b/internal/db/branch/list/list_test.go @@ -17,8 +17,8 @@ func TestListCommand(t *testing.T) { t.Run("lists all branches", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.CurrBranchPath, []byte("main"), 0644)) - base := filepath.Dir(utils.CurrBranchPath) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.CurrBranchPath, []byte("main"), 0644)) + base := filepath.Dir(utils.Paths.CurrBranchPath) require.NoError(t, fsys.Mkdir(filepath.Join(base, "main"), 0755)) require.NoError(t, fsys.Mkdir(filepath.Join(base, "test"), 0755)) // Run test @@ -36,7 +36,7 @@ func TestListCommand(t *testing.T) { t.Run("lists without current branch", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - base := filepath.Dir(utils.CurrBranchPath) + base := filepath.Dir(utils.Paths.CurrBranchPath) require.NoError(t, fsys.Mkdir(filepath.Join(base, "main"), 0755)) require.NoError(t, fsys.Mkdir(filepath.Join(base, "test"), 0755)) // Run test @@ -58,7 +58,7 @@ func TestListCommand(t *testing.T) { t.Run("throws error on unreadable directory", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - _, err := fsys.Create(filepath.Dir(utils.CurrBranchPath)) + _, err := fsys.Create(filepath.Dir(utils.Paths.CurrBranchPath)) require.NoError(t, err) // Run test require.Error(t, Run(fsys, io.Discard)) diff --git a/internal/db/branch/switch_/switch_.go b/internal/db/branch/switch_/switch_.go index d11803e88..0925e64a7 100644 --- a/internal/db/branch/switch_/switch_.go +++ b/internal/db/branch/switch_/switch_.go @@ -27,7 +27,7 @@ func Run(ctx context.Context, target string, fsys afero.Fs, options ...func(*pgx if target != "main" && utils.IsBranchNameReserved(target) { return errors.New("Cannot switch branch " + utils.Aqua(target) + ": branch name is reserved.") } - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), target) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), target) if _, err := fsys.Stat(branchPath); errors.Is(err, os.ErrNotExist) { return errors.New("Branch " + utils.Aqua(target) + " does not exist.") } else if err != nil { @@ -52,8 +52,8 @@ func Run(ctx context.Context, target string, fsys afero.Fs, options ...func(*pgx } // 4. Update current branch - if err := afero.WriteFile(fsys, utils.CurrBranchPath, []byte(target), 0644); err != nil { - return errors.New("Unable to update local branch file. Fix by running: echo '" + target + "' > " + utils.CurrBranchPath) + if err := afero.WriteFile(fsys, utils.Paths.CurrBranchPath, []byte(target), 0644); err != nil { + return errors.New("Unable to update local branch file. Fix by running: echo '" + target + "' > " + utils.Paths.CurrBranchPath) } return nil } diff --git a/internal/db/branch/switch_/switch__test.go b/internal/db/branch/switch_/switch__test.go index f0e51d521..0955f99b2 100644 --- a/internal/db/branch/switch_/switch__test.go +++ b/internal/db/branch/switch_/switch__test.go @@ -25,9 +25,9 @@ func TestSwitchCommand(t *testing.T) { require.NoError(t, utils.WriteConfig(fsys, false)) // Setup target branch branch := "target" - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) require.NoError(t, fsys.Mkdir(branchPath, 0755)) - require.NoError(t, afero.WriteFile(fsys, utils.CurrBranchPath, []byte("main"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.CurrBranchPath, []byte("main"), 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) defer gock.OffAll() @@ -57,7 +57,7 @@ func TestSwitchCommand(t *testing.T) { assert.NoError(t, Run(context.Background(), branch, fsys, conn.Intercept)) // Validate output assert.Empty(t, apitest.ListUnmatchedRequests()) - contents, err := afero.ReadFile(fsys, utils.CurrBranchPath) + contents, err := afero.ReadFile(fsys, utils.Paths.CurrBranchPath) assert.NoError(t, err) assert.Equal(t, []byte(branch), contents) }) @@ -65,7 +65,7 @@ func TestSwitchCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), "target", fsys) // Check error @@ -138,13 +138,13 @@ func TestSwitchCommand(t *testing.T) { JSON(container.InspectResponse{}) // Setup target branch branch := "main" - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) require.NoError(t, fsys.Mkdir(branchPath, 0755)) // Run test assert.NoError(t, Run(context.Background(), branch, fsys)) // Check error assert.Empty(t, apitest.ListUnmatchedRequests()) - contents, err := afero.ReadFile(fsys, utils.CurrBranchPath) + contents, err := afero.ReadFile(fsys, utils.Paths.CurrBranchPath) assert.NoError(t, err) assert.Equal(t, []byte(branch), contents) }) @@ -162,7 +162,7 @@ func TestSwitchCommand(t *testing.T) { JSON(container.InspectResponse{}) // Setup target branch branch := "target" - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) require.NoError(t, fsys.Mkdir(branchPath, 0755)) // Setup mock postgres conn := pgtest.NewConn() @@ -186,7 +186,7 @@ func TestSwitchCommand(t *testing.T) { JSON(container.InspectResponse{}) // Setup target branch branch := "main" - branchPath := filepath.Join(filepath.Dir(utils.CurrBranchPath), branch) + branchPath := filepath.Join(filepath.Dir(utils.Paths.CurrBranchPath), branch) require.NoError(t, fsys.Mkdir(branchPath, 0755)) // Run test err := Run(context.Background(), branch, afero.NewReadOnlyFs(fsys)) diff --git a/internal/db/diff/diff.go b/internal/db/diff/diff.go index 18d342094..42095a866 100644 --- a/internal/db/diff/diff.go +++ b/internal/db/diff/diff.go @@ -52,13 +52,13 @@ func loadDeclaredSchemas(fsys afero.Fs) ([]string, error) { if schemas := utils.Config.Db.Migrations.SchemaPaths; len(schemas) > 0 { return schemas.Files(afero.NewIOFS(fsys)) } - if exists, err := afero.DirExists(fsys, utils.SchemasDir); err != nil { + if exists, err := afero.DirExists(fsys, utils.Paths.SchemasDir); err != nil { return nil, errors.Errorf("failed to check schemas: %w", err) } else if !exists { return nil, nil } var declared []string - if err := afero.Walk(fsys, utils.SchemasDir, func(path string, info fs.FileInfo, err error) error { + if err := afero.Walk(fsys, utils.Paths.SchemasDir, func(path string, info fs.FileInfo, err error) error { if err != nil { return err } @@ -118,7 +118,7 @@ func ConnectShadowDatabase(ctx context.Context, timeout time.Duration, options . const CREATE_TEMPLATE = "CREATE DATABASE contrib_regression TEMPLATE postgres" func MigrateShadowDatabase(ctx context.Context, container string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error { - migrations, err := migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys)) + migrations, err := migration.ListLocalMigrations(utils.Paths.MigrationsDir, afero.NewIOFS(fsys)) if err != nil { return err } diff --git a/internal/db/diff/diff_test.go b/internal/db/diff/diff_test.go index 84e6c9acb..9edb4bdf5 100644 --- a/internal/db/diff/diff_test.go +++ b/internal/db/diff/diff_test.go @@ -87,10 +87,10 @@ func TestRun(t *testing.T) { assert.NoError(t, err) assert.Empty(t, apitest.ListUnmatchedRequests()) // Check diff file - files, err := afero.ReadDir(fsys, utils.MigrationsDir) + files, err := afero.ReadDir(fsys, utils.Paths.MigrationsDir) assert.NoError(t, err) assert.Equal(t, 1, len(files)) - diffPath := filepath.Join(utils.MigrationsDir, files[0].Name()) + diffPath := filepath.Join(utils.Paths.MigrationsDir, files[0].Name()) contents, err := afero.ReadFile(fsys, diffPath) assert.NoError(t, err) assert.Equal(t, []byte(diff), contents) @@ -122,7 +122,7 @@ func TestMigrateShadow(t *testing.T) { utils.InitialSchemaPg14Sql = "create schema private" // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) // Setup mock postgres @@ -162,7 +162,7 @@ func TestMigrateShadow(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Run test err := MigrateShadowDatabase(context.Background(), "", fsys) // Check error @@ -278,7 +278,7 @@ create schema public`) t.Run("throws error on failure to diff target", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) // Setup mock docker @@ -346,10 +346,10 @@ func TestDropStatements(t *testing.T) { func TestLoadSchemas(t *testing.T) { expected := []string{ - filepath.Join(utils.SchemasDir, "comment", "model.sql"), - filepath.Join(utils.SchemasDir, "model.sql"), - filepath.Join(utils.SchemasDir, "reaction", "dislike", "model.sql"), - filepath.Join(utils.SchemasDir, "reaction", "like", "model.sql"), + filepath.Join(utils.Paths.SchemasDir, "comment", "model.sql"), + filepath.Join(utils.Paths.SchemasDir, "model.sql"), + filepath.Join(utils.Paths.SchemasDir, "reaction", "dislike", "model.sql"), + filepath.Join(utils.Paths.SchemasDir, "reaction", "like", "model.sql"), } fsys := afero.NewMemMapFs() for _, fp := range expected { diff --git a/internal/db/pull/pull.go b/internal/db/pull/pull.go index efc93ca90..74ec04793 100644 --- a/internal/db/pull/pull.go +++ b/internal/db/pull/pull.go @@ -29,7 +29,7 @@ import ( var ( errMissing = errors.New("No migrations found") errInSync = errors.New("No schema changes found") - errConflict = errors.Errorf("The remote database's migration history does not match local files in %s directory.", utils.MigrationsDir) + errConflict = errors.Errorf("The remote database's migration history does not match local files in %s directory.", utils.Paths.MigrationsDir) ) func Run(ctx context.Context, schema []string, config pgconn.Config, name string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error { diff --git a/internal/db/pull/pull_test.go b/internal/db/pull/pull_test.go index 49fecb19f..38b955f78 100644 --- a/internal/db/pull/pull_test.go +++ b/internal/db/pull/pull_test.go @@ -86,7 +86,7 @@ func TestPullSchema(t *testing.T) { t.Run("throws error on diff failure", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) @@ -110,7 +110,7 @@ func TestPullSchema(t *testing.T) { func TestSyncRemote(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Setup mock postgres conn := pgtest.NewConn() defer conn.Close(t) @@ -126,7 +126,7 @@ func TestSyncRemote(t *testing.T) { t.Run("throws error on mismatched length", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -143,7 +143,7 @@ func TestSyncRemote(t *testing.T) { t.Run("throws error on mismatched migration", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() diff --git a/internal/db/push/push.go b/internal/db/push/push.go index 6960702d1..f6e8412ce 100644 --- a/internal/db/push/push.go +++ b/internal/db/push/push.go @@ -43,10 +43,10 @@ func Run(ctx context.Context, dryRun, ignoreVersionMismatch bool, includeRoles, } var globals []string if includeRoles { - if exists, err := afero.Exists(fsys, utils.CustomRolesPath); err != nil { + if exists, err := afero.Exists(fsys, utils.Paths.CustomRolesPath); err != nil { return errors.Errorf("failed to find custom roles: %w", err) } else if exists { - globals = append(globals, utils.CustomRolesPath) + globals = append(globals, utils.Paths.CustomRolesPath) } } if len(pending) == 0 && len(seeds) == 0 && len(globals) == 0 { diff --git a/internal/db/push/push_test.go b/internal/db/push/push_test.go index b5d0d2c7f..49745b3bd 100644 --- a/internal/db/push/push_test.go +++ b/internal/db/push/push_test.go @@ -32,7 +32,7 @@ func TestMigrationPush(t *testing.T) { t.Run("dry run", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -91,7 +91,7 @@ func TestMigrationPush(t *testing.T) { t.Run("throws error on push failure", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -115,7 +115,7 @@ func TestPushAll(t *testing.T) { t.Run("ignores missing roles and seed", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -137,7 +137,7 @@ func TestPushAll(t *testing.T) { t.Cleanup(fstest.MockStdin(t, "n")) // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -152,8 +152,8 @@ func TestPushAll(t *testing.T) { t.Run("throws error on roles failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.StatErrorFs{DenyPath: utils.CustomRolesPath} - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + fsys := &fstest.StatErrorFs{DenyPath: utils.Paths.CustomRolesPath} + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -168,12 +168,12 @@ func TestPushAll(t *testing.T) { t.Run("throws error on seed failure", func(t *testing.T) { digest := hex.EncodeToString(sha256.New().Sum(nil)) - seedPath := filepath.Join(utils.SupabaseDirPath, "seed.sql") + seedPath := filepath.Join(utils.Paths.SupabaseDirPath, "seed.sql") utils.Config.Db.Seed.SqlPaths = []string{seedPath} // Setup in-memory fs fsys := afero.NewMemMapFs() require.NoError(t, afero.WriteFile(fsys, seedPath, []byte{}, 0644)) - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Setup mock postgres conn := pgtest.NewConn() diff --git a/internal/db/start/start.go b/internal/db/start/start.go index 3edf86c59..97e27a75b 100644 --- a/internal/db/start/start.go +++ b/internal/db/start/start.go @@ -231,12 +231,12 @@ func IsUnhealthyError(err error) bool { func initCurrentBranch(fsys afero.Fs) error { // Create _current_branch file to avoid breaking db branch commands - if _, err := fsys.Stat(utils.CurrBranchPath); err == nil { + if _, err := fsys.Stat(utils.Paths.CurrBranchPath); err == nil { return nil } else if !errors.Is(err, os.ErrNotExist) { return errors.Errorf("failed init current branch: %w", err) } - return utils.WriteFile(utils.CurrBranchPath, []byte("main"), fsys) + return utils.WriteFile(utils.Paths.CurrBranchPath, []byte("main"), fsys) } func initSchema(ctx context.Context, conn *pgx.Conn, host string, w io.Writer) error { @@ -375,7 +375,7 @@ func SetupDatabase(ctx context.Context, conn *pgx.Conn, host string, w io.Writer if err := vault.UpsertVaultSecrets(ctx, utils.Config.Db.Vault, conn); err != nil { return err } - err := migration.SeedGlobals(ctx, []string{utils.CustomRolesPath}, conn, afero.NewIOFS(fsys)) + err := migration.SeedGlobals(ctx, []string{utils.Paths.CustomRolesPath}, conn, afero.NewIOFS(fsys)) if errors.Is(err, os.ErrNotExist) { return nil } diff --git a/internal/db/start/start_test.go b/internal/db/start/start_test.go index 39f23d8ba..7f028f938 100644 --- a/internal/db/start/start_test.go +++ b/internal/db/start/start_test.go @@ -34,7 +34,7 @@ func TestInitBranch(t *testing.T) { t.Run("throws error on stat failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.StatErrorFs{DenyPath: utils.CurrBranchPath} + fsys := &fstest.StatErrorFs{DenyPath: utils.Paths.CurrBranchPath} // Run test err := initCurrentBranch(fsys) // Check error @@ -43,7 +43,7 @@ func TestInitBranch(t *testing.T) { t.Run("throws error on write failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.CurrBranchPath} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.CurrBranchPath} // Run test err := initCurrentBranch(fsys) // Check error @@ -59,7 +59,7 @@ func TestStartDatabase(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() roles := "create role test" - require.NoError(t, afero.WriteFile(fsys, utils.CustomRolesPath, []byte(roles), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.CustomRolesPath, []byte(roles), 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) defer gock.OffAll() @@ -94,7 +94,7 @@ func TestStartDatabase(t *testing.T) { assert.NoError(t, err) assert.Empty(t, apitest.ListUnmatchedRequests()) // Check current branch - contents, err := afero.ReadFile(fsys, utils.CurrBranchPath) + contents, err := afero.ReadFile(fsys, utils.Paths.CurrBranchPath) assert.NoError(t, err) assert.Equal(t, []byte("main"), contents) }) @@ -128,7 +128,7 @@ func TestStartDatabase(t *testing.T) { assert.NoError(t, err) assert.Empty(t, apitest.ListUnmatchedRequests()) // Check current branch - contents, err := afero.ReadFile(fsys, utils.CurrBranchPath) + contents, err := afero.ReadFile(fsys, utils.Paths.CurrBranchPath) assert.NoError(t, err) assert.Equal(t, []byte("main"), contents) }) @@ -159,7 +159,7 @@ func TestStartCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), "", fsys) // Check error @@ -242,7 +242,7 @@ func TestSetupDatabase(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() roles := "create role postgres" - require.NoError(t, afero.WriteFile(fsys, utils.CustomRolesPath, []byte(roles), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.CustomRolesPath, []byte(roles), 0644)) // Setup mock postgres conn := pgtest.NewConn() defer conn.Close(t) @@ -289,7 +289,7 @@ func TestSetupDatabase(t *testing.T) { t.Run("throws error on read failure", func(t *testing.T) { utils.Config.Db.Port = 5432 // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.CustomRolesPath} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.CustomRolesPath} // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) defer gock.OffAll() diff --git a/internal/db/test/test.go b/internal/db/test/test.go index dadb44736..78ea2b34e 100644 --- a/internal/db/test/test.go +++ b/internal/db/test/test.go @@ -27,7 +27,7 @@ const ( func Run(ctx context.Context, testFiles []string, config pgconn.Config, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error { // Build test command if len(testFiles) == 0 { - absTestsDir, err := filepath.Abs(utils.DbTestsDir) + absTestsDir, err := filepath.Abs(utils.Paths.DbTestsDir) if err != nil { return errors.Errorf("failed to resolve tests dir: %w", err) } diff --git a/internal/functions/deploy/bundle.go b/internal/functions/deploy/bundle.go index ae807aa01..5cf45e309 100644 --- a/internal/functions/deploy/bundle.go +++ b/internal/functions/deploy/bundle.go @@ -33,7 +33,7 @@ func (b *dockerBundler) Bundle(ctx context.Context, slug, entrypoint, importMap return meta, errors.Errorf("failed to get working directory: %w", err) } // BitBucket pipelines require docker bind mounts to be world writable - hostOutputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", slug)) + hostOutputDir := filepath.Join(utils.Paths.TempDir, fmt.Sprintf(".output_%s", slug)) if err := b.fsys.MkdirAll(hostOutputDir, 0777); err != nil { return meta, errors.Errorf("failed to mkdir: %w", err) } @@ -43,7 +43,7 @@ func (b *dockerBundler) Bundle(ctx context.Context, slug, entrypoint, importMap } }() // Create bind mounts - binds, err := GetBindMounts(cwd, utils.FunctionsDir, hostOutputDir, entrypoint, importMap, b.fsys) + binds, err := GetBindMounts(cwd, utils.Paths.FunctionsDir, hostOutputDir, entrypoint, importMap, b.fsys) if err != nil { return meta, err } diff --git a/internal/functions/deploy/deploy.go b/internal/functions/deploy/deploy.go index bcee53c55..73b2535ef 100644 --- a/internal/functions/deploy/deploy.go +++ b/internal/functions/deploy/deploy.go @@ -32,7 +32,7 @@ func Run(ctx context.Context, slugs []string, useDocker bool, noVerifyJWT *bool, } // TODO: require all functions to be deployed from config for v2 if len(slugs) == 0 { - return errors.Errorf("No Functions specified or found in %s", utils.Bold(utils.FunctionsDir)) + return errors.Errorf("No Functions specified or found in %s", utils.Bold(utils.Paths.FunctionsDir)) } // Flag import map is specified relative to current directory instead of workdir cwd, err := os.Getwd() @@ -77,7 +77,7 @@ func Run(ctx context.Context, slugs []string, useDocker bool, noVerifyJWT *bool, } func GetFunctionSlugs(fsys afero.Fs) (slugs []string, err error) { - pattern := filepath.Join(utils.FunctionsDir, "*", "index.ts") + pattern := filepath.Join(utils.Paths.FunctionsDir, "*", "index.ts") paths, err := afero.Glob(fsys, pattern) if err != nil { return nil, errors.Errorf("failed to glob function slugs: %w", err) @@ -101,7 +101,7 @@ func GetFunctionConfig(slugs []string, importMapPath string, noVerifyJWT *bool, fallbackExists := true functionsUsingDeprecatedGlobalFallback := []string{} functionsUsingDeprecatedImportMap := []string{} - if _, err := fsys.Stat(utils.FallbackImportMapPath); errors.Is(err, os.ErrNotExist) { + if _, err := fsys.Stat(utils.Paths.FallbackImportMapPath); errors.Is(err, os.ErrNotExist) { fallbackExists = false } else if err != nil { return nil, errors.Errorf("failed to fallback import map: %w", err) @@ -114,7 +114,7 @@ func GetFunctionConfig(slugs []string, importMapPath string, noVerifyJWT *bool, function.VerifyJWT = true } // Precedence order: flag > config > fallback - functionDir := filepath.Join(utils.FunctionsDir, name) + functionDir := filepath.Join(utils.Paths.FunctionsDir, name) if len(function.Entrypoint) == 0 { function.Entrypoint = filepath.Join(functionDir, "index.ts") } @@ -132,7 +132,7 @@ func GetFunctionConfig(slugs []string, importMapPath string, noVerifyJWT *bool, function.ImportMap = importMapPath functionsUsingDeprecatedImportMap = append(functionsUsingDeprecatedImportMap, name) } else if fallbackExists { - function.ImportMap = utils.FallbackImportMapPath + function.ImportMap = utils.Paths.FallbackImportMapPath functionsUsingDeprecatedGlobalFallback = append(functionsUsingDeprecatedGlobalFallback, name) } } diff --git a/internal/functions/deploy/deploy_test.go b/internal/functions/deploy/deploy_test.go index e746da927..9c45f9914 100644 --- a/internal/functions/deploy/deploy_test.go +++ b/internal/functions/deploy/deploy_test.go @@ -70,7 +70,7 @@ func TestDeployCommand(t *testing.T) { JSON(api.BulkUpdateFunctionResponse{}) // Setup output file for _, v := range functions { - outputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", v)) + outputDir := filepath.Join(utils.Paths.TempDir, fmt.Sprintf(".output_%s", v)) require.NoError(t, afero.WriteFile(fsys, filepath.Join(outputDir, "output.eszip"), []byte(""), 0644)) } // Run test @@ -86,7 +86,7 @@ func TestDeployCommand(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() require.NoError(t, utils.WriteConfig(fsys, false)) - f, err := fsys.OpenFile(utils.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) require.NoError(t, err) _, err = f.WriteString(` [functions.` + slug + `] @@ -94,12 +94,12 @@ import_map = "./import_map.json" `) require.NoError(t, err) require.NoError(t, f.Close()) - importMapPath := filepath.Join(utils.SupabaseDirPath, "import_map.json") + importMapPath := filepath.Join(utils.Paths.SupabaseDirPath, "import_map.json") require.NoError(t, afero.WriteFile(fsys, importMapPath, []byte("{}"), 0644)) // Setup function entrypoint - entrypointPath := filepath.Join(utils.FunctionsDir, slug, "index.ts") + entrypointPath := filepath.Join(utils.Paths.FunctionsDir, slug, "index.ts") require.NoError(t, afero.WriteFile(fsys, entrypointPath, []byte{}, 0644)) - ignorePath := filepath.Join(utils.FunctionsDir, "_ignore", "index.ts") + ignorePath := filepath.Join(utils.Paths.FunctionsDir, "_ignore", "index.ts") require.NoError(t, afero.WriteFile(fsys, ignorePath, []byte{}, 0644)) // Setup valid access token token := apitest.RandomAccessToken(t) @@ -127,7 +127,7 @@ import_map = "./import_map.json" apitest.MockDockerStart(utils.Docker, imageUrl, containerId) require.NoError(t, apitest.MockDockerLogs(utils.Docker, containerId, "bundled")) // Setup output file - outputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", slug)) + outputDir := filepath.Join(utils.Paths.TempDir, fmt.Sprintf(".output_%s", slug)) require.NoError(t, afero.WriteFile(fsys, filepath.Join(outputDir, "output.eszip"), []byte(""), 0644)) // Run test err = Run(context.Background(), nil, true, nil, "", 1, false, fsys) @@ -141,7 +141,7 @@ import_map = "./import_map.json" // Setup in-memory fs fsys := afero.NewMemMapFs() require.NoError(t, utils.WriteConfig(fsys, false)) - f, err := fsys.OpenFile(utils.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) require.NoError(t, err) _, err = f.WriteString(` [functions.disabled-func] @@ -150,12 +150,12 @@ import_map = "./import_map.json" `) require.NoError(t, err) require.NoError(t, f.Close()) - importMapPath, err := filepath.Abs(filepath.Join(utils.SupabaseDirPath, "import_map.json")) + importMapPath, err := filepath.Abs(filepath.Join(utils.Paths.SupabaseDirPath, "import_map.json")) require.NoError(t, err) require.NoError(t, afero.WriteFile(fsys, importMapPath, []byte("{}"), 0644)) // Setup function entrypoints - require.NoError(t, afero.WriteFile(fsys, filepath.Join(utils.FunctionsDir, "enabled-func", "index.ts"), []byte{}, 0644)) - require.NoError(t, afero.WriteFile(fsys, filepath.Join(utils.FunctionsDir, "disabled-func", "index.ts"), []byte{}, 0644)) + require.NoError(t, afero.WriteFile(fsys, filepath.Join(utils.Paths.FunctionsDir, "enabled-func", "index.ts"), []byte{}, 0644)) + require.NoError(t, afero.WriteFile(fsys, filepath.Join(utils.Paths.FunctionsDir, "disabled-func", "index.ts"), []byte{}, 0644)) // Setup valid access token token := apitest.RandomAccessToken(t) t.Setenv("SUPABASE_ACCESS_TOKEN", string(token)) @@ -180,7 +180,7 @@ import_map = "./import_map.json" apitest.MockDockerStart(utils.Docker, imageUrl, containerId) require.NoError(t, apitest.MockDockerLogs(utils.Docker, containerId, "bundled")) // Setup output file - outputDir := filepath.Join(utils.TempDir, ".output_enabled-func") + outputDir := filepath.Join(utils.Paths.TempDir, ".output_enabled-func") require.NoError(t, afero.WriteFile(fsys, filepath.Join(outputDir, "output.eszip"), []byte(""), 0644)) // Run test err = Run(context.Background(), nil, true, nil, "", 1, false, fsys) @@ -214,7 +214,7 @@ import_map = "./import_map.json" // Setup in-memory fs fsys := afero.NewMemMapFs() require.NoError(t, utils.WriteConfig(fsys, false)) - f, err := fsys.OpenFile(utils.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) require.NoError(t, err) _, err = f.WriteString(` [functions.` + slug + `] @@ -247,7 +247,7 @@ verify_jwt = false apitest.MockDockerStart(utils.Docker, imageUrl, containerId) require.NoError(t, apitest.MockDockerLogs(utils.Docker, containerId, "bundled")) // Setup output file - outputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", slug)) + outputDir := filepath.Join(utils.Paths.TempDir, fmt.Sprintf(".output_%s", slug)) require.NoError(t, afero.WriteFile(fsys, filepath.Join(outputDir, "output.eszip"), []byte(""), 0644)) // Run test assert.NoError(t, Run(context.Background(), []string{slug}, true, nil, "", 1, false, fsys)) @@ -260,7 +260,7 @@ verify_jwt = false // Setup in-memory fs fsys := afero.NewMemMapFs() require.NoError(t, utils.WriteConfig(fsys, false)) - f, err := fsys.OpenFile(utils.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_APPEND|os.O_WRONLY, 0600) require.NoError(t, err) _, err = f.WriteString(` [functions.` + slug + `] @@ -293,7 +293,7 @@ verify_jwt = false apitest.MockDockerStart(utils.Docker, imageUrl, containerId) require.NoError(t, apitest.MockDockerLogs(utils.Docker, containerId, "bundled")) // Setup output file - outputDir := filepath.Join(utils.TempDir, fmt.Sprintf(".output_%s", slug)) + outputDir := filepath.Join(utils.Paths.TempDir, fmt.Sprintf(".output_%s", slug)) require.NoError(t, afero.WriteFile(fsys, filepath.Join(outputDir, "output.eszip"), []byte(""), 0644)) // Run test noVerifyJWT := false @@ -307,12 +307,12 @@ func TestImportMapPath(t *testing.T) { t.Run("loads import map from default location", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.FallbackImportMapPath, []byte("{}"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackImportMapPath, []byte("{}"), 0644)) // Run test fc, err := GetFunctionConfig([]string{"test"}, "", nil, fsys) // Check error assert.NoError(t, err) - assert.Equal(t, utils.FallbackImportMapPath, fc["test"].ImportMap) + assert.Equal(t, utils.Paths.FallbackImportMapPath, fc["test"].ImportMap) }) t.Run("per function config takes precedence", func(t *testing.T) { @@ -323,7 +323,7 @@ func TestImportMapPath(t *testing.T) { } // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.FallbackImportMapPath, []byte("{}"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackImportMapPath, []byte("{}"), 0644)) // Run test fc, err := GetFunctionConfig([]string{slug}, "", nil, fsys) // Check error @@ -340,10 +340,10 @@ func TestImportMapPath(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() // Custom global import map loaded via cli flag - customImportMapPath := filepath.Join(utils.FunctionsDir, "custom_import_map.json") + customImportMapPath := filepath.Join(utils.Paths.FunctionsDir, "custom_import_map.json") require.NoError(t, afero.WriteFile(fsys, customImportMapPath, []byte("{}"), 0644)) // Create fallback import map to test precedence order - require.NoError(t, afero.WriteFile(fsys, utils.FallbackImportMapPath, []byte("{}"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackImportMapPath, []byte("{}"), 0644)) // Run test fc, err := GetFunctionConfig([]string{slug}, customImportMapPath, cast.Ptr(false), fsys) // Check error @@ -365,7 +365,7 @@ func TestImportMapPath(t *testing.T) { path := "/tmp/import_map.json" // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.FallbackImportMapPath, []byte("{}"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackImportMapPath, []byte("{}"), 0644)) // Run test fc, err := GetFunctionConfig([]string{"test"}, path, nil, fsys) // Check error diff --git a/internal/functions/download/download.go b/internal/functions/download/download.go index cbfac7b51..1c8d406d9 100644 --- a/internal/functions/download/download.go +++ b/internal/functions/download/download.go @@ -105,7 +105,7 @@ func downloadFunction(ctx context.Context, projectRef, slug, extractScriptPath s } resBuf := bytes.NewReader(resp.Body) - funcDir := filepath.Join(utils.FunctionsDir, slug) + funcDir := filepath.Join(utils.Paths.FunctionsDir, slug) args := []string{"run", "-A", extractScriptPath, funcDir, *meta.EntrypointPath} cmd := exec.CommandContext(ctx, denoPath, args...) var errBuf bytes.Buffer @@ -180,8 +180,8 @@ func downloadOne(ctx context.Context, slug, projectRef string, fsys afero.Fs) (s r = brotli.NewReader(resp.Body) } // Create temp file to store downloaded eszip - eszipPath := filepath.Join(utils.TempDir, fmt.Sprintf("output_%s.eszip", slug)) - if err := utils.MkdirIfNotExistFS(fsys, utils.TempDir); err != nil { + eszipPath := filepath.Join(utils.Paths.TempDir, fmt.Sprintf("output_%s.eszip", slug)) + if err := utils.MkdirIfNotExistFS(fsys, utils.Paths.TempDir); err != nil { return "", err } if err := afero.WriteReader(fsys, eszipPath, r); err != nil { @@ -191,7 +191,7 @@ func downloadOne(ctx context.Context, slug, projectRef string, fsys afero.Fs) (s } func extractOne(ctx context.Context, slug, eszipPath string) error { - hostFuncDirPath, err := filepath.Abs(filepath.Join(utils.FunctionsDir, slug)) + hostFuncDirPath, err := filepath.Abs(filepath.Join(utils.Paths.FunctionsDir, slug)) if err != nil { return errors.Errorf("failed to resolve absolute path: %w", err) } @@ -253,7 +253,7 @@ func suggestDenoV2() string { [edge_runtime] deno_version = 2 -`, utils.Bold(utils.ConfigPath)) +`, utils.Bold(utils.Paths.ConfigPath)) } func suggestLegacyBundle(slug string) string { @@ -304,7 +304,7 @@ func downloadWithServerSideUnbundle(ctx context.Context, slug, projectRef string fmt.Fprintln(utils.GetDebugLogger(), "Using entrypoint path:", metadata.EntrypointPath) // Root directory on disk: supabase/functions/ - funcDir := filepath.Join(utils.FunctionsDir, slug) + funcDir := filepath.Join(utils.Paths.FunctionsDir, slug) for _, data := range form.File { for _, file := range data { if err := saveFile(file, metadata.EntrypointPath, funcDir, fsys); err != nil { diff --git a/internal/functions/download/download_test.go b/internal/functions/download/download_test.go index 713a26243..e783a4b33 100644 --- a/internal/functions/download/download_test.go +++ b/internal/functions/download/download_test.go @@ -208,7 +208,7 @@ func TestRunDockerUnbundle(t *testing.T) { err := Run(context.Background(), slugDocker, project, false, true, fsys) require.NoError(t, err) - eszipPath := filepath.Join(utils.TempDir, fmt.Sprintf("output_%s.eszip", slugDocker)) + eszipPath := filepath.Join(utils.Paths.TempDir, fmt.Sprintf("output_%s.eszip", slugDocker)) exists, err := afero.Exists(fsys, eszipPath) require.NoError(t, err) assert.False(t, exists, "temporary eszip file should be removed after extraction") @@ -243,7 +243,7 @@ func TestRunDockerUnbundle(t *testing.T) { err := Run(context.Background(), slugDocker, project, false, true, fsys) require.NoError(t, err) - data, err := afero.ReadFile(fsys, filepath.Join(utils.FunctionsDir, slugDocker, "index.ts")) + data, err := afero.ReadFile(fsys, filepath.Join(utils.Paths.FunctionsDir, slugDocker, "index.ts")) require.NoError(t, err) assert.Equal(t, "console.log('hello')", string(data)) @@ -270,15 +270,15 @@ func TestRunServerSideUnbundle(t *testing.T) { err := Run(context.Background(), slug, project, false, false, fsys) require.NoError(t, err) - data, err := afero.ReadFile(fsys, filepath.Join(utils.FunctionsDir, slug, "index.ts")) + data, err := afero.ReadFile(fsys, filepath.Join(utils.Paths.FunctionsDir, slug, "index.ts")) require.NoError(t, err) assert.Equal(t, "console.log('hello')", string(data)) - data, err = afero.ReadFile(fsys, filepath.Join(utils.FunctionsDir, slug, "utils.ts")) + data, err = afero.ReadFile(fsys, filepath.Join(utils.Paths.FunctionsDir, slug, "utils.ts")) require.NoError(t, err) assert.Equal(t, "export const value = 1;", string(data)) - entries, err := afero.ReadDir(fsys, utils.TempDir) + entries, err := afero.ReadDir(fsys, utils.Paths.TempDir) if err == nil { assert.Len(t, entries, 0, "expected temporary directory to be cleaned up") } else { @@ -317,7 +317,7 @@ func TestRunServerSideUnbundle(t *testing.T) { err := Run(context.Background(), slug, project, false, false, fsys) require.NoError(t, err) - root := filepath.Join(utils.FunctionsDir, slug) + root := filepath.Join(utils.Paths.FunctionsDir, slug) data, err := afero.ReadFile(fsys, filepath.Join(root, "index.ts")) require.NoError(t, err) assert.Equal(t, "console.log('abs')", string(data)) @@ -385,12 +385,12 @@ func TestRunServerSideUnbundle(t *testing.T) { err := Run(context.Background(), slug, project, false, false, fsys) assert.NoError(t, err) - root := filepath.Join(utils.FunctionsDir, slug) + root := filepath.Join(utils.Paths.FunctionsDir, slug) data, err := afero.ReadFile(fsys, filepath.Join(root, "source", "index.ts")) require.NoError(t, err) assert.Equal(t, "console.log('hello')", string(data)) - data, err = afero.ReadFile(fsys, filepath.Join(utils.FunctionsDir, "secret.env")) + data, err = afero.ReadFile(fsys, filepath.Join(utils.Paths.FunctionsDir, "secret.env")) require.NoError(t, err) assert.Equal(t, "SECRET=1", string(data)) diff --git a/internal/functions/new/new.go b/internal/functions/new/new.go index 1b0f30791..ded213001 100644 --- a/internal/functions/new/new.go +++ b/internal/functions/new/new.go @@ -48,7 +48,7 @@ func Run(ctx context.Context, slug string, fsys afero.Fs) error { isFirstFunction := len(existingSlugs) == 0 // 2. Create new function. - funcDir := filepath.Join(utils.FunctionsDir, slug) + funcDir := filepath.Join(utils.Paths.FunctionsDir, slug) if err := utils.MkdirIfNotExistFS(fsys, funcDir); err != nil { return err } @@ -80,7 +80,7 @@ func Run(ctx context.Context, slug string, fsys afero.Fs) error { } func createEntrypointFile(slug string, fsys afero.Fs) error { - entrypointPath := filepath.Join(utils.FunctionsDir, slug, "index.ts") + entrypointPath := filepath.Join(utils.Paths.FunctionsDir, slug, "index.ts") f, err := fsys.OpenFile(entrypointPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) if err != nil { return errors.Errorf("failed to create entrypoint: %w", err) @@ -97,10 +97,10 @@ func createEntrypointFile(slug string, fsys afero.Fs) error { func appendConfigFile(slug string, fsys afero.Fs) error { if _, exists := utils.Config.Functions[slug]; exists { - fmt.Fprintf(os.Stderr, "[functions.%s] is already declared in %s\n", slug, utils.Bold(utils.ConfigPath)) + fmt.Fprintf(os.Stderr, "[functions.%s] is already declared in %s\n", slug, utils.Bold(utils.Paths.ConfigPath)) return nil } - f, err := fsys.OpenFile(utils.ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return errors.Errorf("failed to append config: %w", err) } diff --git a/internal/functions/new/new_test.go b/internal/functions/new/new_test.go index df082d0d0..55ad625de 100644 --- a/internal/functions/new/new_test.go +++ b/internal/functions/new/new_test.go @@ -18,7 +18,7 @@ func TestNewCommand(t *testing.T) { // Run test assert.NoError(t, Run(context.Background(), "test-func", fsys)) // Validate output - funcPath := filepath.Join(utils.FunctionsDir, "test-func", "index.ts") + funcPath := filepath.Join(utils.Paths.FunctionsDir, "test-func", "index.ts") content, err := afero.ReadFile(fsys, funcPath) assert.NoError(t, err) assert.Contains(t, string(content), @@ -26,16 +26,16 @@ func TestNewCommand(t *testing.T) { ) // Verify config.toml is updated - _, err = afero.ReadFile(fsys, utils.ConfigPath) + _, err = afero.ReadFile(fsys, utils.Paths.ConfigPath) assert.NoError(t, err, "config.toml should be created") // Verify deno.json exists - denoPath := filepath.Join(utils.FunctionsDir, "test-func", "deno.json") + denoPath := filepath.Join(utils.Paths.FunctionsDir, "test-func", "deno.json") _, err = afero.ReadFile(fsys, denoPath) assert.NoError(t, err, "deno.json should be created") // Verify .npmrc exists - npmrcPath := filepath.Join(utils.FunctionsDir, "test-func", ".npmrc") + npmrcPath := filepath.Join(utils.Paths.FunctionsDir, "test-func", ".npmrc") _, err = afero.ReadFile(fsys, npmrcPath) assert.NoError(t, err, ".npmrc should be created") }) @@ -47,7 +47,7 @@ func TestNewCommand(t *testing.T) { t.Run("throws error on duplicate slug", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - funcPath := filepath.Join(utils.FunctionsDir, "test-func", "index.ts") + funcPath := filepath.Join(utils.Paths.FunctionsDir, "test-func", "index.ts") require.NoError(t, afero.WriteFile(fsys, funcPath, []byte{}, 0644)) // Run test assert.Error(t, Run(context.Background(), "test-func", fsys)) diff --git a/internal/functions/serve/serve.go b/internal/functions/serve/serve.go index b0db41ffd..b0763d480 100644 --- a/internal/functions/serve/serve.go +++ b/internal/functions/serve/serve.go @@ -88,7 +88,7 @@ func Run(ctx context.Context, envFilePath string, noVerifyJWT *bool, importMapPa for { select { case <-ctx.Done(): - fmt.Println("Stopped serving " + utils.Bold(utils.FunctionsDir)) + fmt.Println("Stopped serving " + utils.Bold(utils.Paths.FunctionsDir)) return ctx.Err() case <-watcher.RestartCh: if err := restartEdgeRuntime(ctx, envFilePath, noVerifyJWT, importMapPath, runtimeOption, fsys); err != nil { @@ -227,8 +227,8 @@ EOF func parseEnvFile(envFilePath string, fsys afero.Fs) ([]string, error) { if envFilePath == "" { - if f, err := fsys.Stat(utils.FallbackEnvFilePath); err == nil && !f.IsDir() { - envFilePath = utils.FallbackEnvFilePath + if f, err := fsys.Stat(utils.Paths.FallbackEnvFilePath); err == nil && !f.IsDir() { + envFilePath = utils.Paths.FallbackEnvFilePath } } else if !filepath.IsAbs(envFilePath) { envFilePath = filepath.Join(utils.CurrentDirAbs, envFilePath) @@ -257,7 +257,7 @@ func PopulatePerFunctionConfigs(cwd, importMapPath string, noVerifyJWT *bool, fs delete(functionsConfig, slug) continue } - modules, err := deploy.GetBindMounts(cwd, utils.FunctionsDir, "", fc.Entrypoint, fc.ImportMap, fsys) + modules, err := deploy.GetBindMounts(cwd, utils.Paths.FunctionsDir, "", fc.Entrypoint, fc.ImportMap, fsys) if err != nil { return nil, "", err } diff --git a/internal/functions/serve/serve_test.go b/internal/functions/serve/serve_test.go index 38b7f420c..d13ad0de9 100644 --- a/internal/functions/serve/serve_test.go +++ b/internal/functions/serve/serve_test.go @@ -29,9 +29,9 @@ func TestServeCommand(t *testing.T) { t.Run("serves all functions", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, testConfig, 0644)) - require.NoError(t, afero.WriteFile(fsys, utils.FallbackEnvFilePath, []byte{}, 0644)) - require.NoError(t, afero.WriteFile(fsys, utils.FallbackImportMapPath, []byte("{}"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, testConfig, 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackEnvFilePath, []byte{}, 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.FallbackImportMapPath, []byte("{}"), 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) defer gock.OffAll() @@ -55,7 +55,7 @@ func TestServeCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), "", nil, "", RuntimeOption{}, fsys) // Check error @@ -100,7 +100,7 @@ func TestServeCommand(t *testing.T) { fsys := afero.NewMemMapFs() require.NoError(t, utils.InitConfig(utils.InitParams{ProjectId: "test"}, fsys)) require.NoError(t, afero.WriteFile(fsys, ".env", []byte{}, 0644)) - entrypoint := filepath.Join(utils.FunctionsDir, "hello", "index.ts") + entrypoint := filepath.Join(utils.Paths.FunctionsDir, "hello", "index.ts") require.NoError(t, afero.WriteFile(fsys, entrypoint, []byte{}, 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) diff --git a/internal/gen/signingkeys/signingkeys.go b/internal/gen/signingkeys/signingkeys.go index 5651ac265..1621b70f0 100644 --- a/internal/gen/signingkeys/signingkeys.go +++ b/internal/gen/signingkeys/signingkeys.go @@ -123,7 +123,7 @@ To enable JWT signing keys in your local project: [auth] signing_keys_path = "./signing_key.json" -`, utils.Bold(filepath.Join(utils.SupabaseDirPath, "signing_key.json")), utils.Bold(utils.ConfigPath)) +`, utils.Bold(filepath.Join(utils.Paths.SupabaseDirPath, "signing_key.json")), utils.Bold(utils.Paths.ConfigPath)) return nil } diff --git a/internal/init/init.go b/internal/init/init.go index 01c70bcaf..124795fde 100644 --- a/internal/init/init.go +++ b/internal/init/init.go @@ -44,7 +44,7 @@ func Run(ctx context.Context, fsys afero.Fs, interactive bool, params utils.Init // 2. Append to `.gitignore`. if utils.IsGitRepo() { - if err := updateGitIgnore(utils.GitIgnorePath, fsys); err != nil { + if err := updateGitIgnore(utils.Paths.GitIgnorePath, fsys); err != nil { return err } } diff --git a/internal/init/init_test.go b/internal/init/init_test.go index 3d54feb58..f9fdf96f4 100644 --- a/internal/init/init_test.go +++ b/internal/init/init_test.go @@ -21,11 +21,11 @@ func TestInitCommand(t *testing.T) { // Run test (non-interactive mode) assert.NoError(t, Run(context.Background(), fsys, false, utils.InitParams{})) // Validate generated config.toml - exists, err := afero.Exists(fsys, utils.ConfigPath) + exists, err := afero.Exists(fsys, utils.Paths.ConfigPath) assert.NoError(t, err) assert.True(t, exists) // Validate generated .gitignore - exists, err = afero.Exists(fsys, utils.GitIgnorePath) + exists, err = afero.Exists(fsys, utils.Paths.GitIgnorePath) assert.NoError(t, err) assert.True(t, exists) // Validate vscode settings file isn't generated @@ -44,7 +44,7 @@ func TestInitCommand(t *testing.T) { t.Run("throws error when config file exists", func(t *testing.T) { // Setup in-memory fs fsys := &afero.MemMapFs{} - _, err := fsys.Create(utils.ConfigPath) + _, err := fsys.Create(utils.Paths.ConfigPath) require.NoError(t, err) // Run test assert.Error(t, Run(context.Background(), fsys, false, utils.InitParams{})) @@ -52,7 +52,7 @@ func TestInitCommand(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.ConfigPath} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.ConfigPath} // Run test err := Run(context.Background(), fsys, false, utils.InitParams{}) // Check error diff --git a/internal/link/link.go b/internal/link/link.go index 6832876ac..3665892d1 100644 --- a/internal/link/link.go +++ b/internal/link/link.go @@ -32,7 +32,7 @@ func Run(ctx context.Context, projectRef string, skipPooler bool, fsys afero.Fs, } LinkServices(ctx, projectRef, keys.ServiceRole, skipPooler, fsys) // 3. Save project ref - return utils.WriteFile(utils.ProjectRefPath, []byte(projectRef), fsys) + return utils.WriteFile(utils.Paths.ProjectRefPath, []byte(projectRef), fsys) } func LinkServices(ctx context.Context, projectRef, serviceKey string, skipPooler bool, fsys afero.Fs) { @@ -47,7 +47,7 @@ func LinkServices(ctx context.Context, projectRef, serviceKey string, skipPooler func() error { if skipPooler { utils.Config.Db.Pooler.ConnectionString = "" - return fsys.RemoveAll(utils.PoolerUrlPath) + return fsys.RemoveAll(utils.Paths.PoolerUrlPath) } return linkPooler(ctx, projectRef, fsys) }, @@ -83,7 +83,7 @@ func linkPostgrestVersion(ctx context.Context, api tenant.TenantAPI, fsys afero. if err != nil { return err } - return utils.WriteFile(utils.RestVersionPath, []byte(version), fsys) + return utils.WriteFile(utils.Paths.RestVersionPath, []byte(version), fsys) } func linkGotrue(ctx context.Context, projectRef string) error { @@ -102,7 +102,7 @@ func linkGotrueVersion(ctx context.Context, api tenant.TenantAPI, fsys afero.Fs) if err != nil { return err } - return utils.WriteFile(utils.GotrueVersionPath, []byte(version), fsys) + return utils.WriteFile(utils.Paths.GotrueVersionPath, []byte(version), fsys) } func linkStorage(ctx context.Context, projectRef string, fsys afero.Fs) error { @@ -113,7 +113,7 @@ func linkStorage(ctx context.Context, projectRef string, fsys afero.Fs) error { return errors.Errorf("unexpected Storage config status %d: %s", resp.StatusCode(), string(resp.Body)) } utils.Config.Storage.FromRemoteStorageConfig(*resp.JSON200) - return utils.WriteFile(utils.StorageMigrationPath, []byte(utils.Config.Storage.TargetMigration), fsys) + return utils.WriteFile(utils.Paths.StorageMigrationPath, []byte(utils.Config.Storage.TargetMigration), fsys) } func linkStorageVersion(ctx context.Context, api tenant.TenantAPI, fsys afero.Fs) error { @@ -121,7 +121,7 @@ func linkStorageVersion(ctx context.Context, api tenant.TenantAPI, fsys afero.Fs if err != nil { return err } - return utils.WriteFile(utils.StorageVersionPath, []byte(version), fsys) + return utils.WriteFile(utils.Paths.StorageVersionPath, []byte(version), fsys) } const GET_LATEST_STORAGE_MIGRATION = "SELECT name FROM storage.migrations ORDER BY id DESC LIMIT 1" @@ -131,7 +131,7 @@ func linkStorageMigration(ctx context.Context, conn *pgx.Conn, fsys afero.Fs) er if err := conn.QueryRow(ctx, GET_LATEST_STORAGE_MIGRATION).Scan(&name); err != nil { return errors.Errorf("failed to fetch storage migration: %w", err) } - return utils.WriteFile(utils.StorageMigrationPath, []byte(name), fsys) + return utils.WriteFile(utils.Paths.StorageMigrationPath, []byte(name), fsys) } func linkDatabaseSettings(ctx context.Context, projectRef string) error { @@ -182,7 +182,7 @@ func linkPooler(ctx context.Context, projectRef string, fsys afero.Fs) error { return err } updatePoolerConfig(primary) - return utils.WriteFile(utils.PoolerUrlPath, []byte(utils.Config.Db.Pooler.ConnectionString), fsys) + return utils.WriteFile(utils.Paths.PoolerUrlPath, []byte(utils.Config.Db.Pooler.ConnectionString), fsys) } func updatePoolerConfig(config api.SupavisorConfigResponse) { @@ -246,8 +246,8 @@ func linkPostgresVersion(version string, fsys afero.Fs) error { fmt.Fprintf(os.Stderr, `Update your %s to fix it: [db] major_version = %d -`, utils.Bold(utils.ConfigPath), majorVersion) +`, utils.Bold(utils.Paths.ConfigPath), majorVersion) } utils.Config.Db.MajorVersion = uint(majorVersion) - return utils.WriteFile(utils.PostgresVersionPath, []byte(version), fsys) + return utils.WriteFile(utils.Paths.PostgresVersionPath, []byte(version), fsys) } diff --git a/internal/link/link_test.go b/internal/link/link_test.go index bf7c85761..f28db8cae 100644 --- a/internal/link/link_test.go +++ b/internal/link/link_test.go @@ -113,19 +113,19 @@ func TestLinkCommand(t *testing.T) { assert.NoError(t, err) assert.Empty(t, apitest.ListUnmatchedRequests()) // Validate file contents - content, err := afero.ReadFile(fsys, utils.ProjectRefPath) + content, err := afero.ReadFile(fsys, utils.Paths.ProjectRefPath) assert.NoError(t, err) assert.Equal(t, []byte(project), content) - restVersion, err := afero.ReadFile(fsys, utils.RestVersionPath) + restVersion, err := afero.ReadFile(fsys, utils.Paths.RestVersionPath) assert.NoError(t, err) assert.Equal(t, []byte("v"+rest.Info.Version), restVersion) - authVersion, err := afero.ReadFile(fsys, utils.GotrueVersionPath) + authVersion, err := afero.ReadFile(fsys, utils.Paths.GotrueVersionPath) assert.NoError(t, err) assert.Equal(t, []byte(auth.Version), authVersion) - storageVersion, err := afero.ReadFile(fsys, utils.StorageVersionPath) + storageVersion, err := afero.ReadFile(fsys, utils.Paths.StorageVersionPath) assert.NoError(t, err) assert.Equal(t, []byte("v"+storage), storageVersion) - postgresVersion, err := afero.ReadFile(fsys, utils.PostgresVersionPath) + postgresVersion, err := afero.ReadFile(fsys, utils.Paths.PostgresVersionPath) assert.NoError(t, err) assert.Equal(t, []byte(mockPostgres.Database.Version), postgresVersion) }) @@ -254,7 +254,7 @@ func TestLinkCommand(t *testing.T) { assert.ErrorContains(t, err, "operation not permitted") assert.Empty(t, apitest.ListUnmatchedRequests()) // Validate file contents - exists, err := afero.Exists(fsys, utils.ProjectRefPath) + exists, err := afero.Exists(fsys, utils.Paths.ProjectRefPath) assert.NoError(t, err) assert.False(t, exists) }) @@ -283,7 +283,7 @@ func TestStatusCheck(t *testing.T) { err := checkRemoteProjectStatus(context.Background(), project, fsys) // Check error assert.NoError(t, err) - version, err := afero.ReadFile(fsys, utils.PostgresVersionPath) + version, err := afero.ReadFile(fsys, utils.Paths.PostgresVersionPath) assert.NoError(t, err) assert.Equal(t, "15.6.1.139", string(version)) assert.Empty(t, apitest.ListUnmatchedRequests()) @@ -302,7 +302,7 @@ func TestStatusCheck(t *testing.T) { err := checkRemoteProjectStatus(context.Background(), project, fsys) // Check error assert.NoError(t, err) - exists, err := afero.Exists(fsys, utils.PostgresVersionPath) + exists, err := afero.Exists(fsys, utils.Paths.PostgresVersionPath) assert.NoError(t, err) assert.False(t, exists) assert.Empty(t, apitest.ListUnmatchedRequests()) @@ -322,7 +322,7 @@ func TestStatusCheck(t *testing.T) { err := checkRemoteProjectStatus(context.Background(), project, fsys) // Check error assert.ErrorIs(t, err, errProjectPaused) - exists, err := afero.Exists(fsys, utils.PostgresVersionPath) + exists, err := afero.Exists(fsys, utils.Paths.PostgresVersionPath) assert.NoError(t, err) assert.False(t, exists) assert.Empty(t, apitest.ListUnmatchedRequests()) @@ -411,7 +411,7 @@ func TestLinkDatabase(t *testing.T) { err := linkDatabase(context.Background(), dbConfig, fsys, conn.Intercept) // Check error assert.NoError(t, err) - storage, err := afero.ReadFile(fsys, utils.StorageMigrationPath) + storage, err := afero.ReadFile(fsys, utils.Paths.StorageMigrationPath) assert.NoError(t, err) assert.Equal(t, []byte("custom-metadata"), storage) }) @@ -439,7 +439,7 @@ func TestLinkDatabase(t *testing.T) { err := linkDatabase(context.Background(), dbConfig, fsys, conn.Intercept) // Check error assert.NoError(t, err) - version, err := afero.ReadFile(fsys, utils.StorageMigrationPath) + version, err := afero.ReadFile(fsys, utils.Paths.StorageMigrationPath) assert.NoError(t, err) assert.Equal(t, "custom-metadata", string(version)) }) @@ -461,7 +461,7 @@ func TestLinkDatabase(t *testing.T) { // Check error assert.NoError(t, err) assert.Equal(t, uint(15), utils.Config.Db.MajorVersion) - version, err := afero.ReadFile(fsys, utils.StorageMigrationPath) + version, err := afero.ReadFile(fsys, utils.Paths.StorageMigrationPath) assert.NoError(t, err) assert.Equal(t, "custom-metadata", string(version)) }) @@ -479,7 +479,7 @@ func TestLinkDatabase(t *testing.T) { err := linkDatabase(context.Background(), dbConfig, fsys, conn.Intercept) // Check error assert.ErrorContains(t, err, "ERROR: permission denied for relation migrations (SQLSTATE 42501)") - exists, err := afero.Exists(fsys, utils.StorageMigrationPath) + exists, err := afero.Exists(fsys, utils.Paths.StorageMigrationPath) assert.NoError(t, err) assert.False(t, exists) }) diff --git a/internal/migration/apply/apply_test.go b/internal/migration/apply/apply_test.go index f45891cfb..1e39761c3 100644 --- a/internal/migration/apply/apply_test.go +++ b/internal/migration/apply/apply_test.go @@ -20,7 +20,7 @@ func TestMigrateDatabase(t *testing.T) { t.Run("applies local migration", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") sql := "create schema public" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) // Setup mock postgres @@ -42,10 +42,10 @@ func TestMigrateDatabase(t *testing.T) { t.Run("skip seeding when seed config is disabled", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") sql := "create schema public" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) - seedPath := filepath.Join(utils.SupabaseDirPath, "seed.sql") + seedPath := filepath.Join(utils.Paths.SupabaseDirPath, "seed.sql") // This will raise an error when seeding require.NoError(t, afero.WriteFile(fsys, seedPath, []byte("INSERT INTO test_table;"), 0644)) // Setup mock postgres @@ -71,7 +71,7 @@ func TestMigrateDatabase(t *testing.T) { t.Run("throws error on open failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Run test err := MigrateAndSeed(context.Background(), "", nil, fsys) // Check error diff --git a/internal/migration/down/down_test.go b/internal/migration/down/down_test.go index 89d9ff66d..9c0b88dec 100644 --- a/internal/migration/down/down_test.go +++ b/internal/migration/down/down_test.go @@ -29,9 +29,9 @@ func TestMigrationsDown(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() files := []string{ - filepath.Join(utils.MigrationsDir, "20221201000000_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000001_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000002_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000000_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000001_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000002_test.sql"), } for _, path := range files { require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) @@ -80,7 +80,7 @@ func TestResetRemote(t *testing.T) { t.Run("resets remote database", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_schema.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_schema.sql") require.NoError(t, afero.WriteFile(fsys, path, nil, 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -101,9 +101,9 @@ func TestResetRemote(t *testing.T) { t.Run("resets remote database with seed config disabled", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_schema.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_schema.sql") require.NoError(t, afero.WriteFile(fsys, path, nil, 0644)) - seedPath := filepath.Join(utils.SupabaseDirPath, "seed.sql") + seedPath := filepath.Join(utils.Paths.SupabaseDirPath, "seed.sql") // Will raise an error when seeding require.NoError(t, afero.WriteFile(fsys, seedPath, []byte("INSERT INTO test_table;"), 0644)) // Setup mock postgres diff --git a/internal/migration/fetch/fetch.go b/internal/migration/fetch/fetch.go index cb78c70d8..f4447c7b9 100644 --- a/internal/migration/fetch/fetch.go +++ b/internal/migration/fetch/fetch.go @@ -15,13 +15,13 @@ import ( ) func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error { - if err := utils.MkdirIfNotExistFS(fsys, utils.MigrationsDir); err != nil { + if err := utils.MkdirIfNotExistFS(fsys, utils.Paths.MigrationsDir); err != nil { return err } - if empty, err := afero.IsEmpty(fsys, utils.MigrationsDir); err != nil { + if empty, err := afero.IsEmpty(fsys, utils.Paths.MigrationsDir); err != nil { return errors.Errorf("failed to read migrations: %w", err) } else if !empty { - title := fmt.Sprintf("Do you want to overwrite existing files in %s directory?", utils.Bold(utils.MigrationsDir)) + title := fmt.Sprintf("Do you want to overwrite existing files in %s directory?", utils.Bold(utils.Paths.MigrationsDir)) if shouldOverwrite, err := utils.NewConsole().PromptYesNo(ctx, title, true); err != nil { return err } else if !shouldOverwrite { @@ -34,7 +34,7 @@ func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...fu } for _, r := range result { name := fmt.Sprintf("%s_%s.sql", r.Version, r.Name) - path := filepath.Join(utils.MigrationsDir, name) + path := filepath.Join(utils.Paths.MigrationsDir, name) contents := strings.Join(r.Statements, ";\n") + ";\n" if err := afero.WriteFile(fsys, path, []byte(contents), 0644); err != nil { return errors.Errorf("failed to write migration: %w", err) diff --git a/internal/migration/format/format.go b/internal/migration/format/format.go index cb5045745..9ab4e8ddc 100644 --- a/internal/migration/format/format.go +++ b/internal/migration/format/format.go @@ -20,63 +20,63 @@ import ( ) var ( - rolesPath = filepath.Join(utils.ClusterDir, "roles.sql") - extensionsPath = filepath.Join(utils.ClusterDir, "extensions.sql") - foreignDWPath = filepath.Join(utils.ClusterDir, "foreign_data_wrappers.sql") - publicationsPath = filepath.Join(utils.ClusterDir, "publications.sql") - subscriptionsPath = filepath.Join(utils.ClusterDir, "subscriptions.sql") - eventTriggersPath = filepath.Join(utils.ClusterDir, "event_triggers.sql") - tablespacesPath = filepath.Join(utils.ClusterDir, "tablespaces.sql") - variablesPath = filepath.Join(utils.ClusterDir, "variables.sql") - unqualifiedPath = filepath.Join(utils.SchemasDir, "unqualified.sql") + rolesPath = filepath.Join(utils.Paths.ClusterDir, "roles.sql") + extensionsPath = filepath.Join(utils.Paths.ClusterDir, "extensions.sql") + foreignDWPath = filepath.Join(utils.Paths.ClusterDir, "foreign_data_wrappers.sql") + publicationsPath = filepath.Join(utils.Paths.ClusterDir, "publications.sql") + subscriptionsPath = filepath.Join(utils.Paths.ClusterDir, "subscriptions.sql") + eventTriggersPath = filepath.Join(utils.Paths.ClusterDir, "event_triggers.sql") + tablespacesPath = filepath.Join(utils.Paths.ClusterDir, "tablespaces.sql") + variablesPath = filepath.Join(utils.Paths.ClusterDir, "variables.sql") + unqualifiedPath = filepath.Join(utils.Paths.SchemasDir, "unqualified.sql") ) func getSchemaPath(name string) string { - return filepath.Join(utils.SchemasDir, name, "schema.sql") + return filepath.Join(utils.Paths.SchemasDir, name, "schema.sql") } func getTypesPath(schema string) string { - return filepath.Join(utils.SchemasDir, schema, "types.sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "types.sql") } func getSequencesPath(schema string) string { - return filepath.Join(utils.SchemasDir, schema, "sequences.sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "sequences.sql") } func getTablePath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "tables", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "tables", name+".sql") } func getForeignTablePath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "foreign_tables", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "foreign_tables", name+".sql") } func getFunctionPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "functions", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "functions", name+".sql") } func getProcedurePath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "procedures", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "procedures", name+".sql") } func getMaterializedViewPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "materialized_views", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "materialized_views", name+".sql") } func getViewPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "views", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "views", name+".sql") } func getPolicyPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "policies", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "policies", name+".sql") } func getDomainPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "domains", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "domains", name+".sql") } func getOperatorPath(schema, name string) string { - return filepath.Join(utils.SchemasDir, schema, "operators", name+".sql") + return filepath.Join(utils.Paths.SchemasDir, schema, "operators", name+".sql") } func getSequenceOrTablePath(schema, name string, seen map[string]string) string { @@ -101,7 +101,7 @@ func WriteStructuredSchemas(ctx context.Context, sql io.Reader, fsys afero.Fs) e if err != nil { return err } - for _, d := range []string{utils.ClusterDir, utils.SchemasDir} { + for _, d := range []string{utils.Paths.ClusterDir, utils.Paths.SchemasDir} { if err := fsys.RemoveAll(d); err != nil { return errors.Errorf("failed to remove directory: %w", err) } @@ -398,7 +398,7 @@ func WriteStructuredSchemas(ctx context.Context, sql io.Reader, fsys afero.Fs) e } if name == unqualifiedPath { fmt.Fprintf(utils.GetDebugLogger(), "Unqualified (%T): %s\n", parsed[0], line) - } else if strings.HasPrefix(name, utils.SchemasDir) { + } else if strings.HasPrefix(name, utils.Paths.SchemasDir) { schemaPaths = append(schemaPaths, name) if filepath.Base(name) == "schema.sql" { schema := filepath.Base(filepath.Dir(name)) @@ -678,7 +678,7 @@ var pattern = regexp.MustCompile(`(?s)\nschema_paths = \[(.*?)\]\n`) func appendConfig(fsys afero.Fs) error { lines := []string{"\nschema_paths = ["} for _, fp := range utils.Config.Db.Migrations.SchemaPaths { - relPath, err := filepath.Rel(utils.SupabaseDirPath, fp) + relPath, err := filepath.Rel(utils.Paths.SupabaseDirPath, fp) if err != nil { return errors.Errorf("failed to resolve path: %w", err) } @@ -687,15 +687,15 @@ func appendConfig(fsys afero.Fs) error { lines = append(lines, "]\n") schemaPaths := strings.Join(lines, "\n") // Attempt in-line config replacement - data, err := afero.ReadFile(fsys, utils.ConfigPath) + data, err := afero.ReadFile(fsys, utils.Paths.ConfigPath) if err != nil && !errors.Is(err, os.ErrNotExist) { return errors.Errorf("failed to read config: %w", err) } if newConfig := pattern.ReplaceAllLiteral(data, []byte(schemaPaths)); bytes.Contains(newConfig, []byte(schemaPaths)) { - return utils.WriteFile(utils.ConfigPath, newConfig, fsys) + return utils.WriteFile(utils.Paths.ConfigPath, newConfig, fsys) } // Fallback to append - f, err := fsys.OpenFile(utils.ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + f, err := fsys.OpenFile(utils.Paths.ConfigPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return errors.Errorf("failed to open config: %w", err) } diff --git a/internal/migration/format/format_test.go b/internal/migration/format/format_test.go index 45791b433..05d6363db 100644 --- a/internal/migration/format/format_test.go +++ b/internal/migration/format/format_test.go @@ -46,7 +46,7 @@ func TestWriteStructured(t *testing.T) { } expected, err := afero.ReadFile(testFs, fp) assert.NoError(t, err) - actual, _ := afero.ReadFile(fsys, path.Join(utils.SupabaseDirPath, fp)) + actual, _ := afero.ReadFile(fsys, path.Join(utils.Paths.SupabaseDirPath, fp)) assert.Equal(t, string(expected), string(actual), fp) return nil }) @@ -67,7 +67,7 @@ func TestAppendConfig(t *testing.T) { err := appendConfig(fsys) // Check error assert.NoError(t, err) - data, err := afero.ReadFile(fsys, utils.ConfigPath) + data, err := afero.ReadFile(fsys, utils.Paths.ConfigPath) assert.NoError(t, err) assert.True(t, strings.Contains(string(data), ` schema_paths = [ @@ -90,7 +90,7 @@ schema_paths = [ err := appendConfig(fsys) // Check error assert.NoError(t, err) - data, err := afero.ReadFile(fsys, utils.ConfigPath) + data, err := afero.ReadFile(fsys, utils.Paths.ConfigPath) assert.NoError(t, err) assert.Equal(t, ` [db.migrations] diff --git a/internal/migration/list/list.go b/internal/migration/list/list.go index ad4a062c0..9ca04b3c9 100644 --- a/internal/migration/list/list.go +++ b/internal/migration/list/list.go @@ -75,7 +75,7 @@ func LoadLocalVersions(fsys afero.Fs) ([]string, error) { versions = append(versions, v) return true } - _, err := migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys), filter) + _, err := migration.ListLocalMigrations(utils.Paths.MigrationsDir, afero.NewIOFS(fsys), filter) return versions, err } @@ -83,5 +83,5 @@ func LoadPartialMigrations(version string, fsys afero.Fs) ([]string, error) { filter := func(v string) bool { return version == "" || v <= version } - return migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys), filter) + return migration.ListLocalMigrations(utils.Paths.MigrationsDir, afero.NewIOFS(fsys), filter) } diff --git a/internal/migration/list/list_test.go b/internal/migration/list/list_test.go index 9744174df..1c77e4077 100644 --- a/internal/migration/list/list_test.go +++ b/internal/migration/list/list_test.go @@ -52,7 +52,7 @@ func TestMigrationList(t *testing.T) { t.Run("throws error on open failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Setup mock postgres conn := pgtest.NewConn() defer conn.Close(t) @@ -116,9 +116,9 @@ func TestLocalMigrations(t *testing.T) { t.Run("loads migration versions", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "20220727064246_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "20220727064246_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) - path = filepath.Join(utils.MigrationsDir, "20220727064248_test.sql") + path = filepath.Join(utils.Paths.MigrationsDir, "20220727064248_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Run test versions, err := LoadLocalVersions(fsys) @@ -130,9 +130,9 @@ func TestLocalMigrations(t *testing.T) { t.Run("ignores outdated and invalid files", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "20211208000000_init.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "20211208000000_init.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) - path = filepath.Join(utils.MigrationsDir, "20211208000001_invalid.ts") + path = filepath.Join(utils.Paths.MigrationsDir, "20211208000001_invalid.ts") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Run test versions, err := LoadLocalVersions(fsys) @@ -143,7 +143,7 @@ func TestLocalMigrations(t *testing.T) { t.Run("throws error on open failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Run test _, err := LoadLocalVersions(fsys) // Check error diff --git a/internal/migration/new/new.go b/internal/migration/new/new.go index be232b591..51c4b39b2 100644 --- a/internal/migration/new/new.go +++ b/internal/migration/new/new.go @@ -30,7 +30,7 @@ func Run(migrationName string, stdin afero.File, fsys afero.Fs) error { func GetMigrationPath(timestamp, name string) string { fullName := fmt.Sprintf("%s_%s.sql", timestamp, name) - return filepath.Join(utils.MigrationsDir, fullName) + return filepath.Join(utils.Paths.MigrationsDir, fullName) } func CopyStdinIfExists(stdin afero.File, dst io.Writer) error { diff --git a/internal/migration/new/new_test.go b/internal/migration/new/new_test.go index 39e2fe115..a87e2da96 100644 --- a/internal/migration/new/new_test.go +++ b/internal/migration/new/new_test.go @@ -21,7 +21,7 @@ func TestNewCommand(t *testing.T) { // Run test assert.NoError(t, Run("test_migrate", stdin, fsys)) // Validate output - files, err := afero.ReadDir(fsys, utils.MigrationsDir) + files, err := afero.ReadDir(fsys, utils.Paths.MigrationsDir) assert.NoError(t, err) assert.Equal(t, 1, len(files)) assert.Regexp(t, `([0-9]{14})_test_migrate\.sql`, files[0].Name()) @@ -40,10 +40,10 @@ func TestNewCommand(t *testing.T) { // Run test assert.NoError(t, Run("test_migrate", r, fsys)) // Validate output - files, err := afero.ReadDir(fsys, utils.MigrationsDir) + files, err := afero.ReadDir(fsys, utils.Paths.MigrationsDir) assert.NoError(t, err) assert.Equal(t, 1, len(files)) - path := filepath.Join(utils.MigrationsDir, files[0].Name()) + path := filepath.Join(utils.Paths.MigrationsDir, files[0].Name()) contents, err := afero.ReadFile(fsys, path) assert.NoError(t, err) assert.Equal(t, []byte(script), contents) diff --git a/internal/migration/repair/repair.go b/internal/migration/repair/repair.go index a7dfee274..cb44ed33f 100644 --- a/internal/migration/repair/repair.go +++ b/internal/migration/repair/repair.go @@ -88,7 +88,7 @@ func UpdateMigrationTable(ctx context.Context, conn *pgx.Conn, version []string, } func GetMigrationFile(version string, fsys afero.Fs) (string, error) { - path := filepath.Join(utils.MigrationsDir, version+"_*.sql") + path := filepath.Join(utils.Paths.MigrationsDir, version+"_*.sql") matches, err := afero.Glob(fsys, path) if err != nil { return "", errors.Errorf("failed to glob migration files: %w", err) diff --git a/internal/migration/repair/repair_test.go b/internal/migration/repair/repair_test.go index f8eb33cce..2a3c33f90 100644 --- a/internal/migration/repair/repair_test.go +++ b/internal/migration/repair/repair_test.go @@ -32,7 +32,7 @@ func TestRepairCommand(t *testing.T) { t.Run("applies new version", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte("select 1"), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -82,7 +82,7 @@ func TestRepairCommand(t *testing.T) { t.Run("throws error on insert failure", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -102,7 +102,7 @@ func TestRepairAll(t *testing.T) { t.Cleanup(fstest.MockStdin(t, "y")) // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_test.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_test.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte("select 1"), 0644)) // Setup mock postgres conn := pgtest.NewConn() @@ -150,7 +150,7 @@ func TestRepairAll(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { t.Cleanup(fstest.MockStdin(t, "y")) // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Run test err := Run(context.Background(), dbConfig, nil, Applied, fsys) // Check error diff --git a/internal/migration/squash/squash_test.go b/internal/migration/squash/squash_test.go index 9bb51dab6..c5ccbde4a 100644 --- a/internal/migration/squash/squash_test.go +++ b/internal/migration/squash/squash_test.go @@ -46,8 +46,8 @@ func TestSquashCommand(t *testing.T) { fsys := afero.NewMemMapFs() require.NoError(t, flags.LoadConfig(fsys)) paths := []string{ - filepath.Join(utils.MigrationsDir, "0_init.sql"), - filepath.Join(utils.MigrationsDir, "1_target.sql"), + filepath.Join(utils.Paths.MigrationsDir, "0_init.sql"), + filepath.Join(utils.Paths.MigrationsDir, "1_target.sql"), } sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, paths[0], []byte(sql), 0644)) @@ -113,7 +113,7 @@ func TestSquashCommand(t *testing.T) { t.Run("baselines migration history", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_init.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_init.sql") sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) // Setup mock postgres @@ -155,7 +155,7 @@ func TestSquashCommand(t *testing.T) { func TestSquashVersion(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Run test err := squashToVersion(context.Background(), "0", fsys) // Check error @@ -174,9 +174,9 @@ func TestSquashVersion(t *testing.T) { t.Run("throws error on shadow create failure", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_init.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_init.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) - path = filepath.Join(utils.MigrationsDir, "1_target.sql") + path = filepath.Join(utils.Paths.MigrationsDir, "1_target.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte{}, 0644)) // Setup mock docker require.NoError(t, apitest.MockDocker(utils.Docker)) @@ -278,7 +278,7 @@ func TestSquashMigrations(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_init.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_init.sql") sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, path, []byte(sql), 0644)) // Setup mock docker @@ -330,8 +330,8 @@ func TestBaselineMigration(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() paths := []string{ - filepath.Join(utils.MigrationsDir, "0_init.sql"), - filepath.Join(utils.MigrationsDir, "1_target.sql"), + filepath.Join(utils.Paths.MigrationsDir, "0_init.sql"), + filepath.Join(utils.Paths.MigrationsDir, "1_target.sql"), } sql := "create schema test" require.NoError(t, afero.WriteFile(fsys, paths[0], []byte(sql), 0644)) @@ -362,7 +362,7 @@ func TestBaselineMigration(t *testing.T) { t.Run("throws error on query failure", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - path := filepath.Join(utils.MigrationsDir, "0_init.sql") + path := filepath.Join(utils.Paths.MigrationsDir, "0_init.sql") require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) // Setup mock postgres conn := pgtest.NewConn() diff --git a/internal/migration/up/up.go b/internal/migration/up/up.go index 331abce66..40665ad05 100644 --- a/internal/migration/up/up.go +++ b/internal/migration/up/up.go @@ -35,7 +35,7 @@ func GetPendingMigrations(ctx context.Context, includeAll bool, conn *pgx.Conn, if err != nil { return nil, err } - localMigrations, err := migration.ListLocalMigrations(utils.MigrationsDir, afero.NewIOFS(fsys)) + localMigrations, err := migration.ListLocalMigrations(utils.Paths.MigrationsDir, afero.NewIOFS(fsys)) if err != nil { return nil, err } diff --git a/internal/migration/up/up_test.go b/internal/migration/up/up_test.go index 85669d709..1de301182 100644 --- a/internal/migration/up/up_test.go +++ b/internal/migration/up/up_test.go @@ -20,10 +20,10 @@ func TestPendingMigrations(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() files := []string{ - filepath.Join(utils.MigrationsDir, "20221201000000_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000001_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000002_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000003_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000000_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000001_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000002_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000003_test.sql"), } for _, path := range files { require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) @@ -42,7 +42,7 @@ func TestPendingMigrations(t *testing.T) { t.Run("throws error on local load failure", func(t *testing.T) { // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.MigrationsDir} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.MigrationsDir} // Setup mock postgres conn := pgtest.NewConn() defer conn.Close(t) @@ -74,7 +74,7 @@ func TestPendingMigrations(t *testing.T) { fsys := afero.NewMemMapFs() files := []string{"0_test.sql", "1_test.sql"} for _, name := range files { - path := filepath.Join(utils.MigrationsDir, name) + path := filepath.Join(utils.Paths.MigrationsDir, name) require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) } // Setup mock postgres @@ -94,10 +94,10 @@ func TestIgnoreVersionMismatch(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() files := []string{ - filepath.Join(utils.MigrationsDir, "20221201000000_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000001_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000002_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000003_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000000_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000001_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000002_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000003_test.sql"), } for _, path := range files { require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) @@ -118,10 +118,10 @@ func TestIgnoreVersionMismatch(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() files := []string{ - filepath.Join(utils.MigrationsDir, "20221201000000_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000001_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000002_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000003_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000000_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000001_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000002_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000003_test.sql"), } for _, path := range files { require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) @@ -142,8 +142,8 @@ func TestIgnoreVersionMismatch(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() files := []string{ - filepath.Join(utils.MigrationsDir, "20221201000000_test.sql"), - filepath.Join(utils.MigrationsDir, "20221201000002_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000000_test.sql"), + filepath.Join(utils.Paths.MigrationsDir, "20221201000002_test.sql"), } for _, path := range files { require.NoError(t, afero.WriteFile(fsys, path, []byte(""), 0644)) diff --git a/internal/projects/delete/delete.go b/internal/projects/delete/delete.go index f042f62e1..2f4692a88 100644 --- a/internal/projects/delete/delete.go +++ b/internal/projects/delete/delete.go @@ -46,7 +46,7 @@ func Run(ctx context.Context, ref string, fsys afero.Fs) error { if err := credentials.StoreProvider.Delete(ref); err != nil && !errors.Is(err, keyring.ErrNotFound) { fmt.Fprintln(os.Stderr, err) } - if match, err := afero.FileContainsBytes(fsys, utils.ProjectRefPath, []byte(ref)); match { + if match, err := afero.FileContainsBytes(fsys, utils.Paths.ProjectRefPath, []byte(ref)); match { if err := unlink.Unlink(ref, fsys); err != nil { fmt.Fprintln(os.Stderr, err) } diff --git a/internal/projects/delete/delete_test.go b/internal/projects/delete/delete_test.go index b83d4cf8c..36c9af278 100644 --- a/internal/projects/delete/delete_test.go +++ b/internal/projects/delete/delete_test.go @@ -27,7 +27,7 @@ func TestDeleteCommand(t *testing.T) { t.Run("deletes project", func(t *testing.T) { // 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.Paths.ProjectRefPath, []byte(ref), 0644)) // Setup api mock defer gock.OffAll() gock.New(utils.DefaultApiHost). diff --git a/internal/seed/buckets/buckets.go b/internal/seed/buckets/buckets.go index b922e63d8..242bad21a 100644 --- a/internal/seed/buckets/buckets.go +++ b/internal/seed/buckets/buckets.go @@ -31,7 +31,7 @@ func Run(ctx context.Context, projectRef string, interactive bool, fsys afero.Fs return err } prune := func(name string) bool { - label := fmt.Sprintf("Bucket %s not found in %s. Do you want to prune it?", utils.Bold(name), utils.Bold(utils.ConfigPath)) + label := fmt.Sprintf("Bucket %s not found in %s. Do you want to prune it?", utils.Bold(name), utils.Bold(utils.Paths.ConfigPath)) shouldPrune, err := console.PromptYesNo(ctx, label, false) if err != nil { fmt.Fprintln(utils.GetDebugLogger(), err) diff --git a/internal/seed/buckets/buckets_test.go b/internal/seed/buckets/buckets_test.go index 7194f390b..dcb933a48 100644 --- a/internal/seed/buckets/buckets_test.go +++ b/internal/seed/buckets/buckets_test.go @@ -27,7 +27,7 @@ public = false` require.NoError(t, toml.Unmarshal([]byte(config), &utils.Config.Storage.Buckets)) // Setup in-memory fs fsys := afero.NewMemMapFs() - bucketPath := filepath.Join(utils.SupabaseDirPath, "images") + bucketPath := filepath.Join(utils.Paths.SupabaseDirPath, "images") require.NoError(t, fsys.Mkdir(bucketPath, 0755)) // Setup mock api defer gock.OffAll() diff --git a/internal/start/start.go b/internal/start/start.go index c35efa2e3..f10f8afad 100644 --- a/internal/start/start.go +++ b/internal/start/start.go @@ -1147,7 +1147,7 @@ EOF } // Mount snippets directory for Studio to access - hostSnippetsPath := filepath.Join(workdir, utils.SnippetsDir) + hostSnippetsPath := filepath.Join(workdir, utils.Paths.SnippetsDir) containerSnippetsPath := utils.ToDockerPath(hostSnippetsPath) binds = append(binds, fmt.Sprintf("%s:%s:rw", hostSnippetsPath, containerSnippetsPath)) binds = utils.RemoveDuplicates(binds) @@ -1169,7 +1169,7 @@ EOF fmt.Sprintf("LOGFLARE_URL=http://%v:4000", utils.LogflareId), fmt.Sprintf("NEXT_PUBLIC_ENABLE_LOGS=%v", utils.Config.Analytics.Enabled), fmt.Sprintf("NEXT_ANALYTICS_BACKEND_PROVIDER=%v", utils.Config.Analytics.Backend), - "EDGE_FUNCTIONS_MANAGEMENT_FOLDER=" + utils.ToDockerPath(filepath.Join(workdir, utils.FunctionsDir)), + "EDGE_FUNCTIONS_MANAGEMENT_FOLDER=" + utils.ToDockerPath(filepath.Join(workdir, utils.Paths.FunctionsDir)), "SNIPPETS_MANAGEMENT_FOLDER=" + containerSnippetsPath, // Ref: https://github.com/vercel/next.js/issues/51684#issuecomment-1612834913 "HOSTNAME=0.0.0.0", diff --git a/internal/start/start_test.go b/internal/start/start_test.go index bec6da5cf..5b15bbcdc 100644 --- a/internal/start/start_test.go +++ b/internal/start/start_test.go @@ -29,7 +29,7 @@ func TestStartCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), fsys, []string{}, false) // Check error diff --git a/internal/status/status_test.go b/internal/status/status_test.go index c7bfc1bc4..73829ed14 100644 --- a/internal/status/status_test.go +++ b/internal/status/status_test.go @@ -51,7 +51,7 @@ func TestStatusCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), CustomName{}, utils.OutputPretty, fsys) // Check error diff --git a/internal/stop/stop_test.go b/internal/stop/stop_test.go index e39fdd722..4da892450 100644 --- a/internal/stop/stop_test.go +++ b/internal/stop/stop_test.go @@ -136,7 +136,7 @@ func TestStopCommand(t *testing.T) { t.Run("throws error on malformed config", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ConfigPath, []byte("malformed"), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ConfigPath, []byte("malformed"), 0644)) // Run test err := Run(context.Background(), false, "", false, fsys) // Check error diff --git a/internal/test/new/new.go b/internal/test/new/new.go index 506a9e02e..a06ea956c 100644 --- a/internal/test/new/new.go +++ b/internal/test/new/new.go @@ -21,7 +21,7 @@ var ( ) func Run(ctx context.Context, name, template string, fsys afero.Fs) error { - path := filepath.Join(utils.DbTestsDir, fmt.Sprintf("%s_test.sql", name)) + path := filepath.Join(utils.Paths.DbTestsDir, fmt.Sprintf("%s_test.sql", name)) if _, err := fsys.Stat(path); err == nil { return errors.New(path + " already exists.") } diff --git a/internal/test/new/new_test.go b/internal/test/new/new_test.go index d3f980157..305799658 100644 --- a/internal/test/new/new_test.go +++ b/internal/test/new/new_test.go @@ -19,7 +19,7 @@ func TestCreatePgTAP(t *testing.T) { err := Run(context.Background(), "pet", TemplatePgTAP, fsys) // Check error assert.NoError(t, err) - f, err := fsys.Stat(filepath.Join(utils.DbTestsDir, "pet_test.sql")) + f, err := fsys.Stat(filepath.Join(utils.Paths.DbTestsDir, "pet_test.sql")) assert.NoError(t, err) assert.EqualValues(t, len(pgtapTest), f.Size()) }) @@ -36,7 +36,7 @@ func TestCreatePgTAP(t *testing.T) { t.Run("throws error on file exists", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - _, err := fsys.Create(filepath.Join(utils.DbTestsDir, "pet_test.sql")) + _, err := fsys.Create(filepath.Join(utils.Paths.DbTestsDir, "pet_test.sql")) require.NoError(t, err) // Run test err = Run(context.Background(), "pet", TemplatePgTAP, fsys) diff --git a/internal/unlink/unlink.go b/internal/unlink/unlink.go index b59f4d1f0..e25346c0e 100644 --- a/internal/unlink/unlink.go +++ b/internal/unlink/unlink.go @@ -13,7 +13,7 @@ import ( ) func Run(ctx context.Context, fsys afero.Fs) error { - if projectRef, err := afero.ReadFile(fsys, utils.ProjectRefPath); errors.Is(err, os.ErrNotExist) { + if projectRef, err := afero.ReadFile(fsys, utils.Paths.ProjectRefPath); errors.Is(err, os.ErrNotExist) { return errors.New(utils.ErrNotLinked) } else if err != nil { return errors.Errorf("failed to load project ref: %w", err) @@ -28,7 +28,7 @@ func Unlink(projectRef string, fsys afero.Fs) error { fmt.Fprintln(os.Stderr, "Unlinking project:", projectRef) var allErrors []error // Remove temp directory - if err := fsys.RemoveAll(utils.TempDir); err != nil { + if err := fsys.RemoveAll(utils.Paths.TempDir); err != nil { wrapped := errors.Errorf("failed to remove temp directory: %w", err) allErrors = append(allErrors, wrapped) } diff --git a/internal/unlink/unlink_test.go b/internal/unlink/unlink_test.go index 9b526e109..a6343a7d4 100644 --- a/internal/unlink/unlink_test.go +++ b/internal/unlink/unlink_test.go @@ -21,7 +21,7 @@ func TestUnlinkCommand(t *testing.T) { t.Run("unlinks project", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(project), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(project), 0644)) // Save database password require.NoError(t, credentials.StoreProvider.Set(project, "test")) // Run test @@ -29,7 +29,7 @@ func TestUnlinkCommand(t *testing.T) { // Check error assert.NoError(t, err) // Validate file does not exist - exists, err := afero.Exists(fsys, utils.ProjectRefPath) + exists, err := afero.Exists(fsys, utils.Paths.ProjectRefPath) assert.NoError(t, err) assert.False(t, exists) // Check credentials does not exist @@ -40,7 +40,7 @@ func TestUnlinkCommand(t *testing.T) { t.Run("unlinks project without credentials", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(project), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(project), 0644)) // Run test err := Run(context.Background(), fsys) // Check error @@ -59,7 +59,7 @@ func TestUnlinkCommand(t *testing.T) { t.Run("throws error on permission denied", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - require.NoError(t, afero.WriteFile(fsys, utils.ProjectRefPath, []byte(project), 0644)) + require.NoError(t, afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(project), 0644)) // Run test err := Run(context.Background(), afero.NewReadOnlyFs(fsys)) // Check error diff --git a/internal/utils/config.go b/internal/utils/config.go index 108c3391a..e0bdd877a 100644 --- a/internal/utils/config.go +++ b/internal/utils/config.go @@ -226,7 +226,7 @@ func InitConfig(params InitParams, fsys afero.Fs) error { c.Experimental.OrioleDBVersion = "15.1.0.150" } // Create config file - if err := MkdirIfNotExistFS(fsys, SupabaseDirPath); err != nil { + if err := MkdirIfNotExistFS(fsys, Paths.SupabaseDirPath); err != nil { return err } flag := os.O_WRONLY | os.O_CREATE @@ -235,7 +235,7 @@ func InitConfig(params InitParams, fsys afero.Fs) error { } else { flag |= os.O_EXCL } - f, err := fsys.OpenFile(ConfigPath, flag, 0644) + f, err := fsys.OpenFile(Paths.ConfigPath, flag, 0644) if err != nil { return errors.Errorf("failed to create config file: %w", err) } diff --git a/internal/utils/config_test.go b/internal/utils/config_test.go index 9ac835170..45d35c1e3 100644 --- a/internal/utils/config_test.go +++ b/internal/utils/config_test.go @@ -67,7 +67,7 @@ func TestInitConfig(t *testing.T) { err := InitConfig(params, fsys) assert.NoError(t, err) - exists, err := afero.Exists(fsys, ConfigPath) + exists, err := afero.Exists(fsys, Paths.ConfigPath) assert.NoError(t, err) assert.True(t, exists) }) @@ -82,14 +82,14 @@ func TestInitConfig(t *testing.T) { err := InitConfig(params, fsys) assert.NoError(t, err) - content, err := afero.ReadFile(fsys, ConfigPath) + content, err := afero.ReadFile(fsys, Paths.ConfigPath) assert.NoError(t, err) assert.Contains(t, string(content), "15.1.0.150") }) t.Run("fails if config exists and no overwrite", func(t *testing.T) { fsys := afero.NewMemMapFs() - err := afero.WriteFile(fsys, ConfigPath, []byte("existing"), 0644) + err := afero.WriteFile(fsys, Paths.ConfigPath, []byte("existing"), 0644) require.NoError(t, err) params := InitParams{ ProjectId: "test-project", @@ -102,7 +102,7 @@ func TestInitConfig(t *testing.T) { t.Run("overwrites existing config when specified", func(t *testing.T) { fsys := afero.NewMemMapFs() - err := afero.WriteFile(fsys, ConfigPath, []byte("existing"), 0644) + err := afero.WriteFile(fsys, Paths.ConfigPath, []byte("existing"), 0644) require.NoError(t, err) params := InitParams{ ProjectId: "test-project", @@ -112,7 +112,7 @@ func TestInitConfig(t *testing.T) { err = InitConfig(params, fsys) assert.NoError(t, err) - content, err := afero.ReadFile(fsys, ConfigPath) + content, err := afero.ReadFile(fsys, Paths.ConfigPath) assert.NoError(t, err) assert.NotEqual(t, "existing", string(content)) }) diff --git a/internal/utils/docker.go b/internal/utils/docker.go index 6da0d5aa6..65df7465f 100644 --- a/internal/utils/docker.go +++ b/internal/utils/docker.go @@ -322,7 +322,7 @@ func DockerStart(ctx context.Context, config container.Config, hostConfig contai if endpoint, ok := networkingConfig.EndpointsConfig[NetId]; ok && len(endpoint.Aliases) > 0 { name = endpoint.Aliases[0] } - CmdSuggestion += fmt.Sprintf("\n%s a different %s port in %s", prefix, name, Bold(ConfigPath)) + CmdSuggestion += fmt.Sprintf("\n%s a different %s port in %s", prefix, name, Bold(Paths.ConfigPath)) } err = errors.Errorf("failed to start docker container: %w", err) } diff --git a/internal/utils/flags/config_path.go b/internal/utils/flags/config_path.go index 4df1bff74..f07fb9dfc 100644 --- a/internal/utils/flags/config_path.go +++ b/internal/utils/flags/config_path.go @@ -9,7 +9,12 @@ import ( func LoadConfig(fsys afero.Fs) error { utils.Config.ProjectId = ProjectRef - if err := utils.Config.Load("", utils.NewRootFS(fsys)); err != nil { + paths, err := utils.ResolveProjectPaths(fsys) + if err != nil { + return err + } + utils.Paths = paths + if err := utils.Config.Load(paths.ConfigPath, utils.NewRootFS(fsys)); err != nil { return err } utils.UpdateDockerIds() diff --git a/internal/utils/flags/db_url_test.go b/internal/utils/flags/db_url_test.go index c79c7f936..fab58b2a5 100644 --- a/internal/utils/flags/db_url_test.go +++ b/internal/utils/flags/db_url_test.go @@ -70,11 +70,11 @@ func TestParseDatabaseConfig(t *testing.T) { fsys := afero.NewMemMapFs() project := apitest.RandomProjectRef() - err = afero.WriteFile(fsys, utils.ProjectRefPath, []byte(project), 0644) + err = afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(project), 0644) require.NoError(t, err) dbURL := fmt.Sprintf("postgres://postgres:postgres@db.%s.supabase.co:6543/postgres", project) - err = afero.WriteFile(fsys, utils.PoolerUrlPath, []byte(dbURL), 0644) + err = afero.WriteFile(fsys, utils.Paths.PoolerUrlPath, []byte(dbURL), 0644) require.NoError(t, err) viper.Set("DB_PASSWORD", "test") diff --git a/internal/utils/flags/project_ref.go b/internal/utils/flags/project_ref.go index fab292001..d538d60e3 100644 --- a/internal/utils/flags/project_ref.go +++ b/internal/utils/flags/project_ref.go @@ -64,8 +64,8 @@ func LoadProjectRef(fsys afero.Fs) error { return utils.AssertProjectRefIsValid(ProjectRef) } // Load from local file last - projectRefBytes, err := afero.ReadFile(fsys, utils.ProjectRefPath) - fmt.Fprintf(debuglogger, "Loading project ref from file: %s\n", utils.ProjectRefPath) + projectRefBytes, err := afero.ReadFile(fsys, utils.Paths.ProjectRefPath) + fmt.Fprintf(debuglogger, "Loading project ref from file: %s\n", utils.Paths.ProjectRefPath) if errors.Is(err, os.ErrNotExist) { return errors.New(utils.ErrNotLinked) } else if err != nil { diff --git a/internal/utils/flags/project_ref_test.go b/internal/utils/flags/project_ref_test.go index 5c4fc88c7..abefdb3c8 100644 --- a/internal/utils/flags/project_ref_test.go +++ b/internal/utils/flags/project_ref_test.go @@ -36,7 +36,7 @@ func TestProjectRef(t *testing.T) { fsys := afero.NewMemMapFs() // Setup valid project ref project := apitest.RandomProjectRef() - err := afero.WriteFile(fsys, utils.ProjectRefPath, []byte(project), 0644) + err := afero.WriteFile(fsys, utils.Paths.ProjectRefPath, []byte(project), 0644) require.NoError(t, err) // Run test err = ParseProjectRef(context.Background(), fsys) @@ -47,7 +47,7 @@ func TestProjectRef(t *testing.T) { t.Run("throws error on read failure", func(t *testing.T) { ProjectRef = "" // Setup in-memory fs - fsys := &fstest.OpenErrorFs{DenyPath: utils.ProjectRefPath} + fsys := &fstest.OpenErrorFs{DenyPath: utils.Paths.ProjectRefPath} // Run test err := ParseProjectRef(context.Background(), fsys) // Check error diff --git a/internal/utils/misc.go b/internal/utils/misc.go index b7e6315ff..13c2d3723 100644 --- a/internal/utils/misc.go +++ b/internal/utils/misc.go @@ -58,35 +58,6 @@ var ( PgSchemas = migration.InternalSchemas[:2] InternalSchemas = migration.InternalSchemas - 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") - StorageMigrationPath = filepath.Join(TempDir, "storage-migration") - 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") - ProfilePath = filepath.Join(TempDir, "profile") - CurrBranchPath = filepath.Join(SupabaseDirPath, ".branches", "_current_branch") - ClusterDir = filepath.Join(SupabaseDirPath, "cluster") - SchemasDir = filepath.Join(SupabaseDirPath, "schemas") - MigrationsDir = filepath.Join(SupabaseDirPath, "migrations") - FunctionsDir = filepath.Join(SupabaseDirPath, "functions") - SnippetsDir = filepath.Join(SupabaseDirPath, "snippets") - 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_-]*$)") @@ -99,7 +70,7 @@ func GetCurrentTimestamp() string { } func GetCurrentBranchFS(fsys afero.Fs) (string, error) { - branch, err := afero.ReadFile(fsys, CurrBranchPath) + branch, err := afero.ReadFile(fsys, Paths.CurrBranchPath) if err != nil { return "", errors.Errorf("failed to load current branch: %w", err) } @@ -148,18 +119,24 @@ func IsGitIgnored(fp ...string) (bool, error) { return m.Match(fp, false), nil } +func isSupabaseProjectRoot(cwd string, fsys afero.Fs) bool { + if ok, err := afero.Exists(fsys, filepath.Join(cwd, "supabase", "config.toml")); ok && err == nil { + return true + } + if ok, err := afero.Exists(fsys, filepath.Join(cwd, "config.toml")); ok && err == nil { + return true + } + return false +} + // 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 getProjectRoot(absPath string, fsys afero.Fs) string { for cwd := absPath; ; cwd = filepath.Dir(cwd) { - path := filepath.Join(cwd, ConfigPath) // Treat all errors as file not exists - if isSupaProj, err := afero.Exists(fsys, path); isSupaProj { + if isSupabaseProjectRoot(cwd, fsys) { return cwd - } else if err != nil && !errors.Is(err, os.ErrNotExist) { - logger := GetDebugLogger() - fmt.Fprintln(logger, err) } if isRootDirectory(cwd) { break diff --git a/internal/utils/misc_test.go b/internal/utils/misc_test.go index b12d68c78..e085695e6 100644 --- a/internal/utils/misc_test.go +++ b/internal/utils/misc_test.go @@ -30,7 +30,7 @@ func TestProjectRoot(t *testing.T) { t.Run("stops at root dir", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - _, err := fsys.Create(filepath.Join(root, ConfigPath)) + _, err := fsys.Create(filepath.Join(root, Paths.ConfigPath)) require.NoError(t, err) // Run test cwd := filepath.Join(root, "home", "user", "project") @@ -42,7 +42,7 @@ func TestProjectRoot(t *testing.T) { t.Run("stops at closest parent", func(t *testing.T) { // Setup in-memory fs fsys := afero.NewMemMapFs() - _, err := fsys.Create(filepath.Join(root, "supabase", ConfigPath)) + _, err := fsys.Create(filepath.Join(root, "supabase", Paths.ConfigPath)) require.NoError(t, err) // Run test cwd := filepath.Join(root, "supabase", "supabase", "functions") diff --git a/internal/utils/paths.go b/internal/utils/paths.go new file mode 100644 index 000000000..582f57b2e --- /dev/null +++ b/internal/utils/paths.go @@ -0,0 +1,92 @@ +package utils + +import ( + "path/filepath" + + "github.com/spf13/afero" +) + +type ProjectPaths struct { + SupabaseDirPath string + ConfigPath string + GitIgnorePath string + TempDir string + ImportMapsDir string + ProjectRefPath string + PoolerUrlPath string + PostgresVersionPath string + GotrueVersionPath string + RestVersionPath string + StorageVersionPath string + StorageMigrationPath string + StudioVersionPath string + PgmetaVersionPath string + PoolerVersionPath string + RealtimeVersionPath string + CliVersionPath string + ProfilePath string + CurrBranchPath string + ClusterDir string + SchemasDir string + MigrationsDir string + FunctionsDir string + SnippetsDir string + FallbackImportMapPath string + FallbackEnvFilePath string + DbTestsDir string + CustomRolesPath string +} + +var Paths = DefaultPaths("supabase") + +func DefaultPaths(base string) ProjectPaths { + if len(base) == 0 { + base = "supabase" + } + tempDir := filepath.Join(base, ".temp") + functionsDir := filepath.Join(base, "functions") + return ProjectPaths{ + SupabaseDirPath: base, + ConfigPath: filepath.Join(base, "config.toml"), + GitIgnorePath: filepath.Join(base, ".gitignore"), + TempDir: tempDir, + 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"), + StorageMigrationPath: filepath.Join(tempDir, "storage-migration"), + 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"), + ProfilePath: filepath.Join(tempDir, "profile"), + CurrBranchPath: filepath.Join(base, ".branches", "_current_branch"), + ClusterDir: filepath.Join(base, "cluster"), + SchemasDir: filepath.Join(base, "schemas"), + MigrationsDir: filepath.Join(base, "migrations"), + FunctionsDir: functionsDir, + SnippetsDir: filepath.Join(base, "snippets"), + FallbackImportMapPath: filepath.Join(functionsDir, "import_map.json"), + FallbackEnvFilePath: filepath.Join(functionsDir, ".env"), + DbTestsDir: filepath.Join(base, "tests"), + CustomRolesPath: filepath.Join(base, "roles.sql"), + } +} + +func ResolveProjectPaths(fsys afero.Fs) (ProjectPaths, error) { + if ok, err := afero.Exists(fsys, filepath.Join("supabase", "config.toml")); err != nil { + return ProjectPaths{}, err + } else if ok { + return DefaultPaths("supabase"), nil + } + if ok, err := afero.Exists(fsys, "config.toml"); err != nil { + return ProjectPaths{}, err + } else if ok { + return DefaultPaths("."), nil + } + return DefaultPaths("supabase"), nil +} diff --git a/internal/utils/profile.go b/internal/utils/profile.go index 723b52fa8..04ebb7640 100644 --- a/internal/utils/profile.go +++ b/internal/utils/profile.go @@ -121,8 +121,8 @@ func getProfileName(fsys afero.Fs) string { if prof := viper.GetString("PROFILE"); viper.IsSet("PROFILE") { fmt.Fprintln(debuglogger, "Loading profile from flag:", prof) return prof - } else if content, err := afero.ReadFile(fsys, ProfilePath); err == nil { - fmt.Fprintln(debuglogger, "Loading profile from file:", ProfilePath) + } else if content, err := afero.ReadFile(fsys, Paths.ProfilePath); err == nil { + fmt.Fprintln(debuglogger, "Loading profile from file:", Paths.ProfilePath) return string(content) } else { fmt.Fprintln(debuglogger, err)