Some improvements to audiobooker
[cmccabe-bin] / audiobooker.go
index c330c89..7116e3f 100644 (file)
@@ -7,10 +7,12 @@ import (
        "path/filepath"
        "io/ioutil"
        "fmt"
+       "math"
        "os"
        "sort"
        "path"
        "strings"
+       "strconv"
 )
 
 const MP3_SUFFIX = ".mp3"
@@ -120,6 +122,42 @@ func (out *OutDir) CopyFile(src string) error {
        return err
 }
 
+func (out *OutDir) GetNumDigitsNeeded() int {
+       i := math.Log10(float64(out.nextIndex))
+       j := math.Floor(i)
+       if j < i {
+               return 1 + int(j)
+       } else {
+               return int(j)
+       }
+}
+
+func (out *OutDir) RenameOutputFiles() error {
+       numDigitsNeeded := out.GetNumDigitsNeeded()
+       fs := "%0" + strconv.Itoa(numDigitsNeeded) + "d" + MP3_SUFFIX
+       d, err := os.Open(out.outPath); if err != nil {
+               return fmt.Errorf("Unable to open directory %s: %s", out.outPath, err.Error())
+       }
+       defer d.Close()
+       names, err := d.Readdirnames(0); if err != nil && err != io.EOF {
+               return fmt.Errorf("Unable to readdir %s: %s", out.outPath, err.Error())
+       }
+       for i := range names {
+               index := -1
+               _, err = fmt.Sscanf(names[i], "%d", &index); if err != nil {
+                       return fmt.Errorf("Unable to parse file name %s", names[i])
+               }
+               newName := fmt.Sprintf(fs, index)
+               src := path.Join(out.outPath, names[i])
+               dst := path.Join(out.outPath, newName)
+               err = os.Rename(src, dst)
+               if err != nil {
+                       return fmt.Errorf("Failed to rename %s to %s: %s", src, dst, err.Error())
+               }
+       }
+       return nil
+}
+
 type InContext struct {
        inPath string // The original input file path.
        tempDir string // The path to the temporary directory.
@@ -225,5 +263,10 @@ func main() {
                fmt.Printf("Split %s into %d file(s)\n", inPaths[i], len(paths))
                totalFiles += int64(len(paths))
        }
+       err = outDir.RenameOutputFiles()
+       if err != nil {
+               fmt.Printf("Error renaming output files in %s: %s", outDir.outPath, err.Error())
+               os.Exit(1)
+       }
        fmt.Printf("Processed %d total file(s)\n", totalFiles)
 }