2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-10 23:31:09 +00:00
restic/cache.go

94 lines
1.7 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-09 21:26:39 +00:00
// for testing
var getCacheDir = GetCacheDir
2015-02-21 23:09:57 +00:00
type Cache struct {
base string
}
func NewCache() (*Cache, error) {
2015-03-09 21:26:39 +00:00
dir, err := getCacheDir()
2015-02-21 23:09:57 +00:00
if err != nil {
return nil, err
}
return &Cache{base: dir}, nil
}
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)
}