show-ingestion/main.go

99 lines
2.0 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
"path"
"regexp"
"strings"
"syscall"
)
type Fields struct {
Title string
Season string
Episode string
}
func main() {
ctx, can := signal.NotifyContext(context.Background(), syscall.SIGINT)
defer can()
var overrides Fields
json.Unmarshal([]byte(os.Args[3]), &overrides)
if err := Run(ctx,
os.Args[1],
os.Args[2],
os.Args[4:],
overrides,
); err != nil {
panic(err)
}
}
func Run(ctx context.Context, outd, ind string, patterns []string, overrides Fields) error {
entries, err := os.ReadDir(ind)
if err != nil {
return err
}
for _, entry := range entries {
if !entry.Type().IsRegular() {
continue
}
if err := one(ctx, outd, path.Join(ind, entry.Name()), patterns, overrides); err != nil {
return err
}
}
return nil
}
func one(ctx context.Context, outd, inf string, patterns []string, overrides Fields) error {
f := path.Base(inf)
for _, pattern := range patterns {
re := regexp.MustCompile(pattern)
if !re.MatchString(f) {
continue
}
found := overrides
groupNames := re.SubexpNames()
groups := re.FindStringSubmatch(f)
for i := 1; i < len(groupNames); i++ {
v := groups[i]
switch groupNames[i] {
case "title":
found.Title = v
case "season":
found.Season = v
case "episode":
found.Episode = v
default:
return fmt.Errorf("unexpected capture group %q", groupNames[i])
}
}
if found.Title == "" || found.Season == "" || found.Episode == "" {
continue
}
found.Title = strings.Join(strings.Fields(found.Title), "_")
return mvNLn(ctx, outd, inf, found)
}
return nil
}
func mvNLn(ctx context.Context, outd, inf string, fields Fields) error {
outf := path.Join(outd, fmt.Sprintf("%s_S%sE%s%s", fields.Title, fields.Season, fields.Episode, path.Ext(inf)))
if _, err := os.Stat(outf); err == nil {
return nil // fmt.Errorf("conflict: %s already exists", path.Base(outf))
}
if err := os.Rename(inf, outf); err != nil {
return err
}
return os.Symlink(outf, inf)
}