| 1 | |
| 2 | package gitx |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | func Untrusted(ctx context.Context, args ...string) *exec.Cmd { |
| 24 | cmd := exec.CommandContext(ctx, "git", append([]string{"--no-pager", "-c", "safe.bareRepository=explicit", "-c", "core.fsmonitor=false"}, args...)...) |
| 25 | if available, err := Available(ctx); err != nil { |
| 26 | cmd.Err = err |
| 27 | } else if !available { |
| 28 | cmd.Err = exec.ErrNotFound |
| 29 | } |
| 30 | return cmd |
| 31 | } |
| 32 | |
| 33 | |
| 34 | func Have() bool { |
| 35 | available, err := Available(context.Background()) |
| 36 | |
| 37 | |
| 38 | return available || err != nil |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | func Available(ctx context.Context) (bool, error) { |
| 44 | path, err := exec.LookPath("git") |
| 45 | if errors.Is(err, exec.ErrNotFound) { |
| 46 | return false, nil |
| 47 | } |
| 48 | if err != nil { |
| 49 | return false, err |
| 50 | } |
| 51 | resolved, err := filepath.EvalSymlinks(path) |
| 52 | if err != nil { |
| 53 | return false, err |
| 54 | } |
| 55 | if runtime.GOOS != "darwin" || resolved != "/usr/bin/git" { |
| 56 | return true, nil |
| 57 | } |
| 58 | return appleGitAvailable(ctx, "/usr/bin/xcode-select") |
| 59 | } |
| 60 | |
| 61 | func appleGitAvailable(ctx context.Context, selector string) (bool, error) { |
| 62 | ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| 63 | defer cancel() |
| 64 | cmd := exec.CommandContext(ctx, selector, "--print-path") |
| 65 | cmd.Env = append(os.Environ(), "LC_ALL=C", "LANG=C") |
| 66 | out, err := cmd.Output() |
| 67 | if err != nil { |
| 68 | var exit *exec.ExitError |
| 69 | |
| 70 | |
| 71 | if os.Getenv("DEVELOPER_DIR") == "" && errors.As(err, &exit) && |
| 72 | strings.Contains(string(exit.Stderr), "unable to get active developer directory") { |
| 73 | return false, nil |
| 74 | } |
| 75 | return false, fmt.Errorf("cannot determine whether Apple Git is installed") |
| 76 | } |
| 77 | developer := strings.TrimSpace(string(out)) |
| 78 | if !filepath.IsAbs(developer) { |
| 79 | return false, fmt.Errorf("invalid developer tools directory") |
| 80 | } |
| 81 | info, err := os.Stat(filepath.Join(developer, "usr", "bin", "git")) |
| 82 | if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 { |
| 83 | return false, fmt.Errorf("Apple Git is unavailable in the selected developer tools") |
| 84 | } |
| 85 | return true, nil |
| 86 | } |