Add binary autoupdate.

This commit is contained in:
2021-05-15 17:34:50 +01:00
parent 7608d2bc50
commit 29ad85b62a
7 changed files with 92 additions and 12 deletions
+64
View File
@@ -3,11 +3,75 @@ package cmd
import (
"fmt"
"os"
"runtime"
gql "github.com/lukaszraczylo/simple-gql-client"
"github.com/melbahja/got"
"github.com/tidwall/gjson"
)
func updatePackage() bool {
ghToken, ghTokenSet := os.LookupEnv("GITHUB_TOKEN")
if ghTokenSet {
binaryName := fmt.Sprintf("semver-gen-%s-%s", runtime.GOOS, runtime.GOARCH)
fmt.Println("Downloading", binaryName)
gql.GraphQLUrl = "https://api.github.com/graphql"
headers := map[string]interface{}{
"Authorization": fmt.Sprintf("bearer %s", ghToken),
}
variables := map[string]interface{}{
"binaryName": binaryName,
}
var query = `query ($binaryName: String) {
repository(name: "semver-generator", owner: "lukaszraczylo") {
latestRelease {
releaseAssets(first: 10, name: $binaryName) {
edges {
node {
name
downloadUrl
}
}
}
}
}
}`
result, err := gql.Query(query, variables, headers)
if err != nil {
fmt.Println("Query error", err)
return false
}
result = gjson.Get(result, "repository.latestRelease.releaseAssets.edges.0.node.downloadUrl").String()
if result == "" {
fmt.Println("Unable to obtain download url for the binary", binaryName)
return false
}
downloadedBinaryPath := fmt.Sprintf("/tmp/%s", binaryName)
g := got.New()
err = g.Download(result, downloadedBinaryPath)
if err != nil {
fmt.Println("Unable to download binary", err.Error())
return false
}
currentBinary, err := os.Executable()
if err != nil {
fmt.Println("Unable to obtain current binary path", err.Error())
return false
}
err = os.Rename(downloadedBinaryPath, currentBinary)
if err != nil {
fmt.Println("Unable to overwrite current binary", err.Error())
return false
}
err = os.Chmod(currentBinary, 0777)
if err != nil {
fmt.Println("Unable to make binary executable", err.Error())
return false
}
}
return true
}
func checkLatestRelease() (string, bool) {
ghToken, ghTokenSet := os.LookupEnv("GITHUB_TOKEN")
if ghTokenSet {
+3
View File
@@ -242,6 +242,9 @@ func main() {
fmt.Println("semver-gen", PKG_VERSION, "", outdatedMsg, "\tMore information: https://github.com/lukaszraczylo/semver-generator")
return
}
if varUpdate {
updatePackage()
}
if repo.Generate {
err := repo.ReadConfig(repo.LocalConfigFile)
if err != nil {
+2
View File
@@ -59,6 +59,7 @@ var (
varUseLocal bool
varShowVersion bool
varDebug bool
varUpdate bool
)
func init() {
@@ -70,5 +71,6 @@ func init() {
rootCmd.PersistentFlags().BoolVarP(&varUseLocal, "local", "l", false, "Use local repository")
rootCmd.PersistentFlags().BoolVarP(&varShowVersion, "version", "v", false, "Display version")
rootCmd.PersistentFlags().BoolVarP(&varDebug, "debug", "d", false, "Enable debug mode")
rootCmd.PersistentFlags().BoolVarP(&varUpdate, "update", "u", false, "Update binary with latest")
}
}