-
Notifications
You must be signed in to change notification settings - Fork 199
/
dot_git.go
55 lines (43 loc) · 1.33 KB
/
dot_git.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package true_git
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5"
"github.com/werf/werf/pkg/util"
)
func UpwardLookupAndVerifyWorkTree(ctx context.Context, lookupPath string) (bool, string, error) {
lookupPath = util.GetAbsoluteFilepath(lookupPath)
for {
dotGitPath := filepath.Join(lookupPath, git.GitDirName)
if _, err := os.Stat(dotGitPath); os.IsNotExist(err) {
if lookupPath != filepath.Dir(lookupPath) {
lookupPath = filepath.Dir(lookupPath)
continue
}
} else if err != nil {
return false, "", fmt.Errorf("error accessing %q: %w", dotGitPath, err)
} else if isValid, err := IsValidGitDir(ctx, dotGitPath); err != nil {
return false, "", err
} else if isValid {
return true, lookupPath, nil
}
break
}
return false, "", nil
}
func IsValidWorkTree(ctx context.Context, workTree string) (bool, error) {
return IsValidGitDir(ctx, filepath.Join(workTree, git.GitDirName))
}
func IsValidGitDir(ctx context.Context, gitDir string) (bool, error) {
detectGitCmd := NewGitCmd(ctx, nil, "--git-dir", gitDir, "rev-parse")
if err := detectGitCmd.Run(ctx); err != nil {
if strings.HasPrefix(detectGitCmd.ErrBuf.String(), "fatal: not a git repository: ") {
return false, nil
}
return false, fmt.Errorf("git rev parse command failed: %w", err)
}
return true, nil
}