/
path.go
115 lines (102 loc) · 2.39 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package paw
import (
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/mitchellh/go-homedir"
"github.com/sirupsen/logrus"
// log "github.com/sirupsen/logrus"
)
// HasFile : Check if file exists in the current directory
func HasFile(filename string) bool {
if info, err := os.Stat(filename); os.IsExist(err) {
return !info.IsDir()
}
return false
}
// IsFileExist reports whether the named file exists as a boolean
func IsFileExist(name string) bool {
if fi, err := os.Stat(name); err == nil {
if fi.Mode().IsRegular() {
return true
}
}
return false
}
// IsDirExist reports whether the dir exists as a boolean
func IsDirExist(name string) bool {
if fi, err := os.Stat(name); err == nil {
if fi.Mode().IsDir() {
return true
}
}
return false
}
// IsExists reports whether the file or dir exists as a boolean
func IsExist(name string) bool {
return IsDirExist(name) || IsFileExist(name)
}
// IsPathExist return whether the path exists.
func IsPathExist(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
// path/to/whatever does not exist
return false
}
// path/to/whatever exists
return true
}
// GetCurrPath get the current path
func GetCurrPath() string {
// file, _ := exec.LookPath(os.Args[0])
// path, _ := filepath.Abs(file)
// index := strings.LastIndex(path, string(os.PathSeparator))
// ret := path[:index]
// return ret
var abPath string
_, fileName, _, ok := runtime.Caller(1)
if ok {
abPath = filepath.Dir(fileName)
}
return abPath
}
// GetAppDir get the current app directory
func GetAppDir() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
Logger.WithFields(logrus.Fields{
"_os_Args_0": os.Args[0],
}).Warn(err)
}
// Logger.Debugln(dir)
return dir
}
// GetDotDir return the absolute path of "."
func GetDotDir() string {
// w, _ := homedir.Expand(".")
w, _ := filepath.Abs(".")
// Logger.Debugln("get dot working dir", w)
return w
}
// GetHomeDir get the home directory of user
func GetHomeDir() string {
Log.Info("get home dir")
home, _ := homedir.Dir()
return home
}
// MakeAll check path and create like as `make -p path`
func MakeAll(path string) error {
// check
if IsPathExist(path) {
return nil
}
err := os.MkdirAll(path, os.ModePerm) // 0755
if err != nil {
return err
}
// check again
if !IsPathExist(path) {
return fmt.Errorf("Makeall: fail to create %q", path)
}
return nil
}