This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorder-my-files.go
87 lines (72 loc) · 2.08 KB
/
order-my-files.go
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
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
//"reflect"
"strconv"
"os"
"os/exec"
)
func main() {
if (len(os.Args)!=2){
fmt.Println("You need to specify the folder path: order-my-files <folder path>")
os.Exit(1)
}
//Get argument 1 as path
path := os.Args[1]
fmt.Println("Path: ",path)
//Get the list of files of the directory
fileList, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
var folder_name string
photo_directories := make(map[string] int)
for _, f := range fileList {
fmt.Printf("File name: %v\n",f.Name())
if (f.IsDir()){
fmt.Printf("The file is a folder. Let's try with next file.\n")
continue
}
//Get modification time from the file
year, month, _ := f.ModTime().Date()
//fmt.Println(year,reflect.TypeOf(year))
//Create folder name
name := []string{strconv.Itoa(int(year)),strconv.Itoa(int(month))}
if int(month) < 10{
folder_name= strings.Join(name,"_0")
}else{
folder_name= strings.Join(name,"_")
}
//Add folder name to map
photo_directories[folder_name] += 1
if (photo_directories[folder_name] == 1){
fmt.Printf("Creating folder name: %v\n",folder_name)
err := os.Mkdir(path+"/"+folder_name,0777) // Create folder.
if err != nil {
log.Fatal(err)
fmt.Printf("Can not create folder: %v\n",folder_name)
}
}
//Copying file to its directory, if the copy goes fine, delete the file
fmt.Printf("Copying file "+ path+"/"+f.Name()+" to "+path+"/"+folder_name+"/"+f.Name()+"\n")
cpCmd := exec.Command("cp", "-rf", path+"/"+f.Name(), path+"/"+folder_name+"/"+f.Name())
err := cpCmd.Run()
if err != nil {
log.Fatal(err)
fmt.Printf("Can not copy file: %v\n",f.Name())
}else{
fmt.Printf("Deleting file: "+path+"/"+f.Name()+"\n")
err := os.Remove(path+"/"+f.Name()) // Remove file.
if err != nil {
log.Fatal(err)
fmt.Printf("Can not delete file: %v\n",f.Name())
}
}
}
//for key, _ := range photo_directories {
// fmt.Println("Key:", key)
//}
}