restic/cache.go

101 lines
1.9 KiB
Go
Raw Normal View History

2015-02-21 23:09:57 +00:00
package restic
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/restic/restic/backend"
2015-03-14 11:10:08 +00:00
"github.com/restic/restic/debug"
2015-02-21 23:09:57 +00:00
)
type Cache struct {
base string
}
2015-03-14 11:10:08 +00:00
func NewCache(be backend.IDer) (c *Cache, err error) {
// try to get explicit cache dir from environment
dir := os.Getenv("RESTIC_CACHE")
// otherwise try OS specific default
if dir == "" {
dir, err = GetCacheDir()
if err != nil {
return nil, err
}
2015-02-21 23:09:57 +00:00
}
2015-03-14 11:10:08 +00:00
basedir := filepath.Join(dir, be.ID().String())
debug.Log("Cache.New", "opened cache at %v", basedir)
return &Cache{base: basedir}, nil
2015-02-21 23:09:57 +00:00
}
2015-03-09 21:26:39 +00:00
func (c *Cache) Has(t backend.Type, subtype string, id backend.ID) (bool, error) {
2015-02-21 23:09:57 +00:00
// try to open file
2015-03-09 21:26:39 +00:00
filename, err := c.filename(t, subtype, id)
2015-02-21 23:09:57 +00:00
if err != nil {
return false, err
}
fd, err := os.Open(filename)
defer fd.Close()
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
2015-03-09 21:26:39 +00:00
func (c *Cache) Store(t backend.Type, subtype string, id backend.ID) (io.WriteCloser, error) {
filename, err := c.filename(t, subtype, id)
2015-02-21 23:09:57 +00:00
if err != nil {
2015-03-09 21:26:39 +00:00
return nil, err
2015-02-21 23:09:57 +00:00
}
dirname := filepath.Dir(filename)
err = os.MkdirAll(dirname, 0700)
if err != nil {
2015-03-09 21:26:39 +00:00
return nil, err
2015-02-21 23:09:57 +00:00
}
file, err := os.Create(filename)
if err != nil {
2015-03-09 21:26:39 +00:00
return nil, err
2015-02-21 23:09:57 +00:00
}
2015-03-09 21:26:39 +00:00
return file, nil
2015-02-21 23:09:57 +00:00
}
2015-03-09 21:26:39 +00:00
func (c *Cache) Load(t backend.Type, subtype string, id backend.ID) (io.ReadCloser, error) {
2015-02-21 23:09:57 +00:00
// try to open file
2015-03-09 21:26:39 +00:00
filename, err := c.filename(t, subtype, id)
2015-02-21 23:09:57 +00:00
if err != nil {
return nil, err
}
return os.Open(filename)
}
// Construct file name for given Type.
2015-03-09 21:26:39 +00:00
func (c *Cache) filename(t backend.Type, subtype string, id backend.ID) (string, error) {
filename := id.String()
if subtype != "" {
filename += "." + subtype
2015-02-21 23:09:57 +00:00
}
switch t {
case backend.Snapshot:
2015-03-09 21:26:39 +00:00
return filepath.Join(c.base, "snapshots", filename), nil
2015-02-21 23:09:57 +00:00
case backend.Tree:
2015-03-09 21:26:39 +00:00
return filepath.Join(c.base, "trees", filename), nil
2015-02-21 23:09:57 +00:00
}
return "", fmt.Errorf("cache not supported for type %v", t)
}