Mothball work

This commit is contained in:
Neale Pickett 2018-05-10 03:52:52 +00:00
parent 9a2ed15316
commit 3100f34914
3 changed files with 130 additions and 52 deletions

View File

@ -1,52 +0,0 @@
package mothball
import (
"archive/zip"
"os"
"time"
)
type Mothball struct {
zf *zipfile.File,
filename string,
mtime time.Time,
}
func Open(filename string) (*Mothball, error) {
var m Mothball
m.filename = filename
err := m.Refresh()
if err != nil {
return err
}
return &m
}
func (m Mothball) Close() (error) {
return m.zf.Close()
}
func (m Mothball) Refresh() (error) {
mtime, err := os.Stat(m.filename)
if err != nil {
return err
}
if mtime == m.mtime {
return nil
}
zf, err := zip.OpenReader(m.filename)
if err != nil {
return err
}
m.zf.Close()
m.zf = zf
m.mtime = mtime
}
func (m Mothball)

67
src/mothball/mothball.go Normal file
View File

@ -0,0 +1,67 @@
package mothball
import (
"archive/zip"
"fmt"
"io"
"os"
"time"
)
type Mothball struct {
zf *zip.ReadCloser
filename string
mtime time.Time
}
func Open(filename string) (*Mothball, error) {
var m Mothball
m.filename = filename
err := m.Refresh()
if err != nil {
return nil, err
}
return &m, nil
}
func (m *Mothball) Close() (error) {
return m.zf.Close()
}
func (m *Mothball) Refresh() (error) {
info, err := os.Stat(m.filename)
if err != nil {
return err
}
mtime := info.ModTime()
if mtime == m.mtime {
return nil
}
zf, err := zip.OpenReader(m.filename)
if err != nil {
return err
}
if m.zf != nil {
m.zf.Close()
}
m.zf = zf
m.mtime = mtime
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)
}

View File

@ -0,0 +1,63 @@
package mothball
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"testing"
)
func TestMothball(t *testing.T) {
tf, err := ioutil.TempFile("", "mothball")
if err != nil {
t.Error(err)
return
}
defer os.Remove(tf.Name())
w := zip.NewWriter(tf)
f, err := w.Create("moo.txt")
if err != nil {
t.Error(err)
return
}
// no Close method
_, err = fmt.Fprintln(f, "The cow goes moo")
//.Write([]byte("The cow goes moo"))
if err != nil {
t.Error(err)
return
}
w.Close()
tf.Close()
// Now read it in
mb, err := Open(tf.Name())
if err != nil {
t.Error(err)
return
}
cow, err := mb.Open("moo.txt")
if err != nil {
t.Error(err)
return
}
line := make([]byte, 200)
n, err := cow.Read(line)
if (err != nil) && (err != io.EOF) {
t.Error(err)
return
}
if string(line[:n]) != "The cow goes moo\n" {
t.Log(line)
t.Error("Contents didn't match")
return
}
}