From 7bf0709685edb061d71e0dd86f679f3a22d26b7c Mon Sep 17 00:00:00 2001 From: rick Date: Fri, 18 Oct 2013 18:09:57 -0600 Subject: [PATCH] add Queue.Walk() --- queuedir/queuedir.go | 27 +++++++++++++++++++++++++++ queuedir/queuedir_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/queuedir/queuedir.go b/queuedir/queuedir.go index 3ad8b7b1..b0fb257d 100644 --- a/queuedir/queuedir.go +++ b/queuedir/queuedir.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/streadway/simpleuuid" "io" + "io/ioutil" "os" "path/filepath" "time" @@ -33,6 +34,8 @@ type Queue struct { Dir *QueueDir } +type WalkFunc func(id string, body []byte) error + func (q *Queue) Add(reader io.Reader) (string, error) { uuid, err := simpleuuid.NewTime(time.Now()) if err != nil { @@ -48,6 +51,30 @@ func (q *Queue) Add(reader io.Reader) (string, error) { return id, err } +func (q *Queue) Walk(cb WalkFunc) error { + return filepath.Walk(q.Path, func(path string, info os.FileInfo, err error) error { + if info.IsDir() { + return nil + } + + if err != nil { + return err + } + + file, err := os.Open(path) + if err != nil { + return err + } + + body, err := ioutil.ReadAll(file) + if err != nil { + return err + } + + return cb(filepath.Base(path), body) + }) +} + func (q *Queue) AddString(body string) (string, error) { return q.Add(bytes.NewBufferString(body)) } diff --git a/queuedir/queuedir_test.go b/queuedir/queuedir_test.go index 89a15e09..2d65180b 100644 --- a/queuedir/queuedir_test.go +++ b/queuedir/queuedir_test.go @@ -30,7 +30,41 @@ func TestAdd(t *testing.T) { assert.Equal(t, "BOOM", string(by)) } + +func TestWalk(t *testing.T) { + q := Setup(t) + defer q.Teardown() + + id1, err := q.Queue.AddString("BOOM0") + if err != nil { + t.Fatalf("Cannot add to queue: %s", err) } + + id2, err := q.Queue.AddString("BOOM1") + if err != nil { + t.Fatalf("Cannot add to queue: %s", err) + } + + seen := make(map[string]bool) + + q.Queue.Walk(func(id string, body []byte) error { + if err != nil { + t.Errorf("Error reading queue data for %s: %s", id, err) + } + + seen[id] = true + if id == id1 { + assert.Equal(t, id1, id) + } else if id == id2 { + assert.Equal(t, id2, id) + } else { + t.Errorf("Weird ID: %s", id) + } + + return nil + }) + + assert.Equal(t, 2, len(seen)) } func TestMove(t *testing.T) {