Repository: knative/pkg
Pull request #2855 (2023-10-09 09:09:23)

Fix potential `--kubeconfig` redefined error
<!-- Thanks for sending a pull request! -->

# Changes

<!-- 
Describe your changes here- ideally you can get that description straight from
your descriptive commit message(s)! 

- :gift: Add new feature
- :bug: Fix bug
- :broom: Update or clean up current behavior
- :wastebasket: Remove feature or internal logic
-->

- Fix potential redefined error with kubeconfig flag


The `--kubeconfing` flag is a popular one. I've run into a case with `sigs.k8s.io/controller-runtime` & `/pkg` when vendoring together there's `flag redefined` error thrown. Depending on the order of package inits.

This change should make `/pkg` safer to use alongside other K8s libs.  

knative-prow[bot]: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative/pkg/pull/2855#" title="Author self-approved">dsimansk</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative%2Fpkg).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/knative/pkg/blob/main/OWNERS)~~ [dsimansk]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->
knative-prow[bot]: @dsimansk: The following test **failed**, say `/retest` to rerun all failed tests or `/retest-required` to rerun all mandatory failed tests:

Test name | Commit | Details | Required | Rerun command
--- | --- | --- | --- | ---
unit-tests_pkg_main | b8ebbc8f38de76bf53631c679fbf0f75bcbeb8ab | [link](https://prow.knative.dev/view/gs/knative-prow/pr-logs/pull/knative_pkg/2855/unit-tests_pkg_main/1711307870110224384) | true | `/test unit-tests`

[Your PR dashboard](https://prow.knative.dev/pr).

<details>

Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository. I understand the commands that are listed [here](https://go.k8s.io/bot-commands).
</details>
<!-- test report -->
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/knative/pkg/pull/2855?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) Report
All modified lines are covered by tests :white_check_mark:
> Comparison is base [(`d0a82f9`)](https://app.codecov.io/gh/knative/pkg/commit/d0a82f9cbb8f2f92ce8f130c701f2da29bb33109?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) 81.86% compared to head [(`5e094c0`)](https://app.codecov.io/gh/knative/pkg/pull/2855?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) 81.80%.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main    #2855      +/-   ##
==========================================
- Coverage   81.86%   81.80%   -0.07%     
==========================================
  Files         167      167              
  Lines       10224    10227       +3     
==========================================
- Hits         8370     8366       -4     
- Misses       1608     1614       +6     
- Partials      246      247       +1     
```


| [Files](https://app.codecov.io/gh/knative/pkg/pull/2855?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) | Coverage Δ | |
|---|---|---|
| [environment/client\_config.go](https://app.codecov.io/gh/knative/pkg/pull/2855?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative#diff-ZW52aXJvbm1lbnQvY2xpZW50X2NvbmZpZy5nbw==) | `36.53% <100.00%> (+3.88%)` | :arrow_up: |

... and [1 file with indirect coverage changes](https://app.codecov.io/gh/knative/pkg/pull/2855/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative)


</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/knative/pkg/pull/2855?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative).

dsimansk: Failed downstream test is unrelated. The `eventing-rabbitmq` repo needs to be fixed because of the `k8s.io` version bump.
```
Downstream Knative / Unit Test (knative-extensions/eventing-rabbitmq) (pull_request)
```
knative-prow[bot]: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative/pkg/pull/2855#" title="Author self-approved">dsimansk</a>*, *<a href="https://github.com/knative/pkg/pull/2855#pullrequestreview-1664478139" title="Approved">pierDipi</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative%2Fpkg).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/knative/pkg/blob/main/OWNERS)~~ [dsimansk,pierDipi]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->

Patch:
diff --git a/environment/client_config.go b/environment/client_config.go
index aef33927e..0b51857aa 100644
--- a/environment/client_config.go
+++ b/environment/client_config.go
@@ -44,8 +44,12 @@ func (c *ClientConfig) InitFlags(fs *flag.FlagSet) {
 	fs.StringVar(&c.ServerURL, "server", "",
 		"The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
 
-	fs.StringVar(&c.Kubeconfig, "kubeconfig", os.Getenv("KUBECONFIG"),
-		"Path to a kubeconfig. Only required if out-of-cluster.")
+	if f := fs.Lookup("kubeconfig"); f != nil {
+		c.Kubeconfig = f.Value.String()
+	} else {
+		fs.StringVar(&c.Kubeconfig, "kubeconfig", os.Getenv("KUBECONFIG"),
+			"Path to a kubeconfig. Only required if out-of-cluster.")
+	}
 
 	fs.IntVar(&c.Burst, "kube-api-burst", int(envVarOrDefault("KUBE_API_BURST", 0)), "Maximum burst for throttle.")
 


Test patch:
diff --git a/environment/client_config_test.go b/environment/client_config_test.go
index b5f83b16f..2819039ee 100644
--- a/environment/client_config_test.go
+++ b/environment/client_config_test.go
@@ -48,3 +48,24 @@ func TestInitFlag(t *testing.T) {
 		t.Errorf("ClientConfig mismatch: diff(-want,+got):\n%s", cmp.Diff(expect, c))
 	}
 }
+
+// TestInitFlagWithKubeconfing verify flag conflict error "flag redefined: kubeconfig"
+func TestInitFlagWithKubeconfing(t *testing.T) {
+	t.Setenv("KUBECONFIG", "myconfig")
+
+	c := new(ClientConfig)
+	flags := flag.NewFlagSet("test", flag.ExitOnError)
+	flags.String("kubeconfig", "/test/path", "")
+	c.InitFlags(flags)
+
+	// Call parse() here as InitFlags does not call it.
+	flags.Parse([]string{})
+
+	expect := &ClientConfig{
+		Kubeconfig: "/test/path",
+	}
+
+	if !cmp.Equal(c, expect) {
+		t.Errorf("ClientConfig mismatch: diff(-want,+got):\n%s", cmp.Diff(expect, c))
+	}
+}