2019-09-21 19:51:29 +03:00
|
|
|
package mem
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2019-10-25 17:19:27 +03:00
|
|
|
|
|
|
|
"github.com/markbates/pkger/here"
|
|
|
|
"github.com/markbates/pkger/internal/maps"
|
|
|
|
"github.com/markbates/pkger/pkging"
|
|
|
|
"github.com/markbates/pkger/pkging/embed"
|
2019-09-21 19:51:29 +03:00
|
|
|
)
|
|
|
|
|
2019-10-25 17:19:27 +03:00
|
|
|
// MarshalJSON creates a fully re-hydratable JSON representation of *Pkger
|
|
|
|
func (p *Pkger) MarshalJSON() ([]byte, error) {
|
|
|
|
files := map[string]embed.File{}
|
|
|
|
|
|
|
|
p.files.Range(func(key here.Path, file pkging.File) bool {
|
|
|
|
f, ok := file.(*File)
|
|
|
|
if !ok {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
ef := embed.File{
|
|
|
|
Info: f.info,
|
|
|
|
Here: f.Here,
|
|
|
|
Path: f.path,
|
|
|
|
Parent: f.parent,
|
|
|
|
Data: f.data,
|
|
|
|
}
|
|
|
|
files[key.String()] = ef
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
infos := map[string]here.Info{}
|
|
|
|
p.infos.Range(func(key string, info here.Info) bool {
|
|
|
|
infos[key] = info
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
ed := embed.Data{
|
|
|
|
Infos: infos,
|
|
|
|
Files: files,
|
|
|
|
Here: p.Here,
|
2019-09-21 19:51:29 +03:00
|
|
|
}
|
2019-10-25 17:19:27 +03:00
|
|
|
return json.Marshal(ed)
|
2019-09-21 19:51:29 +03:00
|
|
|
}
|
|
|
|
|
2019-10-25 17:19:27 +03:00
|
|
|
// UnmarshalJSON re-hydrates the *Pkger
|
|
|
|
func (p *Pkger) UnmarshalJSON(b []byte) error {
|
|
|
|
y := &embed.Data{
|
|
|
|
Infos: map[string]here.Info{},
|
|
|
|
Files: map[string]embed.File{},
|
2019-10-21 00:52:16 +03:00
|
|
|
}
|
|
|
|
|
2019-10-25 17:19:27 +03:00
|
|
|
if err := json.Unmarshal(b, &y); err != nil {
|
2019-10-21 00:52:16 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-10-25 17:19:27 +03:00
|
|
|
p.Here = y.Here
|
|
|
|
p.infos = &maps.Infos{}
|
|
|
|
for k, v := range y.Infos {
|
|
|
|
p.infos.Store(k, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
p.files = &maps.Files{}
|
|
|
|
for k, v := range y.Files {
|
|
|
|
pt, err := p.Parse(k)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
f := &File{
|
|
|
|
Here: v.Here,
|
|
|
|
info: v.Info,
|
|
|
|
path: v.Path,
|
|
|
|
data: v.Data,
|
|
|
|
parent: v.Parent,
|
|
|
|
}
|
|
|
|
p.files.Store(pt, f)
|
2019-10-21 00:52:16 +03:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-18 19:01:48 +03:00
|
|
|
func UnmarshalEmbed(in []byte) (*Pkger, error) {
|
2019-10-25 17:19:27 +03:00
|
|
|
b, err := embed.Decode(in)
|
2019-09-21 19:51:29 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-10-21 00:52:16 +03:00
|
|
|
p := &Pkger{}
|
2019-10-25 17:19:27 +03:00
|
|
|
if err := json.Unmarshal(b, p); err != nil {
|
2019-09-21 19:51:29 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-21 00:52:16 +03:00
|
|
|
return p, nil
|
2019-09-21 19:51:29 +03:00
|
|
|
}
|