From e93250c90c87e66e083ff3dc3ecba35a1b23660a Mon Sep 17 00:00:00 2001 From: Muhammad Hewedy Date: Sat, 9 May 2020 06:24:39 +0300 Subject: [PATCH] add automatic update checker --- README.md | 4 ++-- cmd/root.go | 1 + cmd/util.go | 6 ++++++ config/updater.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 config/updater.go diff --git a/README.md b/README.md index bff1dc4..9c39e76 100644 --- a/README.md +++ b/README.md @@ -41,11 +41,11 @@ Create, control and connect to VirtualBox VM instances. ## Installation #### Automatic installation: -To install or update for macos and linux: +To install or **update** for macos and linux: ```shell script /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/mhewedy/vermin/master/install.sh)" ``` -To install or update on windows (PowerShell): +To install or **update** on windows (PowerShell): ``` # Should run as Adminstarator C:\> iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/mhewedy/vermin/master/install.ps1')) diff --git a/cmd/root.go b/cmd/root.go index 6460c21..72f7a56 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -34,6 +34,7 @@ $ vermin images Then you can create a vm using: $ vermin create `, + PersistentPreRun: preRun, // Uncomment the following line if your bare application // has an action associated with it: // Run: func(cmd *cobra.Command, args []string) { }, diff --git a/cmd/util.go b/cmd/util.go index 2704994..07cf808 100644 --- a/cmd/util.go +++ b/cmd/util.go @@ -2,6 +2,8 @@ package cmd import ( "fmt" + "github.com/mhewedy/vermin/config" + "github.com/spf13/cobra" "os" ) @@ -11,3 +13,7 @@ func checkFilePath(path string) { os.Exit(1) } } + +func preRun(cmd *cobra.Command, args []string) { + config.CheckForUpdates(version) +} diff --git a/config/updater.go b/config/updater.go new file mode 100644 index 0000000..a43a903 --- /dev/null +++ b/config/updater.go @@ -0,0 +1,49 @@ +package config + +import ( + "fmt" + "math/rand" + "net/http" + "strings" + "time" +) + +const versionURL = "https://github.com/mhewedy/vermin/releases/latest" +const updateURL = "https://github.com/mhewedy/vermin#Automatic-installation" + +var client = &http.Client{ + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, +} + +// CheckForUpdates checks for updates at random times +func CheckForUpdates(currentVersion string) { + rand.Seed(time.Now().UnixNano()) + r := rand.Intn(100) + + if r == 0 { + req, err := http.NewRequest("HEAD", versionURL, nil) + if err != nil { + return + } + + resp, err := client.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + + loc, err := resp.Location() + if err != nil { + return + } + + s := strings.Split(loc.Path, "/") + newVersion := s[len(s)-1] + + if currentVersion != newVersion { + fmt.Printf("\nNew version avaiable %s, check %s\n\n", newVersion, updateURL) + } + } +}