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:
parent
f5e71f5a15
commit
29d369f5ae
@ -3,7 +3,10 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/thebaer/cdr"
|
||||
)
|
||||
@ -16,13 +19,19 @@ var printUsage = func() {
|
||||
func main() {
|
||||
flag.Usage = printUsage
|
||||
flag.Parse()
|
||||
if flag.NArg() != 1 {
|
||||
printUsage()
|
||||
return
|
||||
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
file := flag.Arg(0)
|
||||
oldFilename, trackName := cdr.RenameTrack(file)
|
||||
fmt.Println("Renaming", oldFilename, "to", trackName)
|
||||
os.Rename(oldFilename, trackName)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
11
sanitize.go
11
sanitize.go
@ -15,26 +15,27 @@ 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) {
|
||||
func RenameTrack(file string) string {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
fmt.Printf("error loading file: %v", err)
|
||||
return "", ""
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
fMatch := trackNameReg.FindStringSubmatch(f.Name())
|
||||
fName := f.Name()
|
||||
fMatch := trackNameReg.FindStringSubmatch(fName)
|
||||
if len(fMatch) < 2 {
|
||||
log.Fatal("Unexpect filename format")
|
||||
}
|
||||
trackNum := fMatch[1]
|
||||
ext := ".mp3"
|
||||
ext := fName[strings.LastIndex(fName, "."):]
|
||||
|
||||
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)
|
||||
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.
|
||||
|
Loading…
Reference in New Issue
Block a user