Skip to content

Commit 4e890f5

Browse files
committed
add template function findRootDir
which return path to dir in root hierarchy
1 parent 598ce78 commit 4e890f5

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,9 @@ Additional "magic" vairables:
548548

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

553555
#### Flow
554556

internal/manifest.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@ func (r *renderContext) Render(value string) (string, error) {
282282
funcMap := sprig.TxtFuncMap()
283283
funcMap["getRootFile"] = getRootFile
284284
funcMap["findRootFile"] = findRootFile
285+
funcMap["findRootDir"] = findRootDir
285286
p, err := template.New("").Delims(r.open, r.close).Funcs(funcMap).Parse(value)
286287
if err != nil {
287288
return "", err
@@ -356,3 +357,35 @@ func findRootFile(name string) (string, error) {
356357
root = next
357358
}
358359
}
360+
361+
// find path to directory with specific name (can be only base name) in any of root folders:
362+
//
363+
// WD: /foo/bar/xyz
364+
// Name: .git
365+
// Will check:
366+
// /foo/bar/xyz/.git
367+
// /foo/bar/.git
368+
// /foo/.git
369+
// /.git
370+
//
371+
// If nothing found - ErrNotExists returned
372+
func findRootDir(name string) (string, error) {
373+
root, err := os.Getwd()
374+
if err != nil {
375+
return "", err
376+
}
377+
name = filepath.Base(name)
378+
for {
379+
dirPath := filepath.Join(root, name)
380+
if stat, err := os.Stat(dirPath); err == nil && stat.IsDir() {
381+
return dirPath, nil
382+
} else if err != nil && !os.IsNotExist(err) {
383+
return "", fmt.Errorf("stat %s: %w", dirPath, err)
384+
}
385+
next := filepath.Dir(root)
386+
if next == root {
387+
return "", os.ErrNotExist
388+
}
389+
root = next
390+
}
391+
}

0 commit comments

Comments
 (0)