/
processor.go
140 lines (99 loc) · 2.55 KB
/
processor.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package generic
import (
"strings"
"github.com/mateussouzaweb/compactor/compactor"
"github.com/mateussouzaweb/compactor/os"
)
// RunProcessor create generic copy of file(s) to destination
func RunProcessor(bundle *compactor.Bundle) error {
if bundle.ShouldOutputToMany() {
for _, item := range bundle.Items {
if !item.Exists {
continue
}
destination := bundle.ToDestination(item.Path)
err := os.Copy(item.Path, destination)
if err != nil {
return err
}
bundle.Processed(item.Path)
}
return nil
}
content := ""
for _, item := range bundle.Items {
if item.Exists {
content += item.Content
}
}
destination := bundle.ToDestination(bundle.Destination.File)
perm := bundle.Items[0].Permission
err := os.Write(destination, content, perm)
if err == nil {
bundle.Written(destination)
}
return err
}
// DeleteProcessor remove the destination file(s)
func DeleteProcessor(bundle *compactor.Bundle) error {
toDelete := []string{}
if bundle.ShouldOutputToMany() {
for _, item := range bundle.Items {
destination := bundle.ToDestination(item.Path)
hashed := bundle.ToHashed(destination, item.Checksum)
previous := bundle.ToHashed(destination, item.Previous)
toDelete = append(toDelete, destination, hashed, previous)
}
} else {
content := ""
for _, item := range bundle.Items {
if item.Exists {
content += item.Content
}
}
hash, err := os.Checksum(content)
if err != nil {
return err
}
destination := bundle.ToDestination(bundle.Destination.File)
hashed := bundle.ToHashed(destination, hash)
toDelete = append(toDelete, destination, hashed)
}
for _, file := range toDelete {
if !os.Exist(file) {
continue
}
err := os.Delete(file)
if err != nil {
return err
}
bundle.Deleted(file)
}
return nil
}
// ResolveProcessor fix the path for given file path
func ResolveProcessor(path string) (string, error) {
bundle := compactor.GetBundleFor(path)
if bundle.ShouldOutputToMany() {
destination := bundle.ToDestination(path)
destination = bundle.CleanPath(destination)
if strings.HasPrefix(path, "/") {
destination = "/" + destination
}
return destination, nil
}
destination := bundle.ToDestination(bundle.Destination.File)
destination = bundle.CleanPath(destination)
if strings.HasPrefix(path, "/") {
destination = "/" + destination
}
return destination, nil
}
func Plugin() *compactor.Plugin {
return &compactor.Plugin{
Extensions: []string{},
Run: RunProcessor,
Delete: DeleteProcessor,
Resolve: ResolveProcessor,
}
}