From cf16ba7af0eafa1ae644f1883711d93d68f9206c Mon Sep 17 00:00:00 2001
From: andrey mirtchovski <mirtchovski@gmail.com>
Date: Mon, 26 Dec 2016 13:33:07 -0700
Subject: [PATCH] gomobile: rename packages with clashing names

When two or more packages share the same name rename one or more of them in
the gobind generated main package
---
 bind/gengo.go | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)

diff --git a/bind/gengo.go b/bind/gengo.go
index f86f6c6..eae3f2e 100644
--- a/bind/gengo.go
+++ b/bind/gengo.go
@@ -13,7 +13,8 @@ import (
 
 type goGen struct {
 	*Generator
-	imports map[string]struct{}
+	imports map[string]string
+	names   map[string]struct{}
 }
 
 const (
@@ -497,15 +498,16 @@ func (g *goGen) genPreamble() {
 	g.Printf("import (\n")
 	g.Indent()
 	g.Printf("_seq \"golang.org/x/mobile/bind/seq\"\n")
-	for path := range g.imports {
-		g.Printf("%q\n", path)
+	for path, rename := range g.imports {
+		g.Printf("%s %q\n", rename, path)
 	}
 	g.Outdent()
 	g.Printf(")\n\n")
 }
 
 func (g *goGen) gen() error {
-	g.imports = make(map[string]struct{})
+	g.imports = make(map[string]string)
+	g.names = make(map[string]struct{})
 
 	// Switch to a temporary buffer so the preamble can be
 	// written last.
@@ -545,6 +547,22 @@ func (g *goGen) pkgName(pkg *types.Package) string {
 	if pkg == nil {
 		return ""
 	}
-	g.imports[pkg.Path()] = struct{}{}
-	return pkg.Name() + "."
+
+	name := pkg.Name()
+	if rename, ok := g.imports[pkg.Path()]; ok {
+		name = rename
+	} else {
+		// find a new name for this package; prepend "re_"
+		// until we've found one that isn't used
+		for {
+			if _, ok := g.names[name]; !ok {
+				g.names[name] = struct{}{}
+				g.imports[pkg.Path()] = name
+				break
+			}
+			name = "renamed" + name
+		}
+	}
+
+	return name + "."
 }
-- 
2.5.4 (Apple Git-61)

