1
0
mirror of https://github.com/thebaer/cdr.git synced 2024-11-15 01:31:01 +00:00

Rename all files in current directory

Instead of taking a filename as an argument, we now change all files in the current directory.
This commit is contained in:
Matt Baer 2020-02-25 22:20:12 -05:00
parent f5e71f5a15
commit 29d369f5ae
2 changed files with 23 additions and 13 deletions

View File

@ -3,7 +3,10 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"log"
"os" "os"
"path/filepath"
"strings"
"github.com/thebaer/cdr" "github.com/thebaer/cdr"
) )
@ -16,13 +19,19 @@ var printUsage = func() {
func main() { func main() {
flag.Usage = printUsage flag.Usage = printUsage
flag.Parse() flag.Parse()
if flag.NArg() != 1 {
printUsage()
return
}
file := flag.Arg(0) wd, err := os.Getwd()
oldFilename, trackName := cdr.RenameTrack(file) if err != nil {
fmt.Println("Renaming", oldFilename, "to", trackName) log.Fatal(err)
os.Rename(oldFilename, trackName) }
filepath.Walk(wd, func(path string, i os.FileInfo, err error) error {
if !i.IsDir() && !strings.HasPrefix(i.Name(), ".") {
fName := i.Name()
trackName := cdr.RenameTrack(fName)
fmt.Println("Renaming", fName, "to", trackName)
os.Rename(fName, trackName)
}
return nil
})
} }

View File

@ -15,26 +15,27 @@ var trackNameReg = regexp.MustCompile("^([0-9]{2}).+")
// RenameTrack takes a filename, opens it, reads the metadata, and returns both // RenameTrack takes a filename, opens it, reads the metadata, and returns both
// the old and new filename. // the old and new filename.
func RenameTrack(file string) (string, string) { func RenameTrack(file string) string {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
fmt.Printf("error loading file: %v", err) fmt.Printf("error loading file: %v", err)
return "", "" return ""
} }
defer f.Close() defer f.Close()
fMatch := trackNameReg.FindStringSubmatch(f.Name()) fName := f.Name()
fMatch := trackNameReg.FindStringSubmatch(fName)
if len(fMatch) < 2 { if len(fMatch) < 2 {
log.Fatal("Unexpect filename format") log.Fatal("Unexpect filename format")
} }
trackNum := fMatch[1] trackNum := fMatch[1]
ext := ".mp3" ext := fName[strings.LastIndex(fName, "."):]
m, err := tag.ReadFrom(f) m, err := tag.ReadFrom(f)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
return f.Name(), fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(m.Artist()), Sanitize(m.Title()), ext) return fmt.Sprintf("%s-%s-%s%s", trackNum, Sanitize(m.Artist()), Sanitize(m.Title()), ext)
} }
// Sanitize takes a string and removes problematic characters from it. // Sanitize takes a string and removes problematic characters from it.