86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func SafeJoin(base string, elements ...string) string {
|
|
path := filepath.Join(append([]string{base}, elements...)...)
|
|
return filepath.Clean(path)
|
|
}
|
|
|
|
func EnsureDir(path string) error {
|
|
if err := os.MkdirAll(path, 0755); err != nil {
|
|
return fmt.Errorf("failed to create directory %s: %w", path, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func PathExists(path string) bool {
|
|
_, err := os.Stat(path)
|
|
return !os.IsNotExist(err)
|
|
}
|
|
|
|
// IsValidPath reports whether path is usable on Windows, the stricter of the
|
|
// two platforms this project targets, which reserves <>:"|?* in names.
|
|
//
|
|
// A leading drive letter is checked separately: its colon is legal there and
|
|
// nowhere else in the path. Without that carve-out the function rejects every
|
|
// absolute Windows path, including the drive-qualified ones it exists to
|
|
// validate.
|
|
func IsValidPath(path string) bool {
|
|
if path == "" {
|
|
return false
|
|
}
|
|
|
|
rest := path
|
|
if len(rest) >= 2 && rest[1] == ':' && isDriveLetter(rest[0]) {
|
|
rest = rest[2:]
|
|
}
|
|
|
|
return !strings.ContainsAny(rest, `<>:"|?*`)
|
|
}
|
|
|
|
func isDriveLetter(c byte) bool {
|
|
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|
|
}
|
|
|
|
func NormalizePath(path string) string {
|
|
return filepath.Clean(strings.ReplaceAll(path, "\\", string(filepath.Separator)))
|
|
}
|
|
|
|
func GetRelativePath(basePath, targetPath string) (string, error) {
|
|
// filepath.Rel("", "") succeeds and returns ".", which is a meaningless
|
|
// answer to a meaningless question; callers passing an empty path have a
|
|
// bug worth surfacing rather than papering over.
|
|
if basePath == "" || targetPath == "" {
|
|
return "", fmt.Errorf("both base and target paths are required (base %q, target %q)", basePath, targetPath)
|
|
}
|
|
|
|
rel, err := filepath.Rel(basePath, targetPath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to get relative path: %w", err)
|
|
}
|
|
return rel, nil
|
|
}
|
|
|
|
func ValidateWritablePath(path string) error {
|
|
dir := filepath.Dir(path)
|
|
if err := EnsureDir(dir); err != nil {
|
|
return err
|
|
}
|
|
|
|
testFile := filepath.Join(dir, ".write_test")
|
|
file, err := os.Create(testFile)
|
|
if err != nil {
|
|
return fmt.Errorf("path %s is not writable: %w", dir, err)
|
|
}
|
|
file.Close()
|
|
os.Remove(testFile)
|
|
|
|
return nil
|
|
}
|