Repository: kubesphere/ks-devops
Pull request #426 (2021-12-27 01:29:26)

Add an override flag to the tool cmd jwt
<!-- Thanks for sending a pull request! Here are some tips for you:

1. If you want **faster** PR reviews, read how: https://github.com/kubesphere/community/blob/master/developer-guide/development/the-pr-author-guide-to-getting-through-code-review.md
2. In case you want to know how your PR got reviewed, read: https://github.com/kubesphere/community/blob/master/developer-guide/development/code-review-guide.md
3. Here are some coding conventions followed by the KubeSphere community: https://github.com/kubesphere/community/blob/master/developer-guide/development/coding-conventions.md
4. Additional open-source best practice: https://github.com/LinuxSuRen/open-source-best-practice
-->

### What type of PR is this?
<!-- 
Add one of the following kinds:
/kind bug
/kind cleanup
/kind documentation
/kind design
/kind chore

Optionally add one or more of the following kinds if applicable:
/kind api-change
/kind deprecation
/kind failing-test
/kind flake
/kind regression
-->
/kind feature

### What this PR does / why we need it:
Users cannot set a customized token of the Jenkins if there's no the override flag.

### Which issue(s) this PR fixes:
<!--
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
_If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
Please leave it or change # to be None if there is no corresponding issue that exists
-->
Fixes #

### Special notes for reviewers:
<!--
You can use the following command to let the DevOps SIG members help you to review your PR.
/cc @kubesphere/sig-devops 
And please avoid cc any individual.
-->
You can use the following image to test it.
```
surenpi/devops-tools:dev-v3.2.1-f4b07eb
```

you can add the flag like this: `--override-jenkins-token=false`

### Does this PR introduce a user-facing change??
<!--
If no, just write "None" in the release-note block below.
If yes, a release note is required:
Enter your extended-release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

Please keep the note be same as your PR title if you believe it should be in the release notes.
-->
```release-note
None
```


ks-ci-bot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/kubesphere/ks-devops/pull/426#" title="Author self-approved">LinuxSuRen</a>*

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

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/kubesphere/ks-devops/blob/master/OWNERS)~~ [LinuxSuRen]

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":[]} -->
codecov[bot]: # [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) Report
> Merging [#426](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (f4b07eb) into [master](https://codecov.io/gh/kubesphere/ks-devops/commit/c8724da90d775995e821c8ae7b82c45eaef7b90f?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) (c8724da) will **increase** coverage by `0.05%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/kubesphere/ks-devops/pull/426/graphs/tree.svg?width=650&height=150&src=pr&token=qSK4RBbyNg&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere)](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere)

```diff
@@            Coverage Diff            @@
##           master    #426      +/-   ##
=========================================
+ Coverage    7.86%   7.92%   +0.05%     
=========================================
  Files         102     102              
  Lines       21812   21815       +3     
=========================================
+ Hits         1716    1729      +13     
+ Misses      19970   19961       -9     
+ Partials      126     125       -1     
```

| Flag | Coverage Δ | |
|---|---|---|
| unittests | `7.92% <100.00%> (+0.05%)` | :arrow_up: |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere) | Coverage Δ | |
|---|---|---|
| [cmd/tools/jwt/app/configmap\_updater.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y21kL3Rvb2xzL2p3dC9hcHAvY29uZmlnbWFwX3VwZGF0ZXIuZ28=) | `100.00% <100.00%> (ø)` | |
| [cmd/tools/jwt/app/jwt\_root.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y21kL3Rvb2xzL2p3dC9hcHAvand0X3Jvb3QuZ28=) | `100.00% <100.00%> (ø)` | |
| [controllers/pipeline/pipeline\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvcGlwZWxpbmUvcGlwZWxpbmVfY29udHJvbGxlci5nbw==) | `38.23% <0.00%> (-3.68%)` | :arrow_down: |
| [...trollers/devopsproject/devopsproject\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvZGV2b3BzcHJvamVjdC9kZXZvcHNwcm9qZWN0X2NvbnRyb2xsZXIuZ28=) | `43.22% <0.00%> (+2.60%)` | :arrow_up: |
| [...rs/devopscredential/devopscredential\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvZGV2b3BzY3JlZGVudGlhbC9kZXZvcHNjcmVkZW50aWFsX2NvbnRyb2xsZXIuZ28=) | `36.48% <0.00%> (+3.37%)` | :arrow_up: |
| [controllers/s2irun/s2irun\_controller.go](https://codecov.io/gh/kubesphere/ks-devops/pull/426/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere#diff-Y29udHJvbGxlcnMvczJpcnVuL3MyaXJ1bl9jb250cm9sbGVyLmdv) | `37.22% <0.00%> (+3.64%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Last update [c8724da...f4b07eb](https://codecov.io/gh/kubesphere/ks-devops/pull/426?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=kubesphere).

ks-ci-bot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/kubesphere/ks-devops/pull/426#pullrequestreview-840149181" title="LGTM">JohnNiang</a>*, *<a href="https://github.com/kubesphere/ks-devops/pull/426#" title="Author self-approved">LinuxSuRen</a>*

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

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/kubesphere/ks-devops/blob/master/OWNERS)~~ [LinuxSuRen]

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":[]} -->
JohnNiang: /label tide/merge-method-squash

