version.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "fmt"
  16. "strings"
  17. "github.com/docker/cli/cli/command"
  18. "github.com/docker/compose/v2/cmd/formatter"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose/v2/internal"
  21. )
  22. type versionOptions struct {
  23. format string
  24. short bool
  25. }
  26. func versionCommand(dockerCli command.Cli) *cobra.Command {
  27. opts := versionOptions{}
  28. cmd := &cobra.Command{
  29. Use: "version [OPTIONS]",
  30. Short: "Show the Docker Compose version information",
  31. Args: cobra.NoArgs,
  32. RunE: func(cmd *cobra.Command, _ []string) error {
  33. runVersion(opts, dockerCli)
  34. return nil
  35. },
  36. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  37. // overwrite parent PersistentPreRunE to avoid trying to load
  38. // compose file on version command if COMPOSE_FILE is set
  39. return nil
  40. },
  41. }
  42. // define flags for backward compatibility with com.docker.cli
  43. flags := cmd.Flags()
  44. flags.StringVarP(&opts.format, "format", "f", "", "Format the output. Values: [pretty | json]. (Default: pretty)")
  45. flags.BoolVar(&opts.short, "short", false, "Shows only Compose's version number")
  46. return cmd
  47. }
  48. func runVersion(opts versionOptions, dockerCli command.Cli) {
  49. if opts.short {
  50. _, _ = fmt.Fprintln(dockerCli.Out(), strings.TrimPrefix(internal.Version, "v"))
  51. return
  52. }
  53. if opts.format == formatter.JSON {
  54. _, _ = fmt.Fprintf(dockerCli.Out(), "{\"version\":%q}\n", internal.Version)
  55. return
  56. }
  57. _, _ = fmt.Fprintln(dockerCli.Out(), "Docker Compose version", internal.Version)
  58. }