From 5bb26c9e15fb6b20770c4b00f74b844c8c2787bf Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Mon, 12 Aug 2024 00:10:01 +0200 Subject: [PATCH] Implement fmoditer --- main.go | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index 7f7c572..15382d4 100644 --- a/main.go +++ b/main.go @@ -5,9 +5,10 @@ import ( "fmt" "log" "os" + "path" "regexp" + "strings" "sync" - "sync/atomic" ) func init() { @@ -15,17 +16,13 @@ func init() { } func main() { - padSize := flag.Int("n", 5, "Pad size for new file names") recreate := flag.Bool("f", false, "First rename all files to .bak and then rename them to iter (to prevent conflicts of already existing files)") flag.Parse() - nameFormat := fmt.Sprintf("%%0%dd", *padSize) originalExtensions := make(map[string]string) var mapMutex sync.RWMutex var wg sync.WaitGroup - var mutex sync.Mutex extensionRegex := regexp.MustCompile(`\.[a-zA-Z0-9]+$`) - var i int32 if *recreate { log.Printf("Recreating all files first") @@ -33,35 +30,42 @@ func main() { wg.Add(1) go func(file string) { defer wg.Done() + _, err := os.Stat(file) + if os.IsNotExist(err) { + log.Printf("File %s does not exist", file) + return + } + res := extensionRegex.FindAllString(file, -1) if len(res) == 0 { log.Printf("No extension found for file %s", file) return } + dir := path.Dir(file) extension := res[0] - bckpFile := file + ".bak" + bckpFile := fmt.Sprintf("%s/%s.bak", dir, file) - _, err := os.Stat(bckpFile) + _, err = os.Stat(bckpFile) if !os.IsNotExist(err) { log.Printf("File %s already exists", bckpFile) return } - + log.Printf("%s -> %s", file, bckpFile) err = os.Rename(file, bckpFile) if err != nil { log.Printf("Error renaming file %s to %s: %s", file, bckpFile, err) } - + mapMutex.Lock() originalExtensions[bckpFile] = extension mapMutex.Unlock() }(file) } } + wg.Wait() wg = sync.WaitGroup{} - for _, file := range flag.Args() { wg.Add(1) go func(file string) { @@ -81,12 +85,12 @@ func main() { return } - mutex.Lock() - atomic.AddInt32(&i, 1) - newFile := fmt.Sprintf(nameFormat, i) - mutex.Unlock() + modtime := info.ModTime() + modtimeString := modtime.Local().Format("2006-01-02T15-04-05") + newFile := modtimeString - res := extensionRegex.FindAllString(file, -1) + bakless := strings.TrimRight(file, ".bak") + res := extensionRegex.FindAllString(bakless, -1) if len(res) == 0 { log.Printf("No extension found for file %s", file) return @@ -100,12 +104,18 @@ func main() { extension = prevExtension } - newFile = newFile + extension + dir := path.Dir(file) + newFile = fmt.Sprintf("%s/%s%s", dir, newFile, extension) + newFile = path.Clean(newFile) + newFile = strings.TrimRight(newFile, ".bak") _, err = os.Stat(newFile) - if !os.IsNotExist(err) { + if os.IsExist(err) { log.Printf("File %s already exists", newFile) return + } else if !os.IsNotExist(err) { + log.Printf("An unexpected error occurred: %v", err) + return } log.Printf("%s -> %s", file, newFile)