| 1 | package gitguard |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/sylvinus/agent-vm/internal/gitx" |
| 11 | "github.com/sylvinus/agent-vm/internal/version" |
| 12 | ) |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | const ( |
| 23 | BareOK = "ok" |
| 24 | BareUnset = "unset" |
| 25 | BareOld = "old" |
| 26 | BareNoGit = "nogit" |
| 27 | BareUnavailable = "unavailable" |
| 28 | ) |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | func BareState(ctx context.Context) string { |
| 34 | available, err := gitx.Available(ctx) |
| 35 | if err != nil { |
| 36 | return BareUnavailable |
| 37 | } |
| 38 | if !available { |
| 39 | return BareNoGit |
| 40 | } |
| 41 | ctx, cancel := context.WithTimeout(ctx, gitTimeout) |
| 42 | defer cancel() |
| 43 | out, err := gitx.Untrusted(ctx, "--version").Output() |
| 44 | if err != nil { |
| 45 | return BareUnavailable |
| 46 | } |
| 47 | v := strings.TrimPrefix(strings.TrimSpace(string(out)), "git version ") |
| 48 | v, _, _ = strings.Cut(v, " ") |
| 49 | |
| 50 | v, _, _ = strings.Cut(v, "-") |
| 51 | if !version.AtLeast(v, "2.38.0") { |
| 52 | return BareOld |
| 53 | } |
| 54 | |
| 55 | |
| 56 | cmd := gitx.Untrusted(ctx, "config", "--show-scope", "--get-all", "safe.bareRepository") |
| 57 | |
| 58 | |
| 59 | cmd.Dir = string(filepath.Separator) |
| 60 | if home, err := os.UserHomeDir(); err == nil { |
| 61 | cmd.Dir = filepath.VolumeName(home) + string(filepath.Separator) |
| 62 | } |
| 63 | cmd.WaitDelay = 2 * time.Second |
| 64 | out, _ = cmd.Output() |
| 65 | value := "" |
| 66 | for _, l := range strings.Split(string(out), "\n") { |
| 67 | if scope, v, ok := strings.Cut(l, "\t"); ok && scope != "command" { |
| 68 | value = strings.TrimSpace(v) |
| 69 | } |
| 70 | } |
| 71 | if value == "explicit" { |
| 72 | return BareOK |
| 73 | } |
| 74 | return BareUnset |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | const BareHint = `Git treats any folder with HEAD, objects/ and refs/ as a repository, even without .git, and runs commands its config names (on ` + "`git log`" + `, for one). A VM could create one in your projects, and the .git protection does not cover it. |
| 80 | |
| 81 | This makes git ignore such folders unless named with --git-dir: |
| 82 | git config --global safe.bareRepository explicit |
| 83 | ` |