Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify template/cplatform working directory handling #100

Merged
merged 1 commit into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions pkg/application/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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())

Expand Down Expand Up @@ -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")
Expand Down
21 changes: 7 additions & 14 deletions pkg/cmd/application/create/app_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package create
import (
"errors"
"fmt"
"github.com/coreeng/corectl/pkg/cmdutil/configpath"
"os"
"path/filepath"
"slices"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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.")
Expand All @@ -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),
Expand Down
47 changes: 8 additions & 39 deletions pkg/cmd/config/init/config_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -23,7 +22,6 @@ import (
type ConfigInitOpt struct {
EnvironmentsRepo string
File string
RepositoriesDir string
GitHubToken string
GitHubOrganisation string
NonInteractive bool
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
}

Expand All @@ -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)
}
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -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))
Expand All @@ -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))
Expand Down
9 changes: 2 additions & 7 deletions pkg/cmd/env/active.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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
}

Expand Down
9 changes: 2 additions & 7 deletions pkg/cmd/env/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"github.com/coreeng/corectl/pkg/cmdutil/configpath"
"os"
"strings"

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down
9 changes: 2 additions & 7 deletions pkg/cmd/env/disconnect.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package env
import (
"bytes"
"fmt"
"github.com/coreeng/corectl/pkg/cmdutil/configpath"
"os"

"github.com/coreeng/core-platform/pkg/environment"
Expand Down Expand Up @@ -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")
}
Expand All @@ -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
}

Expand Down
Loading