pkger/pkger.go

86 lines
1.6 KiB
Go
Raw Normal View History

2019-07-31 00:21:26 +03:00
package pkger
2019-08-02 07:22:17 +03:00
import (
"bytes"
"compress/gzip"
2019-08-03 01:14:48 +03:00
"encoding/hex"
2019-08-02 07:22:17 +03:00
"encoding/json"
2019-08-03 01:14:48 +03:00
"fmt"
2019-08-02 07:22:17 +03:00
"io"
"log"
)
2019-07-31 23:29:49 +03:00
// Open opens the named file for reading.
func Open(p string) (*File, error) {
2019-08-02 05:34:32 +03:00
pt, err := Parse(p)
2019-07-31 00:21:26 +03:00
if err != nil {
2019-07-31 23:29:49 +03:00
return nil, err
2019-07-31 00:21:26 +03:00
}
2019-07-31 23:29:49 +03:00
return rootIndex.Open(pt)
2019-07-31 00:21:26 +03:00
}
2019-07-31 23:29:49 +03:00
// Create creates the named file with mode 0666 (before umask), truncating it if it already exists. If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.
func Create(p string) (*File, error) {
2019-08-02 05:34:32 +03:00
pt, err := Parse(p)
2019-07-31 00:21:26 +03:00
if err != nil {
return nil, err
}
2019-07-31 23:29:49 +03:00
return rootIndex.Create(pt)
2019-07-31 00:21:26 +03:00
}
2019-08-02 07:22:17 +03:00
func Unpack(ind string) error {
2019-08-03 01:14:48 +03:00
b, err := hex.DecodeString(ind)
2019-08-02 07:22:17 +03:00
if err != nil {
2019-08-03 01:14:48 +03:00
log.Fatal("hex.DecodeString", err)
2019-08-02 07:22:17 +03:00
return err
}
gz, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
2019-08-03 01:14:48 +03:00
log.Fatal("gzip.NewReader", err)
2019-08-02 07:22:17 +03:00
return err
}
defer gz.Close()
if err := json.NewDecoder(gz).Decode(rootIndex); err != nil {
2019-08-03 01:14:48 +03:00
log.Fatal("json.NewDecoder", err)
2019-08-02 07:22:17 +03:00
return err
}
2019-08-03 01:14:48 +03:00
fmt.Println(rootIndex.Files.Keys())
2019-08-02 07:22:17 +03:00
return nil
}
func Pack(out io.Writer, paths []Path) error {
2019-08-03 01:14:48 +03:00
bb := &bytes.Buffer{}
gz := gzip.NewWriter(bb)
defer gz.Close()
2019-08-02 07:22:17 +03:00
for _, p := range paths {
f, err := Open(p.String())
if err != nil {
return err
}
fi, err := f.Stat()
if err != nil {
return err
}
if fi.IsDir() {
continue
}
2019-08-02 21:47:59 +03:00
rootIndex.Files.Store(p, f)
2019-08-02 07:22:17 +03:00
f.Close()
}
2019-08-03 01:14:48 +03:00
if err := json.NewEncoder(gz).Encode(rootIndex); err != nil {
return err
}
if err := gz.Close(); err != nil {
return err
}
s := hex.EncodeToString(bb.Bytes())
fmt.Fprint(out, s)
return nil
2019-08-02 07:22:17 +03:00
}