Patch:
diff --git a/cmd/tools/jwt/app/configmap_updater.go b/cmd/tools/jwt/app/configmap_updater.go
index 7e43c13..a69877c 100644
--- a/cmd/tools/jwt/app/configmap_updater.go
+++ b/cmd/tools/jwt/app/configmap_updater.go
@@ -37,7 +37,7 @@ func (o *jwtOption) updateJenkinsToken(jwt, ns, configMapName string) (err error
 		cfg = content
 	}
 
-	cfg = updateToken(cfg, jwt)
+	cfg = updateToken(cfg, jwt, o.overrideJenkinsToken)
 
 	configMap.Data[config.DefaultConfigurationFileName] = cfg
 	_, err = o.configMapUpdater.UpdateConfigMap(ctx, configMap)
diff --git a/cmd/tools/jwt/app/jwt_root.go b/cmd/tools/jwt/app/jwt_root.go
index 3bc5b23..f67d8ab 100644
--- a/cmd/tools/jwt/app/jwt_root.go
+++ b/cmd/tools/jwt/app/jwt_root.go
@@ -37,12 +37,15 @@ func NewCmd(k8sClientFactory k8sClientFactory) (cmd *cobra.Command) {
 		"The name of target ConfigMap")
 	flags.StringVarP(&opt.output, "output", "o", "",
 		"The destination of the JWT output. Print to the stdout if it's empty.")
+	flags.BoolVarP(&opt.overrideJenkinsToken, "override-jenkins-token", "", true,
+		"If you want to override the Jenkins token.")
 	return
 }
 
 type jwtOption struct {
-	secret string
-	output string
+	secret               string
+	output               string
+	overrideJenkinsToken bool
 
 	namespace string
 	name      string
@@ -129,11 +132,13 @@ func (o *jwtOption) runE(cmd *cobra.Command, args []string) (err error) {
 	return
 }
 
-func updateToken(content, token string) string {
+func updateToken(content, token string, override bool) string {
 	dataMap := make(map[string]map[string]string, 0)
 	if err := yaml.Unmarshal([]byte(content), dataMap); err == nil {
 		if _, ok := dataMap["devops"]; ok {
-			dataMap["devops"]["password"] = token
+			if dataMap["devops"]["password"] != "" && override {
+				dataMap["devops"]["password"] = token
+			}
 
 			if result, err := yaml.Marshal(dataMap); err == nil {
 				return strings.TrimSpace(string(result))


Test patch:
diff --git a/cmd/tools/jwt/app/jwt_root_test.go b/cmd/tools/jwt/app/jwt_root_test.go
index 01c69b7..65e195b 100644
--- a/cmd/tools/jwt/app/jwt_root_test.go
+++ b/cmd/tools/jwt/app/jwt_root_test.go
@@ -37,8 +37,9 @@ func Test_generateJWT(t *testing.T) {
 
 func Test_updateToken(t *testing.T) {
 	type args struct {
-		content string
-		token   string
+		content  string
+		token    string
+		override bool
 	}
 	tests := []struct {
 		name string
@@ -47,13 +48,15 @@ func Test_updateToken(t *testing.T) {
 	}{{
 		name: "invalid yaml content",
 		args: args{
-			content: "fake",
+			content:  "fake",
+			override: true,
 		},
 		want: "fake",
 	}, {
 		name: "valid yaml without devops.token",
 		args: args{
-			content: "name: rick",
+			content:  "name: rick",
+			override: true,
 		},
 		want: "name: rick",
 	}, {
@@ -61,14 +64,25 @@ func Test_updateToken(t *testing.T) {
 		args: args{
 			content: `devops:
   password: fake`,
-			token: "token",
+			token:    "token",
+			override: true,
 		},
 		want: `devops:
   password: token`,
+	}, {
+		name: "do not override",
+		args: args{
+			content: `devops:
+  password: fake`,
+			token:    "token",
+			override: false,
+		},
+		want: `devops:
+  password: fake`,
 	}}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			if got := updateToken(tt.args.content, tt.args.token); got != tt.want {
+			if got := updateToken(tt.args.content, tt.args.token, tt.args.override); got != tt.want {
 				t.Errorf("updateToken() = %v, want %v", got, tt.want)
 			}
 		})