Repository: caicloud/nirvana
Pull request #416 (2020-12-15 11:50:23)

fix(generator): sort type names to make the package aliases deterministic
**What this PR does / why we need it**:

Currently the aliases of foreign packages imported in the generated client code are non-deterministic, which leads to unnecessary changes of the generated client code.

For instance, let's say the client code imports `github.com/repo/apis/v1alpha1` and `github.com/repo/server/v1alpha1`, then the aliases could be
```
import (
  v1alpha1 "github.com/repo/apis/v1alpha1"
  v1alpha11 "github.com/repo/server/v1alpha1"
)
```
Or
```
import (
  v1alpha11 "github.com/repo/apis/v1alpha1"
  v1alpha1 "github.com/repo/server/v1alpha1"
)
```
And the client code would be changed slightly because of the different alias even if nothing actually changes.

This PR sorts the type names before parsing them to address this issue.

**Which issue(s) this PR is related to** *(optional, link to 3rd issue(s))*:

Fixes #

Reference to #
<!-- 填在 Fixes，PR 合并就会关 issue。填在 Reference to 会关联 issue，不会联动关闭。-->

**Special notes for your reviewer**:

/cc @iawia002 

<!-- Please answer the following questions during the code freeze, and delete this line.
**Code freeze questions**

1. What causes this PR to not be merged before code freeze?
2. Why this PR is absolutely necessary for this version? Paste a screenshot of smoke testing docs if you could.
3. What's the effects after merging it?
4. Is there anyway we can skip this to not affect the overall process?
-->

**Release note**:
<!--  Write your release note:
1. Enter your extended release note in the below block. If the PR requires additional action from users switching to the new release, include the string "action required".
2. If no release note is required, just write "NONE".
-->

```release-note
NONE
```

<!--  Thanks for sending a pull request! Here are some tips:

1. https://github.com/caicloud/engineering/blob/master/guidelines/review_conventions.md      <-- what is the review process looks like
2. https://github.com/caicloud/engineering/blob/master/guidelines/git_commit_conventions.md  <-- how to structure your git commit
3. https://github.com/caicloud/engineering/blob/master/guidelines/caicloud_bot.md            <-- how to work with caicloud bot

Other tips:

If this is your first contribution, read our Getting Started guide https://github.com/caicloud/engineering/blob/master/guidelines/README.md
-->


caicloud-bot: [APPROVALNOTIFIER] This PR is **NOT APPROVED**

This pull-request has been approved by: 
To fully approve this pull request, please assign additional approvers.
We suggest the following additional approver: **supereagle**

Assign the PR to them by writing `/assign @supereagle` in a comment when ready.

The full list of commands accepted by this bot can be found [here](https://github.com/caicloud/engineering/blob/master/guidelines/caicloud_bot.md#bot-commands).

The pull request process is described [here](https://github.com/caicloud/engineering/blob/master/guidelines/caicloud_bot.md#typical-workflow)

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

- **[OWNERS](https://github.com/caicloud/nirvana/blob/master/OWNERS)**

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":["supereagle"]} -->
iawia002: /lgtm
/cherrypick release-0.3
caicloud-bot: @iawia002: once the present PR merges, I will cherry-pick it on top of release-0.3 in a new PR and assign it to you.

<details>

In response to [this](https://github.com/caicloud/nirvana/pull/416#issuecomment-745241710):

>/lgtm
>/cherrypick release-0.3


Instructions for interacting with me using PR comments are available [here](https://github.com/caicloud/engineering/blob/master/docs/caicloud_bot.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.
</details>
caicloud-bot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/caicloud/nirvana/pull/416#issuecomment-745241710" title="LGTM">iawia002</a>*

The full list of commands accepted by this bot can be found [here](https://github.com/caicloud/engineering/blob/master/guidelines/caicloud_bot.md#bot-commands).

The pull request process is described [here](https://github.com/caicloud/engineering/blob/master/guidelines/caicloud_bot.md#typical-workflow)

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

- ~~[OWNERS](https://github.com/caicloud/nirvana/blob/master/OWNERS)~~ [iawia002]

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/utils/generators/golang/helper.go b/utils/generators/golang/helper.go
index 9536f58..f1a8a92 100644
--- a/utils/generators/golang/helper.go
+++ b/utils/generators/golang/helper.go
@@ -541,8 +541,15 @@ func newTypeNamer(rootPkg string, types map[api.TypeName]*api.Type) (*typeNamer,
 		comments: make(map[api.TypeName]string),
 		rootPkg:  rootPkg,
 	}
-	for tn := range n.types {
-		if _, err := n.parse(tn); err != nil {
+
+	typeNames := make([]string, 0, len(types))
+	for name := range types {
+		typeNames = append(typeNames, string(name))
+	}
+	sort.Strings(typeNames)
+
+	for _, tn := range typeNames {
+		if _, err := n.parse(api.TypeName(tn)); err != nil {
 			return nil, err
 		}
 	}


Test patch:
diff --git a/utils/generators/golang/helper_test.go b/utils/generators/golang/helper_test.go
new file mode 100644
index 0000000..f2e4790
--- /dev/null
+++ b/utils/generators/golang/helper_test.go
@@ -0,0 +1,58 @@
+/*
+Copyright 2020 Caicloud 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 golang
+
+import (
+	"reflect"
+	"testing"
+
+	"github.com/caicloud/nirvana/utils/api"
+)
+
+func TestDeterministicClientPackageAlias(t *testing.T) {
+	const (
+		rounds  = 20
+		rootPkg = "github.com/caicloud/nirvana"
+	)
+	types := map[api.TypeName]*api.Type{
+		api.TypeName("github.com/caicloud/repo/v1.Foo"): {
+			Name:    "Foo",
+			PkgPath: "github.com/caicloud/repo/v1",
+			Kind:    reflect.Struct,
+		},
+		api.TypeName("github.com/caicloud/repo/pkg/v1.Bar"): {
+			Name:    "Bar",
+			PkgPath: "github.com/caicloud/repo/pkg/v1",
+			Kind:    reflect.Struct,
+		},
+	}
+	namer, err := newTypeNamer(rootPkg, types)
+	if err != nil {
+		t.Fatal(err)
+	}
+	expected := namer.packages
+
+	for i := 0; i < rounds; i++ {
+		namer, err := newTypeNamer(rootPkg, types)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if !reflect.DeepEqual(expected, namer.packages) {
+			t.Fatalf("Package alias changed:\nExpected: %#v\nGot: %#v\n", expected, namer.packages)
+		}
+	}
+}