utils/convids/logic.go

85 lines
1.5 KiB
Go

package convids
import (
"fmt"
"io"
"os"
fp "path/filepath"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
func NewData(path string) (*Data, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
ydec := yaml.NewDecoder(f)
var data Data
err = ydec.Decode(&data)
return &data, err
}
func ensureExtRe(c *Config) (err error) {
if c.extRe != nil {
return nil
}
c.extRe, err = regexp.Compile("(" + strings.Join(c.Extensions, "|") + ")$")
return
}
type ShowWalker func(show *Show, path string) error
type GroupPrinter func(name string, group Shows)
func WalkFiles(d *Data, stopOnError bool, gp GroupPrinter, cb ShowWalker) (err error) {
err = ensureExtRe(d.Config)
if err != nil {
return
}
if cb == nil {
cb = DryRun(os.Stdout)
}
var files []os.DirEntry
files, err = os.ReadDir(d.Config.Source)
if err != nil {
return
}
for s := range d.AllShows(gp) {
var found bool
for _, file := range files {
if file.IsDir() {
continue
}
if !d.Config.extRe.MatchString(file.Name()) {
continue
}
found, err = s.Match(file.Name())
if err != nil {
return
}
if found {
err = cb(s, fp.Join(d.Config.Source, file.Name()))
if err != nil && stopOnError {
return
}
break
}
}
}
return nil
}
func DryRun(out io.Writer) ShowWalker {
return func(s *Show, path string) error {
fmt.Fprintf(out, "Saving %s to %s\n", path, s.Folder)
return nil
}
}
func PrintGroupName(out io.Writer) GroupPrinter {
return func(name string, group Shows) {
fmt.Fprintf(out, "Checking %s shows\n\n", name)
}
}