2015-09-12 10:54:43 +00:00
|
|
|
// Package fileutil contains common file functions.
|
|
|
|
package fileutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2023-05-05 05:52:16 +00:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2015-09-12 10:54:43 +00:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
2016-08-23 19:59:34 +00:00
|
|
|
// FileDoesExist returns true if the file exists.
|
|
|
|
func FileDoesExist(path string) bool {
|
2015-09-12 10:54:43 +00:00
|
|
|
_, err := os.Stat(path)
|
|
|
|
return !os.IsNotExist(err)
|
|
|
|
}
|
|
|
|
|
2016-08-23 19:59:34 +00:00
|
|
|
// DirectoryDoesExist returns true if the file exists.
|
|
|
|
func DirectoryDoesExist(path string) bool {
|
2015-09-12 10:54:43 +00:00
|
|
|
fi, err := os.Stat(path)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return fi.Mode().IsDir()
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
// AccessExists checks whether the file exists.
|
|
|
|
AccessExists = unix.F_OK
|
|
|
|
|
|
|
|
// AccessRead checks whether the user has read permissions on
|
|
|
|
// the file.
|
|
|
|
AccessRead = unix.R_OK
|
|
|
|
|
|
|
|
// AccessWrite checks whether the user has write permissions
|
|
|
|
// on the file.
|
|
|
|
AccessWrite = unix.W_OK
|
|
|
|
|
|
|
|
// AccessExec checks whether the user has executable
|
|
|
|
// permissions on the file.
|
|
|
|
AccessExec = unix.X_OK
|
|
|
|
)
|
|
|
|
|
|
|
|
// Access returns a boolean indicating whether the mode being checked
|
|
|
|
// for is valid.
|
|
|
|
func Access(path string, mode int) error {
|
|
|
|
return unix.Access(path, uint32(mode))
|
|
|
|
}
|
2023-05-05 05:52:16 +00:00
|
|
|
|
|
|
|
// ValidateSymlink checks to make sure a symlink exists in some top-level
|
|
|
|
// directory.
|
|
|
|
func ValidateSymlink(symlink, topLevel string) bool {
|
|
|
|
target, err := filepath.EvalSymlinks(symlink)
|
|
|
|
return strings.HasPrefix(target, topLevel)
|
|
|
|
}
|