Skip to content

Commit

Permalink
Clear cache (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
knqyf263 authored May 7, 2019
1 parent 2b5cb30 commit ceab600
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 10 deletions.
23 changes: 13 additions & 10 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand All @@ -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
}
11 changes: 11 additions & 0 deletions cmd/fanal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down

0 comments on commit ceab600

Please sign in to comment.