summaryrefslogtreecommitdiff
path: root/brewcheck.go
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-11-11 11:47:05 +0800
committerEltrac <hi@guhub.cn>2025-11-11 11:47:05 +0800
commitc996508bf1e15b78a1e2580a48c82132ea6f3a4b (patch)
tree06219a46a9c4514538db6ef1a05c4966583aa679 /brewcheck.go
parent6741bc05e978676e77be06571e98a1f1eaa1d878 (diff)
perf: simplify brewcheck cache - ditch JSON format, store empty file and use
modification timestamp - if no brew, then no cache. if brew, then cache. - simply check if file exists and is fresh to read cache
Diffstat (limited to 'brewcheck.go')
-rw-r--r--brewcheck.go67
1 files changed, 14 insertions, 53 deletions
diff --git a/brewcheck.go b/brewcheck.go
index b811fa6..8223aff 100644
--- a/brewcheck.go
+++ b/brewcheck.go
@@ -1,76 +1,37 @@
package main
import (
- "encoding/json"
- "errors"
"os"
"os/exec"
"path/filepath"
"time"
"fmt"
+ "github.com/adrg/xdg"
"github.com/fatih/color"
)
-type BrewCache struct {
- Found bool `json:"found"`
- Timestamp time.Time `json:"timestamp"`
-}
-
-// Don't check Homebrew installation for a week
const cacheTTL = 7 * 24 * time.Hour
func EnsureBrewAvailable() {
- ok, err := isBrewAvailable()
- if err != nil {
- color.Red("⚠️ Error checking Homebrew: %v", err)
- os.Exit(1)
+ cacheFile := filepath.Join(xdg.CacheHome, "wthis", "brew-checked")
+
+ // 1. check if cache file exists and is fresh
+ if info, err := os.Stat(cacheFile); err == nil {
+ if time.Since(info.ModTime()) < cacheTTL {
+ return // recently verified that brew exists
+ }
}
- if !ok {
+ // 2. otherwise, actually check
+ if _, err := exec.LookPath("brew"); err != nil {
+ // brew not found — no cache write
color.Red("🍺 Homebrew not installed.")
fmt.Println("This tool works only with Homebrew formulae and casks.")
os.Exit(1)
}
-}
-
-func isBrewAvailable() (bool, error) {
- cachePath, err := getCacheFile()
- if err != nil {
- return false, err
- }
- // Try to read cache
- if data, err := os.ReadFile(cachePath); err == nil {
- var cache BrewCache
- if json.Unmarshal(data, &cache) == nil {
- if time.Since(cache.Timestamp) < cacheTTL {
- return cache.Found, nil
- }
- }
- }
-
- // Perform actual check
- _, err = exec.LookPath("brew")
- found := err == nil
-
- // Save to cache
- _ = os.MkdirAll(filepath.Dir(cachePath), 0o755)
- cache := BrewCache{Found: found, Timestamp: time.Now()}
- data, _ := json.Marshal(cache)
- _ = os.WriteFile(cachePath, data, 0o644)
-
- return found, nil
-}
-
-func getCacheFile() (string, error) {
- base := os.Getenv("XDG_CACHE_HOME")
- if base == "" {
- home, err := os.UserHomeDir()
- if err != nil {
- return "", errors.New("cannot determine user home")
- }
- base = filepath.Join(home, ".cache")
- }
- return filepath.Join(base, "wthis", "brew-check.json"), nil
+ // 3. write cache
+ _ = os.MkdirAll(filepath.Dir(cacheFile), 0o755)
+ _ = os.WriteFile(cacheFile, []byte{}, 0o644)
}