Last active
November 30, 2021 00:57
-
-
Save awnumar/ce482e315653aa83c8fc400b8ec89987 to your computer and use it in GitHub Desktop.
sort files into folders according to date (must be on same drive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/base64" | |
"flag" | |
"fmt" | |
"io/fs" | |
"os" | |
"path/filepath" | |
"strings" | |
"lukechampine.com/frand" | |
) | |
var ( | |
inputDirectory string | |
outputDirectory string | |
) | |
func main() { | |
var err error | |
flag.StringVar(&inputDirectory, "input", "DCIM", "path to input directory") | |
flag.StringVar(&outputDirectory, "output", "Raw", "path to output directory") | |
flag.Parse() | |
inputDirectory, err = filepath.Abs(inputDirectory) | |
if err != nil { | |
handleError(err) | |
} | |
outputDirectory, err = filepath.Abs(outputDirectory) | |
if err != nil { | |
handleError(err) | |
} | |
if err := process(); err != nil { | |
handleError(err) | |
} | |
} | |
func process() error { | |
if err := filepath.WalkDir(inputDirectory, | |
func(path string, d fs.DirEntry, err error) error { | |
if err != nil { | |
return err | |
} | |
if d.IsDir() { | |
return nil | |
} | |
info, err := d.Info() | |
if err != nil { | |
return err | |
} | |
destDir := filepath.Join(outputDirectory, info.ModTime().Format("2006-01-02")) | |
if err := os.MkdirAll(destDir, os.ModeDir); err != nil { | |
return err | |
} | |
if err := os.Rename(path, filepath.Join(destDir, randomFileName(d.Name()))); err != nil { | |
return err | |
} | |
return nil | |
}); err != nil { | |
return err | |
} | |
if err := os.RemoveAll(inputDirectory); err != nil { | |
return err | |
} | |
return nil | |
} | |
func randomFileName(name string) string { | |
return strings.TrimSuffix(name, filepath.Ext(name)) + "_" + base64.RawURLEncoding.EncodeToString(frand.Bytes(4)) + filepath.Ext(name) | |
} | |
func handleError(err error) { | |
fmt.Fprintln(os.Stderr, err) | |
os.Exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment