2018-09-14 18:24:48 -06:00
|
|
|
package main
|
2018-05-09 21:52:52 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/zip"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2018-09-14 18:24:48 -06:00
|
|
|
"io/ioutil"
|
2018-05-09 21:52:52 -06:00
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Mothball struct {
|
2018-09-17 17:00:08 -06:00
|
|
|
zf *zip.ReadCloser
|
2018-05-09 21:52:52 -06:00
|
|
|
filename string
|
2018-09-17 17:00:08 -06:00
|
|
|
mtime time.Time
|
2018-05-09 21:52:52 -06:00
|
|
|
}
|
|
|
|
|
2018-09-14 18:24:48 -06:00
|
|
|
func OpenMothball(filename string) (*Mothball, error) {
|
2018-05-09 21:52:52 -06:00
|
|
|
var m Mothball
|
2018-09-17 17:00:08 -06:00
|
|
|
|
2018-05-09 21:52:52 -06:00
|
|
|
m.filename = filename
|
2018-09-17 17:00:08 -06:00
|
|
|
|
2018-05-09 21:52:52 -06:00
|
|
|
err := m.Refresh()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &m, nil
|
|
|
|
}
|
|
|
|
|
2018-09-17 17:00:08 -06:00
|
|
|
func (m *Mothball) Close() error {
|
2018-05-09 21:52:52 -06:00
|
|
|
return m.zf.Close()
|
|
|
|
}
|
|
|
|
|
2018-09-17 17:00:08 -06:00
|
|
|
func (m *Mothball) Refresh() error {
|
2018-05-09 21:52:52 -06:00
|
|
|
info, err := os.Stat(m.filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
mtime := info.ModTime()
|
2018-09-17 17:00:08 -06:00
|
|
|
|
|
|
|
if !mtime.After(m.mtime) {
|
2018-05-09 21:52:52 -06:00
|
|
|
return nil
|
|
|
|
}
|
2018-09-17 17:00:08 -06:00
|
|
|
|
2018-05-09 21:52:52 -06:00
|
|
|
zf, err := zip.OpenReader(m.filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if m.zf != nil {
|
|
|
|
m.zf.Close()
|
|
|
|
}
|
|
|
|
m.zf = zf
|
|
|
|
m.mtime = mtime
|
2018-09-17 17:00:08 -06:00
|
|
|
|
2018-05-09 21:52:52 -06:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Mothball) Open(filename string) (io.ReadCloser, error) {
|
|
|
|
for _, f := range m.zf.File {
|
|
|
|
if filename == f.Name {
|
|
|
|
ret, err := f.Open()
|
|
|
|
return ret, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("File not found: %s in %s", filename, m.filename)
|
|
|
|
}
|
2018-09-14 18:24:48 -06:00
|
|
|
|
|
|
|
func (m *Mothball) ReadFile(filename string) ([]byte, error) {
|
|
|
|
f, err := m.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
2018-09-17 17:00:08 -06:00
|
|
|
|
2018-09-14 18:24:48 -06:00
|
|
|
bytes, err := ioutil.ReadAll(f)
|
|
|
|
return bytes, err
|
|
|
|
}
|