From ba4ba32a955ef2faf673046e4973a9328050b740 Mon Sep 17 00:00:00 2001 From: Andre Brisco Date: Fri, 20 Nov 2026 10:11:42 -0800 Subject: [PATCH] Allow trailing args in `kubectl_binary` --- .bcr/presubmit.yml | 5 +- docs/src/index.md | 16 ++++ kubectl/private/kubectl_binary.bzl | 17 ++++ tests/BUILD.bazel | 23 +++++- tests/binary_test.go | 128 +++++++++++++++++++++++++++++ tests/binary_test.sh | 43 ---------- 6 files changed, 185 insertions(+), 47 deletions(-) create mode 100644 tests/binary_test.go delete mode 100755 tests/binary_test.sh diff --git a/.bcr/presubmit.yml b/.bcr/presubmit.yml index c87b352..9b56436 100644 --- a/.bcr/presubmit.yml +++ b/.bcr/presubmit.yml @@ -2,13 +2,16 @@ bcr_test_module: module_path: "." matrix: - platform: ["macos_arm64", "ubuntu2004", "windows"] + platform: ["macos_arm64", "ubuntu2404", "windows"] bazel: ["7.x", "8.x", "9.x"] tasks: run_tests: name: "Run test module" platform: ${{ platform }} bazel: ${{ bazel }} + build_targets: + - "--" + - "//..." test_targets: - "--" - "//..." diff --git a/docs/src/index.md b/docs/src/index.md index 41cc55c..32ca915 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -67,6 +67,22 @@ kubectl_binary( bazel run //deploy:apply -- --namespace my-namespace ``` +`kubectl` accepts flags ahead of the verb, so `args` can fix the file a command +operates on while leaving the verb to the caller: + +```python +kubectl_binary( + name = "kubectl", + args = ["--filename=$(rlocationpath :manifests)"], + data = [":manifests"], +) +``` + +```bash +bazel run //deploy:kubectl -- diff +bazel run //deploy:kubectl -- apply --server-side +``` + `env` takes the same references, for example to point `KUBECONFIG` at a file in the repository. Clusters, contexts and namespaces stay in your hands. diff --git a/kubectl/private/kubectl_binary.bzl b/kubectl/private/kubectl_binary.bzl index 51b2cd3..b5e3f28 100644 --- a/kubectl/private/kubectl_binary.bzl +++ b/kubectl/private/kubectl_binary.bzl @@ -138,6 +138,23 @@ def kubectl_binary(name, args = [], data = [], env = {}, kubectl = None, **kwarg bazel run //deploy:apply -- --namespace my-namespace ``` + `kubectl` accepts flags ahead of the verb, so `args` can fix the file a \ + command operates on while leaving the verb to the caller. Only positional \ + arguments have to follow the verb: + + ```python + kubectl_binary( + name = "kubectl", + args = ["--filename=$(rlocationpath :manifests)"], + data = [":manifests"], + ) + ``` + + ```bash + bazel run //deploy:kubectl -- diff + bazel run //deploy:kubectl -- apply --server-side + ``` + Nothing about clusters, contexts or namespaces is decided here; that is \ left to the arguments and the environment. diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index a362094..e156bcc 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -1,3 +1,4 @@ +load("@rules_go//go:def.bzl", "go_test") load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//kubectl:defs.bzl", "kubectl_binary") @@ -113,17 +114,33 @@ kubectl_binary( env = {"KUBECONFIG": "$(rlocationpath kubeconfig.yaml)"}, ) -sh_test( +# `kubectl_binary` with a generated manifest but no verb, which the caller +# supplies on the command line. +genrule( + name = "manifest", + outs = ["manifest.yaml"], + cmd = "printf 'apiVersion: v1\\nkind: ConfigMap\\nmetadata:\\n name: manifest-test\\n' > $@", +) + +kubectl_binary( + name = "manifest_kubectl", + args = ["--filename=$(rlocationpath :manifest)"], + data = [":manifest"], +) + +go_test( name = "binary_test", size = "small", - srcs = ["binary_test.sh"], + srcs = ["binary_test.go"], data = [ ":config_view", ":configmap_dry_run", + ":manifest_kubectl", ], env = { "CONFIGMAP_DRY_RUN": "$(rlocationpath :configmap_dry_run)", "CONFIG_VIEW": "$(rlocationpath :config_view)", + "MANIFEST_KUBECTL": "$(rlocationpath :manifest_kubectl)", }, - deps = ["@bazel_tools//tools/bash/runfiles"], + deps = ["@rules_go//go/runfiles"], ) diff --git a/tests/binary_test.go b/tests/binary_test.go new file mode 100644 index 0000000..2f1d39f --- /dev/null +++ b/tests/binary_test.go @@ -0,0 +1,128 @@ +// Checks that `kubectl_binary` wires generated files, environment and extra +// arguments through to kubectl, from any working directory. +package tests + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/bazelbuild/rules_go/go/runfiles" +) + +// binaries holds the `kubectl_binary` targets under test, resolved through +// runfiles from the rlocationpaths in the test environment. +type binaries struct { + configmapDryRun string + configView string + manifestKubectl string + // env is passed to every binary: the test's environment with runfiles + // variables for the launcher, a scratch HOME and no kubeconfig, so the + // tests are independent of anything on the host. + env []string + // elsewhere is a directory with nothing in it, used as the working + // directory to show that generated files are found through runfiles. + elsewhere string +} + +func setup(t *testing.T) *binaries { + t.Helper() + + r, err := runfiles.New() + if err != nil { + t.Fatalf("failed to locate runfiles: %v", err) + } + locate := func(variable string) string { + path, err := r.Rlocation(os.Getenv(variable)) + if err != nil { + t.Fatalf("failed to locate %s: %v", variable, err) + } + return path + } + + tmp := t.TempDir() + home := filepath.Join(tmp, "home") + elsewhere := filepath.Join(tmp, "elsewhere") + for _, dir := range []string{home, elsewhere} { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + } + + env := append(os.Environ(), r.Env()...) + env = append(env, "HOME="+home, "KUBECONFIG=", "BUILD_WORKING_DIRECTORY=") + + return &binaries{ + configmapDryRun: locate("CONFIGMAP_DRY_RUN"), + configView: locate("CONFIG_VIEW"), + manifestKubectl: locate("MANIFEST_KUBECTL"), + env: env, + elsewhere: elsewhere, + } +} + +// run executes a binary from `elsewhere` and returns its combined output. +func (b *binaries) run(t *testing.T, binary string, extraEnv []string, args ...string) (string, error) { + t.Helper() + cmd := exec.Command(binary, args...) + cmd.Dir = b.elsewhere + cmd.Env = append(append([]string{}, b.env...), extraEnv...) + output, err := cmd.CombinedOutput() + return strings.TrimSpace(string(output)), err +} + +func (b *binaries) mustRun(t *testing.T, binary string, extraEnv []string, args ...string) string { + t.Helper() + output, err := b.run(t, binary, extraEnv, args...) + if err != nil { + t.Fatalf("%s %s failed: %v\n%s", filepath.Base(binary), strings.Join(args, " "), err, output) + } + return output +} + +func TestKubectlBinary(t *testing.T) { + b := setup(t) + + t.Run("a generated file referenced with $(rlocationpath) is found from another directory", func(t *testing.T) { + output := b.mustRun(t, b.configmapDryRun, []string{"BUILD_WORKING_DIRECTORY=" + b.elsewhere}) + for _, want := range []string{"name: binary-test", "generated by bazel"} { + if !strings.Contains(output, want) { + t.Errorf("expected %q in the output, got:\n%s", want, output) + } + } + }) + + t.Run("arguments on the command line are appended", func(t *testing.T) { + output := b.mustRun(t, b.configmapDryRun, nil, "--namespace=appended") + if !strings.Contains(output, "namespace: appended") { + t.Errorf("expected the namespace from the command line, got:\n%s", output) + } + }) + + t.Run("env is set for kubectl", func(t *testing.T) { + output := b.mustRun(t, b.configView, nil) + if want := "https://binary-test.invalid:6443"; output != want { + t.Errorf("expected the server from the generated kubeconfig %q, got: %q", want, output) + } + }) + + t.Run("kubectl takes a configured flag ahead of a verb given on the command line", func(t *testing.T) { + // `--local` keeps kubectl off the network, which the sandbox has none of. + output := b.mustRun(t, b.manifestKubectl, nil, "label", "--local", "--dry-run=client", "--output=name", "checked=yes") + if want := "configmap/manifest-test"; output != want { + t.Errorf("expected the manifest to be labelled as %q, got: %q", want, output) + } + }) + + t.Run("a verb that takes no file rejects the flag", func(t *testing.T) { + output, err := b.run(t, b.manifestKubectl, nil, "version", "--client") + if err == nil { + t.Fatalf("expected kubectl to reject --filename for 'version', got:\n%s", output) + } + if !strings.Contains(output, "unknown flag: --filename") { + t.Errorf("expected an unknown flag error, got:\n%s", output) + } + }) +} diff --git a/tests/binary_test.sh b/tests/binary_test.sh deleted file mode 100755 index 5669e50..0000000 --- a/tests/binary_test.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -# Checks that `kubectl_binary` wires generated files, environment and extra -# arguments through to kubectl, from any working directory. -# --- begin runfiles.bash initialization v3 --- -# Copy-pasted from the Bazel Bash runfiles library v3. -set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash -# shellcheck disable=SC1090 -source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \ - source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \ - source "$0.runfiles/$f" 2>/dev/null || \ - source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ - source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ - { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e -# --- end runfiles.bash initialization v3 --- - -set -euo pipefail - -configmap_dry_run="$(rlocation "${CONFIGMAP_DRY_RUN}")" -config_view="$(rlocation "${CONFIG_VIEW}")" - -# Keep the test independent of any kubeconfig on the host. -export HOME="${TEST_TMPDIR}/home" -export KUBECONFIG= -mkdir -p "${HOME}" - -elsewhere="${TEST_TMPDIR}/elsewhere" -mkdir -p "${elsewhere}" - -echo "--- a generated file referenced with \$(rlocationpath) is found from another directory" -output="$(cd "${elsewhere}" && BUILD_WORKING_DIRECTORY="${elsewhere}" "${configmap_dry_run}")" -grep -q "name: binary-test" <<<"${output}" -grep -q "generated by bazel" <<<"${output}" - -echo "--- arguments on the command line are appended" -output="$(cd "${elsewhere}" && "${configmap_dry_run}" --namespace=appended)" -grep -q "namespace: appended" <<<"${output}" - -echo "--- env is set for kubectl" -output="$(cd "${elsewhere}" && "${config_view}")" -if [[ "${output}" != "https://binary-test.invalid:6443" ]]; then - echo "Expected the server from the generated kubeconfig, got: ${output}" >&2 - exit 1 -fi