Skip to content

Commit

Permalink
fix conflicted alias name
Browse files Browse the repository at this point in the history
  • Loading branch information
goccy committed Aug 21, 2024
1 parent 346ef10 commit 9ad91fa
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 42 deletions.
56 changes: 28 additions & 28 deletions _examples/06_alias/federation/federation_grpc_federation.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions _examples/06_alias/post/v2/post.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion _examples/06_alias/post/v2/post_grpc.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion _examples/06_alias/proto/post/v2/post.proto
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ syntax = "proto3";

package org.post.v2;

option go_package = "example/post/v2;postv2";
option go_package = "example/post/v2;post";

service PostService {
rpc GetPost(GetPostRequest) returns (GetPostResponse) {};
Expand Down
22 changes: 19 additions & 3 deletions generator/code_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -463,9 +463,11 @@ func (f *File) DefaultImports() []*Import {
}

func (f *File) Imports() []*Import {
defaultImportMap := make(map[string]struct{})
importPathMap := make(map[string]struct{})
importAliasMap := make(map[string]struct{})
for _, imprt := range f.DefaultImports() {
defaultImportMap[imprt.Path] = struct{}{}
importPathMap[imprt.Path] = struct{}{}
importAliasMap[imprt.Alias] = struct{}{}
}
curImportPath := f.GoPackage.ImportPath

Expand All @@ -478,14 +480,28 @@ func (f *File) Imports() []*Import {
if pkg.ImportPath == curImportPath {
return
}
if _, exists := defaultImportMap[pkg.ImportPath]; exists {
if _, exists := importPathMap[pkg.ImportPath]; exists {
return
}
if _, exists := importAliasMap[pkg.Name]; exists {
// conflict alias name
suffixIndex := 1 // start from 1.
for {
alias := pkg.Name + fmt.Sprint(suffixIndex)
if _, exists := importAliasMap[alias]; !exists {
pkg.Name = alias
break
}
suffixIndex++
}
}
imports = append(imports, &Import{
Path: pkg.ImportPath,
Alias: pkg.Name,
Used: true,
})
importPathMap[pkg.ImportPath] = struct{}{}
importAliasMap[pkg.Name] = struct{}{}
}
for pkg := range f.pkgMap {
addImport(pkg)
Expand Down

0 comments on commit 9ad91fa

Please sign in to comment.