github.com/daniellockard/packer@v0.7.6-0.20141210173435-5a9390934716/command/version.go (about)

     1  package command
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  )
     7  
     8  // VersionCommand is a Command implementation prints the version.
     9  type VersionCommand struct {
    10  	Meta
    11  
    12  	Revision          string
    13  	Version           string
    14  	VersionPrerelease string
    15  	CheckFunc         VersionCheckFunc
    16  }
    17  
    18  // VersionCheckFunc is the callback called by the Version command to
    19  // check if there is a new version of Packer.
    20  type VersionCheckFunc func() (VersionCheckInfo, error)
    21  
    22  // VersionCheckInfo is the return value for the VersionCheckFunc callback
    23  // and tells the Version command information about the latest version
    24  // of Packer.
    25  type VersionCheckInfo struct {
    26  	Outdated bool
    27  	Latest   string
    28  	Alerts   []string
    29  }
    30  
    31  func (c *VersionCommand) Help() string {
    32  	return ""
    33  }
    34  
    35  func (c *VersionCommand) Run(args []string) int {
    36  	env, err := c.Meta.Environment()
    37  	if err != nil {
    38  		c.Ui.Error(fmt.Sprintf("Error initializing environment: %s", err))
    39  		return 1
    40  	}
    41  
    42  	env.Ui().Machine("version", c.Version)
    43  	env.Ui().Machine("version-prelease", c.VersionPrerelease)
    44  	env.Ui().Machine("version-commit", c.Revision)
    45  
    46  	var versionString bytes.Buffer
    47  	fmt.Fprintf(&versionString, "Packer v%s", c.Version)
    48  	if c.VersionPrerelease != "" {
    49  		fmt.Fprintf(&versionString, ".%s", c.VersionPrerelease)
    50  
    51  		if c.Revision != "" {
    52  			fmt.Fprintf(&versionString, " (%s)", c.Revision)
    53  		}
    54  	}
    55  
    56  	c.Ui.Output(versionString.String())
    57  
    58  	// If we have a version check function, then let's check for
    59  	// the latest version as well.
    60  	if c.CheckFunc != nil {
    61  		// Separate the prior output with a newline
    62  		c.Ui.Output("")
    63  
    64  		// Check the latest version
    65  		info, err := c.CheckFunc()
    66  		if err != nil {
    67  			c.Ui.Error(fmt.Sprintf(
    68  				"Error checking latest version: %s", err))
    69  		}
    70  		if info.Outdated {
    71  			c.Ui.Output(fmt.Sprintf(
    72  				"Your version of Packer is out of date! The latest version\n"+
    73  					"is %s. You can update by downloading from www.packer.io",
    74  				info.Latest))
    75  		}
    76  	}
    77  
    78  	return 0
    79  }
    80  
    81  func (c *VersionCommand) Synopsis() string {
    82  	return "Prints the Packer version"
    83  }