1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
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))
}
|