goldsmith/file_exporter.go

91 lines
1.7 KiB
Go
Raw Normal View History

2023-12-10 17:41:50 +00:00
package goldsmith
import (
2024-02-20 00:26:41 +00:00
"io"
2023-12-10 17:41:50 +00:00
"os"
"path/filepath"
)
type fileExporter struct {
targetDir string
clean bool
tokens map[string]bool
}
func (*fileExporter) Name() string {
return "exporter"
}
func (self *fileExporter) Initialize(context *Context) error {
2023-12-10 17:41:50 +00:00
self.tokens = make(map[string]bool)
context.Threads(1)
return nil
}
func (self *fileExporter) Process(context *Context, file *File) error {
2023-12-10 17:41:50 +00:00
slicePath := func(path string) string {
if filepath.IsAbs(path) {
var err error
if path, err = filepath.Rel("/", path); err != nil {
panic(err)
}
}
return filepath.Clean(path)
}
2024-02-20 00:26:41 +00:00
for token := slicePath(file.Path()); token != "."; token = filepath.Dir(token) {
2023-12-10 17:41:50 +00:00
self.tokens[token] = true
}
2024-02-20 00:26:41 +00:00
targetPath := filepath.Join(self.targetDir, file.Path())
if targetInfo, err := os.Stat(targetPath); err == nil && !targetInfo.ModTime().Before(file.ModTime()) {
return nil
}
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
return err
}
fw, err := os.Create(targetPath)
if err != nil {
return err
}
defer fw.Close()
if _, err := file.Seek(0, io.SeekStart); err != nil {
return err
}
if _, err := file.WriteTo(fw); err != nil {
return err
}
return nil
2023-12-10 17:41:50 +00:00
}
func (self *fileExporter) Finalize(context *Context) error {
2023-12-10 17:41:50 +00:00
if !self.clean {
return nil
}
2023-12-10 17:51:46 +00:00
return filepath.Walk(self.targetDir, func(path string, info os.FileInfo, err error) error {
if path == self.targetDir {
return nil
2023-12-10 17:41:50 +00:00
}
2023-12-10 17:51:46 +00:00
relPath, err := filepath.Rel(self.targetDir, path)
2023-12-10 17:41:50 +00:00
if err != nil {
panic(err)
}
if tokenized, _ := self.tokens[relPath]; !tokenized {
2023-12-10 17:51:46 +00:00
if err := os.RemoveAll(path); err != nil {
2023-12-10 17:41:50 +00:00
return err
}
}
2023-12-10 17:51:46 +00:00
return nil
})
2023-12-10 17:41:50 +00:00
}