github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/version.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/google/go-github/v42/github"
     7  	goversion "github.com/hashicorp/go-version"
     8  	"github.com/manifoldco/promptui"
     9  	"github.com/spf13/cobra"
    10  	"github.com/unionj-cloud/go-doudou/cmd/internal/svc"
    11  	"github.com/unionj-cloud/go-doudou/version"
    12  	"os"
    13  	"time"
    14  )
    15  
    16  func LatestReleaseVer() string {
    17  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    18  	defer cancel()
    19  	release, _, err := github.NewClient(nil).Repositories.GetLatestRelease(ctx, "unionj-cloud", "go-doudou")
    20  	if err != nil {
    21  		panic(err)
    22  	}
    23  	return release.GetTagName()
    24  }
    25  
    26  var Prompt ISelect = &promptui.Select{
    27  	Label:  "Do you want to upgrade?",
    28  	Items:  []string{"Yes", "No"},
    29  	Stdin:  os.Stdin,
    30  	Stdout: os.Stdout,
    31  }
    32  
    33  var VersionSvc = svc.NewSvc
    34  var LatestReleaseVerFunc = LatestReleaseVer
    35  
    36  var versionCmd = &cobra.Command{
    37  	Use:   "version",
    38  	Short: "Print the version number of go-doudou",
    39  	Long:  `You can get information about latest release version besides version number of installed go-doudou`,
    40  	Run: func(cmd *cobra.Command, args []string) {
    41  		fmt.Printf("Installed version is %s\n", version.Release)
    42  		latest := LatestReleaseVerFunc()
    43  		currentVersion, _ := goversion.NewVersion(version.Release)
    44  		latestVersion, _ := goversion.NewVersion(latest)
    45  		if currentVersion.LessThan(latestVersion) {
    46  			fmt.Printf("Latest release version is %s\n", latest)
    47  			_, result, err := Prompt.Run()
    48  			if err != nil {
    49  				panic(err)
    50  			}
    51  			if result == "Yes" {
    52  				s := VersionSvc("")
    53  				s.Upgrade(latest)
    54  				fmt.Println("DONE")
    55  			}
    56  		}
    57  	},
    58  }
    59  
    60  func init() {
    61  	rootCmd.AddCommand(versionCmd)
    62  }