-
Notifications
You must be signed in to change notification settings - Fork 212
/
dirs.go
78 lines (66 loc) · 2.09 KB
/
dirs.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
// Package filesystem provides functionality for interacting with directories and files in a cross-platform manner.
package filesystem
import (
"fmt"
"os"
"os/user"
"path"
"strings"
)
// Using a function pointer to get the current user so we can more easily mock in tests.
var currentUser = user.Current
// Directory and paths funcs
// OwnerReadWriteExec is a standard owner read / write / exec file permission.
const OwnerReadWriteExec = 0o700
// OwnerReadWrite is a standard owner read / write file permission.
const OwnerReadWrite = 0o600
// PathExists returns true iff file exists in local store and is accessible.
func PathExists(path string) bool {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return err == nil
}
// GetUserHomeDirectory returns the current user's home directory if one is set by the system.
func GetUserHomeDirectory() string {
if home := os.Getenv("HOME"); home != "" {
return home
}
if usr, err := currentUser(); err == nil {
return usr.HomeDir
}
return ""
}
// GetCanonicalPath returns an os-specific full path following these rules:
// - replace ~ with user's home dir path
// - expand any ${vars} or $vars
// - resolve relative paths /.../
// p: source path name
func GetCanonicalPath(p string) string {
if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
if home := GetUserHomeDirectory(); home != "" {
p = home + p[1:]
}
}
return path.Clean(os.ExpandEnv(p))
}
// GetFullDirectoryPath gets the OS specific full path for a named directory.
// The directory is created if it doesn't exist.
func GetFullDirectoryPath(name string) (string, error) {
aPath := GetCanonicalPath(name)
// create dir if it doesn't exist
if err := os.MkdirAll(aPath, OwnerReadWriteExec); err != nil {
return aPath, fmt.Errorf("os.MkdirAll: %w", err)
}
return aPath, nil
}
// ExistOrCreate creates the given path if it does not exist.
func ExistOrCreate(path string) (err error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := os.MkdirAll(path, OwnerReadWriteExec); err != nil {
return fmt.Errorf("os.MkdirAll: %w", err)
}
}
return nil
}