...

Source file src/sigs.k8s.io/release-utils/version/command.go

Documentation: sigs.k8s.io/release-utils/version

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package version
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/spf13/cobra"
    23  )
    24  
    25  // Version returns a cobra command to be added to another cobra command, like:
    26  // ```go
    27  //
    28  //	rootCmd.AddCommand(version.Version())
    29  //
    30  // ```
    31  func Version() *cobra.Command {
    32  	return version("")
    33  }
    34  
    35  // WithFont returns a cobra command to be added to another cobra command with a select font for ASCII, like:
    36  // ```go
    37  //
    38  //	rootCmd.AddCommand(version.WithFont("starwars"))
    39  //
    40  // ```
    41  func WithFont(fontName string) *cobra.Command {
    42  	return version(fontName)
    43  }
    44  
    45  func version(fontName string) *cobra.Command {
    46  	var outputJSON bool
    47  	cmd := &cobra.Command{
    48  		Use:   "version",
    49  		Short: "Prints the version",
    50  		RunE: func(cmd *cobra.Command, args []string) error {
    51  			v := GetVersionInfo()
    52  			v.Name = cmd.Root().Name()
    53  			v.Description = cmd.Root().Short
    54  
    55  			v.FontName = ""
    56  			if fontName != "" && v.CheckFontName(fontName) {
    57  				v.FontName = fontName
    58  			}
    59  			cmd.SetOut(cmd.OutOrStdout())
    60  
    61  			if outputJSON {
    62  				out, err := v.JSONString()
    63  				if err != nil {
    64  					return fmt.Errorf("unable to generate JSON from version info: %w", err)
    65  				}
    66  				cmd.Println(out)
    67  			} else {
    68  				cmd.Println(v.String())
    69  			}
    70  			return nil
    71  		},
    72  	}
    73  
    74  	cmd.Flags().BoolVar(&outputJSON, "json", false, "print JSON instead of text")
    75  
    76  	return cmd
    77  }
    78  

View as plain text