Fix var name generation to avoid conflict (#145)

When the type and the package name is the same for an anonymous
parameter (ex: time.Time), and there are more than 1 such parameters,
the generated name for both was the same. And the generated code would
not be valid.

Fix the bug by ensuring the parameter name does not conflict with
package imports first before checking against other parameter names.
This commit is contained in:
Suhas Karanth
2021-02-14 18:40:16 +05:30
committed by GitHub
parent 9a74351eb1
commit fe0d4f3360
4 changed files with 109 additions and 96 deletions

View File

@@ -38,7 +38,25 @@ func (v Var) packageQualifier(pkg *types.Package) string {
return v.imports[path].Qualifier()
}
// generateVarName generates a name for the variable using the type
func varName(vr *types.Var, suffix string) string {
name := vr.Name()
if name != "" && name != "_" {
return name + suffix
}
name = varNameForType(vr.Type()) + suffix
switch name {
case "mock", "callInfo", "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch", "const", "fallthrough", "if", "range", "type", "continue", "for",
"import", "return", "var":
name += "MoqParam"
}
return name
}
// varNameForType generates a name for the variable using the type
// information.
//
// Examples:
@@ -49,12 +67,12 @@ func (v Var) packageQualifier(pkg *types.Package) string {
// - map[string]int -> stringToInt
// - error -> err
// - a.MyType -> myType
func generateVarName(t types.Type) string {
func varNameForType(t types.Type) string {
nestedType := func(t types.Type) string {
if t, ok := t.(*types.Basic); ok {
return deCapitalise(t.String())
}
return generateVarName(t)
return varNameForType(t)
}
switch t := t.(type) {
@@ -83,7 +101,7 @@ func generateVarName(t types.Type) string {
return "val"
case *types.Pointer:
return generateVarName(t.Elem())
return varNameForType(t.Elem())
case *types.Signature:
return "fn"