dl-rename/main.go
2017-09-16 18:03:32 +02:00

61 lines
1.2 KiB
Go

package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Println("No action specified")
return
}
switch args[0] {
case "removesuffix":
fallthrough
case "rs":
suffix := args[1]
removeSuffix(suffix)
break
default:
fmt.Println("Invalid action specified")
return
}
}
func removeSuffix(suffix string) {
filepath.Walk(".", removeSuffixFunc(suffix))
}
func removeSuffixFunc(suffix string) filepath.WalkFunc {
return func(p string, f os.FileInfo, err error) error {
filename := f.Name()
if filename == "." || filename == ".." {
return nil
}
element := newMediaElement(p)
fmt.Println(element.String())
dir := filepath.Dir(p)
ext := filepath.Ext(filename)
filenameNoExt := trimSuffix(filename, ext)
filenameNoSuff := trimSuffix(filenameNoExt, suffix)
if filenameNoSuff != filenameNoExt {
newFilename := filenameNoSuff + ext
err := os.Rename(filepath.Join(dir, filename), filepath.Join(dir, newFilename))
if err != nil {
fmt.Printf("Could not rename %s: %v\n", filename, err)
} else {
fmt.Println("Renamed " + filename + " to " + newFilename)
}
}
return nil
}
}