Last active
August 30, 2018 18:13
-
-
Save dansku/0e707da68e67667c6e75393e6a122cc3 to your computer and use it in GitHub Desktop.
Script to organize photos upload to Camera Upload dropbox folder.
This file contains 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 ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
"strconv" | |
"strings" | |
"time" | |
) | |
func main() { | |
// Start timer to calculate time to execute all functions | |
start := time.Now() | |
// Accepted file format array | |
fileFormats := []string{".JPG", ".jpg", ".MOV", ".mov", ".PNG", ".png", ".mp4", ".MP4"} | |
// List all files in directory | |
files := listFilesInDirectory(".") | |
for _, f := range files { | |
fileExtension := filepath.Ext(f.Name()) | |
// Only work with file extensions from fileFormats | |
if stringInSlice(fileExtension, fileFormats) { | |
go moveFile(f.Name(), parseDate(f.Name())) | |
} | |
} | |
elapsed := time.Since(start) | |
fmt.Println("Job completed in", elapsed) | |
fmt.Println("Press ENTER to quit application/") | |
var input string | |
fmt.Scanln(&input) | |
} | |
func stringInSlice(a string, list []string) bool { | |
for _, b := range list { | |
if b == a { | |
return true | |
} | |
} | |
return false | |
} | |
func parseDate(a string) []string { | |
fileDates := strings.Split(strings.Split(a, " ")[0], "-") | |
return fileDates | |
} | |
func createDirIfNotExist(dir string) { | |
if _, err := os.Stat(dir); os.IsNotExist(err) { | |
err = os.MkdirAll(dir, 0755) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
func listFilesInDirectory(dir string) []os.FileInfo { | |
files, err := ioutil.ReadDir(dir) | |
// In case of error, print the error message | |
if err != nil { | |
log.Fatal(err) | |
} | |
return files | |
} | |
func moveFile(filename string, parsedDate []string) { | |
// Months of the year | |
monthsOfTheYear := [12]string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} | |
year := parsedDate[0] | |
month := parsedDate[1] | |
monthInt, _ := strconv.ParseInt(parsedDate[1], 10, 64) | |
// Create directory to move file | |
createDirIfNotExist(filepath.Join(year, month+"-"+monthsOfTheYear[monthInt-1])) | |
// Move file | |
os.Rename(filename, filepath.Join(year, month+"-"+monthsOfTheYear[monthInt-1], filename)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment