This repository has been archived by the owner on May 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
/
osutil.go
67 lines (60 loc) · 1.76 KB
/
osutil.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
package osutil
import (
"fmt"
"os"
"runtime"
"syscall"
)
// Exists returns whether the given file or directory exists or not.
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// SymlinkWithFallback attempts to symlink a file or directory, but falls back to a move operation
// in the event of the user not having the required privileges to create the symlink.
func SymlinkWithFallback(oldname, newname string) (err error) {
err = os.Symlink(oldname, newname)
if runtime.GOOS == "windows" {
// If creating the symlink fails on Windows because the user
// does not have the required privileges, ignore the error and
// fall back to renaming the file.
//
// ERROR_PRIVILEGE_NOT_HELD is 0x522:
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx
if lerr, ok := err.(*os.LinkError); ok && lerr.Err == syscall.Errno(0x522) {
err = os.Rename(oldname, newname)
}
}
return
}
// EnsureDirectory checks if a directory exists and creates it if it doesn't exist
func EnsureDirectory(dir string) error {
if fi, err := os.Stat(dir); err != nil {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("Could not create %s: %s", dir, err)
}
} else if !fi.IsDir() {
return fmt.Errorf("%s must be a directory", dir)
}
return nil
}
// EnsureFile checks if a file exists and creates it if it doesn't exist
func EnsureFile(file string) error {
fi, err := os.Stat(file)
if err != nil {
f, err := os.Create(file)
if err != nil {
return fmt.Errorf("Could not create %s: %s", file, err)
}
defer f.Close()
} else if fi.IsDir() {
return fmt.Errorf("%s must not be a directory", file)
}
return nil
}