[submodule] Add hash suffix to submodule names

This change adds a hash suffix to each submodule name as git submodule
does not support duplicated names.

Bug: 69335
Change-Id: I0f255c4ec130c4d7d80cef445cb5088a9bed8269
Reviewed-on: https://fuchsia-review.googlesource.com/c/jiri/+/490858
Reviewed-by: Oliver Newman <olivernewman@google.com>
Commit-Queue: Haowei Wu <haowei@google.com>
diff --git a/cmd/jiri/generate-gitmodules.go b/cmd/jiri/generate-gitmodules.go
index d59214b..35c4f33 100644
--- a/cmd/jiri/generate-gitmodules.go
+++ b/cmd/jiri/generate-gitmodules.go
@@ -6,6 +6,8 @@
 
 import (
 	"bytes"
+	"crypto/sha256"
+	"encoding/hex"
 	"errors"
 	"fmt"
 	"io/ioutil"
@@ -303,7 +305,8 @@
 
 func moduleDecl(p project.Project) string {
 	tmpl := "[submodule \"%s\"]\n\tpath = %s\n\turl = %s"
-	return fmt.Sprintf(tmpl, p.Name, p.Path, p.Remote)
+	hashBytes := (sha256.Sum256([]byte(p.Key())))
+	return fmt.Sprintf(tmpl, p.Name+"-"+hex.EncodeToString(hashBytes[:5]), p.Path, p.Remote)
 }
 
 func commandDecl(p project.Project) string {
diff --git a/cmd/jiri/generate-gitmodules_test.go b/cmd/jiri/generate-gitmodules_test.go
index 3a23c53..5510559 100644
--- a/cmd/jiri/generate-gitmodules_test.go
+++ b/cmd/jiri/generate-gitmodules_test.go
@@ -100,16 +100,16 @@
 git update-index --add --cacheinfo 160000 87f863bcbc7cd2177bac17c61e31093de6eeed28 "path-1"
 git update-index --add --cacheinfo 160000 87f863bcbc7cd2177bac17c61e31093de6eeed28 "path-2"`)
 
-	goldenModule := []byte(`[submodule "manifest"]
+	goldenModule := []byte(`[submodule "manifest-31b42b3e96"]
 	path = manifest
 	url = /tmp/115893653/manifest
-[submodule "project-0"]
+[submodule "project-0-50299b644d"]
 	path = path-0
 	url = /tmp/115893653/project-0
-[submodule "project-1"]
+[submodule "project-1-743aa3e46a"]
 	path = path-1
 	url = /tmp/115893653/project-1
-[submodule "project-2"]
+[submodule "project-2-1615f49046"]
 	path = path-2
 	url = /tmp/115893653/project-2`)
 
@@ -243,6 +243,14 @@
 			}
 			continue
 		}
+		if strings.HasPrefix(testLine, "[submodule ") {
+			testProjectName := testLine[:strings.LastIndex(testLine, "-")]
+			goldenProjectName := goldenLine[:strings.LastIndex(testLine, "-")]
+			if testProjectName != goldenProjectName {
+				return fmt.Errorf("project name mismatch, expection %q, got %q", goldenProjectName, testProjectName)
+			}
+			continue
+		}
 		if goldenLine != testLine {
 			return fmt.Errorf("in generated .gitmodules file, expecting %q, got %q", goldenLine, testLine)
 		}