git-lfs/queuedir/queuedir.go

84 lines
1.6 KiB
Go
Raw Normal View History

2013-10-18 17:41:29 +00:00
// Package queue implements a simple file system queue. Jobs are stored as
// files in a directory. Loosely implements something like maildir, without
// any specific code for dealing with email.
package queuedir
import (
2013-10-18 23:25:30 +00:00
"bytes"
2013-10-18 23:40:07 +00:00
"fmt"
2013-10-18 23:23:16 +00:00
"github.com/streadway/simpleuuid"
2013-10-18 17:41:29 +00:00
"io"
"os"
"path/filepath"
2013-10-18 23:23:16 +00:00
"time"
2013-10-18 17:41:29 +00:00
)
type QueueDir struct {
Path string
TempQueue *Queue
}
func New(path string) (*QueueDir, error) {
q := &QueueDir{Path: path}
tq, err := q.Queue("tmp")
q.TempQueue = tq
return q, err
}
func (q *QueueDir) Queue(name string) (*Queue, error) {
qu := &Queue{name, filepath.Join(q.Path, name), q}
err := os.MkdirAll(qu.Path, 0777)
return qu, err
}
type Queue struct {
Name string
Path string
Dir *QueueDir
}
func (q *Queue) Add(reader io.Reader) (string, error) {
2013-10-18 23:23:16 +00:00
uuid, err := simpleuuid.NewTime(time.Now())
if err != nil {
return "", err
}
id := uuid.String()
2013-10-18 23:40:07 +00:00
file, err := os.Create(q.FullPath(id))
2013-10-18 17:41:29 +00:00
if err == nil {
defer file.Close()
_, err = io.Copy(file, reader)
}
return id, err
}
2013-10-18 23:25:30 +00:00
func (q *Queue) AddString(body string) (string, error) {
return q.Add(bytes.NewBufferString(body))
}
func (q *Queue) AddBytes(body []byte) (string, error) {
return q.Add(bytes.NewBuffer(body))
}
2013-10-18 23:40:07 +00:00
2013-10-18 23:45:46 +00:00
func (q *Queue) Move(newqueue *Queue, id string) error {
return os.Rename(q.FullPath(id), newqueue.FullPath(id))
}
2013-10-18 23:40:07 +00:00
func (q *Queue) Del(id string) error {
full := q.FullPath(id)
stat, err := os.Stat(full)
if err != nil {
return err
}
if stat.IsDir() {
return fmt.Errorf("%s in %s is a directory", id, q.Path)
}
return os.Remove(full)
}
func (q *Queue) FullPath(id string) string {
return filepath.Join(q.Path, id)
}