Skip to content
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

Add commit ID to version output #370

Merged
merged 1 commit into from
Jul 18, 2023
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
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ WORKDIR /tmp/src

COPY . .

RUN CGO_ENABLED=0 go build -o ./out/chart-verifier main.go
RUN make bin

FROM registry.access.redhat.com/ubi9/ubi-minimal

Expand Down
9 changes: 7 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
IMAGE_BUILDER?=podman
IMAGE_REPO?=quay.io/redhat-certification
COMMIT_ID=$(shell git rev-parse --short HEAD)
COMMIT_ID_LONG=$(shell git rev-parse HEAD)

default: bin

Expand Down Expand Up @@ -33,15 +34,19 @@ fmt: install.gofumpt

.PHONY: bin
bin:
CGO_ENABLED=0 go build -o ./out/chart-verifier main.go
CGO_ENABLED=0 go build \
-ldflags "-X 'github.com/redhat-certification/chart-verifier/cmd.CommitIDLong=$(COMMIT_ID_LONG)'" \
-o ./out/chart-verifier main.go

.PHONY: lint
lint: install.golangci-lint
$(GOLANGCI_LINT) run

.PHONY: bin_win
bin_win:
env GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o .\out\chart-verifier.exe main.go
env GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build \
-ldflags "-X 'github.com/redhat-certification/chart-verifier/cmd.CommitIDLong=$(COMMIT_ID_LONG)'" \
-o .\out\chart-verifier.exe main.go

.PHONY: test
test:
Expand Down
30 changes: 29 additions & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
_ "embed"
"encoding/json"
"fmt"
"io"
"os"
Expand All @@ -11,10 +12,27 @@ import (
apiversion "github.com/redhat-certification/chart-verifier/pkg/chartverifier/version"
)

// Print version and commit ID as json blob
var asData bool

func init() {
rootCmd.AddCommand(NewVersionCmd())
}

// CommitIDLong contains the commit ID the binary was build on. It is populated at build time by ldflags.
// If you're running from a local debugger it will show an empty commit ID.
var CommitIDLong string = "unknown"

type VersionContext struct {
Version string `json:"version"`
Commit string `json:"commit"`
}

var Version = VersionContext{
Version: apiversion.GetVersion(),
Commit: CommitIDLong,
}

func NewVersionCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Expand All @@ -24,10 +42,20 @@ func NewVersionCmd() *cobra.Command {
return runVersion(os.Stdout)
},
}
cmd.Flags().BoolVar(&asData, "as-data", false, "output the version and commit ID information in JSON format")
return cmd
}

func runVersion(out io.Writer) error {
fmt.Fprintf(out, "v%s\n", apiversion.GetVersion())
if asData {
marshalledVersion, err := json.Marshal(Version)
if err != nil {
return err
komish marked this conversation as resolved.
Show resolved Hide resolved
}
fmt.Fprintf(out, "%s\n", string(marshalledVersion))
return nil
}

fmt.Fprintf(out, "chart-verifier v%s <commit: %s>\n", apiversion.GetVersion(), CommitIDLong)
return nil
}
8 changes: 4 additions & 4 deletions scripts/src/buildandtest/buildandtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ def test_image(image_id,chart,verifier_version):
print(f'[ERROR] Chart verifier report version {report["metadata"]["tool"]["verifier-version"]} does not match expected version: {verifier_version}')
return False

docker_command = "version"
# sample output: v1.0.0
docker_command = "version --as-data"
# sample output: {"version":"1.12.0","commit":"4dcd90a273747df545df2c4414f091caa8b0eb3d"}
out = client.containers.run(image_id, docker_command, stdin_open=True, tty=True, stderr=True)
if not out or out[1:] != verifier_version:
if not out or out["version"] != verifier_version:
print(f"[ERROR] 'chart-verifier version' output {out} does not match expected version: {verifier_version}")

print("[INFO] report:\n", report)
Expand Down Expand Up @@ -130,7 +130,7 @@ def main():

if not args.build_only:

chart = {"url" : "https://github.com/redhat-certification/chart-verifier/blob/main/pkg/chartverifier/checks/chart-0.1.0-v3.valid.tgz?raw=true",
chart = {"url" : "https://github.com/redhat-certification/chart-verifier/blob/main/internal/chartverifier/checks/chart-0.1.0-v3.valid.tgz?raw=true",
"results":{"passed":"10","failed":"1"},
"metadata":{"vendorType":"partner","profileVersion":"v1.0"}}

Expand Down
13 changes: 7 additions & 6 deletions tests/tests/functional/chart_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,28 +226,29 @@ def run_report_docker_image(verifier_image_name,verifier_image_tag,profile_type,
def run_version_tarball_image(tarball_name):
tar = tarfile.open(tarball_name, "r:gz")
tar.extractall(path="./test_verifier")
out = subprocess.run(["./test_verifier/chart-verifier","version"],capture_output=True)
out = subprocess.run(["./test_verifier/chart-verifier","version", "--as-data"],capture_output=True)
return normalize_version(out.stdout.decode("utf-8"))

def normalize_version(version):
"""Trim trailing newlines and leading v from semantic versions.
"""Extract normalized version from JSON data

Parameters:
version (string): a semver string like v0.0.0\n
version (string): the version and commit ID in JSON

Returns:
string: a normalized semver like 0.0.0.
"""
print(f'version input to normalize_version function is: {version}')
return version.rstrip().lstrip('v')
version_dict = json.loads(version)
return version_dict["version"]

def run_version_docker_image(verifier_image_name,verifier_image_tag):
"""Run chart verifier's version command using the Docker image."""
verifier_image = f"{verifier_image_name}:{verifier_image_tag}"
os.environ["VERIFIER_IMAGE"] = verifier_image
try:
client = docker.from_env()
output = client.containers.run(verifier_image,"version",stdin_open=True,tty=True,stdout=True,remove=True)
output = client.containers.run(verifier_image,"version --as-data",stdin_open=True,tty=True,stdout=True,remove=True)
except docker.errors.ContainerError as exc:
return f"FAIL: docker.errors.ContainerError: {exc.args}"
except docker.errors.ImageNotFound as exc:
Expand All @@ -262,7 +263,7 @@ def run_version_docker_image(verifier_image_name,verifier_image_tag):

def run_version_podman_image(verifier_image_name,verifier_image_tag):
"""Run chart verifier's version command in Podman."""
out = subprocess.run(["podman", "run", "--rm", f"{verifier_image_name}:{verifier_image_tag}", "version"], capture_output=True)
out = subprocess.run(["podman", "run", "--rm", f"{verifier_image_name}:{verifier_image_tag}", "version", "--as-data"], capture_output=True)
return normalize_version(out.stdout.decode("utf-8"))

def run_verify_tarball_image(tarball_name,profile_type, chart_location,pgp_key_location=None):
Expand Down