Skip to content

Commit

Permalink
refactor: expose APIs for finding git repo by different methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Excoriate committed Apr 17, 2024
1 parent b791280 commit 17e7960
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
39 changes: 39 additions & 0 deletions pkg/git_tools/finder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package git_tools

Check warning on line 1 in pkg/git_tools/finder.go

View workflow job for this annotation

GitHub Actions / Golangci-lint

var-naming: don't use an underscore in package name (revive)

import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)

func FindGitRepoRootUsingGit(dir string) (string, error) {
cmd := exec.Command("git", "rev-parse", "--show-toplevel")
cmd.Dir = dir
output, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(output)), nil
}

// FindGitRepoRootByTraversal finds the Git repository root for the given directory by manually checking for a .git directory.
func FindGitRepoRootByTraversal(dir string) (string, error) {
currentPath, err := filepath.Abs(dir)
if err != nil {
return "", fmt.Errorf("failed to resolve absolute path for %s: %v", dir, err)
}

// Check up to the filesystem root
for currentPath != filepath.Dir(currentPath) { // Continue until the root directory is reached
if _, err := os.Stat(filepath.Join(currentPath, ".git")); err == nil {
return currentPath, nil
}

// Move up one directory level
currentPath = filepath.Dir(currentPath)
}

return "", fmt.Errorf("no Git repository found starting from directory %s", dir)
}
5 changes: 3 additions & 2 deletions pkg/utils/git.go → pkg/git_tools/git.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package utils
package git_tools

Check warning on line 1 in pkg/git_tools/git.go

View workflow job for this annotation

GitHub Actions / Golangci-lint

var-naming: don't use an underscore in package name (revive)

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

if err := DirExistAndHasContent(originalPath); err != nil {
if err := utils.DirExistAndHasContent(originalPath); err != nil {
return "", "", err
}

Expand Down

0 comments on commit 17e7960

Please sign in to comment.