1/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package verflag defines utility functions to handle command line flags
18// related to version of Kubernetes.
19package verflag
20
21import (
22	"fmt"
23	"os"
24	"strconv"
25
26	flag "github.com/spf13/pflag"
27
28	"k8s.io/component-base/version"
29)
30
31type versionValue int
32
33const (
34	VersionFalse versionValue = 0
35	VersionTrue  versionValue = 1
36	VersionRaw   versionValue = 2
37)
38
39const strRawVersion string = "raw"
40
41func (v *versionValue) IsBoolFlag() bool {
42	return true
43}
44
45func (v *versionValue) Get() interface{} {
46	return versionValue(*v)
47}
48
49func (v *versionValue) Set(s string) error {
50	if s == strRawVersion {
51		*v = VersionRaw
52		return nil
53	}
54	boolVal, err := strconv.ParseBool(s)
55	if boolVal {
56		*v = VersionTrue
57	} else {
58		*v = VersionFalse
59	}
60	return err
61}
62
63func (v *versionValue) String() string {
64	if *v == VersionRaw {
65		return strRawVersion
66	}
67	return fmt.Sprintf("%v", bool(*v == VersionTrue))
68}
69
70// The type of the flag as required by the pflag.Value interface
71func (v *versionValue) Type() string {
72	return "version"
73}
74
75func VersionVar(p *versionValue, name string, value versionValue, usage string) {
76	*p = value
77	flag.Var(p, name, usage)
78	// "--version" will be treated as "--version=true"
79	flag.Lookup(name).NoOptDefVal = "true"
80}
81
82func Version(name string, value versionValue, usage string) *versionValue {
83	p := new(versionValue)
84	VersionVar(p, name, value, usage)
85	return p
86}
87
88const versionFlagName = "version"
89
90var (
91	versionFlag = Version(versionFlagName, VersionFalse, "Print version information and quit")
92	programName = "Kubernetes"
93)
94
95// AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the
96// same value as the global flags.
97func AddFlags(fs *flag.FlagSet) {
98	fs.AddFlag(flag.Lookup(versionFlagName))
99}
100
101// PrintAndExitIfRequested will check if the -version flag was passed
102// and, if so, print the version and exit.
103func PrintAndExitIfRequested() {
104	if *versionFlag == VersionRaw {
105		fmt.Printf("%#v\n", version.Get())
106		os.Exit(0)
107	} else if *versionFlag == VersionTrue {
108		fmt.Printf("%s %s\n", programName, version.Get())
109		os.Exit(0)
110	}
111}
112