summaryrefslogtreecommitdiff
path: root/cmd/podman/system/version.go
blob: 5f39b4820b25f6738778c382df513d55122ef2a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package system

import (
	"fmt"
	"io"
	"os"
	"strings"
	"text/tabwriter"

	"github.com/containers/buildah/pkg/formats"
	"github.com/containers/podman/v2/cmd/podman/parse"
	"github.com/containers/podman/v2/cmd/podman/registry"
	"github.com/containers/podman/v2/cmd/podman/validate"
	"github.com/containers/podman/v2/libpod/define"
	"github.com/containers/podman/v2/pkg/domain/entities"
	"github.com/spf13/cobra"
)

var (
	versionCommand = &cobra.Command{
		Use:   "version",
		Args:  validate.NoArgs,
		Short: "Display the Podman Version Information",
		RunE:  version,
	}
	versionFormat string
)

func init() {
	registry.Commands = append(registry.Commands, registry.CliCommand{
		Mode:    []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
		Command: versionCommand,
	})
	flags := versionCommand.Flags()
	flags.StringVarP(&versionFormat, "format", "f", "", "Change the output format to JSON or a Go template")
}

func version(cmd *cobra.Command, args []string) error {
	versions, err := registry.ContainerEngine().Version(registry.Context())
	if err != nil {
		return err
	}

	switch {
	case parse.MatchesJSONFormat(versionFormat):
		s, err := json.MarshalToString(versions)
		if err != nil {
			return err
		}
		_, err = io.WriteString(os.Stdout, s+"\n")
		return err
	case cmd.Flag("format").Changed:
		out := formats.StdoutTemplate{Output: versions, Template: versionFormat}
		err := out.Out()
		if err != nil {
			// On Failure, assume user is using older version of podman version --format and check client
			versionFormat = strings.Replace(versionFormat, ".Server.", ".", 1)
			out = formats.StdoutTemplate{Output: versions.Client, Template: versionFormat}
			if err1 := out.Out(); err1 != nil {
				return err
			}
		}
		return nil
	}

	w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
	defer w.Flush()

	if versions.Server != nil {
		if _, err := fmt.Fprintf(w, "Client:\n"); err != nil {
			return err
		}
		formatVersion(w, versions.Client)
		if _, err := fmt.Fprintf(w, "\nServer:\n"); err != nil {
			return err
		}
		formatVersion(w, versions.Server)
	} else {
		formatVersion(w, versions.Client)
	}
	return nil
}

func formatVersion(writer io.Writer, version *define.Version) {
	fmt.Fprintf(writer, "Version:\t%s\n", version.Version)
	fmt.Fprintf(writer, "API Version:\t%d\n", version.APIVersion)
	fmt.Fprintf(writer, "Go Version:\t%s\n", version.GoVersion)
	if version.GitCommit != "" {
		fmt.Fprintf(writer, "Git Commit:\t%s\n", version.GitCommit)
	}
	fmt.Fprintf(writer, "Built:\t%s\n", version.BuiltTime)
	fmt.Fprintf(writer, "OS/Arch:\t%s\n", version.OsArch)
}