-
Notifications
You must be signed in to change notification settings - Fork 38
/
static_unit.go
107 lines (94 loc) · 2 KB
/
static_unit.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
package core
import (
"os"
"path/filepath"
)
type (
StaticUnit struct {
Name string
IndexDocument string
StaticFiles ConcurrentMap[string, File]
SharedFiles ConcurrentMap[string, File]
}
)
var StaticUnitKind = "static_unit"
func (unit *StaticUnit) Key() ResourceKey {
return ResourceKey{
Name: unit.Name,
Kind: StaticUnitKind,
}
}
func (unit *StaticUnit) OutputTo(dest string) error {
errs := make(chan error)
files := unit.Files()
for idx := range files {
go func(f File) {
path := filepath.Join(dest, unit.Name, f.Path())
dir := filepath.Dir(path)
err := os.MkdirAll(dir, 0777)
if err != nil {
errs <- err
return
}
file, err := os.OpenFile(path, os.O_RDWR, 0777)
if os.IsNotExist(err) {
file, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0777)
} else if err == nil {
ovr, ok := f.(NonOverwritable)
if ok && !ovr.Overwrite(file) {
errs <- nil
return
}
err = file.Truncate(0)
}
if err != nil {
errs <- err
return
}
_, err = f.WriteTo(file)
file.Close()
errs <- err
}(files[idx])
}
for i := 0; i < len(files); i++ {
err := <-errs
if err != nil {
return err
}
}
return nil
}
func (unit *StaticUnit) Files() map[string]File {
m := make(map[string]File)
for _, f := range unit.SharedFiles.Values() {
m[f.Path()] = f
}
for _, f := range unit.StaticFiles.Values() {
m[f.Path()] = f
}
return m
}
func (unit *StaticUnit) AddStaticFile(f File) {
if f != nil {
unit.StaticFiles.Set(f.Path(), f)
}
}
func (unit *StaticUnit) AddSharedFile(f File) {
if f != nil {
unit.SharedFiles.Set(f.Path(), f)
}
}
func (unit *StaticUnit) RemoveSharedFile(path string) {
unit.SharedFiles.Delete(path)
}
func (unit *StaticUnit) RemoveStaticFile(path string) {
unit.StaticFiles.Delete(path)
}
func (unit *StaticUnit) GetSharedFile(path string) File {
f, _ := unit.SharedFiles.Get(path)
return f
}
func (unit *StaticUnit) GetStaticFile(path string) File {
f, _ := unit.StaticFiles.Get(path)
return f
}