github.com/kilpkonn/gtm-enhanced@v1.3.5/command/verify.go (about) 1 // Copyright 2016 Michael Schenk. All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE file. 4 5 package command 6 7 import ( 8 "bytes" 9 "flag" 10 "fmt" 11 "os" 12 "strings" 13 14 "github.com/hashicorp/go-version" 15 "github.com/mitchellh/cli" 16 ) 17 18 // VerifyCmd contains CLI commands for verify 19 type VerifyCmd struct { 20 UI cli.Ui 21 Version string 22 Out *bytes.Buffer 23 } 24 25 func (c VerifyCmd) output(s string) { 26 var err error 27 if c.Out != nil { 28 _, err = fmt.Fprint(c.Out, s) 29 } else { 30 _, err = fmt.Fprint(os.Stdout, s) 31 } 32 if err != nil { 33 fmt.Printf("Error printing output, %s\n", err) 34 } 35 } 36 37 // Help returns CLI help for Verify command 38 func (c VerifyCmd) Help() string { 39 helpText := ` 40 Usage: gtm verify <version-constraint> 41 42 Check if gtm satisfies a Semantic Version 2.0 constraint. 43 ` 44 return strings.TrimSpace(helpText) 45 } 46 47 // Run executes verify commands with args 48 func (c VerifyCmd) Run(args []string) int { 49 cmdFlags := flag.NewFlagSet("verify", flag.ContinueOnError) 50 cmdFlags.Usage = func() { c.UI.Output(c.Help()) } 51 if err := cmdFlags.Parse(args); err != nil { 52 return 1 53 } 54 55 if len(args) == 0 { 56 c.UI.Error("Unable to verify version, version constraint not provided") 57 return 1 58 } 59 60 valid, err := c.check(args[0]) 61 if err != nil { 62 c.UI.Error(err.Error()) 63 return 1 64 } 65 66 // NOTE a newline is not sent when outputting to terminal. 67 // THis makes it easier to assign to a shell variable. 68 // For example, v=$(gtm verify "1.0.0") but because there is 69 // no newline running gtm verify will not display anything 70 c.output(fmt.Sprintf("%t", valid)) 71 return 0 72 } 73 74 // Synopsis returns verify help 75 func (c VerifyCmd) Synopsis() string { 76 return "Check if gtm satisfies a Semantic Version 2.0 constraint" 77 } 78 79 func (c VerifyCmd) check(constraint string) (bool, error) { 80 // Our version tags can have a 'v' prefix 81 // Strip v prefix if it exists because it's not valid for a Semantic version 82 cleanVersion := c.Version 83 if strings.HasPrefix(strings.ToLower(cleanVersion), "v") { 84 cleanVersion = cleanVersion[1:] 85 } 86 87 ver, err := version.NewVersion(cleanVersion) 88 if err != nil { 89 return false, err 90 } 91 92 vc, err := version.NewConstraint(constraint) 93 if err != nil { 94 return false, err 95 } 96 97 return vc.Check(ver), nil 98 }