github.com/azunymous/cdx@v0.0.0-20201122180449-fbb46cc4d252/commands/latest.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/azunymous/cdx/commands/options"
     6  	"github.com/azunymous/cdx/vcs"
     7  	"github.com/azunymous/cdx/vcs/gogit"
     8  	"github.com/sirupsen/logrus"
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  // addLatest adds the latest command to a top level command.
    13  func addLatest(topLevel *cobra.Command, app *options.App) {
    14  	gitOpts := &options.Git{}
    15  	latestCmd := &cobra.Command{
    16  		Use:   "latest [promotion stage]",
    17  		Short: "Get the latest version of an application",
    18  		Long: `The latest command fetches the latest version of an application from git tags. 
    19  If a stage is specified, the latest version promoted to that stage is returned.
    20  `,
    21  		Run: func(cmd *cobra.Command, args []string) {
    22  			err := latest(args, app, gitOpts)
    23  			if err != nil {
    24  				logrus.Fatal(err)
    25  			}
    26  		},
    27  		Args: cobra.MaximumNArgs(1),
    28  	}
    29  
    30  	options.AddHeadOnlyArg(latestCmd, gitOpts)
    31  	options.AddFallbackHashArg(latestCmd, gitOpts)
    32  	topLevel.AddCommand(latestCmd)
    33  }
    34  
    35  func latest(args []string, app *options.App, gitOpts *options.Git) error {
    36  	stage := ""
    37  	if len(args) > 0 {
    38  		stage = args[0]
    39  	}
    40  	v, err := vcs.NewGit(app.Name, -1, false, func() (vcs.Repository, error) { return gogit.NewRepo() })
    41  	if err != nil {
    42  		return err
    43  	}
    44  	version, err := v.Version(stage, gitOpts.HeadOnly, gitOpts.FallbackHash)
    45  	if err != nil {
    46  		return err
    47  	}
    48  	fmt.Println(version)
    49  	return nil
    50  }