# How no-mistakes Detects Bare Git Repositories Under GIT_CONFIG safe.bareRepository

> Learn how no-mistakes detects bare Git repositories when safe bareRepository is explicit. Ensure secure Git operations with this guide.

- Repository: [Kun Chen/no-mistakes](https://github.com/kunchenguid/no-mistakes)
- Tags: internals
- Published: 2026-07-04

---

**When the Git configuration `safe.bareRepository=explicit` blocks automatic discovery, no-mistakes detects bare repositories by validating the presence of `HEAD` and `objects` directories while excluding paths containing `.git`, then forces Git commands to use the `--git-dir` flag to bypass cwd-based lookups.**

The `kunchenguid/no-mistakes` repository implements a defensive mechanism for bare repository detection that ensures gate-repo operations continue functioning even when Git's security-hardened `safe.bareRepository` setting is enabled. This configuration, commonly injected in hardened CI environments or via `GIT_CONFIG` environment variables, prevents Git from automatically discovering bare repositories by inspecting the current working directory. To counter this, the project uses explicit filesystem heuristics in [`internal/git/git.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git.go) that mirror Git's own internal logic for identifying git directories.

## The Challenge of safe.bareRepository=explicit

When `safe.bareRepository` is set to `explicit`, Git refuses to enter bare repositories through normal path traversal or cwd-based discovery. This security feature prevents accidental operations on potentially untrusted bare repositories but breaks workflows that depend on automatic detection. In no-mistakes, background daemons, step-executors, and agents must operate reliably on gate-repositories regardless of these environmental restrictions, necessitating an explicit detection mechanism (see issue #362).

## Detection Logic in isBareGitDir

The core detection logic resides in the private function `isBareGitDir` within [`internal/git/git.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git.go). This function implements a filesystem-based heuristic that distinguishes bare repositories from normal worktrees or linked worktrees by checking for three specific conditions:

1. The directory must not contain a `.git` subdirectory (which would indicate a normal worktree)
2. The directory must contain a `HEAD` file (not a directory)
3. The directory must contain an `objects` subdirectory

```go
// isBareGitDir reports whether dir is itself a git directory (a bare repo),
// as opposed to a working tree or linked worktree, which carry a .git entry
// and keep using normal discovery. The check mirrors git's own git-dir
// heuristic: a HEAD file plus an objects directory.
func isBareGitDir(dir string) bool {
    if dir == "" {
        return false
    }
    if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
        return false               // a normal worktree has a .git directory
    }
    if fi, err := os.Stat(filepath.Join(dir, "HEAD")); err != nil || fi.IsDir() {
        return false               // no HEAD file → not a bare repo
    }
    fi, err := os.Stat(filepath.Join(dir, "objects"))
    return err == nil && fi.IsDir() // objects dir present → bare repo
}

```

This implementation follows Git's own internal structure validation, ensuring that only true bare repositories—those that serve as the actual git directory without a separate working tree—are recognized.

## Runtime Handling in the Run Function

The public `Run` function in [`internal/git/git.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git.go) integrates this detection into every Git command execution. Before invoking `git`, `Run` checks whether the supplied directory is a bare repository and, if so, injects the `--git-dir` flag to explicitly point Git to the repository:

```go
func Run(ctx context.Context, dir string, args ...string) (string, error) {
    if isBareGitDir(dir) {
        args = append([]string{"--git-dir=" + dir}, args...)
    }
    // … exec.CommandContext, capture output, etc.
}

```

By prepending `--git-dir=<dir>` to the argument list, the function bypasses Git's cwd-based discovery mechanism entirely. This allows operations to succeed even when `safe.bareRepository=explicit` would normally prevent Git from recognizing the directory as a valid repository.

## Practical Implementation Examples

When executing commands against a bare repository path, the detection happens transparently. Here is how the `Run` function handles a `rev-parse` operation:

```go
// Example: running `git rev-parse --show-toplevel` inside a bare repo.
ctx := context.Background()
bareRepoPath := "/var/lib/no-mistakes/gate-repo" // path that is itself a bare repo
out, err := git.Run(ctx, bareRepoPath, "rev-parse", "--show-toplevel")
if err != nil {
    log.Fatalf("git failed: %v", err)
}
fmt.Println("Repo root:", out)
// Internally, Run will translate the call to:
//   git --git-dir=/var/lib/no-mistakes/gate-repo rev-parse --show-toplevel

```

The detection can also be verified programmatically in test environments:

```go
// Unit‑test style: confirming detection works.
func TestIsBareGitDir(t *testing.T) {
    // Set up a temporary bare repository.
    dir := t.TempDir()
    git.InitBare(t, dir) // helper that runs `git init --bare`
    if !git.IsBareGitDir(dir) {
        t.Fatalf("expected %s to be recognised as a bare repo", dir)
    }
}

```

## Testing Bare Repository Detection

The project verifies this behavior across multiple test files. The primary test coverage exists in [`internal/git/git_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git_test.go), which validates the `isBareGitDir` logic against various filesystem configurations. Additional integration tests in [`internal/git/hook_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/hook_test.go) simulate the restricted environment by setting `GIT_CONFIG_KEY_0=safe.bareRepository` and verifying that commands execute successfully when the detection mechanism activates. These tests ensure that pipeline steps in `internal/pipeline/steps/*` continue functioning correctly when operating under hardened Git configurations.

## Summary

- **Explicit detection bypasses `safe.bareRepository=explicit`**: When Git's security setting blocks automatic discovery, no-mistakes uses filesystem heuristics to identify bare repositories.
- **`isBareGitDir` validates structure**: The function checks for `HEAD` and `objects` entries while excluding `.git` directories to distinguish bare repos from worktrees.
- **`Run` injects `--git-dir`**: Upon detection, the `Run` function in [`internal/git/git.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git.go) prefixes commands with `--git-dir=<path>`, forcing Git to use the specified directory regardless of cwd restrictions.
- **Comprehensive test coverage**: Tests in [`internal/git/git_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git_test.go) and [`internal/git/hook_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/hook_test.go) verify detection works under `GIT_CONFIG` restrictions.

## Frequently Asked Questions

### What does the Git configuration `safe.bareRepository=explicit` do?

This setting instructs Git to disable automatic discovery of bare repositories based on the current working directory. When enabled, Git will only operate on repositories explicitly specified via command-line flags like `--git-dir`, preventing accidental execution within potentially malicious bare repositories.

### How does `isBareGitDir` distinguish between a bare repository and a normal worktree?

The function checks for the presence of a `HEAD` file and an `objects` directory while explicitly verifying that no `.git` subdirectory exists. Normal worktrees contain a `.git` directory pointing to the actual git directory, while bare repositories contain the git contents (including `HEAD` and `objects`) directly at the root.

### Why does no-mistakes need to handle bare repository detection explicitly?

The project manages gate-repositories through background daemons and step-executors that must remain functional in hardened CI environments where `safe.bareRepository=explicit` is enforced. Without explicit detection and the `--git-dir` flag injection, Git commands would fail to locate the repository, breaking the pipeline (as documented in issue #362).

### Where can I find the test cases for this detection logic?

The unit tests for bare repository detection reside in [`internal/git/git_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/git_test.go), while integration tests that simulate the `safe.bareRepository` environment variable are located in [`internal/git/hook_test.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/git/hook_test.go). These files verify that the `Run` function correctly handles bare repositories under restricted Git configurations.