Skip to content

Commit

Permalink
add template function findRootDir
Browse files Browse the repository at this point in the history
which return path to dir in root hierarchy
  • Loading branch information
reddec committed May 29, 2022
1 parent 598ce78 commit 4e890f5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 548,9 @@ Additional "magic" vairables:

If nothing found - `ErrNotExists` returned
* `findRootFile` (v1.3.2 ) - (`{{findRootFile "myfile"}}`) find path to file with specific name in any of root
folders. Same as `getRootFile` but instead of returning content it returning path to file.
folders. Same as `getRootFile` but instead of returning content it is returning path to file.
* `findRootDir` (v1.3.2 ) - (`{{findRootDir "mydir"}}`) find path to directory with specific name in any of root
folders. Same as `findRootFile` but instead of looking for file it is looking for directory.

#### Flow

Expand Down
33 changes: 33 additions & 0 deletions internal/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 282,7 @@ func (r *renderContext) Render(value string) (string, error) {
funcMap := sprig.TxtFuncMap()
funcMap["getRootFile"] = getRootFile
funcMap["findRootFile"] = findRootFile
funcMap["findRootDir"] = findRootDir
p, err := template.New("").Delims(r.open, r.close).Funcs(funcMap).Parse(value)
if err != nil {
return "", err
Expand Down Expand Up @@ -356,3 357,35 @@ func findRootFile(name string) (string, error) {
root = next
}
}

// find path to directory with specific name (can be only base name) in any of root folders:
//
// WD: /foo/bar/xyz
// Name: .git
// Will check:
// /foo/bar/xyz/.git
// /foo/bar/.git
// /foo/.git
// /.git
//
// If nothing found - ErrNotExists returned
func findRootDir(name string) (string, error) {
root, err := os.Getwd()
if err != nil {
return "", err
}
name = filepath.Base(name)
for {
dirPath := filepath.Join(root, name)
if stat, err := os.Stat(dirPath); err == nil && stat.IsDir() {
return dirPath, nil
} else if err != nil && !os.IsNotExist(err) {
return "", fmt.Errorf("stat %s: %w", dirPath, err)
}
next := filepath.Dir(root)
if next == root {
return "", os.ErrNotExist
}
root = next
}
}

0 comments on commit 4e890f5

Please sign in to comment.