Skip to content

✨clusterctl: add version command #2061

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ ifeq ($(SELINUX_ENABLED),1)
DOCKER_VOL_OPTS?=:z
endif

# Set build time variables including version details
LDFLAGS := $(shell hack/version.sh)

all: test manager clusterctl

help: ## Display this help
Expand Down Expand Up @@ -133,7 +136,7 @@ managers: ## Build all managers

.PHONY: clusterctl
clusterctl: ## Build clusterctl binary
go build -o bin/clusterctl sigs.k8s.io/cluster-api/cmd/clusterctl
go build -ldflags "$(LDFLAGS)" -o bin/clusterctl sigs.k8s.io/cluster-api/cmd/clusterctl

$(KUSTOMIZE): $(TOOLS_DIR)/go.mod # Build kustomize from tools folder.
cd $(TOOLS_DIR); go build -tags=tools -o $(BIN_DIR)/kustomize sigs.k8s.io/kustomize/kustomize/v3
Expand Down
2 changes: 1 addition & 1 deletion cmd/clusterctl/cmd/config_providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ var configProvidersCmd = &cobra.Command{
clusterctl config provider aws:v0.4.1 -o yaml`),

RunE: func(cmd *cobra.Command, args []string) error {
if !(cpo.output == "" || cpo.output == "yaml" || cpo.output == "text") {
if !(cpo.output == "" || cpo.output == "yaml" || cpo.output == "text") { //nolint goconst
return errors.New("please provide a valid output. Supported values are [ text, yaml ]")
}

Expand Down
68 changes: 66 additions & 2 deletions cmd/clusterctl/cmd/version.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2019 The Kubernetes Authors.
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -16,4 +16,68 @@ limitations under the License.

package cmd

// TODO: version command
import (
"encoding/json"
"fmt"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"sigs.k8s.io/cluster-api/cmd/version"
"sigs.k8s.io/yaml"
)

// Version provides the version information of clusterctl
type Version struct {
ClientVersion *version.Info `json:"clusterctl"`
}

type versionOptions struct {
output string
}

var vo = &versionOptions{}

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version of clustectl",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
return runVersion()
},
}

func init() {
versionCmd.Flags().StringVarP(&vo.output, "output", "o", "", "Output format; available options are 'yaml', 'json' and 'short'")

RootCmd.AddCommand(versionCmd)
}

func runVersion() error {
clientVersion := version.Get()
v := Version{
ClientVersion: &clientVersion,
}

switch vo.output {
case "":
fmt.Printf("clusterctl version: %#v\n", v.ClientVersion)
case "short":
fmt.Printf("%s\n", v.ClientVersion.GitVersion)
case "yaml":
y, err := yaml.Marshal(&v)
if err != nil {
return err
}
fmt.Print(string(y))
case "json":
y, err := json.MarshalIndent(&v, "", " ")
if err != nil {
return err
}
fmt.Println(string(y))
default:
return errors.Errorf("invalid output format: %s", vo.output)
}

return nil
}
62 changes: 62 additions & 0 deletions cmd/version/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package version

import (
"fmt"
"runtime"
)

var (
gitMajor string // major version, always numeric
gitMinor string // minor version, numeric possibly followed by "+"
gitVersion string // semantic version, derived by build scripts
gitCommit string // sha1 from git, output of $(git rev-parse HEAD)
gitTreeState string // state of git tree, either "clean" or "dirty"
buildDate string // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
)

type Info struct {
Major string `json:"major,omitempty"`
Minor string `json:"minor,omitempty"`
GitVersion string `json:"gitVersion,omitempty"`
GitCommit string `json:"gitCommit,omitempty"`
GitTreeState string `json:"gitTreeState,omitempty"`
BuildDate string `json:"buildDate,omitempty"`
GoVersion string `json:"goVersion,omitempty"`
Compiler string `json:"compiler,omitempty"`
Platform string `json:"platform,omitempty"`
}

func Get() Info {
return Info{
Major: gitMajor,
Minor: gitMinor,
GitVersion: gitVersion,
GitCommit: gitCommit,
GitTreeState: gitTreeState,
BuildDate: buildDate,
GoVersion: runtime.Version(),
Compiler: runtime.Compiler,
Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
}
}

// String returns info as a human-friendly version string.
func (info Info) String() string {
return info.GitVersion
}
104 changes: 104 additions & 0 deletions hack/version.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# Copyright 2020 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

version::get_version_vars() {
# shellcheck disable=SC1083
GIT_COMMIT="$(git rev-parse HEAD^{commit})"

if git_status=$(git status --porcelain 2>/dev/null) && [[ -z ${git_status} ]]; then
GIT_TREE_STATE="clean"
else
GIT_TREE_STATE="dirty"
fi

# stolen from k8s.io/hack/lib/version.sh
# Use git describe to find the version based on tags.
if GIT_VERSION=$(git describe --tags --abbrev=14 2>/dev/null); then
# This translates the "git describe" to an actual semver.org
# compatible semantic version that looks something like this:
# v1.1.0-alpha.0.6+84c76d1142ea4d
#
# TODO: We continue calling this "git version" because so many
# downstream consumers are expecting it there.
# shellcheck disable=SC2001
DASHES_IN_VERSION=$(echo "${GIT_VERSION}" | sed "s/[^-]//g")
if [[ "${DASHES_IN_VERSION}" == "---" ]] ; then
# We have distance to subversion (v1.1.0-subversion-1-gCommitHash)
# shellcheck disable=SC2001
GIT_VERSION=$(echo "${GIT_VERSION}" | sed "s/-\([0-9]\{1,\}\)-g\([0-9a-f]\{14\}\)$/.\1\-\2/")
elif [[ "${DASHES_IN_VERSION}" == "--" ]] ; then
# We have distance to base tag (v1.1.0-1-gCommitHash)
# shellcheck disable=SC2001
GIT_VERSION=$(echo "${GIT_VERSION}" | sed "s/-g\([0-9a-f]\{14\}\)$/-\1/")
fi
if [[ "${GIT_TREE_STATE}" == "dirty" ]]; then
# git describe --dirty only considers changes to existing files, but
# that is problematic since new untracked .go files affect the build,
# so use our idea of "dirty" from git status instead.
GIT_VERSION+="-dirty"
fi


# Try to match the "git describe" output to a regex to try to extract
# the "major" and "minor" versions and whether this is the exact tagged
# version or whether the tree is between two tagged versions.
if [[ "${GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?([-].*)?([+].*)?$ ]]; then
GIT_MAJOR=${BASH_REMATCH[1]}
GIT_MINOR=${BASH_REMATCH[2]}
fi

# If GIT_VERSION is not a valid Semantic Version, then refuse to build.
if ! [[ "${GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then
echo "GIT_VERSION should be a valid Semantic Version. Current value: ${GIT_VERSION}"
echo "Please see more details here: https://semver.org"
exit 1
fi
fi

GIT_RELEASE_TAG=$(git describe --abbrev=0 --tags)
GIT_RELEASE_COMMIT=$(git rev-list -n 1 "${GIT_RELEASE_TAG}")
}

# stolen from k8s.io/hack/lib/version.sh and modified
# Prints the value that needs to be passed to the -ldflags parameter of go build
version::ldflags() {
version::get_version_vars

local -a ldflags
function add_ldflag() {
local key=${1}
local val=${2}
ldflags+=(
"-X 'sigs.k8s.io/cluster-api/cmd/version.${key}=${val}'"
)
}

add_ldflag "buildDate" "$(date ${SOURCE_DATE_EPOCH:+"--date=@${SOURCE_DATE_EPOCH}"} -u +'%Y-%m-%dT%H:%M:%SZ')"
add_ldflag "gitCommit" "${GIT_COMMIT}"
add_ldflag "gitTreeState" "${GIT_TREE_STATE}"
add_ldflag "gitMajor" "${GIT_MAJOR}"
add_ldflag "gitMinor" "${GIT_MINOR}"
add_ldflag "gitVersion" "${GIT_VERSION}"
add_ldflag "gitReleaseCommit" "${GIT_RELEASE_COMMIT}"

# The -ldflags parameter takes a single string, so join the output.
echo "${ldflags[*]-}"
}

version::ldflags