diff options
| author | Eltrac <hi@guhub.cn> | 2025-11-11 11:15:24 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-11-11 11:15:24 +0800 |
| commit | 6741bc05e978676e77be06571e98a1f1eaa1d878 (patch) | |
| tree | 3df39aa67863abdf89b95ed77a6e12d52bd07a4e | |
| parent | 06dcdf457d25a707f6a25237f09a6e186173bbb7 (diff) | |
perf: cache homebrew installation check - looking for brew path takes a
significant amount of time - caching (supports XDG) brew check result to improve
performance
| -rw-r--r-- | brewcheck.go | 76 | ||||
| -rw-r--r-- | main.go | 10 |
2 files changed, 77 insertions, 9 deletions
diff --git a/brewcheck.go b/brewcheck.go new file mode 100644 index 0000000..b811fa6 --- /dev/null +++ b/brewcheck.go @@ -0,0 +1,76 @@ +package main + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "time" + "fmt" + + "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) + } + + if !ok { + 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,7 +3,6 @@ package main import ( "fmt" "os" - "os/exec" "context" "log" "github.com/fatih/color" @@ -11,14 +10,7 @@ import ( ) func main() { - // Check if Homebrew is installed - _, brewInstallationErr := exec.LookPath("brew") - if brewInstallationErr != nil { - color.Red("🍺 Homebrew not installed.") - fmt.Println("This tool is for looking up formulae/cask information about packages installed with Homebrew.") - fmt.Println("If you don't have Homebrew, it's no use.") - os.Exit(0) - } + EnsureBrewAvailable() // declare CLI app cmd := &cli.Command{ |
