Files
BigChef/utils/file.go

97 lines
2.7 KiB
Go

package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
"git.site.quack-lab.dev/dave/cylogger"
)
func CleanPath(path string) string {
log := cylogger.Default.WithPrefix(fmt.Sprintf("CleanPath: %q", path))
log.Trace("Start")
path = filepath.Clean(path)
path = strings.ReplaceAll(path, "\\", "/")
log.Trace("Done: %q", path)
return path
}
func ToAbs(path string) string {
log := cylogger.Default.WithPrefix(fmt.Sprintf("ToAbs: %q", path))
log.Trace("Start")
if filepath.IsAbs(path) {
log.Trace("Path is already absolute: %q", path)
return CleanPath(path)
}
cwd, err := os.Getwd()
if err != nil {
log.Error("Error getting cwd: %v", err)
return CleanPath(path)
}
log.Trace("Cwd: %q", cwd)
return CleanPath(filepath.Join(cwd, path))
}
func ResetWhereNecessary(associations map[string]FileCommandAssociation, db DB) error {
log := cylogger.Default.WithPrefix("ResetWhereNecessary")
log.Debug("Start")
dirtyFiles := make(map[string]struct{})
for _, association := range associations {
for _, command := range association.Commands {
log.Debug("Checking command %q for file %q", command.Name, association.File)
if command.Reset {
log.Debug("Command %q requires reset for file %q", command.Name, association.File)
dirtyFiles[association.File] = struct{}{}
}
}
for _, command := range association.IsolateCommands {
log.Debug("Checking isolate command %q for file %q", command.Name, association.File)
if command.Reset {
log.Debug("Isolate command %q requires reset for file %q", command.Name, association.File)
dirtyFiles[association.File] = struct{}{}
}
}
}
log.Debug("Dirty files: %v", dirtyFiles)
for file := range dirtyFiles {
log.Debug("Resetting file %q", file)
fileData, err := db.GetFile(file)
if err != nil {
log.Warning("Failed to get file %q: %v", file, err)
continue
}
log.Debug("Writing file %q to disk", file)
err = os.WriteFile(file, fileData, 0644)
if err != nil {
log.Warning("Failed to write file %q: %v", file, err)
continue
}
log.Debug("File %q written to disk", file)
}
log.Debug("Done")
return nil
}
func ResetAllFiles(db DB) error {
log := cylogger.Default.WithPrefix("ResetAllFiles")
log.Debug("Start")
fileSnapshots, err := db.GetAllFiles()
if err != nil {
return err
}
log.Debug("Found %d files in database", len(fileSnapshots))
for _, fileSnapshot := range fileSnapshots {
log.Debug("Resetting file %q", fileSnapshot.FilePath)
err = os.WriteFile(fileSnapshot.FilePath, fileSnapshot.FileData, 0644)
if err != nil {
log.Warning("Failed to write file %q: %v", fileSnapshot.FilePath, err)
continue
}
log.Debug("File %q written to disk", fileSnapshot.FilePath)
}
log.Debug("Done")
return nil
}