github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/compose_version.go (about)

     1  /*
     2     Copyright The containerd 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 main
    18  
    19  import (
    20  	"fmt"
    21  	"strings"
    22  
    23  	"github.com/containerd/nerdctl/pkg/version"
    24  	"github.com/spf13/cobra"
    25  )
    26  
    27  func newComposeVersionCommand() *cobra.Command {
    28  	var composeVersionCommand = &cobra.Command{
    29  		Use:           "version",
    30  		Short:         "Show the Compose version information",
    31  		Args:          cobra.NoArgs,
    32  		RunE:          composeVersionAction,
    33  		SilenceUsage:  true,
    34  		SilenceErrors: true,
    35  	}
    36  	composeVersionCommand.Flags().StringP("format", "f", "pretty", "Format the output. Values: [pretty | json]")
    37  	composeVersionCommand.RegisterFlagCompletionFunc("format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    38  		return []string{"json", "pretty"}, cobra.ShellCompDirectiveNoFileComp
    39  	})
    40  	composeVersionCommand.Flags().Bool("short", false, "Shows only Compose's version number")
    41  	return composeVersionCommand
    42  }
    43  
    44  func composeVersionAction(cmd *cobra.Command, args []string) error {
    45  	short, err := cmd.Flags().GetBool("short")
    46  	if err != nil {
    47  		return err
    48  	}
    49  	if short {
    50  		fmt.Fprintln(cmd.OutOrStdout(), strings.TrimPrefix(version.GetVersion(), "v"))
    51  		return nil
    52  	}
    53  
    54  	format, err := cmd.Flags().GetString("format")
    55  	if err != nil {
    56  		return err
    57  	}
    58  	switch format {
    59  	case "pretty":
    60  		fmt.Fprintln(cmd.OutOrStdout(), "nerdctl Compose version "+version.GetVersion())
    61  	case "json":
    62  		fmt.Fprintf(cmd.OutOrStdout(), "{\"version\":\"%v\"}\n", version.Version)
    63  	default:
    64  		return fmt.Errorf("format can be either pretty or json, not %v", format)
    65  	}
    66  
    67  	return nil
    68  }