From 03da33fad5f6034c0899f70e1d024811d672a3c6 Mon Sep 17 00:00:00 2001 From: Paul Rhodes Date: Fri, 17 Jan 2025 16:37:18 +0000 Subject: [PATCH] Initial routine changes to use config/GetCorectl... functions --- pkg/application/create_test.go | 27 +++--- pkg/cmd/application/create/app_create.go | 21 ++--- pkg/cmd/config/init/config_init.go | 47 ++-------- pkg/cmd/env/active.go | 9 +- pkg/cmd/env/connect.go | 9 +- pkg/cmd/env/disconnect.go | 9 +- pkg/cmd/env/list.go | 20 ++--- pkg/cmd/env/open.go | 10 +-- pkg/cmd/p2p/env/sync/env_sync.go | 9 +- pkg/cmd/p2p/export/export.go | 3 +- pkg/cmd/p2p/export/export_test.go | 87 +++++++------------ .../template/describe/template_describe.go | 3 +- pkg/cmd/template/list/template_list.go | 8 +- .../template/render/template_render_test.go | 40 +++------ pkg/cmd/tenant/addrepo/tenant_add_repo.go | 6 +- pkg/cmd/tenant/create/tenant_create.go | 11 +-- pkg/cmd/tenant/describe/tenant_describe.go | 4 +- pkg/cmd/tenant/list/tenant_list.go | 4 +- pkg/cmd/tenant/tree/tenant_tree.go | 4 +- pkg/cmdutil/config/config.go | 9 +- pkg/cmdutil/config/update.go | 4 +- pkg/cmdutil/configpath/configpath.go | 48 ++++++++++ pkg/cmdutil/selector/input.go | 7 +- pkg/cmdutil/selector/input_test.go | 18 ++-- pkg/logger/logger.go | 10 +-- pkg/tenant/write.go | 3 +- pkg/tenant/write_test.go | 9 +- pkg/testutil/gittest/bare_repo.go | 15 ++++ .../cplatform}/environments/dev/config.yaml | 0 .../cplatform/environments/environments.yaml | 3 + .../cplatform}/environments/prod/config.yaml | 0 .../tenants/tenants/default-tenant.yaml | 0 .../cplatform}/tenants/tenants/parent.yaml | 0 .../.github/workflows/extended-test.yaml | 0 .../.github/workflows/fast-feedback.yaml | 0 .../templates}/blank/skeleton/README.md | 0 .../templates}/blank/template.yaml | 0 .../templates}/go/web/skeleton/README.md | 0 .../templates}/go/web/template.yaml | 0 .../templates}/monorepo/README.md | 0 .../templates}/with-args/skeleton/args.txt | 0 .../templates}/with-args/template.yaml | 0 testdata/testdata.go | 4 +- tests/integration/application/application.go | 4 +- tests/integration/config/config.go | 44 ++++------ tests/integration/env/connect.go | 2 + tests/integration/p2p/export.go | 4 +- tests/integration/p2p/p2p.go | 4 +- tests/integration/tenant/tenant.go | 2 + .../integration/testconfig/corectl_client.go | 6 -- tests/integration/testsetup/config_init.go | 7 +- 51 files changed, 244 insertions(+), 290 deletions(-) create mode 100644 pkg/cmdutil/configpath/configpath.go rename testdata/{cplatform-environments => repositories/cplatform}/environments/dev/config.yaml (100%) create mode 100644 testdata/repositories/cplatform/environments/environments.yaml rename testdata/{cplatform-environments => repositories/cplatform}/environments/prod/config.yaml (100%) rename testdata/{cplatform-environments => repositories/cplatform}/tenants/tenants/default-tenant.yaml (100%) rename testdata/{cplatform-environments => repositories/cplatform}/tenants/tenants/parent.yaml (100%) rename testdata/{software-templates => repositories/templates}/blank/skeleton/.github/workflows/extended-test.yaml (100%) rename testdata/{software-templates => repositories/templates}/blank/skeleton/.github/workflows/fast-feedback.yaml (100%) rename testdata/{software-templates => repositories/templates}/blank/skeleton/README.md (100%) rename testdata/{software-templates => repositories/templates}/blank/template.yaml (100%) rename testdata/{software-templates => repositories/templates}/go/web/skeleton/README.md (100%) rename testdata/{software-templates => repositories/templates}/go/web/template.yaml (100%) rename testdata/{software-templates => repositories/templates}/monorepo/README.md (100%) rename testdata/{software-templates => repositories/templates}/with-args/skeleton/args.txt (100%) rename testdata/{software-templates => repositories/templates}/with-args/template.yaml (100%) diff --git a/pkg/application/create_test.go b/pkg/application/create_test.go index 7ef4035f..77303077 100644 --- a/pkg/application/create_test.go +++ b/pkg/application/create_test.go @@ -2,14 +2,15 @@ package application import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" + "github.com/stretchr/testify/assert" "os" "path/filepath" "slices" - "github.com/coreeng/corectl/pkg/cmd/template/render" - "github.com/coreeng/core-platform/pkg/environment" coretnt "github.com/coreeng/core-platform/pkg/tenant" + "github.com/coreeng/corectl/pkg/cmd/template/render" "github.com/coreeng/corectl/pkg/git" "github.com/coreeng/corectl/pkg/template" "github.com/coreeng/corectl/pkg/testutil/gittest" @@ -26,9 +27,7 @@ var _ = Describe("Create new application", func() { var ( cplatformServerRepo *gittest.BareRepository - cplatformLocalRepo *git.LocalRepository templatesServerRepo *gittest.BareRepository - templatesLocalRepo *git.LocalRepository newAppServerRepo *gittest.BareRepository newRepoId int64 @@ -53,27 +52,29 @@ var _ = Describe("Create new application", func() { githubOrg = "github-org-name" var err error - cplatformServerRepo, cplatformLocalRepo, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ + _, err = gittest.CreateTestCorectlConfig(t.TempDir()) + assert.NoError(t, err) + cplatformServerRepo, _, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: testdata.CPlatformEnvsPath(), TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlCPlatformDir(), }) Expect(err).NotTo(HaveOccurred()) - templatesServerRepo, templatesLocalRepo, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ + templatesServerRepo, _, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: testdata.TemplatesPath(), TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlTemplatesDir(), }) Expect(err).NotTo(HaveOccurred()) newAppServerRepo, err = gittest.InitBareRepository(t.TempDir()) Expect(err).NotTo(HaveOccurred()) - defaultTenant, err = coretnt.FindByName(coretnt.DirFromCPlatformPath(cplatformLocalRepo.Path()), testdata.DefaultTenant()) + defaultTenant, err = coretnt.FindByName(configpath.GetCorectlCPlatformDir("tenants"), testdata.DefaultTenant()) Expect(err).NotTo(HaveOccurred()) - allEnvs, err := environment.List(environment.DirFromCPlatformRepoPath(cplatformLocalRepo.Path())) + allEnvs, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) Expect(err).NotTo(HaveOccurred()) devEnvIdx := slices.IndexFunc(allEnvs, func(e environment.Environment) bool { return e.Environment == testdata.DevEnvironment() @@ -133,7 +134,7 @@ var _ = Describe("Create new application", func() { Renderer: &render.FlagsAwareTemplateRenderer{}, } service = NewService(renderer, githubClient, false) - templateToUse, err := template.FindByName(templatesLocalRepo.Path(), testdata.BlankTemplate()) + templateToUse, err := template.FindByName(configpath.GetCorectlTemplatesDir(), testdata.BlankTemplate()) Expect(err).NotTo(HaveOccurred()) localAppRepoDir = t.TempDir() @@ -348,7 +349,7 @@ var _ = Describe("Create new application", func() { }) Expect(err).NotTo(HaveOccurred()) - templateToUse, err := template.FindByName(templatesLocalRepo.Path(), testdata.BlankTemplate()) + templateToUse, err := template.FindByName(configpath.GetCorectlTemplatesDir(), testdata.BlankTemplate()) Expect(err).NotTo(HaveOccurred()) Expect(templateToUse).NotTo(BeNil()) @@ -507,7 +508,7 @@ var _ = Describe("Create new application", func() { }) Expect(err).NotTo(HaveOccurred()) - templateToUse, _ := template.FindByName(templatesLocalRepo.Path(), testdata.BlankTemplate()) + templateToUse, _ := template.FindByName(configpath.GetCorectlTemplatesDir(), testdata.BlankTemplate()) monorepoLocalPath = monorepoLocalRepo.Path() newAppLocalPath = filepath.Join(monorepoLocalRepo.Path(), "app-with-error") diff --git a/pkg/cmd/application/create/app_create.go b/pkg/cmd/application/create/app_create.go index 9e69e27b..157094a9 100644 --- a/pkg/cmd/application/create/app_create.go +++ b/pkg/cmd/application/create/app_create.go @@ -3,6 +3,7 @@ package create import ( "errors" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" "slices" @@ -128,14 +129,6 @@ NOTE: &cfg.GitHub.Organization, appCreateCmd.Flags(), ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - appCreateCmd.Flags(), - ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.Templates, - appCreateCmd.Flags(), - ) return appCreateCmd, nil } @@ -171,7 +164,7 @@ func run(opts *AppCreateOpt, cfg *config.Config) error { logger.Info().Msg(msg) - existingTemplates, err := template.List(cfg.Repositories.Templates.Value) + existingTemplates, err := template.List(configpath.GetCorectlTemplatesDir()) if err != nil { return err } @@ -187,13 +180,13 @@ func run(opts *AppCreateOpt, cfg *config.Config) error { return err } - appTenant, err := selector.Tenant(cfg.Repositories.CPlatform.Value, opts.Tenant, opts.Streams) + appTenant, err := selector.Tenant(configpath.GetCorectlCPlatformDir("tenants"), opts.Tenant, opts.Streams) if err != nil { return err } logger.Info().Msgf("tenant selected: %s", appTenant.Name) - existingEnvs, err := environment.List(environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value)) + existingEnvs, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) if err != nil { return err } @@ -352,8 +345,8 @@ func createPRWithUpdatedReposListForTenant( appTenant *coretnt.Tenant, createdAppResult application.CreateResult, ) (*tenant.CreateOrUpdateResult, error) { - logger.Warn().Msgf("Creating PR with new application %s for tenant %s in platform repo %s", - opts.Name, opts.Tenant, cfg.Repositories.CPlatform.Value) + logger.Warn().Msgf("Creating PR with new application %s for tenant %s in platform repo", + opts.Name, opts.Tenant) if err := appTenant.AddRepository(createdAppResult.RepositoryFullname.HttpUrl()); err != nil && errors.Is(err, coretnt.ErrRepositoryAlreadyPresent) { logger.Warn().Msgf("Application is already registered for tenant. Skipping.") @@ -368,7 +361,7 @@ func createPRWithUpdatedReposListForTenant( tenantUpdateResult, err := tenant.CreateOrUpdate( &tenant.CreateOrUpdateOp{ Tenant: appTenant, - CplatformRepoPath: cfg.Repositories.CPlatform.Value, + CplatformRepoPath: configpath.GetCorectlCPlatformDir(), BranchName: fmt.Sprintf("%s-add-repo-%s", appTenant.Name, createdAppResult.RepositoryFullname.Name()), CommitMessage: fmt.Sprintf("Add new repository %s for tenant %s", createdAppResult.RepositoryFullname.Name(), appTenant.Name), PRName: fmt.Sprintf("Add new repository %s for tenant %s", createdAppResult.RepositoryFullname.Name(), appTenant.Name), diff --git a/pkg/cmd/config/init/config_init.go b/pkg/cmd/config/init/config_init.go index 7f66d83c..35a41c2a 100644 --- a/pkg/cmd/config/init/config_init.go +++ b/pkg/cmd/config/init/config_init.go @@ -5,10 +5,9 @@ import ( "encoding/base64" "errors" "fmt" - "regexp" - + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" - "path/filepath" + "regexp" "github.com/coreeng/corectl/pkg/cmdutil/config" "github.com/coreeng/corectl/pkg/cmdutil/userio" @@ -23,7 +22,6 @@ import ( type ConfigInitOpt struct { EnvironmentsRepo string File string - RepositoriesDir string GitHubToken string GitHubOrganisation string NonInteractive bool @@ -77,18 +75,6 @@ func NewConfigInitCmd(cfg *config.Config) *cobra.Command { "", "Initialization file. This is mutually exclusive with the '--environments-repo' option.", ) - defaultRepositoriesPath, err := repositoriesPath() - if err != nil { - // We couldn't calculate the default value. That's fine, because the user could override it, it will be checked later. - defaultRepositoriesPath = "" - } - newInitCmd.Flags().StringVarP( - &opt.RepositoriesDir, - "repositories", - "r", - defaultRepositoriesPath, - "Directory to store platform local repositories. Default is near config file.", - ) newInitCmd.Flags().StringVarP( &opt.GitHubToken, "github-token", @@ -180,14 +166,7 @@ func run(cmd *cobra.Command, opt *ConfigInitOpt, cfg *config.Config) error { } githubOrgInInitFile := initC.Github.Organization - repositoriesDir := opt.RepositoriesDir - if repositoriesDir == "" { - repositoriesDir, err = repositoriesPath() - if err != nil { - return err - } - } - if err = os.MkdirAll(repositoriesDir, 0o755); err != nil { + if err = os.MkdirAll(configpath.GetCorectlCacheDir(), 0o755); err != nil { return err } @@ -204,7 +183,7 @@ func run(cmd *cobra.Command, opt *ConfigInitOpt, cfg *config.Config) error { return fmt.Errorf("failed to construct corectl config directory path: %w", err) } gitAuth := git.UrlTokenAuthMethod(githubToken) - clonedRepositories, err := cloneRepositories(opt.Streams, gitAuth, githubClient, repositoriesDir, cplatformRepoFullname, templateRepoFullname) + clonedRepositories, err := cloneRepositories(opt.Streams, gitAuth, githubClient, cplatformRepoFullname, templateRepoFullname) if err != nil { return tryAppendHint(err, configBaseDir) } @@ -223,8 +202,8 @@ func run(cmd *cobra.Command, opt *ConfigInitOpt, cfg *config.Config) error { return err } - cfg.Repositories.CPlatform.Value = clonedRepositories.cplatform.Path() - cfg.Repositories.Templates.Value = clonedRepositories.templates.Path() + cfg.Repositories.CPlatform.Value = initC.Repositories.Cplatform + cfg.Repositories.Templates.Value = initC.Repositories.Templates cfg.GitHub.Token.Value = githubToken cfg.GitHub.Organization.Value = githubOrg cfg.P2P.FastFeedback.DefaultEnvs.Value = initC.P2P.FastFeedback.DefaultEnvs @@ -282,15 +261,6 @@ func fetchInitConfigFromGitHub(githubClient *github.Client, repoUrl string, repo return content, nil } -func repositoriesPath() (string, error) { - configPath, err := config.Path() - if err != nil { - return "", err - } - configPath = filepath.Dir(configPath) - return filepath.Join(configPath, "repositories"), nil -} - type cloneRepositoriesResult struct { cplatform *git.LocalRepository templates *git.LocalRepository @@ -300,7 +270,6 @@ func cloneRepositories( streams userio.IOStreams, gitAuth git.AuthMethod, githubClient *github.Client, - repositoriesDir string, cplatformRepoFullname git.RepositoryFullname, templatesRepoFullname git.RepositoryFullname, ) (cloneRepositoriesResult, error) { @@ -316,7 +285,7 @@ func cloneRepositories( } cloneOpt := git.CloneOp{ URL: cplatformGitHubRepo.GetCloneURL(), - TargetPath: filepath.Join(repositoriesDir, cplatformRepoFullname.Name()), + TargetPath: configpath.GetCorectlCPlatformDir(), Auth: gitAuth, } streams.CurrentHandler.Info(fmt.Sprintf("cloning platform repo: %s", cloneOpt.URL)) @@ -335,7 +304,7 @@ func cloneRepositories( } cloneOpt = git.CloneOp{ URL: templatesGitHubRepo.GetCloneURL(), - TargetPath: filepath.Join(repositoriesDir, templatesRepoFullname.Name()), + TargetPath: configpath.GetCorectlTemplatesDir(), Auth: gitAuth, } streams.CurrentHandler.Info(fmt.Sprintf("cloning templates: %s", cloneOpt.URL)) diff --git a/pkg/cmd/env/active.go b/pkg/cmd/env/active.go index 23937e77..23d9d751 100644 --- a/pkg/cmd/env/active.go +++ b/pkg/cmd/env/active.go @@ -2,6 +2,7 @@ package env import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/core-platform/pkg/environment" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -50,7 +51,7 @@ func activeCmd(cfg *config.Config) *cobra.Command { return fmt.Errorf("failed to update config repos: %w", err) } - availableEnvironments, err = environment.List(environment.DirFromCPlatformRepoPath(opts.RepositoryLocation)) + availableEnvironments, err = environment.List(configpath.GetCorectlCPlatformDir("environments")) if err != nil { return fmt.Errorf("unable to load environments") } @@ -90,16 +91,10 @@ func activeCmd(cfg *config.Config) *cobra.Command { "Don't print output just set the exitcode", ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - activeCmd.Flags(), - ) config.RegisterBoolParameterAsFlag( &cfg.Repositories.AllowDirty, activeCmd.Flags(), ) - opts.RepositoryLocation = cfg.Repositories.CPlatform.Value - return activeCmd } diff --git a/pkg/cmd/env/connect.go b/pkg/cmd/env/connect.go index 8ba70a80..8dbe523d 100644 --- a/pkg/cmd/env/connect.go +++ b/pkg/cmd/env/connect.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "strings" @@ -80,7 +81,7 @@ func connectCmd(cfg *config.Config) *cobra.Command { } if len(args) > 0 { - availableEnvironments, err = environment.List(environment.DirFromCPlatformRepoPath(opts.RepositoryLocation)) + availableEnvironments, err = environment.List(configpath.GetCorectlCPlatformDir("environments")) if err == nil { env, err := findEnvironmentByName(args[0], availableEnvironments) if err != nil { @@ -120,16 +121,10 @@ func connectCmd(cfg *config.Config) *cobra.Command { "Force replacement of existing connection", ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - connectCmd.Flags(), - ) config.RegisterBoolParameterAsFlag( &cfg.Repositories.AllowDirty, connectCmd.Flags(), ) - opts.RepositoryLocation = cfg.Repositories.CPlatform.Value - return connectCmd } diff --git a/pkg/cmd/env/disconnect.go b/pkg/cmd/env/disconnect.go index b2fcde99..e5a2285e 100644 --- a/pkg/cmd/env/disconnect.go +++ b/pkg/cmd/env/disconnect.go @@ -3,6 +3,7 @@ package env import ( "bytes" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "github.com/coreeng/core-platform/pkg/environment" @@ -56,7 +57,7 @@ func disconnectCmd(cfg *config.Config) *cobra.Command { return fmt.Errorf("failed to update config repos: %w", err) } - availableEnvironments, err = environment.List(environment.DirFromCPlatformRepoPath(opts.RepositoryLocation)) + availableEnvironments, err = environment.List(configpath.GetCorectlCPlatformDir("environments")) if err != nil { return fmt.Errorf("unable to load environments") } @@ -76,16 +77,10 @@ func disconnectCmd(cfg *config.Config) *cobra.Command { }, } - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - disconnectCmd.Flags(), - ) config.RegisterBoolParameterAsFlag( &cfg.Repositories.AllowDirty, disconnectCmd.Flags(), ) - opts.RepositoryLocation = cfg.Repositories.CPlatform.Value - return disconnectCmd } diff --git a/pkg/cmd/env/list.go b/pkg/cmd/env/list.go index 9a8597ca..23dd04d3 100644 --- a/pkg/cmd/env/list.go +++ b/pkg/cmd/env/list.go @@ -2,11 +2,12 @@ package env import ( "fmt" - "github.com/coreeng/core-platform/pkg/environment" "github.com/coreeng/corectl/pkg/cmdutil/config" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/corectl/pkg/cmdutil/userio" corectlenv "github.com/coreeng/corectl/pkg/env" + "github.com/coreeng/corectl/pkg/logger" "github.com/spf13/cobra" ) @@ -21,6 +22,7 @@ func listCmd(cfg *config.Config) *cobra.Command { Use: "list", Short: "List all environments", RunE: func(cmd *cobra.Command, args []string) error { + logger.Info().Msgf("Invoked with args: %+v", opts) opts.Streams = userio.NewIOStreams( cmd.InOrStdin(), cmd.OutOrStdout(), @@ -31,18 +33,6 @@ func listCmd(cfg *config.Config) *cobra.Command { }, } - listCmd.Flags().StringVarP( - &opts.RepositoryLocation, - "repository", - "r", - cfg.Repositories.CPlatform.Value, - "Repository to source environments from", - ) - - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - listCmd.Flags(), - ) config.RegisterBoolParameterAsFlag( &cfg.Repositories.AllowDirty, listCmd.Flags(), @@ -58,9 +48,9 @@ func list(opts ListOpt, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - existing, err := environment.List(environment.DirFromCPlatformRepoPath(opts.RepositoryLocation)) + existing, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) if err != nil { - return fmt.Errorf("could not find repository location %q: %w", opts.RepositoryLocation, err) + return fmt.Errorf("could not find repository location: %w", err) } table := corectlenv.NewTable(opts.Streams, false) diff --git a/pkg/cmd/env/open.go b/pkg/cmd/env/open.go index 7964d711..fe669b41 100644 --- a/pkg/cmd/env/open.go +++ b/pkg/cmd/env/open.go @@ -2,6 +2,7 @@ package env import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "strings" "github.com/coreeng/core-platform/pkg/environment" @@ -37,10 +38,6 @@ func openResource(cfg *config.Config) *cobra.Command { return run(cfg, &opts) }, } - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - cmd.Flags(), - ) config.RegisterBoolParameterAsFlag( &cfg.Repositories.AllowDirty, cmd.Flags(), @@ -55,10 +52,7 @@ func run(cfg *config.Config, opts *EnvOpenResourceOpt) error { return fmt.Errorf("failed to update config repos: %w", err) } - env, err := environment.FindByName( - environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value), - opts.Environment, - ) + env, err := environment.FindByName(configpath.GetCorectlCPlatformDir("environments"), opts.Environment) if err != nil { return err } diff --git a/pkg/cmd/p2p/env/sync/env_sync.go b/pkg/cmd/p2p/env/sync/env_sync.go index 721300c3..504a0ebb 100644 --- a/pkg/cmd/p2p/env/sync/env_sync.go +++ b/pkg/cmd/p2p/env/sync/env_sync.go @@ -3,6 +3,7 @@ package sync import ( "context" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "slices" "github.com/coreeng/core-platform/pkg/environment" @@ -49,10 +50,6 @@ func NewP2PSyncCmd(cfg *config.Config) (*cobra.Command, error) { false, "Clean existing environments", ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - syncEnvironmentsCmd.Flags()) - config.RegisterStringParameterAsFlag( &cfg.GitHub.Organization, syncEnvironmentsCmd.Flags()) @@ -79,14 +76,14 @@ func run(opts *EnvCreateOpts, cfg *config.Config) error { spinnerHandler := opts.Streams.Wizard("Configuring platform environments", "Configured platform environments") defer spinnerHandler.Done() - t, err := tenant.FindByName(tenant.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value), opts.Tenant) + t, err := tenant.FindByName(configpath.GetCorectlCPlatformDir("tenants"), opts.Tenant) if err != nil { return err } if t == nil { return fmt.Errorf("tenant not found: %s", opts.Tenant) } - environments, err := environment.List(environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value)) + environments, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) if err != nil { return err } diff --git a/pkg/cmd/p2p/export/export.go b/pkg/cmd/p2p/export/export.go index ef1d1567..66c55ef8 100644 --- a/pkg/cmd/p2p/export/export.go +++ b/pkg/cmd/p2p/export/export.go @@ -2,6 +2,7 @@ package export import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "strings" @@ -138,7 +139,7 @@ func run(opts *exportOpts, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - context, err := opts.processFlags(cfg.Repositories.CPlatform.Value, false) + context, err := opts.processFlags(configpath.GetCorectlCPlatformDir(), false) if err != nil { return err } diff --git a/pkg/cmd/p2p/export/export_test.go b/pkg/cmd/p2p/export/export_test.go index 5dc96b6d..74e328d8 100644 --- a/pkg/cmd/p2p/export/export_test.go +++ b/pkg/cmd/p2p/export/export_test.go @@ -3,6 +3,7 @@ package export import ( "bytes" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "testing" @@ -25,115 +26,93 @@ func TestMain(m *testing.M) { func TestRunExportPrintsEnvVarsToStdOut(t *testing.T) { var output, stderr bytes.Buffer - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - CPlatform: config.Parameter[string]{ - Value: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), - }, - }, - } - err := run(&exportOpts{ + _ = testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) + err = run(&exportOpts{ tenant: testdata.DefaultTenant(), environmentName: testdata.DevEnvironment(), repoPath: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), streams: userio.NewIOStreams(os.Stdin, &output, &stderr), - }, &cfg) + }, cfg) assert.NoError(t, err) assert.Contains(t, stderr.String(), "export", p2p.BaseDomain, p2p.Registry, p2p.Version, p2p.RepoPath, p2p.TenantName, p2p.Region) } func TestRunExportNonExistingAppRepo(t *testing.T) { - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - CPlatform: config.Parameter[string]{ - Value: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), - }, - }, - } + _ = testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) appRepoPath := t.TempDir() - err := run(&exportOpts{ + err = run(&exportOpts{ tenant: testdata.DefaultTenant(), environmentName: testdata.DevEnvironment(), repoPath: appRepoPath, streams: streams, - }, &cfg) + }, cfg) assert.ErrorContains(t, err, fmt.Sprintf("repository on path %s not found: repository does not exist", appRepoPath)) } func TestRunExportNonExistingTenant(t *testing.T) { tenantName := fmt.Sprintf("%s-tenant", t.Name()) - cPlatRepoPath := testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() - - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - CPlatform: config.Parameter[string]{ - Value: cPlatRepoPath, - }, - }, - } + _ = testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - err := run(&exportOpts{ + err = run(&exportOpts{ tenant: tenantName, environmentName: testdata.DevEnvironment(), repoPath: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), streams: streams, - }, &cfg) + }, cfg) - assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/tenants/tenants: tenant %s invalid: cannot find %s tenant, available tenants: [default-tenant parent root]", cPlatRepoPath, tenantName, tenantName)) + assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/tenants: tenant %s invalid: cannot find %s tenant, available tenants: [default-tenant parent root]", + configpath.GetCorectlCPlatformDir(), tenantName, tenantName)) } func TestFailureWithRootTenant(t *testing.T) { tenantName := tenant.RootName - cPlatRepoPath := testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() - - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - CPlatform: config.Parameter[string]{ - Value: cPlatRepoPath, - }, - }, - } + _ = testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - err := run(&exportOpts{ + err = run(&exportOpts{ tenant: tenantName, environmentName: testdata.DevEnvironment(), repoPath: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), streams: streams, - }, &cfg) + }, cfg) assert.ErrorContains(t, err, fmt.Sprintf("cannot connect to '%s' as that's the root tenant and cannot be used", tenant.RootName)) } func TestRunExportNonExistingEnvironment(t *testing.T) { envName := fmt.Sprintf("%s-env", t.Name()) - cPlatRepoPath := testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() - - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - CPlatform: config.Parameter[string]{ - Value: cPlatRepoPath, - }, - }, - } + _ = testLocalRepo(t, testdata.CPlatformEnvsPath()).Path() + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - err := run(&exportOpts{ + err = run(&exportOpts{ tenant: testdata.DefaultTenant(), environmentName: envName, repoPath: testLocalRepo(t, testdata.CPlatformEnvsPath()).Path(), streams: streams, - }, &cfg) + }, cfg) - assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/environments: environment %s invalid: cannot find %s environment, available envs: [dev prod]", cPlatRepoPath, envName, envName)) + assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/environments: environment %s invalid: cannot find %s environment, available envs: [dev prod]", + configpath.GetCorectlCPlatformDir(), envName, envName)) } func testLocalRepo(t *testing.T, path string) *git.LocalRepository { + corectlDir := t.TempDir() + configpath.SetCorectlHome(corectlDir) _, repo, err := gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: path, TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlCPlatformDir(), }) assert.NoError(t, err) return repo diff --git a/pkg/cmd/template/describe/template_describe.go b/pkg/cmd/template/describe/template_describe.go index ae32c320..6da8dc60 100644 --- a/pkg/cmd/template/describe/template_describe.go +++ b/pkg/cmd/template/describe/template_describe.go @@ -2,6 +2,7 @@ package describe import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -33,7 +34,7 @@ func NewTemplateDescribeCmd(cfg *config.Config) *cobra.Command { return fmt.Errorf("failed to update config repos: %w", err) } } - t, err := template.FindByName(cfg.Repositories.Templates.Value, templateName) + t, err := template.FindByName(configpath.GetCorectlTemplatesDir(), templateName) if err != nil { return err } diff --git a/pkg/cmd/template/list/template_list.go b/pkg/cmd/template/list/template_list.go index ee5a8150..3c87b114 100644 --- a/pkg/cmd/template/list/template_list.go +++ b/pkg/cmd/template/list/template_list.go @@ -2,6 +2,7 @@ package list import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -29,7 +30,7 @@ func NewTemplateListCmd(cfg *config.Config) *cobra.Command { return fmt.Errorf("failed to update config repos: %w", err) } } - ts, err := template.List(cfg.Repositories.Templates.Value) + ts, err := template.List(configpath.GetCorectlTemplatesDir()) if err != nil { return err } @@ -49,10 +50,5 @@ func NewTemplateListCmd(cfg *config.Config) *cobra.Command { "Ignore checks for uncommitted changes and branch status", ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.Templates, - templateListCmd.Flags(), - ) - return templateListCmd } diff --git a/pkg/cmd/template/render/template_render_test.go b/pkg/cmd/template/render/template_render_test.go index 48dba93c..f55bed62 100644 --- a/pkg/cmd/template/render/template_render_test.go +++ b/pkg/cmd/template/render/template_render_test.go @@ -1,6 +1,8 @@ package render import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" + "github.com/stretchr/testify/assert" "os" "path/filepath" @@ -30,10 +32,11 @@ var _ = Describe("Template Render", Ordered, func() { ) BeforeAll(func() { + _, err = gittest.CreateTestCorectlConfig(t.TempDir()) _, templatesLocalRepo, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: testdata.TemplatesPath(), TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlTemplatesDir(), }) Expect(err).NotTo(HaveOccurred()) @@ -58,16 +61,10 @@ var _ = Describe("Template Render", Ordered, func() { TemplatesPath: templatesLocalRepo.Path(), Streams: userio.NewIOStreams(os.Stdin, os.Stdout, os.Stderr), } + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - Templates: config.Parameter[string]{ - Value: templatesLocalRepo.Path(), - }, - }, - } - - err := run(opts, &cfg) + err = run(opts, cfg) Expect(err).NotTo(HaveOccurred()) renderedContent, err := os.ReadFile(filepath.Join(targetDir, ".github", "workflows", "extended-test.yaml")) @@ -85,15 +82,10 @@ var _ = Describe("Template Render", Ordered, func() { Streams: userio.NewIOStreams(os.Stdin, os.Stdout, os.Stderr), } - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - Templates: config.Parameter[string]{ - Value: templatesLocalRepo.Path(), - }, - }, - } + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - err := run(opts, &cfg) + err = run(opts, cfg) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("required argument name is missing")) }) @@ -113,16 +105,10 @@ var _ = Describe("Template Render", Ordered, func() { TemplatesPath: templatesLocalRepo.Path(), Streams: userio.NewIOStreams(os.Stdin, os.Stdout, os.Stderr), } + cfg, err := config.DiscoverConfig() + assert.NoError(t, err) - cfg := config.Config{ - Repositories: config.RepositoriesConfig{ - Templates: config.Parameter[string]{ - Value: templatesLocalRepo.Path(), - }, - }, - } - - err := run(opts, &cfg) + err = run(opts, cfg) Expect(err).NotTo(HaveOccurred()) renderedContent, err := os.ReadFile(filepath.Join(targetDir, "args.txt")) diff --git a/pkg/cmd/tenant/addrepo/tenant_add_repo.go b/pkg/cmd/tenant/addrepo/tenant_add_repo.go index 4f787d37..a530f230 100644 --- a/pkg/cmd/tenant/addrepo/tenant_add_repo.go +++ b/pkg/cmd/tenant/addrepo/tenant_add_repo.go @@ -2,6 +2,7 @@ package addrepo import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/core-platform/pkg/tenant" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -40,7 +41,6 @@ func NewTenantAddRepoCmd(cfg *config.Config) *cobra.Command { }, } - config.RegisterStringParameterAsFlag(&cfg.Repositories.CPlatform, tenantAddRepoCmd.Flags()) config.RegisterStringParameterAsFlag(&cfg.GitHub.Token, tenantAddRepoCmd.Flags()) config.RegisterBoolParameterAsFlag(&cfg.Repositories.AllowDirty, tenantAddRepoCmd.Flags()) @@ -60,7 +60,7 @@ func run(opts *TenantAddRepoOpts, cfg *config.Config) error { ) defer opts.Streams.CurrentHandler.Done() - tenantsDir := tenant.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value) + tenantsDir := configpath.GetCorectlCPlatformDir("tenants") t, err := tenant.FindByName(tenantsDir, opts.TenantName) if err != nil { return fmt.Errorf("failed to find the tenant: %w", err) @@ -88,7 +88,7 @@ func run(opts *TenantAddRepoOpts, cfg *config.Config) error { opts.Streams.CurrentHandler.Info("creating GitHub PR") result, err := corectltnt.CreateOrUpdate(&corectltnt.CreateOrUpdateOp{ Tenant: t, - CplatformRepoPath: cfg.Repositories.CPlatform.Value, + CplatformRepoPath: configpath.GetCorectlCPlatformDir(), BranchName: fmt.Sprintf("%s-add-repo-%s", t.Name, repoName.Name()), CommitMessage: fmt.Sprintf("Add repository %s for tenant %s", repoName.Name(), t.Name), PRName: fmt.Sprintf("Add repository %s for tenant %s", repoName.Name(), t.Name), diff --git a/pkg/cmd/tenant/create/tenant_create.go b/pkg/cmd/tenant/create/tenant_create.go index 78f2fe72..184c14c8 100644 --- a/pkg/cmd/tenant/create/tenant_create.go +++ b/pkg/cmd/tenant/create/tenant_create.go @@ -3,6 +3,7 @@ package create import ( "errors" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" "slices" @@ -117,10 +118,6 @@ func NewTenantCreateCmd(cfg *config.Config) *cobra.Command { "Dry run", ) - config.RegisterStringParameterAsFlag( - &cfg.Repositories.CPlatform, - tenantCreateCmd.Flags(), - ) config.RegisterStringParameterAsFlag( &cfg.GitHub.Token, tenantCreateCmd.Flags(), @@ -140,14 +137,14 @@ func run(opt *TenantCreateOpt, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - tenantsPath := coretnt.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value) + tenantsPath := configpath.GetCorectlCPlatformDir("tenants") existingTenants, err := coretnt.List(tenantsPath) if err != nil { return err } rootTenant := coretnt.RootTenant(tenantsPath) - envsDir := environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value) + envsDir := configpath.GetCorectlCPlatformDir("environments") envFilePath := filepath.Join(envsDir, "environments.yaml") envs, err := listEnabledEnvironments(envFilePath) if err != nil { @@ -252,7 +249,7 @@ func createTenant( &tenant.CreateOrUpdateOp{ Tenant: t, ParentTenant: parentTenant, - CplatformRepoPath: cfg.Repositories.CPlatform.Value, + CplatformRepoPath: configpath.GetCorectlCPlatformDir(), BranchName: fmt.Sprintf("new-tenant-%s", t.Name), CommitMessage: fmt.Sprintf("Add new tenant: %s", t.Name), PRName: fmt.Sprintf("New tenant: %s", t.Name), diff --git a/pkg/cmd/tenant/describe/tenant_describe.go b/pkg/cmd/tenant/describe/tenant_describe.go index 390286c8..cbd9941d 100644 --- a/pkg/cmd/tenant/describe/tenant_describe.go +++ b/pkg/cmd/tenant/describe/tenant_describe.go @@ -2,6 +2,7 @@ package describe import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/core-platform/pkg/tenant" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -32,7 +33,6 @@ func NewTenantDescribeCmd(cfg *config.Config) *cobra.Command { return run(&opts, cfg) }, } - config.RegisterStringParameterAsFlag(&cfg.Repositories.CPlatform, tenantDescribeCmd.Flags()) config.RegisterBoolParameterAsFlag(&cfg.Repositories.AllowDirty, tenantDescribeCmd.Flags()) return tenantDescribeCmd } @@ -44,7 +44,7 @@ func run(opts *TenantDescribeOpts, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - t, err := tenant.FindByName(tenant.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value), opts.TenantName) + t, err := tenant.FindByName(configpath.GetCorectlCPlatformDir("tenants"), opts.TenantName) if err != nil { return fmt.Errorf("failed to find the tenant: %w", err) } diff --git a/pkg/cmd/tenant/list/tenant_list.go b/pkg/cmd/tenant/list/tenant_list.go index 465c4e24..0c3e0954 100644 --- a/pkg/cmd/tenant/list/tenant_list.go +++ b/pkg/cmd/tenant/list/tenant_list.go @@ -2,6 +2,7 @@ package list import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/core-platform/pkg/tenant" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -30,7 +31,6 @@ func NewTenantListCmd(cfg *config.Config) *cobra.Command { }, } - config.RegisterStringParameterAsFlag(&cfg.Repositories.CPlatform, tenantListCmd.Flags()) config.RegisterBoolParameterAsFlag(&cfg.Repositories.AllowDirty, tenantListCmd.Flags()) return tenantListCmd @@ -43,7 +43,7 @@ func run(opts *TenantListOpts, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - tenants, err := tenant.List(tenant.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value)) + tenants, err := tenant.List(configpath.GetCorectlCPlatformDir("tenants")) if err != nil { return fmt.Errorf("failed to list tenants: %w", err) } diff --git a/pkg/cmd/tenant/tree/tenant_tree.go b/pkg/cmd/tenant/tree/tenant_tree.go index af6d3b9f..1d41d2c3 100644 --- a/pkg/cmd/tenant/tree/tenant_tree.go +++ b/pkg/cmd/tenant/tree/tenant_tree.go @@ -2,6 +2,7 @@ package tree import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" coretnt "github.com/coreeng/core-platform/pkg/tenant" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -33,7 +34,6 @@ func NewTenantTreeCmd(cfg *config.Config) *cobra.Command { }, } - config.RegisterStringParameterAsFlag(&cfg.Repositories.CPlatform, tenantTreeCmd.Flags()) config.RegisterBoolParameterAsFlag(&cfg.Repositories.AllowDirty, tenantTreeCmd.Flags()) tenantTreeCmd.Flags().StringVarP( @@ -54,7 +54,7 @@ func run(opts *TenantTreeOpts, cfg *config.Config) error { return fmt.Errorf("failed to update config repos: %w", err) } - tenants, err := coretnt.List(coretnt.DirFromCPlatformPath(cfg.Repositories.CPlatform.Value)) + tenants, err := coretnt.List(configpath.GetCorectlCPlatformDir("tenants")) if err != nil { return fmt.Errorf("failed to list tenants: %w", err) } diff --git a/pkg/cmdutil/config/config.go b/pkg/cmdutil/config/config.go index c1caf8dc..f9d31bb9 100644 --- a/pkg/cmdutil/config/config.go +++ b/pkg/cmdutil/config/config.go @@ -3,6 +3,7 @@ package config import ( "errors" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" @@ -235,13 +236,7 @@ func (c *Config) BaseDir() (string, error) { } func Path() (string, error) { - homeDir, err := os.UserHomeDir() - if err != nil { - return "", err - } - - path := filepath.Join(homeDir, CORECTL_DIR, "corectl", CORECTL_CONFIG) - + path := filepath.Join(configpath.GetCorectlHomeDir(), CORECTL_CONFIG) return path, nil } diff --git a/pkg/cmdutil/config/update.go b/pkg/cmdutil/config/update.go index f7c7f851..9ce78753 100644 --- a/pkg/cmdutil/config/update.go +++ b/pkg/cmdutil/config/update.go @@ -3,16 +3,18 @@ package config import ( "errors" "fmt" - + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/corectl/pkg/cmdutil/userio" "github.com/coreeng/corectl/pkg/git" "github.com/coreeng/corectl/pkg/logger" + "path/filepath" ) func Update(githubToken string, streams userio.IOStreams, ignoreDirty bool, repoParams []Parameter[string]) error { gitAuth := git.UrlTokenAuthMethod(githubToken) for _, repoParam := range repoParams { + repoParam.Value = filepath.Join(configpath.GetCorectlCacheDir(), repoParam.flag) err := updateRepository(&repoParam, gitAuth, streams, ignoreDirty) if err != nil { return err diff --git a/pkg/cmdutil/configpath/configpath.go b/pkg/cmdutil/configpath/configpath.go new file mode 100644 index 00000000..4031a5bf --- /dev/null +++ b/pkg/cmdutil/configpath/configpath.go @@ -0,0 +1,48 @@ +package configpath + +import ( + "os" + "path/filepath" +) + +func GetCorectlCacheDir() string { + return filepath.Join(GetCorectlHomeDir(), "repositories") +} + +func SetCorectlHome(path string) { + os.Setenv(`CORECTL_HOME`, path) +} + +func GetCorectlHomeDir() string { + if corectlHome := os.Getenv("CORECTL_HOME"); corectlHome != "" { + return corectlHome + } + if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { + return filepath.Join(xdgConfigHome, "corectl") + } + // Default to $HOME/.config/corectl - this will change on Windows + // which should be ~/AppData/Local/corectl ? + homeDir, err := os.UserHomeDir() + if err != nil { + panic("Unable to determine user home directory") + } + return filepath.Join(homeDir, ".config", "corectl") +} + +func GetCorectlCPlatformDir(paths ...string) string { + baseDir := filepath.Join(GetCorectlCacheDir(), "cplatform") + if len(paths) > 0 { + allPaths := append([]string{baseDir}, paths...) + return filepath.Join(allPaths...) + } + return baseDir +} + +func GetCorectlTemplatesDir(paths ...string) string { + baseDir := filepath.Join(GetCorectlCacheDir(), "templates") + if len(paths) > 0 { + allPaths := append([]string{baseDir}, paths...) + return filepath.Join(allPaths...) + } + return baseDir +} diff --git a/pkg/cmdutil/selector/input.go b/pkg/cmdutil/selector/input.go index 85cbb769..7beb5fd4 100644 --- a/pkg/cmdutil/selector/input.go +++ b/pkg/cmdutil/selector/input.go @@ -2,6 +2,7 @@ package selector import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "slices" "strings" @@ -11,8 +12,8 @@ import ( "github.com/coreeng/corectl/pkg/tenant" ) -func Tenant(cPlatRepoPath string, overrideTenantName string, streams userio.IOStreams) (*coretnt.Tenant, error) { - cPlatRepoPath = coretnt.DirFromCPlatformPath(cPlatRepoPath) +func Tenant(_ string, overrideTenantName string, streams userio.IOStreams) (*coretnt.Tenant, error) { + cPlatRepoPath := configpath.GetCorectlCPlatformDir("tenants") existingTenants, err := coretnt.List(cPlatRepoPath) if err != nil { return nil, fmt.Errorf("couldn't load tenant configuration in path %s: %w", cPlatRepoPath, err) @@ -26,7 +27,7 @@ func Tenant(cPlatRepoPath string, overrideTenantName string, streams userio.IOSt } func Environment(cPlatRepoPath, overrideEnvName string, tenantOnboardedEnvs []string, streams userio.IOStreams) (*environment.Environment, error) { - cPlatEnvRepoPath := environment.DirFromCPlatformRepoPath(cPlatRepoPath) + cPlatEnvRepoPath := configpath.GetCorectlCPlatformDir("environments") tenantEnvs, err := getTenantEnvs(cPlatEnvRepoPath, tenantOnboardedEnvs) if err != nil { return nil, err diff --git a/pkg/cmdutil/selector/input_test.go b/pkg/cmdutil/selector/input_test.go index 99e5ca6d..ac912dee 100644 --- a/pkg/cmdutil/selector/input_test.go +++ b/pkg/cmdutil/selector/input_test.go @@ -2,10 +2,10 @@ package selector import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "testing" - "github.com/coreeng/core-platform/pkg/environment" coretnt "github.com/coreeng/core-platform/pkg/tenant" "github.com/coreeng/corectl/pkg/cmdutil/userio" "github.com/coreeng/corectl/pkg/git" @@ -35,16 +35,17 @@ func TestTenantSelectorNonExistingTenant(t *testing.T) { tenant, err := Tenant(cPlatRepo.Path(), fmt.Sprintf("%s-tenant", t.Name()), streams) - assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/tenants/tenants: tenant %s invalid: cannot find %s tenant, available tenants: [default-tenant parent root]", cPlatRepo.Path(), tenantName, tenantName)) + assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s/tenants: tenant %s invalid: cannot find %s tenant, available tenants: [default-tenant parent root]", cPlatRepo.Path(), tenantName, tenantName)) assert.Nil(t, tenant) } func TestTenantSelectorInvalidCPlatRepo(t *testing.T) { cPlatRepoPath := t.TempDir() + configpath.SetCorectlHome(cPlatRepoPath) tenant, err := Tenant(cPlatRepoPath, testdata.DefaultTenant(), streams) - assert.ErrorContains(t, err, fmt.Sprintf("couldn't load tenant configuration in path %s/tenants/tenants: stat .: no such file or directory", cPlatRepoPath)) + assert.ErrorContains(t, err, fmt.Sprintf("couldn't load tenant configuration in path %s/repositories/cplatform/tenants: stat .: no such file or directory", cPlatRepoPath)) assert.Nil(t, tenant) } @@ -72,24 +73,27 @@ func TestEnvironmentSelectorNonExistingEnvironment(t *testing.T) { tenant, err := Environment(cPlatRepo.Path(), env, testdata.TenantEnvs(), streams) - assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s: environment %s invalid: cannot find %s environment, available envs: [dev prod]", environment.DirFromCPlatformRepoPath(cPlatRepo.Path()), env, env)) + assert.ErrorContains(t, err, fmt.Sprintf("config repo path %s: environment %s invalid: cannot find %s environment, available envs: [dev prod]", configpath.GetCorectlCPlatformDir("environments"), env, env)) assert.Nil(t, tenant) } func TestEnvironmentSelectorInvalidCPlatRepo(t *testing.T) { cPlatRepoPath := t.TempDir() + _, err := gittest.CreateTestCorectlConfig(cPlatRepoPath) + assert.NoError(t, err) tenant, err := Environment(cPlatRepoPath, testdata.DevEnvironment(), testdata.TenantEnvs(), streams) - - assert.ErrorContains(t, err, fmt.Sprintf("couldn't load environment configuration: open %s/environments: no such file or directory", cPlatRepoPath)) + assert.ErrorContains(t, err, fmt.Sprintf("couldn't load environment configuration: open %s/repositories/cplatform/environments: no such file or directory", cPlatRepoPath)) assert.Nil(t, tenant) } func testLocalRepo(t *testing.T, path string) *git.LocalRepository { + _, err := gittest.CreateTestCorectlConfig(t.TempDir()) + assert.NoError(t, err) _, repo, err := gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: path, TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlCPlatformDir(), }) assert.NoError(t, err) return repo diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 1131d1cb..c52fc0c0 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -3,9 +3,9 @@ package logger import ( "errors" "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" - "strings" "syscall" "go.uber.org/zap" @@ -56,13 +56,7 @@ func Init(logLevelFlag string) { } configuredConsoleLogLevel = consoleLogLevel - homeDir, err := os.UserHomeDir() - if err != nil { - fmt.Printf("Failed to get home directory: %v\n", err) - os.Exit(1) - } - logPath = strings.Replace(LogFile, "$HOME", homeDir, 1) - + logPath = filepath.Join(configpath.GetCorectlHomeDir(), "corectl.log") logDir := filepath.Dir(logPath) if err := os.MkdirAll(logDir, 0755); err != nil { fmt.Printf("fail to create folder path: %v\n", err) diff --git a/pkg/tenant/write.go b/pkg/tenant/write.go index 42192692..156f56ca 100644 --- a/pkg/tenant/write.go +++ b/pkg/tenant/write.go @@ -2,6 +2,7 @@ package tenant import ( "fmt" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "path/filepath" "github.com/coreeng/core-platform/pkg/tenant" @@ -65,7 +66,7 @@ func CreateOrUpdate( if err = tenant.CreateOrUpdate(tenant.CreateOrUpdateOp{ Tenant: op.Tenant, ParentTenant: op.ParentTenant, - TenantsDir: tenant.DirFromCPlatformPath(op.CplatformRepoPath), + TenantsDir: configpath.GetCorectlCPlatformDir("tenants"), }); err != nil { return result, err } diff --git a/pkg/tenant/write_test.go b/pkg/tenant/write_test.go index b34d596c..92bbd19d 100644 --- a/pkg/tenant/write_test.go +++ b/pkg/tenant/write_test.go @@ -1,6 +1,8 @@ package tenant import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" + "github.com/stretchr/testify/assert" "os" "path/filepath" @@ -47,14 +49,17 @@ repos: [] ) BeforeEach(OncePerOrdered, func() { var err error + _, err = gittest.CreateTestCorectlConfig(t.TempDir()) + assert.NoError(t, err) + cplatformServerRepo, cplatformLocalRepo, err = gittest.CreateBareAndLocalRepoFromDir(&gittest.CreateBareAndLocalRepoOp{ SourceDir: testdata.CPlatformEnvsPath(), TargetBareRepoDir: t.TempDir(), - TargetLocalRepoDir: t.TempDir(), + TargetLocalRepoDir: configpath.GetCorectlCPlatformDir(), }) Expect(err).NotTo(HaveOccurred()) - parentTenant, err = tenant.FindByName(tenant.DirFromCPlatformPath(cplatformLocalRepo.Path()), "parent") + parentTenant, err = tenant.FindByName(configpath.GetCorectlCPlatformDir("tenants"), "parent") Expect(parentTenant).NotTo(BeNil()) Expect(err).NotTo(HaveOccurred()) defaultTenant = tenant.Tenant{ diff --git a/pkg/testutil/gittest/bare_repo.go b/pkg/testutil/gittest/bare_repo.go index 09ec06bd..c7fead8e 100644 --- a/pkg/testutil/gittest/bare_repo.go +++ b/pkg/testutil/gittest/bare_repo.go @@ -1,6 +1,7 @@ package gittest import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" "slices" @@ -24,6 +25,20 @@ type CreateBareAndLocalRepoOp struct { TargetLocalRepoDir string } +type CreateTestCorectlConfigOp struct { + Path string + CPlatform CreateBareAndLocalRepoOp + Templates CreateBareAndLocalRepoOp +} + +func CreateTestCorectlConfig(path string) (*CreateTestCorectlConfigOp, error) { + op := &CreateTestCorectlConfigOp{ + Path: path, + } + configpath.SetCorectlHome(path) + return op, nil +} + func CreateBareAndLocalRepoFromDir(op *CreateBareAndLocalRepoOp) (*BareRepository, *git.LocalRepository, error) { if err := os.MkdirAll(op.TargetBareRepoDir, 0o777); err != nil { return nil, nil, err diff --git a/testdata/cplatform-environments/environments/dev/config.yaml b/testdata/repositories/cplatform/environments/dev/config.yaml similarity index 100% rename from testdata/cplatform-environments/environments/dev/config.yaml rename to testdata/repositories/cplatform/environments/dev/config.yaml diff --git a/testdata/repositories/cplatform/environments/environments.yaml b/testdata/repositories/cplatform/environments/environments.yaml new file mode 100644 index 00000000..d29481e6 --- /dev/null +++ b/testdata/repositories/cplatform/environments/environments.yaml @@ -0,0 +1,3 @@ +enabled: + - dev + - prod \ No newline at end of file diff --git a/testdata/cplatform-environments/environments/prod/config.yaml b/testdata/repositories/cplatform/environments/prod/config.yaml similarity index 100% rename from testdata/cplatform-environments/environments/prod/config.yaml rename to testdata/repositories/cplatform/environments/prod/config.yaml diff --git a/testdata/cplatform-environments/tenants/tenants/default-tenant.yaml b/testdata/repositories/cplatform/tenants/tenants/default-tenant.yaml similarity index 100% rename from testdata/cplatform-environments/tenants/tenants/default-tenant.yaml rename to testdata/repositories/cplatform/tenants/tenants/default-tenant.yaml diff --git a/testdata/cplatform-environments/tenants/tenants/parent.yaml b/testdata/repositories/cplatform/tenants/tenants/parent.yaml similarity index 100% rename from testdata/cplatform-environments/tenants/tenants/parent.yaml rename to testdata/repositories/cplatform/tenants/tenants/parent.yaml diff --git a/testdata/software-templates/blank/skeleton/.github/workflows/extended-test.yaml b/testdata/repositories/templates/blank/skeleton/.github/workflows/extended-test.yaml similarity index 100% rename from testdata/software-templates/blank/skeleton/.github/workflows/extended-test.yaml rename to testdata/repositories/templates/blank/skeleton/.github/workflows/extended-test.yaml diff --git a/testdata/software-templates/blank/skeleton/.github/workflows/fast-feedback.yaml b/testdata/repositories/templates/blank/skeleton/.github/workflows/fast-feedback.yaml similarity index 100% rename from testdata/software-templates/blank/skeleton/.github/workflows/fast-feedback.yaml rename to testdata/repositories/templates/blank/skeleton/.github/workflows/fast-feedback.yaml diff --git a/testdata/software-templates/blank/skeleton/README.md b/testdata/repositories/templates/blank/skeleton/README.md similarity index 100% rename from testdata/software-templates/blank/skeleton/README.md rename to testdata/repositories/templates/blank/skeleton/README.md diff --git a/testdata/software-templates/blank/template.yaml b/testdata/repositories/templates/blank/template.yaml similarity index 100% rename from testdata/software-templates/blank/template.yaml rename to testdata/repositories/templates/blank/template.yaml diff --git a/testdata/software-templates/go/web/skeleton/README.md b/testdata/repositories/templates/go/web/skeleton/README.md similarity index 100% rename from testdata/software-templates/go/web/skeleton/README.md rename to testdata/repositories/templates/go/web/skeleton/README.md diff --git a/testdata/software-templates/go/web/template.yaml b/testdata/repositories/templates/go/web/template.yaml similarity index 100% rename from testdata/software-templates/go/web/template.yaml rename to testdata/repositories/templates/go/web/template.yaml diff --git a/testdata/software-templates/monorepo/README.md b/testdata/repositories/templates/monorepo/README.md similarity index 100% rename from testdata/software-templates/monorepo/README.md rename to testdata/repositories/templates/monorepo/README.md diff --git a/testdata/software-templates/with-args/skeleton/args.txt b/testdata/repositories/templates/with-args/skeleton/args.txt similarity index 100% rename from testdata/software-templates/with-args/skeleton/args.txt rename to testdata/repositories/templates/with-args/skeleton/args.txt diff --git a/testdata/software-templates/with-args/template.yaml b/testdata/repositories/templates/with-args/template.yaml similarity index 100% rename from testdata/software-templates/with-args/template.yaml rename to testdata/repositories/templates/with-args/template.yaml diff --git a/testdata/testdata.go b/testdata/testdata.go index 65aed962..980d19d2 100644 --- a/testdata/testdata.go +++ b/testdata/testdata.go @@ -23,11 +23,11 @@ func Path(rel string) string { } func CPlatformEnvsPath() string { - return Path("./cplatform-environments") + return Path("./repositories/cplatform") } func TemplatesPath() string { - return Path("./software-templates") + return Path("./repositories/templates") } func RenderInitFile( diff --git a/tests/integration/application/application.go b/tests/integration/application/application.go index 59809876..f8669290 100644 --- a/tests/integration/application/application.go +++ b/tests/integration/application/application.go @@ -10,6 +10,7 @@ import ( "github.com/coreeng/core-platform/pkg/environment" "github.com/coreeng/corectl/pkg/cmdutil/config" + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "github.com/coreeng/corectl/pkg/git" "github.com/coreeng/corectl/testdata" "github.com/coreeng/corectl/tests/integration/testconfig" @@ -38,13 +39,14 @@ var _ = Describe("application", Ordered, func() { var err error testRunId = testconfig.GetTestRunId() homeDir = t.TempDir() + configpath.SetCorectlHome(homeDir) corectl = testconfig.NewCorectlClient(homeDir) cfg, cfgDetails, err = testsetup.InitCorectl(corectl) Expect(err).ToNot(HaveOccurred()) githubClient = testconfig.NewGitHubClient() testsetup.SetupGitGlobalConfigFromCurrentToOtherHomeDir(homeDir) - envs, err := environment.List(environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value)) + envs, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) Expect(err).NotTo(HaveOccurred()) devEnvIdx := slices.IndexFunc(envs, func(e environment.Environment) bool { return e.Environment == testdata.DevEnvironment() diff --git a/tests/integration/config/config.go b/tests/integration/config/config.go index 1cdb5d0b..0b45605d 100644 --- a/tests/integration/config/config.go +++ b/tests/integration/config/config.go @@ -1,6 +1,7 @@ package config import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "path/filepath" "time" @@ -17,17 +18,16 @@ import ( var _ = Describe("config", Ordered, func() { var ( - homeDir, baseDirPath, repositoriesPath, configPath, initConfigPath string - corectl *testconfig.CorectlClient + homeDir, configPath, initConfigPath string + corectl *testconfig.CorectlClient ) t := GinkgoT() BeforeAll(func() { homeDir = t.TempDir() - baseDirPath = filepath.Join(homeDir, ".config", "corectl") - repositoriesPath = filepath.Join(baseDirPath, "repositories") - configPath = filepath.Join(baseDirPath, "corectl.yaml") + configpath.SetCorectlHome(homeDir) + configPath = filepath.Join(homeDir, "corectl.yaml") corectl = testconfig.NewCorectlClient(homeDir) initConfigPath = filepath.Join(homeDir, "corectl-init.yaml") testsetup.SetupGitGlobalConfigFromCurrentToOtherHomeDir(homeDir) @@ -35,27 +35,26 @@ var _ = Describe("config", Ordered, func() { Context("init", Ordered, func() { var ( - cfg *config.Config - cfgDetails *testsetup.CorectlConfigDetails + cfg *config.Config ) Context("errors", func() { AfterEach(func() { - Expect(os.RemoveAll(baseDirPath)).ToNot(HaveOccurred()) + Expect(os.RemoveAll(filepath.Join(homeDir, "repositories"))).ToNot(HaveOccurred()) }) It("returns meaningful error when cplatform repository already exist", func() { - cloneOpt := cloneGit(testconfig.Cfg.CPlatformRepoFullId, repositoriesPath) + cloneOpt := cloneGit(testconfig.Cfg.CPlatformRepoFullId, configpath.GetCorectlCPlatformDir()) _, _, err := testsetup.InitCorectl(corectl) Expect(err.Error()).To(ContainSubstring("Error: repoUrl \"%s.git\", target dir \"%s\": failed to clone repository: repository already exists: initialised already? run `corectl config update` to update repositories", cloneOpt.URL, cloneOpt.TargetPath)) }) It("returns meaningful error when templates repository already exist", func() { - cloneOpt := cloneGit(testconfig.Cfg.TemplatesRepoFullId, repositoriesPath) + cloneOpt := cloneGit(testconfig.Cfg.TemplatesRepoFullId, configpath.GetCorectlTemplatesDir()) _, _, err := testsetup.InitCorectl(corectl) - Expect(err.Error()).To(ContainSubstring("Error: repoUrl \"%s.git\", target dir \"%s\": failed to clone repository: repository already exists: initialised already? run `corectl config update` to update repositories, alternatively to initialise again delete corectl config dir at \"%s\" and run `corectl config init`", cloneOpt.URL, cloneOpt.TargetPath, baseDirPath)) + Expect(err.Error()).To(ContainSubstring("Error: repoUrl \"%s.git\", target dir \"%s\": failed to clone repository: repository already exists: initialised already? run `corectl config update` to update repositories, alternatively to initialise again delete corectl config dir at \"%s\" and run `corectl config init`", cloneOpt.URL, cloneOpt.TargetPath, homeDir)) }) It("returns meaningful error when invalid templates remote repository configuration", func() { err := testdata.RenderInitFile( @@ -85,7 +84,7 @@ var _ = Describe("config", Ordered, func() { Context("successfully initialise", func() { BeforeAll(func() { var err error - cfg, cfgDetails, err = testsetup.InitCorectl(corectl) + cfg, _, err = testsetup.InitCorectl(corectl) Expect(err).ToNot(HaveOccurred()) }) @@ -93,10 +92,6 @@ var _ = Describe("config", Ordered, func() { Expect(cfg.Path()).To(Equal(configPath)) Expect(cfg).NotTo(BeNil()) Expect(cfg.IsPersisted()).To(BeTrue()) - Expect(cfg.Repositories.CPlatform.Value).To( - Equal(filepath.Join(repositoriesPath, cfgDetails.CPlatformRepoName.Name()))) - Expect(cfg.Repositories.Templates.Value).To( - Equal(filepath.Join(repositoriesPath, cfgDetails.TemplatesRepoName.Name()))) Expect(cfg.GitHub.Organization.Value).To(Equal(testconfig.Cfg.GitHubOrg)) Expect(cfg.GitHub.Token.Value).To(Equal(testconfig.Cfg.GitHubToken)) Expect(cfg.P2P.FastFeedback.DefaultEnvs.Value).To(ConsistOf(testdata.DevEnvironment())) @@ -104,12 +99,12 @@ var _ = Describe("config", Ordered, func() { Expect(cfg.P2P.Prod.DefaultEnvs.Value).To(ConsistOf(testdata.ProdEnvironment())) }) It("cloned cplatform repository", func() { - repo, err := git.OpenLocalRepository(cfg.Repositories.CPlatform.Value, false) + repo, err := git.OpenLocalRepository(configpath.GetCorectlCPlatformDir(), false) Expect(repo).NotTo(BeNil()) Expect(err).NotTo(HaveOccurred()) }) It("cloned templates repository", func() { - repo, err := git.OpenLocalRepository(cfg.Repositories.Templates.Value, false) + repo, err := git.OpenLocalRepository(configpath.GetCorectlTemplatesDir(), false) Expect(repo).NotTo(BeNil()) Expect(err).NotTo(HaveOccurred()) }) @@ -119,19 +114,16 @@ var _ = Describe("config", Ordered, func() { Context("update", Ordered, func() { var ( - cfg *config.Config originalCPlatformPullTimestamp time.Time originalTemplatesPullTimestamp time.Time ) BeforeAll(func() { var err error - cfg, err = config.ReadConfig(corectl.ConfigPath()) - Expect(err).NotTo(HaveOccurred()) - originalCPlatformPullTimestamp, err = getLastPullTime(cfg.Repositories.CPlatform.Value) + originalCPlatformPullTimestamp, err = getLastPullTime(configpath.GetCorectlCPlatformDir()) Expect(err).NotTo(HaveOccurred()) - originalTemplatesPullTimestamp, err = getLastPullTime(cfg.Repositories.Templates.Value) + originalTemplatesPullTimestamp, err = getLastPullTime(configpath.GetCorectlTemplatesDir()) Expect(err).NotTo(HaveOccurred()) _, err = corectl.Run("config", "update", "--non-interactive") @@ -139,11 +131,11 @@ var _ = Describe("config", Ordered, func() { }) It("pulls configuration changes from remote configuration repositories", func() { - updateCPlatformPullTimestamp, err := getLastPullTime(cfg.Repositories.CPlatform.Value) + updateCPlatformPullTimestamp, err := getLastPullTime(configpath.GetCorectlCPlatformDir()) Expect(err).NotTo(HaveOccurred()) Expect(originalCPlatformPullTimestamp.Before(updateCPlatformPullTimestamp)).To(BeTrue()) - updatedTemplatesPullTimestamp, err := getLastPullTime(cfg.Repositories.Templates.Value) + updatedTemplatesPullTimestamp, err := getLastPullTime(configpath.GetCorectlTemplatesDir()) Expect(err).NotTo(HaveOccurred()) Expect(originalTemplatesPullTimestamp.Before(updatedTemplatesPullTimestamp)).To(BeTrue()) }) @@ -162,7 +154,7 @@ func getLastPullTime(repoPath string) (time.Time, error) { func cloneGit(repoId git.GithubRepoFullId, dstPath string) git.CloneOp { cloneOpt := git.CloneOp{ URL: repoId.HttpUrl(), - TargetPath: filepath.Join(dstPath, repoId.RepositoryFullname.Name()), + TargetPath: filepath.Join(dstPath), Auth: git.UrlTokenAuthMethod(testconfig.Cfg.GitHubToken), } _, err := git.CloneToLocalRepository(cloneOpt) diff --git a/tests/integration/env/connect.go b/tests/integration/env/connect.go index eabc8be8..4963496e 100644 --- a/tests/integration/env/connect.go +++ b/tests/integration/env/connect.go @@ -1,6 +1,7 @@ package env import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "os" "github.com/coreeng/corectl/testdata" @@ -18,6 +19,7 @@ var _ = Describe("env", Ordered, func() { BeforeAll(func() { homeDir := t.TempDir() + configpath.SetCorectlHome(homeDir) corectl = testconfig.NewCorectlClient(homeDir) _, _, err := testsetup.InitCorectl(corectl) Expect(err).ToNot(HaveOccurred()) diff --git a/tests/integration/p2p/export.go b/tests/integration/p2p/export.go index 0662ba42..aa352686 100644 --- a/tests/integration/p2p/export.go +++ b/tests/integration/p2p/export.go @@ -1,6 +1,7 @@ package p2p import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "path/filepath" "github.com/coreeng/core-platform/pkg/environment" @@ -25,6 +26,7 @@ var _ = Describe("export", Ordered, func() { BeforeAll(func() { var cfg *config.Config homeDir := tmpDir(t) + configpath.SetCorectlHome(homeDir) corectl, cfg = initCorectl(homeDir) appDir = onboardTestApp(homeDir, corectl) env = defaultEnv(cfg.Repositories.CPlatform.Value) @@ -103,7 +105,7 @@ func tmpDir(t GinkgoTInterface) string { } func defaultEnv(cPlatRepoPath string) *environment.Environment { - e, err := environment.FindByName(environment.DirFromCPlatformRepoPath(cPlatRepoPath), testdata.DevEnvironment()) + e, err := environment.FindByName(configpath.GetCorectlCPlatformDir("environments"), testdata.DevEnvironment()) Expect(err).ToNot(HaveOccurred()) return e } diff --git a/tests/integration/p2p/p2p.go b/tests/integration/p2p/p2p.go index 4599ac9f..fe32c524 100644 --- a/tests/integration/p2p/p2p.go +++ b/tests/integration/p2p/p2p.go @@ -1,6 +1,7 @@ package p2p import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "slices" "time" @@ -30,12 +31,13 @@ var _ = Describe("p2p", Ordered, func() { BeforeAll(func(ctx SpecContext) { var err error homeDir = t.TempDir() + configpath.SetCorectlHome(homeDir) corectl = testconfig.NewCorectlClient(homeDir) cfg, _, err = testsetup.InitCorectl(corectl) Expect(err).ToNot(HaveOccurred()) githubClient = testconfig.NewGitHubClient() testsetup.SetupGitGlobalConfigFromCurrentToOtherHomeDir(homeDir) - envs, err := environment.List(environment.DirFromCPlatformRepoPath(cfg.Repositories.CPlatform.Value)) + envs, err := environment.List(configpath.GetCorectlCPlatformDir("environments")) Expect(err).NotTo(HaveOccurred()) devEnvIdx := slices.IndexFunc(envs, func(e environment.Environment) bool { return e.Environment == testdata.DevEnvironment() diff --git a/tests/integration/tenant/tenant.go b/tests/integration/tenant/tenant.go index c9f477f6..2030ac79 100644 --- a/tests/integration/tenant/tenant.go +++ b/tests/integration/tenant/tenant.go @@ -1,6 +1,7 @@ package tenant import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "time" "github.com/coreeng/corectl/pkg/git" @@ -24,6 +25,7 @@ var _ = Describe("tenant", Ordered, func() { BeforeAll(func() { var err error homeDir = t.TempDir() + configpath.SetCorectlHome(homeDir) corectl = testconfig.NewCorectlClient(homeDir) _, cfgDetails, err = testsetup.InitCorectl(corectl) Expect(err).ToNot(HaveOccurred()) diff --git a/tests/integration/testconfig/corectl_client.go b/tests/integration/testconfig/corectl_client.go index 62af091a..1fdf0518 100644 --- a/tests/integration/testconfig/corectl_client.go +++ b/tests/integration/testconfig/corectl_client.go @@ -18,7 +18,6 @@ type CorectlClient struct { func NewCorectlClient(homeDir string) *CorectlClient { env := os.Environ() - env = append(env, "HOME="+homeDir) return &CorectlClient{ binaryPath: Cfg.CoreCTLBinary, homeDir: homeDir, @@ -52,11 +51,6 @@ func (c *CorectlClient) HomeDir() string { } func (c *CorectlClient) ConfigPath() string { - originalHome := os.Getenv("HOME") - defer func() { - Expect(os.Setenv("HOME", originalHome)).To(Succeed()) - }() - Expect(os.Setenv("HOME", c.homeDir)).To(Succeed()) configPath, err := config.Path() Expect(err).NotTo(HaveOccurred()) return configPath diff --git a/tests/integration/testsetup/config_init.go b/tests/integration/testsetup/config_init.go index 583dc776..9aa41b91 100644 --- a/tests/integration/testsetup/config_init.go +++ b/tests/integration/testsetup/config_init.go @@ -1,6 +1,7 @@ package testsetup import ( + "github.com/coreeng/corectl/pkg/cmdutil/configpath" "path/filepath" "github.com/coreeng/corectl/pkg/cmdutil/config" @@ -16,7 +17,7 @@ type CorectlConfigDetails struct { } func InitCorectl(corectl *testconfig.CorectlClient) (*config.Config, *CorectlConfigDetails, error) { - initFilePath := filepath.Join(corectl.HomeDir(), "corectl-init.yaml") + initFilePath := filepath.Join(configpath.GetCorectlHomeDir(), "corectl-init.yaml") err := testdata.RenderInitFile( initFilePath, testconfig.Cfg.CPlatformRepoFullId.RepositoryFullname.HttpUrl(), @@ -39,7 +40,7 @@ func InitCorectlWithFile(corectl *testconfig.CorectlClient, initFilePath string) } cfg := corectl.Config() - cplatformRepo, err := git.OpenLocalRepository(cfg.Repositories.CPlatform.Value, false) + cplatformRepo, err := git.OpenLocalRepository(configpath.GetCorectlCPlatformDir(), false) if err != nil { return nil, nil, err } @@ -47,7 +48,7 @@ func InitCorectlWithFile(corectl *testconfig.CorectlClient, initFilePath string) if err != nil { return nil, nil, err } - templatesRepo, err := git.OpenLocalRepository(cfg.Repositories.Templates.Value, false) + templatesRepo, err := git.OpenLocalRepository(configpath.GetCorectlTemplatesDir(), false) if err != nil { return nil, nil, err }