File: pathutil.go

package info (click to toggle)
golang-k8s-sigs-kustomize-kyaml 0.20.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,180 kB
  • sloc: makefile: 220; sh: 68
file content (39 lines) | stat: -rw-r--r-- 960 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package pathutil

import (
	"os"
	"path/filepath"
)

// DirsWithFile takes the root directory path and returns all the paths of
// sub-directories(including itself) which contain file with input fileName
// at top level if recurse is true
func DirsWithFile(root, fileName string, recurse bool) ([]string, error) {
	var res []string
	if !recurse {
		// check if the file with fileName is present in root and return it
		// else return empty list
		_, err := os.Stat(filepath.Join(root, fileName))
		if !os.IsNotExist(err) {
			res = append(res, filepath.Clean(root))
		}
		return res, nil
	}
	err := filepath.Walk(root,
		func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if filepath.Base(path) == fileName {
				res = append(res, filepath.Dir(path))
			}
			return nil
		})
	if err != nil {
		return res, err
	}
	return res, nil
}