github.com/tcnksm/gcli@v0.2.4-0.20170129033839-7eb950507e5a/command/version.go (about)

     1  package command
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/tcnksm/go-latest"
     9  )
    10  
    11  // CheckTimeout is timeout of executing go-latest.Check()
    12  const CheckTimeout = 3 * time.Second
    13  
    14  // VersionCommand is a Command that shows version
    15  type VersionCommand struct {
    16  	Meta
    17  
    18  	Version  string
    19  	Revision string
    20  }
    21  
    22  // Run shows version string and commit hash if it exists.
    23  // It returns exit code
    24  func (c *VersionCommand) Run(args []string) int {
    25  	var versionString bytes.Buffer
    26  
    27  	fmt.Fprintf(&versionString, "gcli version %s", c.Version)
    28  	if c.Revision != "" {
    29  		fmt.Fprintf(&versionString, " (%s)", c.Revision)
    30  	}
    31  
    32  	c.UI.Output(versionString.String())
    33  
    34  	resCh := CheckLatest(c.Version)
    35  	select {
    36  	case res := <-resCh:
    37  		if res != nil && res.Outdated {
    38  			msg := fmt.Sprintf(
    39  				"\nYour versin of gcli is out of date! The latest version is %s.",
    40  				res.Current)
    41  			c.UI.Error(msg)
    42  		}
    43  	case <-time.After(CheckTimeout):
    44  		// Time out & do nothing
    45  	}
    46  
    47  	return 0
    48  }
    49  
    50  // Synopsis is a one-line, short synopsis of the command.
    51  func (c *VersionCommand) Synopsis() string {
    52  	return "Print the gcli version"
    53  }
    54  
    55  // Help is a long-form help text. In this case, help text is not  neccessary.
    56  func (c *VersionCommand) Help() string {
    57  	return ""
    58  }
    59  
    60  // CheckLatest run tcnksm/go-latest with gcli settings.
    61  // It retuns channel of checking results. Even if something wrong happened,
    62  // it neglects error because this is not important part of gcli execution.
    63  func CheckLatest(version string) <-chan *latest.CheckResponse {
    64  	// Check version is latest or not
    65  	fix := latest.DeleteFrontV()
    66  	github := &latest.GithubTag{
    67  		Owner:             "tcnksm",
    68  		Repository:        "gcli",
    69  		FixVersionStrFunc: fix,
    70  	}
    71  
    72  	resCh := make(chan *latest.CheckResponse)
    73  	go func() {
    74  		// Ignore error because it not critical for main fucntion
    75  		res, _ := latest.Check(github, fix(version))
    76  		resCh <- res
    77  	}()
    78  
    79  	return resCh
    80  }