Skip to content

Commit

Permalink
Add clear-cache command
Browse files Browse the repository at this point in the history
  • Loading branch information
waynezhang committed Dec 29, 2023
1 parent 409f417 commit 2e5a125
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
17 changes: 16 additions & 1 deletion internal/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"github.com/waynezhang/foto/internal/log"
)

var cacheDirectory = ".foto"

func AddImage(src string, width int, file string) {
checksum, err := checksum(src)
if err != nil {
Expand Down Expand Up @@ -44,6 +46,19 @@ func CachedImage(src string, width int) *string {
return &path
}

func Clear() {
if _, err := os.Stat(cacheDirectory); err != nil {
if !os.IsNotExist(err) {
log.Fatal("Failed to find cache directory %s (%s).", cacheDirectory, err.Error())
}
return
}
err := os.RemoveAll(cacheDirectory)
if err != nil {
log.Fatal("Failed to remove cache directory %s (%s).", cacheDirectory, err.Error())
}
}

func checksum(path string) (*string, error) {
f, err := os.Open(path)
if err != nil {
Expand All @@ -62,5 +77,5 @@ func checksum(path string) (*string, error) {
}

func imagePath(checksum string, width int) string {
return filepath.Join(".foto", fmt.Sprintf("%s-%d", checksum, width))
return filepath.Join(cacheDirectory, fmt.Sprintf("%s-%d", checksum, width))
}
14 changes: 14 additions & 0 deletions internal/cmd/clear-cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package cmd

import (
"github.com/spf13/cobra"
"github.com/waynezhang/foto/internal/cache"
)

var ClearCacheCmd = &cobra.Command {
Use: "clear-cache",
Short: "Clear local cache",
Run: func(cmd *cobra.Command, args []string) {
cache.Clear()
},
}
3 changes: 2 additions & 1 deletion internal/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ func Execute() {

rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")

rootCmd.AddCommand(ClearCacheCmd)
rootCmd.AddCommand(CreateCmd)
rootCmd.AddCommand(PreviewCmd)
rootCmd.AddCommand(ExportCmd)
rootCmd.AddCommand(PreviewCmd)
rootCmd.AddCommand(VersionCmd)

err := rootCmd.Execute()
Expand Down

0 comments on commit 2e5a125

Please sign in to comment.