2017-06-10 11:10:08 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2020-02-27 22:03:22 +00:00
|
|
|
"fmt"
|
2017-06-10 11:10:08 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/restic/restic/internal/debug"
|
|
|
|
"github.com/restic/restic/internal/fs"
|
|
|
|
)
|
|
|
|
|
2020-02-27 22:03:22 +00:00
|
|
|
// DefaultDir returns $RESTIC_CACHE_DIR, or the default cache directory
|
|
|
|
// for the current OS if that variable is not set.
|
|
|
|
func DefaultDir() (cachedir string, err error) {
|
|
|
|
cachedir = os.Getenv("RESTIC_CACHE_DIR")
|
2019-09-26 22:48:52 +00:00
|
|
|
if cachedir != "" {
|
|
|
|
return cachedir, nil
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|
|
|
|
|
2020-02-27 22:03:22 +00:00
|
|
|
cachedir, err = os.UserCacheDir()
|
2017-11-20 05:11:18 +00:00
|
|
|
if err != nil {
|
2020-02-27 22:03:22 +00:00
|
|
|
return "", fmt.Errorf("unable to locate cache directory: %v", err)
|
2017-11-20 05:11:18 +00:00
|
|
|
}
|
|
|
|
|
2020-02-27 22:03:22 +00:00
|
|
|
return filepath.Join(cachedir, "restic"), nil
|
2017-11-20 20:58:38 +00:00
|
|
|
}
|
|
|
|
|
2018-08-28 20:03:47 +00:00
|
|
|
// mkdirCacheDir ensures that the cache directory exists. It it didn't, created
|
|
|
|
// is set to true.
|
|
|
|
func mkdirCacheDir(cachedir string) (created bool, err error) {
|
|
|
|
var newCacheDir bool
|
|
|
|
|
2017-06-10 11:10:08 +00:00
|
|
|
fi, err := fs.Stat(cachedir)
|
|
|
|
if os.IsNotExist(errors.Cause(err)) {
|
|
|
|
err = fs.MkdirAll(cachedir, 0700)
|
|
|
|
if err != nil {
|
2018-08-28 20:03:47 +00:00
|
|
|
return true, errors.Wrap(err, "MkdirAll")
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fi, err = fs.Stat(cachedir)
|
|
|
|
debug.Log("create cache dir %v", cachedir)
|
2018-08-28 20:03:47 +00:00
|
|
|
|
|
|
|
newCacheDir = true
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2018-08-28 20:03:47 +00:00
|
|
|
return newCacheDir, errors.Wrap(err, "Stat")
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if !fi.IsDir() {
|
2018-08-28 20:03:47 +00:00
|
|
|
return newCacheDir, errors.Errorf("cache dir %v is not a directory", cachedir)
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|
|
|
|
|
2018-08-28 20:03:47 +00:00
|
|
|
return newCacheDir, nil
|
2017-06-10 11:10:08 +00:00
|
|
|
}
|