-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
57 lines (51 loc) · 1.37 KB
/
path.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
package path
import (
"os"
"os/exec"
"path/filepath"
"strings"
)
// IsExist returns boolean indicating whether the path of file or directory already exists.
// Returns an unknown error if not match some syscall errors.
func IsExist(_path string) (ok bool, err error) {
_, err = os.Stat(_path)
if ok = err == nil; !ok && os.IsNotExist(err) {
err = nil
}
return
}
// MustExist returns a boolean, it true if the path of file or directory already exists.
func MustExist(_path string) bool {
ok, _ := IsExist(_path)
return ok
}
// Ensure returns an error if the path of file or directory(dir is true) isn't existed or catches other error.
func Ensure(_path string, dir bool) error {
if ok, _ := IsExist(_path); !ok {
if dir {
if err := os.MkdirAll(_path, os.ModePerm); err != nil {
return err
}
} else if err := Ensure(filepath.Dir(_path), true); err != nil {
return err
} else if err := CreateFile(_path); err != nil {
return err
}
}
return nil
}
// ExecPath returns the path of the command-line program.
func ExecPath() string {
if len(os.Args) != 0 {
return os.Args[0]
}
return ""
}
// ExecDir returns the directory path of the command-line program.
func ExecDir() string {
file, _ := exec.LookPath(ExecPath())
filePath, _ := filepath.Abs(file)
index := strings.LastIndex(filePath, string(os.PathSeparator))
ret := filePath[:index]
return ret
}