Files
fmoditer/main.go

107 lines
2.2 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"os"
"path"
"regexp"
"strings"
"sync"
)
func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
}
func main() {
flag.Parse()
var wg sync.WaitGroup
var renamedFiles map[string]struct{} = make(map[string]struct{})
var mapMutex sync.RWMutex
extensionRegex := regexp.MustCompile(`\.[a-zA-Z0-9]+$`)
wg.Wait()
wg = sync.WaitGroup{}
for _, file := range flag.Args() {
wg.Add(1)
go func(file string) {
defer wg.Done()
file = path.Clean(file)
log.Printf("Checking file %s", file)
if !DoesFileExist(file) {
log.Printf("File %s does not exist", file)
return
}
info, err := os.Stat(file)
if info == nil {
log.Printf("Error checking file %s: %s", file, err)
return
}
if info.IsDir() {
log.Printf("File %s is a directory", file)
return
}
modtime := info.ModTime()
modtimeString := modtime.Local().Format("2006-01-02T15-04-05")
newFile := modtimeString
res := extensionRegex.FindAllString(file, -1)
if len(res) == 0 {
log.Printf("No extension found for file %s", file)
return
}
extension := res[0]
dir := path.Dir(file)
newFile = fmt.Sprintf("%s/%s%s", dir, newFile, extension)
newFile = path.Clean(newFile)
newFile = strings.TrimRight(newFile, ".bak")
log.Printf("New file name for %s: %s", file, newFile)
if DoesFileExist(newFile) {
log.Printf("File %s already exists", newFile)
return
}
log.Printf("%#v", newFile)
mapMutex.RLock()
_, ok := renamedFiles[newFile]
mapMutex.RUnlock()
if ok {
log.Printf("File %s already renamed", newFile)
return
}
if file == newFile {
log.Printf("File %s already has the correct name", file)
return
}
log.Printf("%s -> %s", file, newFile)
mapMutex.Lock()
renamedFiles[newFile] = struct{}{}
mapMutex.Unlock()
err = os.Rename(file, newFile)
if err != nil {
log.Printf("Error renaming file %s to %s: %s", file, newFile, err)
return
}
}(file)
}
wg.Wait()
}
func DoesFileExist(input string) bool {
file, err := os.Open(input)
if err != nil {
return false
}
file.Close()
return true
}