fixrbc

Tool to rename RBC statements to yyyy-mm-dd format
git clone https://git.bracken.jp/fixrbc.git
Log | Files | Refs | LICENSE

fixrbc.go (1683B)


      1 // CLI tool to rename all RBC statement PDFs in the current directory to
      2 // YYYY-MM-DD.pdf format.
      3 package main
      4 
      5 import (
      6 	"errors"
      7 	"fmt"
      8 	"io/ioutil"
      9 	"log"
     10 	"os"
     11 	"regexp"
     12 	"strings"
     13 )
     14 
     15 func IsValidFilename(n string) bool {
     16 	r := regexp.MustCompile(`\d+-\d{4}[A-Za-z]{3}\d\d-\d{4}[A-Za-z]{3}\d\d\.pdf`)
     17 	return r.MatchString(n)
     18 }
     19 
     20 // SanitizedFilename returns a filename in YYYY-mm-dd.pdf format. As input, it
     21 // takes a filename in default RBC format (ACCTNO-YYYYmmmDD-YYYYmmmDD.pdf).
     22 func SanitizedFilename(n string) (string, error) {
     23 	if !IsValidFilename(n) {
     24 		return "", errors.New(fmt.Sprintf("invalid filename %s", n))
     25 	}
     26 	date := strings.Split(n, "-")[2][0:9]
     27 	y := date[0:4]
     28 	m, err := getMonthNumber(strings.ToLower(date[4:7]))
     29 	if err != nil {
     30 		return "", err
     31 	}
     32 	d := date[7:9]
     33 	return fmt.Sprintf("%s-%s-%s.pdf", y, m, d), nil
     34 }
     35 
     36 func main() {
     37 	files, err := ioutil.ReadDir("./")
     38 	if err != nil {
     39 		log.Fatal(err)
     40 	}
     41 	for _, f := range files {
     42 		if IsValidFilename(f.Name()) {
     43 			newFname, err := SanitizedFilename(f.Name())
     44 			if err != nil {
     45 				log.Fatal(err)
     46 			}
     47 			os.Rename(f.Name(), newFname)
     48 		}
     49 	}
     50 }
     51 
     52 func getMonthNumber(m string) (string, error) {
     53 	switch {
     54 	case m == "jan":
     55 		return "01", nil
     56 	case m == "feb":
     57 		return "02", nil
     58 	case m == "mar":
     59 		return "03", nil
     60 	case m == "apr":
     61 		return "04", nil
     62 	case m == "may":
     63 		return "05", nil
     64 	case m == "jun":
     65 		return "06", nil
     66 	case m == "jul":
     67 		return "07", nil
     68 	case m == "aug":
     69 		return "08", nil
     70 	case m == "sep":
     71 		return "09", nil
     72 	case m == "oct":
     73 		return "10", nil
     74 	case m == "nov":
     75 		return "11", nil
     76 	case m == "dec":
     77 		return "12", nil
     78 	}
     79 	return "", fmt.Errorf("Bad month name: %s", m)
     80 }