forked from flant/shell-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
directory.go
59 lines (47 loc) · 1.03 KB
/
directory.go
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
51
52
53
54
55
56
57
58
59
package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
utils_file "github.com/flant/shell-operator/pkg/utils/file"
)
// ChooseExistedDirectoryPath returns first non-empty existed directory path from arguments.
//
// Each argument is prefixed with current directory if is not started with /
//
// Example:
// dir, err := ExtractExistedDirectoryPath(os.Getenv("DIR"), defaultDir)
func ChooseExistedDirectoryPath(paths ...string) (path string, err error) {
for _, p := range paths {
if p != "" {
path = p
break
}
}
if path == "" {
return "", nil
}
path, err = ToAbsolutePath(path)
if err != nil {
return
}
if exists, _ := utils_file.DirExists(path); !exists {
return "", fmt.Errorf("no working dir")
}
return "", nil
}
func ToAbsolutePath(path string) (string, error) {
if filepath.IsAbs(path) {
return path, nil
}
if strings.HasPrefix(path, "./") {
cwd, _ := os.Getwd()
return strings.Replace(path, ".", cwd, 1), nil
}
p, err := filepath.Abs(path)
if err != nil {
return "", err
}
return p, nil
}