Skip to content
This repository has been archived by the owner on Jun 25, 2022. It is now read-only.

Commit

Permalink
added the ability to add string or bytes to a box
Browse files Browse the repository at this point in the history
  • Loading branch information
markbates committed Mar 14, 2018
1 parent d1edcde commit 3b045e9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
14 changes: 13 additions & 1 deletion box.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func NewBox(path string) Box {
return Box{
Path: path,
callingDir: cd,
data: map[string][]byte{},
}
}

Expand All @@ -50,6 +51,14 @@ type Box struct {
directories map[string]bool
}

func (b Box) AddString(path string, t string) {
b.AddBytes(path, []byte(t))
}

func (b Box) AddBytes(path string, t []byte) {
b.data[path] = t
}

// String of the file asked for or an empty string.
func (b Box) String(name string) string {
return string(b.Bytes(name))
Expand Down Expand Up @@ -102,6 +111,9 @@ func (b Box) decompress(bb []byte) []byte {
}

func (b Box) find(name string) (File, error) {
if bb, ok := b.data[name]; ok {
return newVirtualFile(name, bb), nil
}
if b.directories == nil {
b.indexDirectories()
}
Expand Down Expand Up @@ -183,7 +195,7 @@ func (b Box) Open(name string) (http.File, error) {
func (b Box) List() []string {
var keys []string

if b.data == nil {
if b.data == nil || len(b.data) == 0 {
b.Walk(func(path string, info File) error {
finfo, _ := info.FileInfo()
if !finfo.IsDir() {
Expand Down
28 changes: 27 additions & 1 deletion box_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,30 @@ func Test_Virtual_Directory_Not_Found(t *testing.T) {
r.NoError(err)
_, err = virtualBox.find("does-not-exist")
r.Error(err)
}
}

func Test_AddString(t *testing.T) {
r := require.New(t)

_, err := virtualBox.find("string")
r.Error(err)

virtualBox.AddString("string", "hello")

_, err = virtualBox.find("string")
r.NoError(err)
r.Equal("hello", virtualBox.String("string"))
}

func Test_AddBytes(t *testing.T) {
r := require.New(t)

_, err := virtualBox.find("bytes")
r.Error(err)

virtualBox.AddBytes("bytes", []byte("hello"))

_, err = virtualBox.find("bytes")
r.NoError(err)
r.Equal("hello", virtualBox.String("bytes"))
}

0 comments on commit 3b045e9

Please sign in to comment.