diff --git a/cache/cache.go b/cache/cache.go index 97d3ea5d95..f0fa456c78 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -5,20 +5,13 @@ import ( "os" "path/filepath" + "github.com/knqyf263/fanal/utils" + "golang.org/x/xerrors" ) -func init() { - d, err := os.UserCacheDir() - if err != nil { - d = os.TempDir() - } - cacheDir = filepath.Join(d, "fanal") - os.MkdirAll(cacheDir, os.ModePerm) -} - var ( - cacheDir string + cacheDir = utils.CacheDir() ) func Get(key string) io.Reader { @@ -32,6 +25,9 @@ func Get(key string) io.Reader { func Set(key string, file io.Reader) (io.Reader, error) { filePath := filepath.Join(cacheDir, key) + if err := os.MkdirAll(cacheDir, os.ModePerm); err != nil { + return nil, xerrors.Errorf("failed to mkdir all: %w", err) + } cacheFile, err := os.Create(filePath) if err != nil { return file, xerrors.Errorf("failed to create cache file: %w", err) @@ -40,3 +36,10 @@ func Set(key string, file io.Reader) (io.Reader, error) { tee := io.TeeReader(file, cacheFile) return tee, nil } + +func Clear() error { + if err := os.RemoveAll(utils.CacheDir()); err != nil { + return xerrors.New("failed to remove cache") + } + return nil +} diff --git a/cmd/fanal/main.go b/cmd/fanal/main.go index b0d1d65d26..24bdd1ac70 100644 --- a/cmd/fanal/main.go +++ b/cmd/fanal/main.go @@ -7,6 +7,10 @@ import ( "log" "os" + "golang.org/x/xerrors" + + "github.com/knqyf263/fanal/cache" + "github.com/knqyf263/fanal/analyzer" _ "github.com/knqyf263/fanal/analyzer/library/bundler" _ "github.com/knqyf263/fanal/analyzer/library/composer" @@ -33,8 +37,15 @@ func main() { func run() (err error) { ctx := context.Background() tarPath := flag.String("f", "-", "layer.tar path") + clearCache := flag.Bool("clear", false, "clear cache") flag.Parse() + if *clearCache { + if err = cache.Clear(); err != nil { + return xerrors.Errorf("error in cache clear: %w", err) + } + } + args := flag.Args() var files extractor.FileMap diff --git a/utils/utils.go b/utils/utils.go index bcde9f53af..540d28454d 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -1,5 +1,19 @@ package utils +import ( + "os" + "path/filepath" +) + +func CacheDir() string { + cacheDir, err := os.UserCacheDir() + if err != nil { + cacheDir = os.TempDir() + } + dir := filepath.Join(cacheDir, "fanal") + return dir +} + func StringInSlice(a string, list []string) bool { for _, b := range list { if b == a {