zk/util/paths/paths.go

64 lines
1.3 KiB
Go
Raw Normal View History

2020-12-28 15:00:48 +00:00
package paths
import (
"os"
"path/filepath"
"strings"
2021-01-09 12:01:41 +00:00
"time"
2020-12-28 15:00:48 +00:00
)
2021-01-09 12:01:41 +00:00
// Metadata holds information about a file path.
type Metadata struct {
Path string
Modified time.Time
}
2020-12-28 15:00:48 +00:00
// Exists returns whether the given path exists on the file system.
func Exists(path string) (bool, error) {
2020-12-31 12:44:17 +00:00
fi, err := fileInfo(path)
if err != nil {
return false, err
2020-12-28 15:00:48 +00:00
} else {
2020-12-31 12:44:17 +00:00
return fi != nil, nil
}
}
// DirExists returns whether the given path exists and is a directory.
func DirExists(path string) (bool, error) {
fi, err := fileInfo(path)
if err != nil {
2020-12-28 15:00:48 +00:00
return false, err
2020-12-31 12:44:17 +00:00
} else {
return fi != nil && (*fi).Mode().IsDir(), nil
}
}
func fileInfo(path string) (*os.FileInfo, error) {
if fi, err := os.Stat(path); err == nil {
return &fi, nil
} else if os.IsNotExist(err) {
return nil, nil
} else {
return nil, err
2020-12-28 15:00:48 +00:00
}
}
// FilenameStem returns the filename component of the given path,
// after removing its file extension.
func FilenameStem(path string) string {
filename := filepath.Base(path)
ext := filepath.Ext(filename)
return strings.TrimSuffix(filename, ext)
}
// WriteString writes the given content into a new file at the given path.
func WriteString(path string, content string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(content)
return err
}