From eb2e857d05e43bfcc5b0eed09958d96c3aab55eb Mon Sep 17 00:00:00 2001 From: jesperkha Date: Mon, 26 May 2025 13:55:30 +0200 Subject: [PATCH] Check version only every 24 hours Check version only every 24 hours --- cmd/version.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/cmd/version.go b/cmd/version.go index ae232c3..a59e3af 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -2,9 +2,13 @@ package cmd import ( "encoding/json" + "io" + "log" "net/http" "os" + "path" "strings" + "time" "slices" @@ -23,6 +27,10 @@ func checkIfLatestVersion() { return } + if !shouldCheck() { + return + } + resp, err := http.Get("https://api.github.com/repos/echo-webkom/cenv/releases/latest") if err != nil { return @@ -48,3 +56,37 @@ func checkIfLatestVersion() { color.Yellow("A new version of cenv is available. Run 'cenv upgrade' to upgrade to the latest version.") } } + +// cenv creates the file .cenv-version in your home dir, which contains +// the last time for version check. If the file does not exist or the the time +// is past expiration, cenv checks again. This is to minimize delay when running +// cenv as checking for an update may be slow and annoying on slower internet. +func shouldCheck() bool { + home, err := os.UserHomeDir() + if err != nil { + log.Fatal(err) + } + + filepath := path.Join(home, ".cenv-version") + + file, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE, 0644) + if err != nil { + log.Fatal(err) + } + + defer file.Close() + b, err := io.ReadAll(file) + if err != nil { + log.Fatal(err) + } + + expiration := time.Hour * 24 + checked, err := time.Parse(time.RFC3339, string(b)) + if err != nil || time.Now().Sub(checked) > expiration { + file.Seek(0, io.SeekStart) + file.WriteString(time.Now().Format(time.RFC3339)) + return true + } + + return false +}