test: resolve changes for PR #1004, add unit test, fix issue uncovered by unit test

Alec Lanter created

Change summary

repository/gogit.go      |  9 ++++-----
repository/gogit_test.go | 19 +++++++++++++++++++
2 files changed, 23 insertions(+), 5 deletions(-)

Detailed changes

repository/gogit.go 🔗

@@ -172,25 +172,24 @@ func detectGitPath(path string) (string, error) {
 		if err == nil {
 			if !fi.IsDir() {
 				// See if our .git item is a dotfile that holds a submodule reference
-				dotfile, err := os.Open(fi.Name())
+				dotfile, err := os.Open(filepath.Join(path, fi.Name()))
 				if err != nil {
-					// Can't open" error
+					// Can't open error
 					return "", fmt.Errorf(".git exists but is not a directory or a readable file: %w", err)
 				}
 				// We aren't going to defer the dotfile.Close, because we might keep looping, so we have to be sure to
 				// clean up before returning an error
 				reader := bufio.NewReader(dotfile)
 				line, _, err := reader.ReadLine()
+				_ = dotfile.Close()
 				if err != nil {
-					_ = dotfile.Close()
 					return "", fmt.Errorf(".git exists but is not a direcctory and cannot be read: %w", err)
 				}
 				dotContent := string(line)
 				if strings.HasPrefix(dotContent, "gitdir:") {
-					_ = dotfile.Close()
 					// This is a submodule parent path link. Strip the prefix, clean the string of whitespace just to
 					// be safe, and return
-					dotContent = strings.TrimSpace(dotContent[7:])
+					dotContent = strings.TrimSpace(strings.TrimPrefix(dotContent, "gitdir: "))
 					return dotContent, nil
 				}
 				return "", fmt.Errorf(".git exist but is not a directory")

repository/gogit_test.go 🔗

@@ -1,6 +1,7 @@
 package repository
 
 import (
+	"os"
 	"path"
 	"path/filepath"
 	"testing"
@@ -81,3 +82,21 @@ func TestGoGitRepo_Indexes(t *testing.T) {
 	require.NoError(t, err)
 	require.NotZero(t, indexA)
 }
+
+func TestGoGit_DetectsSubmodules(t *testing.T) {
+	expectedPath := "../foo/bar"
+	submoduleData := "gitdir: " + expectedPath
+	d := t.TempDir()
+	if f, err := os.Create(filepath.Join(d, ".git")); err != nil {
+		t.Fatal("could not create necessary temp file:", err)
+	} else {
+		t.Log(f.Name())
+		if _, err := f.Write([]byte(submoduleData)); err != nil {
+			t.Fatal("could not write necessary data to temp file:", err)
+		}
+		_ = f.Close()
+	}
+	result, err := detectGitPath(d)
+	assert.Empty(t, err)
+	assert.Equal(t, expectedPath, result)
+}