DEV Community

polycratia
polycratia

Posted on Originally published at polycratia.com

core.hooksPath outside the checkout: a finding, not a refusal

A repository that shows up as plain files brings its own git configuration along, and that configuration decides which programs a git run starts. Before anyone types a command, an inspector has to answer one narrow question: which directory would git take its hooks from, and what is sitting in it. The interesting case is the one where that directory lies outside the checkout, and the answer there cannot be the answer the inspector gives to a .git file pointing out of the tree.

Two rules in the same tree

I wrote repo.Resolve in gitdisarm to read a checkout's pointer files as data: .git as a directory, as a symlink, or as a file carrying a gitdir: line taken relative to the directory holding it; the commondir pointer a linked worktree leaves in its git directory; the gitdir pointer that leads back to that worktree's own .git file. Every one of those paths has to stay inside the checkout. One that leaves it refuses the repository outright:

type EscapeError struct {
    // Pointer is the file that named the path.
    Pointer string
    // Field is what it stood for: "gitdir", "commondir" or "worktree".
    Field string
    Path  string
    Root  string
}

func (e *EscapeError) Error() string {
    return fmt.Sprintf("%s: %s %s %s at %s", e.Pointer, e.Field, e.Path, ErrEscapesCheckout, e.Root)
}

func (e *EscapeError) Unwrap() error { return ErrEscapesCheckout }
Enter fullscreen mode Exit fullscreen mode

The question gets asked twice: lexically, so a path that never existed is refused all the same, and then again after filepath.EvalSymlinks has followed as much of the path as exists, so a .git symlinked out of the tree is refused just like a gitdir: ../elsewhere line. Nothing is followed once it fails. For a pointer file that is the right behaviour, because a pointer file leaving the checkout is not a configuration choice anybody makes on purpose in a tree you were handed: it is the tree reaching for something you did not receive.

Extending that rule to core.hooksPath would be consistent. It would also be wrong.

Why the same rule cannot apply to the configuration

Git reads core.hooksPath as a path to a hooks directory, and it accepts that path pointing anywhere. A shared hooks directory kept outside the repository is an ordinary, supported setup. So a hooks path that leads out of the checkout is not a malformed repository, it is a configured one, and git will run what it finds there whatever an inspector thinks about the location.

Refuse at that point and the person running the tool gets an error where they needed a list. The directory, the entry that chose it, and the executables in it are exactly what a reviewer came to the tree to learn. Refusing would hide the thing the tool exists to show.

I have spent most of the last several years on payment and crypto systems, where refusing early is almost always the correct instinct: an unexpected value in a settlement path should stop the transaction, not get reasoned about. Carry that instinct into an inspector and you get a tool that is safe and useless. A gate refuses. A report does not get to refuse the parts it finds alarming, those are the findings.

So in gitdisarm, Layout.Hooks returns no error for a hooks directory outside the checkout. It records the fact and lists the directory anyway.

The effective directory is a computation, not a lookup

There is no single place to read the hooks path from. Git applies configuration in order, a later declaration of the same key overrides an earlier one, and included files are spliced in where their directive stood. gitconfig.Load hands back entries in that order, each one keeping the file and line it came from, so the effective value is whatever the last matching entry says, not the first one found.

That shapes the loop: it does not break.

