nf/nft/nfctl/version/version.go

96 lines
2.2 KiB
Go
Raw Normal View History

package version
import (
2024-07-14 17:26:48 +08:00
"crypto/tls"
"fmt"
"github.com/fatih/color"
"github.com/loveuer/nf/nft/log"
"github.com/savioxavier/termlink"
2024-07-14 21:17:40 +08:00
"io"
"net/http"
"strings"
2024-07-14 17:26:48 +08:00
"time"
)
var (
2024-07-14 17:26:48 +08:00
uri = "https://raw.gitcode.com/loveuer/nf/raw/master/nft/nfctl/version/var.go"
prefix = "const Version = "
)
2024-07-14 17:26:48 +08:00
func UpgradePrint(newVersion string) {
2024-07-14 21:17:40 +08:00
fmt.Printf(`+----------------------------------------------------------------------+
| 🎉 🎉 🎉 %s 🎉 🎉 🎉 |
| %s |
| Or Download by: |
| %s |
| %s |
+----------------------------------------------------------------------+
`,
color.GreenString("New Version Found: %s", newVersion),
color.CyanString("Upgrade it with: [go install github.com/loveuer/nf/nft/nfctl@master]"),
color.CyanString(termlink.Link("Releases", "https://github.com/loveuer/nf/releases")),
color.CyanString(termlink.Link("Releases", "https://gitcode.com/loveuer/nf/releases")),
)
2024-07-14 17:26:48 +08:00
}
2024-07-14 21:17:40 +08:00
func Check(printUpgradable bool, printNoNeedUpgrade bool, timeouts ...int) string {
2024-07-14 17:26:48 +08:00
var (
v string
)
2024-07-14 17:26:48 +08:00
defer func() {
if printUpgradable {
if v > Version {
UpgradePrint(v)
}
}
2024-07-14 17:26:48 +08:00
if printNoNeedUpgrade {
if v == Version {
color.Cyan("Your Version: %s is Newest", Version)
}
}
}()
2024-07-14 17:26:48 +08:00
2024-07-14 21:17:40 +08:00
timeout := time.Duration(30) * time.Second
if len(timeouts) > 0 && timeouts[0] > 0 {
timeout = time.Duration(timeouts[0]) * time.Second
2024-07-14 17:26:48 +08:00
}
2024-07-14 21:17:40 +08:00
req, _ := http.NewRequest(http.MethodGet, uri, nil)
resp, err := (&http.Client{
Timeout: timeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}).Do(req)
2024-07-14 17:26:48 +08:00
if err != nil {
log.Debug("[Check] http get[%s] err: %v", uri, err.Error())
return ""
}
2024-07-14 21:17:40 +08:00
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
if err != nil {
log.Debug("[Check] http read all body err: %v", err)
}
2024-07-14 17:26:48 +08:00
2024-07-14 21:17:40 +08:00
log.Debug("[Check] http get[%s] body:\n%s", uri, string(content))
2024-07-14 17:26:48 +08:00
2024-07-14 21:17:40 +08:00
for _, line := range strings.Split(string(content), "\n") {
2024-07-14 17:26:48 +08:00
log.Debug("[Check] version.go line: %s", line)
if strings.HasPrefix(line, prefix) {
may := strings.TrimPrefix(line, prefix)
if len(may) > 2 {
v = may[1 : len(may)-1]
}
return v
}
}
return ""
}