Skip to content

Commit 17e7960

Browse files
committed
refactor: expose APIs for finding git repo by different methods
1 parent b791280 commit 17e7960

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

pkg/git_tools/finder.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package git_tools
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"os/exec"
7+
"path/filepath"
8+
"strings"
9+
)
10+
11+
func FindGitRepoRootUsingGit(dir string) (string, error) {
12+
cmd := exec.Command("git", "rev-parse", "--show-toplevel")
13+
cmd.Dir = dir
14+
output, err := cmd.Output()
15+
if err != nil {
16+
return "", err
17+
}
18+
return strings.TrimSpace(string(output)), nil
19+
}
20+
21+
// FindGitRepoRootByTraversal finds the Git repository root for the given directory by manually checking for a .git directory.
22+
func FindGitRepoRootByTraversal(dir string) (string, error) {
23+
currentPath, err := filepath.Abs(dir)
24+
if err != nil {
25+
return "", fmt.Errorf("failed to resolve absolute path for %s: %v", dir, err)
26+
}
27+
28+
// Check up to the filesystem root
29+
for currentPath != filepath.Dir(currentPath) { // Continue until the root directory is reached
30+
if _, err := os.Stat(filepath.Join(currentPath, ".git")); err == nil {
31+
return currentPath, nil
32+
}
33+
34+
// Move up one directory level
35+
currentPath = filepath.Dir(currentPath)
36+
}
37+
38+
return "", fmt.Errorf("no Git repository found starting from directory %s", dir)
39+
}
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
package utils
1+
package git_tools
22

33
import (
44
"fmt"
5+
"github.com/Excoriate/tftest/pkg/utils"
56
"os"
67
"path/filepath"
78
)
@@ -21,7 +22,7 @@ func IsAGitRepository(repoRoot string, levels int) (gitRoot, subDir string, err
2122
return "", "", fmt.Errorf("failed to resolve absolute path for %s: %v", repoRoot, err)
2223
}
2324

24-
if err := DirExistAndHasContent(originalPath); err != nil {
25+
if err := utils.DirExistAndHasContent(originalPath); err != nil {
2526
return "", "", err
2627
}
2728

0 commit comments

Comments
 (0)