func (l *Layout) Hooks(entries []gitconfig.Entry) (*Hooks, error) {
    h := &Hooks{Dir: filepath.Join(l.CommonDir, "hooks")}
    for i := range entries {
        e := &entries[i]
        if e.Section != "core" || e.Subsection != "" || e.Key != "hookspath" || e.Value == "" {
            continue
        }
        h.Dir = against(l.Worktree, e.Value)
        h.FromConfig = e
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Four details are doing work there.

The section and key are compared lowercased because the parser reports them that way (git's section and key names are case-insensitive), and the subsection has to be empty, so nothing inside a [core "something"] block gets mistaken for the real key.

An empty value changes nothing. It is skipped instead of being treated as a request to use the empty path, so a stray hooksPath = cannot quietly point the effective directory at the work tree root.

The path is taken relative to the top of the work tree, not to the git directory and not to the process's working directory. against keeps an absolute path as it is and joins a relative one onto l.Worktree, which, for a linked worktree, is the directory holding its .git file rather than the checkout root.

And the fallback is CommonDir, not GitDir. Hooks are shared from the common directory, so a linked worktree with no core.hooksPath resolves to the same hooks its main checkout would run.

Given this configuration, the second declaration wins and the first one is not a finding at all:

[core]
    hooksPath = .githooks

[core]
    hooksPath = /opt/shared-hooks
Enter fullscreen mode Exit fullscreen mode

Reporting the first line would describe a git run that is not going to happen. Reporting only that "a hooks path is set" would describe nothing. The entry that actually chose the directory is kept in FromConfig, so the report can name the file and the line responsible.

Outside is a field, not an error

type Hooks struct {
    Dir string
    // FromConfig is the core.hooksPath entry that chose the directory, nil
    // when git would take its default.
    FromConfig *gitconfig.Entry
    // Outside reports that Dir lies outside the checkout, which the
    // configuration may ask for where a pointer file may not.
    Outside bool
    Executables []string
}
Enter fullscreen mode Exit fullscreen mode

The outside test reuses the same two-stage question Resolve asks, and ends in a boolean instead of an *EscapeError: the directory is compared against Root lexically, then again after the symlinks of the longest part of the path that exists have been followed. A path that does not exist yet still gets an answer, and a hooks directory that is a symlink out of the tree is answered the same way as one spelled ../../hooks. Only an unexpected filesystem error on the way is passed up as an error.

That asymmetry (identical reasoning, different outcome) is the whole design. The checkout boundary is a hard constraint on structure and a reportable fact about intent.

A missing directory runs nothing

With the directory decided, what is left is the question of what git would actually start from it:

func executables(dir string) ([]string, error) {
    info, err := os.Stat(dir)
    if errors.Is(err, fs.ErrNotExist) {
        return nil, nil
    } else if err != nil {
        return nil, err
    }
    if !info.IsDir() {
        return nil, nil
    }
    ents, err := os.ReadDir(dir)
    if err != nil {
        return nil, err
    }
    var names []string
    for _, ent := range ents {
        st, err := os.Stat(filepath.Join(dir, ent.Name()))
        if err != nil {
            continue
        }
        if m := st.Mode(); m.IsRegular() && m.Perm()&0o111 != 0 {
            names = append(names, ent.Name())
        }
    }
    return names, nil
}
Enter fullscreen mode Exit fullscreen mode

A directory that is absent, or that is no directory at all, runs nothing, and "runs nothing" is an empty list rather than an error. A core.hooksPath pointing at a path that does not exist on this machine is a real and common state; treating it as a failure would turn a finding worth one line into a stack of noise, and would stop the rest of the report from being produced.

Every entry is stat'ed again instead of trusting the type os.ReadDir already returned. That extra call is the point: DirEntry reports a symlink as a symlink, and a symlink to an executable file is one more program git would start. Following it costs one syscall per entry, and it is the difference between listing pre-commit and missing it. An entry that cannot be stat'ed is skipped rather than guessed at, and a name is kept only when the target is a regular file with any bit of 0o111 set, because git does not care which bit, so neither does this.

What I would do differently

Two things.

Executables carries names, in the order the directory lists them, and nothing else. A reviewer who reads pre-commit in the output does not learn from it that the name is a symlink, or where it leads. The stat already follows the link, so the resolved target is free information that currently gets thrown away, and I would carry it.

The second one is about how the finding is framed rather than how it is computed. The catalog row for core.hooksPath classifies it as executing and carries its own override, -c core.hooksPath=/dev/null, so the report can print the invocation that neutralizes the setting next to the finding. Alongside it, NotCovered has to be printed too: it names what can still end in a program being run and has no verdict, including the executables already sitting in .git/hooks. A short list of findings must not read as a clean repository, and that is probably easier to get wrong in the presentation layer than in the resolution logic.

The rule

Refuse what the format does not permit. Report what the format permits and a reviewer would want to know. Pointer files are structure, and a structure that leaves the checkout is broken. Configuration is intent, and intent that leaves the checkout is the finding itself.


Originally published on polycratia.com — where I write about payment systems, crypto rails and marketplace backends.

Top comments (0)