From 31ca9ffe7b1d51ebdee4e308813ee4261c4c7e32 Mon Sep 17 00:00:00 2001 From: Ole Magnus Fon Johnsen Date: Sun, 24 Nov 2024 21:43:00 +0100 Subject: [PATCH] Check if cnev is running latest version --- .github/workflows/build.yaml | 1 + README.md | 13 ++++++++++ cmd/cmd.go | 47 ++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index a4b0af5..4c2fd00 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -29,4 +29,5 @@ jobs: goarch: ${{ matrix.goarch }} multi_binaries: true binary_name: cenv + ldflags: -X main.Version=${{ github.event.release.tag_name }} project_path: . ./cenv-install diff --git a/README.md b/README.md index 8f50a43..e3ebff4 100644 --- a/README.md +++ b/README.md @@ -67,3 +67,16 @@ You can fix and outdated .env with the fix command. Note that this will overwrit cenv fix ``` +## Building + +To build the project, you need to have Go installed. Run the following command to build the project: + +```sh +go build -o cenv cmd/cenv/main.go +``` + +If you want to overwrite the `Version` variable in `main.go` you have add the following flags: + +```sh +go build -o cenv -ldflags "-X main.Version=" cmd/cenv/main.go +``` diff --git a/cmd/cmd.go b/cmd/cmd.go index 77ee454..fa1d8df 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,14 +1,19 @@ package cmd import ( + "encoding/json" "fmt" + "net/http" "os" "os/exec" + "strings" "github.com/echo-webkom/cenv/cenv" "github.com/fatih/color" ) +var Version = "dev" + func showHelp() { fmt.Println("cenv [command] ") fmt.Println() @@ -23,6 +28,7 @@ func showHelp() { fmt.Println("Flags:") fmt.Println(" --env Path to env file, default is current dir") fmt.Println(" --schema Path to schema file, default is current dir") + fmt.Println(" --skip-version Skip version check") fmt.Println() } @@ -36,7 +42,48 @@ func errorExit(err error) { os.Exit(1) } +func checkIfLatestVersion() { + if Version == "dev" { + return + } + + for _, arg := range os.Args { + if arg == "--skip-version" { + return + } + } + + resp, err := http.Get("https://api.github.com/repos/echo-webkom/cenv/releases/latest") + if err != nil { + return + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return + } + + var result struct { + TagName string `json:"tag_name"` + } + err = json.NewDecoder(resp.Body).Decode(&result) + if err != nil { + return + } + + latestVersion := strings.TrimSpace(result.TagName) + currentVersion := strings.TrimSpace(Version) + + isLatest := currentVersion == latestVersion + + if !isLatest { + color.Yellow("A new version of cenv is available. Run 'cenv upgrade' to upgrade.") + } +} + func Run() { + checkIfLatestVersion() + if len(os.Args) < 2 { showHelp() os.Exit(1)