This repository has been archived by the owner on Jun 25, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
hex_gzip.go
112 lines (93 loc) · 2 KB
/
hex_gzip.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
package resolver
import (
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"os"
"strings"
"sync"
"github.com/gobuffalo/packr/v2/file/resolver/encoding/hex"
"github.com/gobuffalo/packr/v2/plog"
"github.com/gobuffalo/packr/v2/file"
)
var _ Resolver = &HexGzip{}
type HexGzip struct {
packed map[string]string
unpacked map[string]string
moot *sync.RWMutex
}
func (hg HexGzip) String() string {
return String(&hg)
}
var _ file.FileMappable = &HexGzip{}
func (hg *HexGzip) FileMap() map[string]file.File {
hg.moot.RLock()
var names []string
for k := range hg.packed {
names = append(names, k)
}
hg.moot.RUnlock()
m := map[string]file.File{}
for _, n := range names {
if f, err := hg.Resolve("", n); err == nil {
m[n] = f
}
}
return m
}
func (hg *HexGzip) Resolve(box string, name string) (file.File, error) {
plog.Debug(hg, "Resolve", "box", box, "name", name)
hg.moot.Lock()
defer hg.moot.Unlock()
if s, ok := hg.unpacked[name]; ok {
return file.NewFile(name, []byte(s))
}
packed, ok := hg.packed[name]
if !ok {
return nil, os.ErrNotExist
}
unpacked, err := UnHexGzipString(packed)
if err != nil {
return nil, err
}
f, err := file.NewFile(OsPath(name), []byte(unpacked))
if err != nil {
return nil, err
}
hg.unpacked[name] = f.String()
return f, nil
}
func NewHexGzip(files map[string]string) (*HexGzip, error) {
if files == nil {
files = map[string]string{}
}
hg := &HexGzip{
packed: files,
unpacked: map[string]string{},
moot: &sync.RWMutex{},
}
return hg, nil
}
func HexGzipString(s string) (string, error) {
bb := &bytes.Buffer{}
enc := hex.NewEncoder(bb)
zw := gzip.NewWriter(enc)
io.Copy(zw, strings.NewReader(s))
zw.Close()
return bb.String(), nil
}
func UnHexGzipString(packed string) (string, error) {
br := bytes.NewBufferString(packed)
dec := hex.NewDecoder(br)
zr, err := gzip.NewReader(dec)
if err != nil {
return "", err
}
defer zr.Close()
b, err := ioutil.ReadAll(zr)
if err != nil {
return "", err
}
return string(b), nil
}