Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ package cmd

import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"time"

"slices"

Expand All @@ -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
Expand All @@ -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
}