commit f5e71f5a15167e185c5e8f14187a0b92f2872993 Author: Matt Baer Date: Tue Feb 25 20:54:12 2020 -0500 Add basic file renaming utility diff --git a/cmd/cdr/main.go b/cmd/cdr/main.go new file mode 100644 index 0000000..d9de0e6 --- /dev/null +++ b/cmd/cdr/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/thebaer/cdr" +) + +var printUsage = func() { + fmt.Fprintf(os.Stderr, "usage: %s [optional flags] filename\n", os.Args[0]) + flag.PrintDefaults() +} + +func main() { + flag.Usage = printUsage + flag.Parse() + if flag.NArg() != 1 { + printUsage() + return + } + + file := flag.Arg(0) + oldFilename, trackName := cdr.RenameTrack(file) + fmt.Println("Renaming", oldFilename, "to", trackName) + os.Rename(oldFilename, trackName) +} diff --git a/sanitize.go b/sanitize.go new file mode 100644 index 0000000..15284ba --- /dev/null +++ b/sanitize.go @@ -0,0 +1,52 @@ +package cdr + +import ( + "fmt" + "log" + "os" + "regexp" + "strings" + "unicode" + + "github.com/dhowden/tag" +) + +var trackNameReg = regexp.MustCompile("^([0-9]{2}).+") + +// RenameTrack takes a filename, opens it, reads the metadata, and returns both +// the old and new filename. +func RenameTrack(file string) (string, string) { + f, err := os.Open(file) + if err != nil { + fmt.Printf("error loading file: %v", err) + return "", "" + } + defer f.Close() + + fMatch := trackNameReg.FindStringSubmatch(f.Name()) + if len(fMatch) < 2 { + log.Fatal("Unexpect filename format") + } + trackNum := fMatch[1] + ext := ".mp3" + + m, err := tag.ReadFrom(f) + if err != nil { + log.Fatal(err) + } + return f.Name(), fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(m.Artist()), Sanitize(m.Title()), ext) +} + +// Sanitize takes a string and removes problematic characters from it. +func Sanitize(s string) string { + s = strings.Map(func(r rune) rune { + if r == '(' || r == ')' || r == '[' || r == ']' || r == '.' { + return -1 + } + if unicode.IsSpace(r) { + return '_' + } + return r + }, s) + return s +}