-
Notifications
You must be signed in to change notification settings - Fork 0
/
changes.go
94 lines (79 loc) · 1.82 KB
/
changes.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
88
89
90
91
92
93
94
package files
import (
"os"
"path"
"github.com/CyrusRoshan/pickture/utils"
)
type fileAction string
const move = fileAction("mv")
const copy = fileAction("cp")
const delete = fileAction("rm")
type Change struct {
OriginalPath string // the original path of the file
NewPaths []string // the new [...copied, moved] file paths
}
type ChangeCommand struct {
Action fileAction
Path1 string
Path2 string
}
func GetChangeCommands(c Change) []ChangeCommand {
commands := make([]ChangeCommand, len(c.NewPaths))
var i int
for i = 0; i < len(c.NewPaths)-1; i++ {
commands[i] = ChangeCommand{
Action: copy,
Path1: c.OriginalPath,
Path2: c.NewPaths[i],
}
}
commands[i] = ChangeCommand{
Action: move,
Path1: c.OriginalPath,
Path2: c.NewPaths[i],
}
return commands
}
func GetReverseChangeCommands(c Change) []ChangeCommand {
commands := make([]ChangeCommand, len(c.NewPaths))
var i int
for i = 0; i < len(c.NewPaths)-1; i++ {
commands[i] = ChangeCommand{
Action: delete,
Path1: c.NewPaths[i],
}
}
commands[i] = ChangeCommand{
Action: move,
Path1: c.NewPaths[i],
Path2: c.OriginalPath,
}
return commands
}
func ExecuteChangeCommands(ccs []ChangeCommand) {
createParentFolder := func(filePath string) {
// Get parent folder
dir := path.Dir(filePath)
// Create only if it doesn't exist
_, err := os.Stat(dir)
if os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
utils.PanicIfErr(err)
}
}
for _, change := range ccs {
switch change.Action {
case move:
createParentFolder(change.Path2)
err := os.Rename(change.Path1, change.Path2)
utils.PanicIfErr(err)
case copy:
createParentFolder(change.Path2)
err := os.Link(change.Path1, change.Path2)
utils.PanicIfErr(err)
case delete:
err := os.Remove(change.Path1)
utils.PanicIfErr(err)
}
}
}