rest-server/repository.go

97 lines
2.2 KiB
Go
Raw Normal View History

2015-08-14 11:17:57 +02:00
package main
2015-08-15 10:06:10 +02:00
import (
2015-08-25 11:35:49 +02:00
"io"
2015-08-15 10:06:10 +02:00
"io/ioutil"
"os"
"path/filepath"
"github.com/restic/restic/backend"
)
2015-08-14 11:17:57 +02:00
// A Repository is the place where backups are stored
type Repository struct {
path string
}
2015-09-07 15:29:24 +02:00
func NewRepository(path string) (*Repository, error) {
2015-08-15 10:06:10 +02:00
dirs := []string{
2015-09-07 15:29:24 +02:00
path,
filepath.Join(path, string(backend.Data)),
filepath.Join(path, string(backend.Snapshot)),
filepath.Join(path, string(backend.Index)),
filepath.Join(path, string(backend.Lock)),
filepath.Join(path, string(backend.Key)),
2015-08-15 10:06:10 +02:00
}
for _, d := range dirs {
2015-09-07 15:29:24 +02:00
_, err := os.Stat(d)
if err != nil {
err := os.MkdirAll(d, backend.Modes.Dir)
if err != nil {
return nil, err
2015-08-15 10:06:10 +02:00
}
}
}
2015-09-07 15:29:24 +02:00
return &Repository{path}, nil
2015-08-15 10:06:10 +02:00
}
func (r *Repository) HasConfig() bool {
file := filepath.Join(r.path, string(backend.Config))
if _, err := os.Stat(file); err != nil {
return false
}
return true
}
func (r *Repository) ReadConfig() ([]byte, error) {
file := filepath.Join(r.path, string(backend.Config))
return ioutil.ReadFile(file)
}
func (r *Repository) WriteConfig(data []byte) error {
file := filepath.Join(r.path, string(backend.Config))
return ioutil.WriteFile(file, data, backend.Modes.File)
}
func (r *Repository) ListBlob(t backend.Type) ([]string, error) {
var blobs []string
dir := filepath.Join(r.path, string(t))
files, err := ioutil.ReadDir(dir)
if err != nil {
return blobs, err
}
blobs = make([]string, len(files))
for i, f := range files {
blobs[i] = f.Name()
}
return blobs, nil
}
func (r *Repository) HasBlob(bt backend.Type, id backend.ID) bool {
file := filepath.Join(r.path, string(bt), id.String())
if _, err := os.Stat(file); err != nil {
return false
}
return true
}
2015-08-25 11:35:49 +02:00
func (r *Repository) ReadBlob(bt backend.Type, id backend.ID) (io.ReadSeeker, error) {
2015-08-15 10:06:10 +02:00
file := filepath.Join(r.path, string(bt), id.String())
f, err := os.Open(file)
2015-09-08 21:35:48 +02:00
defer f.Close()
2015-08-15 10:06:10 +02:00
if err != nil {
return f, err
}
return f, nil
}
func (r *Repository) WriteBlob(bt backend.Type, id backend.ID, data []byte) error {
file := filepath.Join(r.path, string(bt), id.String())
return ioutil.WriteFile(file, data, backend.Modes.File)
}
2015-08-14 11:17:57 +02:00
2015-08-15 10:06:10 +02:00
func (r *Repository) DeleteBlob(bt backend.Type, id backend.ID) error {
file := filepath.Join(r.path, string(bt), id.String())
return os.Remove(file)
2015-08-14 11:17:57 +02:00
}