From 83b10d40317f9bf38fb05287f4319dbf4394ae1d Mon Sep 17 00:00:00 2001 From: Richard Jones Date: Wed, 8 Dec 2021 15:28:02 -0700 Subject: [PATCH] refactored finding of cue.mod parent Signed-off-by: Richard Jones --- plan/plan.go | 1 + state/project.go | 45 +++++++++++++++++++++++++++++---------------- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/plan/plan.go b/plan/plan.go index f2dc0015..b5c295a5 100644 --- a/plan/plan.go +++ b/plan/plan.go @@ -25,6 +25,7 @@ type Plan struct { func Load(ctx context.Context, args ...string) (*Plan, error) { // FIXME: universe vendoring + if err := state.VendorUniverse(ctx, ""); err != nil { return nil, err } diff --git a/state/project.go b/state/project.go index 0c70c9e1..4b28e4e2 100644 --- a/state/project.go +++ b/state/project.go @@ -356,22 +356,6 @@ func (w *Project) cleanPackageName(ctx context.Context, pkg string) (string, err func cueModInit(ctx context.Context, parentDir string) error { lg := log.Ctx(ctx) - if parentDir == "" { - wd, _ := os.Getwd() - separator := string(os.PathSeparator) - dirs := strings.Split(wd, separator) - dirsLen := len(dirs) - - // traverse the directory tree starting from PWD going up to successive parents - for i := dirsLen; i > 0; i-- { - parentDir = strings.Join(dirs[:i], separator) - // look for the cue.mod filder - if _, err := os.Stat(parentDir + "/cue.mod"); !os.IsNotExist(err) { - break // found it! - } - } - } - modDir := path.Join(parentDir, "cue.mod") if err := os.Mkdir(modDir, 0755); err != nil { if !errors.Is(err, os.ErrExist) { @@ -407,6 +391,11 @@ func cueModInit(ctx context.Context, parentDir string) error { } func VendorUniverse(ctx context.Context, p string) error { + + if p == "" { + p = getCueModParent() + } + // ensure cue module is initialized if err := cueModInit(ctx, p); err != nil { return err @@ -430,3 +419,27 @@ func VendorUniverse(ctx context.Context, p string) error { return nil } + +func getCueModParent() string { + + cwd, _ := os.Getwd() + parentDir := cwd + + // traverse the directory tree up through ancestors looking for a cue.mod folder + for { + + if _, err := os.Stat(path.Join(parentDir, "cue.mod")); !errors.Is(err, os.ErrNotExist) { + break // found it! + } + + parentDir = filepath.Dir(parentDir) + + if parentDir == string(os.PathSeparator) { + // reached the root + parentDir = cwd // reset to working directory + break + } + } + + return parentDir +}