hibiscus/internal/files/files.go

69 lines
1.9 KiB
Go
Raw Normal View History

2024-10-21 16:46:25 +03:00
package files
2024-03-15 18:34:24 +03:00
import (
2024-03-30 14:33:39 +03:00
"bytes"
"errors"
2024-03-20 16:18:23 +03:00
"log/slog"
2024-03-15 18:34:24 +03:00
"os"
2024-03-18 20:04:14 +03:00
"path"
2024-03-15 18:34:24 +03:00
"path/filepath"
"strings"
)
// DataFile modifies file path to ensure it's a .txt inside the data folder.
2024-05-09 23:44:37 +03:00
func DataFile(filename string) string {
return "data/" + path.Clean(filename) + ".txt"
}
2024-10-21 16:46:25 +03:00
// Read returns contents of a file.
func Read(filename string) ([]byte, error) {
2024-03-18 20:04:14 +03:00
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
return nil, err
2024-03-15 18:34:24 +03:00
}
2024-03-18 20:04:14 +03:00
fileContents, err := os.ReadFile(filename)
2024-03-15 18:34:24 +03:00
if err != nil {
slog.Error("error reading file", "error", err, "file", filename)
return nil, err
2024-03-15 18:34:24 +03:00
}
return fileContents, nil
2024-03-15 18:34:24 +03:00
}
2024-10-21 16:46:25 +03:00
// Save Writes contents to a file.
func Save(filename string, contents []byte) error {
contents = bytes.TrimSpace(contents)
if len(contents) == 0 { // Delete empty files
err := os.Remove(filename)
slog.Error("error deleting empty file", "error", err, "file", filename)
return err
}
2024-05-04 22:42:47 +03:00
err := os.MkdirAll(path.Dir(filename), 0755) // Create dir in case it doesn't exist yet to avoid errors
if err != nil {
slog.Error("error creating directory", "error", err, "file", filename)
return err
}
2024-03-30 14:33:39 +03:00
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
2024-03-15 18:34:24 +03:00
if err != nil {
slog.Error("error opening/creating file", "error", err, "file", filename)
return err
2024-03-15 18:34:24 +03:00
}
if _, err := f.Write(contents); err != nil {
slog.Error("error writing to file", "error", err, "file", filename)
return err
2024-03-15 18:34:24 +03:00
}
return nil
2024-03-15 18:34:24 +03:00
}
2024-10-21 16:46:25 +03:00
// List returns slice of filenames in a directory without extensions or path.
2024-05-09 23:44:37 +03:00
// NOTE: What if I ever want to list non-text files or those outside data directory?
2024-10-21 16:46:25 +03:00
func List(directory string) ([]string, error) {
2024-05-09 23:44:37 +03:00
filenames, err := filepath.Glob("data/" + path.Clean(directory) + "/*.txt")
2024-03-15 18:34:24 +03:00
if err != nil {
return nil, err
2024-03-15 18:34:24 +03:00
}
for i, file := range filenames {
file, _ := strings.CutSuffix(filepath.Base(file), filepath.Ext(file))
filenames[i] = file
}
return filenames, nil
2024-03-15 18:34:24 +03:00
}