/
blob.go
82 lines (72 loc) · 1.69 KB
/
blob.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
package allocation
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
const (
blobSpecPrefix = "### BLOB "
blobV2Prefix = "### BLOB_V2 "
)
type BlobSlice []*Blob
func (s *BlobSlice) GetEmpty(paths SystemPaths) (empty Asset) {
empty = &Blob{
Permissions: 0644,
}
return
}
func (s *BlobSlice) GetVersionPrefix(v string) (p string) {
p = blobSpecPrefix
return
}
func (s *BlobSlice) AppendItem(v Asset) {
*s = append(*s, v.(*Blob))
}
type Blob struct {
Name string
Permissions int `json:",omitempty"`
Leave bool `json:",omitempty"`
Source string `json:"-"`
}
func (b *Blob) MarshalSpec(w io.Writer) (err error) {
if _, err = w.Write([]byte(blobSpecPrefix)); err != nil {
return
}
err = json.NewEncoder(w).Encode(b)
return
}
// Unmarshal blob item from manifest. Line may be in two revisions:
func (b *Blob) UnmarshalSpec(line string, spec Spec, paths SystemPaths) (err error) {
switch spec.Revision {
case "":
if _, err = fmt.Sscanf(line, "### BLOB %s", &b.Name); err != nil {
return
}
line = strings.TrimPrefix(line, fmt.Sprintf("%s%s ", blobSpecPrefix, b.Name))
if err = json.NewDecoder(strings.NewReader(line)).Decode(b); err != nil {
return
}
case SpecRevision:
// v2
if err = json.NewDecoder(strings.NewReader(strings.TrimPrefix(line, blobSpecPrefix))).Decode(b); err != nil {
return
}
}
src, err := ioutil.ReadFile(b.Name)
if err != nil {
return
}
b.Source = string(src)
return
}
func (b *Blob) Write() (err error) {
if err = os.MkdirAll(filepath.Dir(b.Name), os.FileMode(b.Permissions)); err != nil {
return
}
err = ioutil.WriteFile(b.Name, []byte(b.Source), os.FileMode(b.Permissions))
return
}