File: file_finder.go

package info (click to toggle)
golang-github-traefik-paerser 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 612 kB
  • sloc: makefile: 14
file content (50 lines) | stat: -rw-r--r-- 890 bytes parent folder | download
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
40
41
42
43
44
45
46
47
48
49
50
package cli

import (
	"os"
	"path/filepath"
	"strings"
)

// Finder holds a list of file paths.
type Finder struct {
	BasePaths  []string
	Extensions []string
}

// Find returns the first valid existing file among configFile
// and the paths already registered with Finder.
func (f Finder) Find(configFile string) (string, error) {
	paths := f.getPaths(configFile)

	for _, filePath := range paths {
		fp := os.ExpandEnv(filePath)

		_, err := os.Stat(fp)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return "", err
		}

		return filepath.Abs(fp)
	}

	return "", nil
}

func (f Finder) getPaths(configFile string) []string {
	var paths []string
	if strings.TrimSpace(configFile) != "" {
		paths = append(paths, configFile)
	}

	for _, basePath := range f.BasePaths {
		for _, ext := range f.Extensions {
			paths = append(paths, basePath+"."+ext)
		}
	}

	return paths
}