get.porter.sh/porter@v1.3.0/pkg/porter/version/version.go (about) 1 package version 2 3 import ( 4 "fmt" 5 6 "get.porter.sh/porter/pkg/pkgmgmt" 7 "get.porter.sh/porter/pkg/portercontext" 8 "get.porter.sh/porter/pkg/printer" 9 ) 10 11 // VersionOptions represent generic options for use by version commands 12 type Options struct { 13 printer.PrintOptions 14 } 15 16 var DefaultVersionFormat = printer.FormatPlaintext 17 18 func (o *Options) Validate() error { 19 if o.RawFormat == "" { 20 o.RawFormat = string(DefaultVersionFormat) 21 } 22 23 err := o.ParseFormat() 24 if err != nil { 25 return err 26 } 27 28 switch o.Format { 29 case printer.FormatJson, printer.FormatPlaintext: 30 return nil 31 default: 32 return fmt.Errorf("unsupported format, %s. Supported formats are: %s and %s", o.Format, printer.FormatJson, printer.FormatPlaintext) 33 } 34 } 35 36 // PrintVersion prints the version based on the version flags using the binary's metadata. 37 // Suitable for any mixin or plugin to use to implement its version command. 38 func PrintVersion(cxt *portercontext.Context, opts Options, metadata pkgmgmt.PackageMetadata) error { 39 switch opts.Format { 40 case printer.FormatJson: 41 return printer.PrintJson(cxt.Out, metadata) 42 case printer.FormatPlaintext: 43 vi := metadata.GetVersionInfo() 44 authorship := "" 45 if vi.Author != "" { 46 authorship = " by " + vi.Author 47 } 48 _, err := fmt.Fprintf(cxt.Out, "%s %s (%s)%s\n", metadata.GetName(), vi.Version, vi.Commit, authorship) 49 return err 50 default: 51 return fmt.Errorf("unsupported format: %s", opts.Format) 52 } 53 }