github.com/gofiber/fiber-cli@v0.0.3/cmd/version.go (about) 1 package cmd 2 3 import ( 4 "errors" 5 "fmt" 6 "io/ioutil" 7 "net/http" 8 "regexp" 9 10 "github.com/spf13/cobra" 11 ) 12 13 var versionCmd = &cobra.Command{ 14 Use: "version", 15 Short: "Print the local and released version number of fiber", 16 Run: versionRun, 17 } 18 19 func versionRun(cmd *cobra.Command, _ []string) { 20 var ( 21 cur, latest string 22 err error 23 w = cmd.OutOrStdout() 24 ) 25 26 if cur, err = currentVersion(); err != nil { 27 cur = err.Error() 28 } 29 30 if latest, err = latestVersion(false); err != nil { 31 _, _ = fmt.Fprintf(w, "fiber version: %v\n", err) 32 return 33 } 34 35 _, _ = fmt.Fprintf(w, "fiber version: %s (latest %s)\n", cur, latest) 36 } 37 38 var currentVersionRegexp = regexp.MustCompile(`github\.com/gofiber/fiber[^\n]*? (.*)\n`) 39 var currentVersionFile = "go.mod" 40 41 func currentVersion() (string, error) { 42 b, err := ioutil.ReadFile(currentVersionFile) 43 if err != nil { 44 return "", err 45 } 46 47 if submatch := currentVersionRegexp.FindSubmatch(b); len(submatch) == 2 { 48 return string(submatch[1]), nil 49 } 50 51 return "", errors.New("github.com/gofiber/fiber was not found in go.mod") 52 } 53 54 var latestVersionRegexp = regexp.MustCompile(`"name":\s*?"v(.*?)"`) 55 56 func latestVersion(isCli bool) (v string, err error) { 57 var ( 58 res *http.Response 59 b []byte 60 ) 61 62 if isCli { 63 res, err = http.Get("https://api.github.com/repos/gofiber/fiber-cli/releases/latest") 64 } else { 65 res, err = http.Get("https://api.github.com/repos/gofiber/fiber/releases/latest") 66 } 67 68 if err != nil { 69 return 70 } 71 72 defer func() { 73 _ = res.Body.Close() 74 }() 75 76 if b, err = ioutil.ReadAll(res.Body); err != nil { 77 return 78 } 79 80 if submatch := latestVersionRegexp.FindSubmatch(b); len(submatch) == 2 { 81 return string(submatch[1]), nil 82 } 83 84 return "", errors.New("no version found in github response body") 85 }