Documentation
¶
Overview ¶
Package gittest is the shared hermetic-git environment for tests that spawn git as a subprocess (iss-28).
The problem it closes: a test that builds `exec.Command("git", …)` and lets it inherit os.Environ() also inherits any ambient GIT_DIR/GIT_WORK_TREE/ GIT_INDEX_FILE/GIT_CONFIG_* the process was launched with. A pre-commit or prompt hook, for instance, exports GIT_DIR — which OVERRIDES `-C dir`/cmd.Dir and silently redirects the test's `git init`/`commit` onto the real repository. The developer's ~/.gitconfig identity/aliases leak in the same way. Both make a test non-hermetic, and the redirect can mutate the ambient repo.
Env(t) is the single fix: it reuses the SAME production scrub as gitutil.IsolatedEnv() (so a test git command runs under exactly the isolation production git runs under) and additionally pins HOME/XDG to a per-test temp dir. Assign its result to cmd.Env for every git command a test spawns.
Index ¶
- Constants
- func CloneBare(t *testing.T, src, path string)
- func Env(t *testing.T) []string
- func HideGHLogin() (cleanup func(), err error)
- func InitBare(t *testing.T, path string)
- func InitBareFormat(t *testing.T, path, format string)
- func NeutralCaller(t *testing.T) string
- func NeutralHomeIn(dir string) (string, error)
- func PushEmptyTreeCommit(t *testing.T, dir, ref, msg string) string
- func RootCommit(t *testing.T, dir string) string
- func ShimGit(t *testing.T, when []string, out string, code int)
- func ShimGitNamingNoGitfileTarget(t *testing.T)
- func SlowPipeGit(t *testing.T, match string, hangs int) (calls func() int)
- type Abcd
- type Person
- type Repo
- func (r *Repo) AddSubmodule(rel string) (gitDir string)
- func (r *Repo) Commit(msg string)
- func (r *Repo) Env() []string
- func (r *Repo) Git(args ...string) string
- func (r *Repo) MergeParentlessRoots(n int)
- func (r *Repo) Record(rel, id, impact string)
- func (r *Repo) Remove(rel string)
- func (r *Repo) Root() string
- func (r *Repo) Write(rel, content string)
- type Templates
- type Tree
Constants ¶
const NeutralAccount = "zzneutralcaller"
NeutralAccount is the account name a neutral caller's HOME ends in: a word no committed content carries.
Variables ¶
This section is empty.
Functions ¶
func CloneBare ¶ added in v0.14.0
CloneBare clones src into a new bare repository at path, with the same maintenance config as InitBare.
func Env ¶
Env pins HOME and the XDG config/data dirs to a per-test temp location and returns the isolated environment a git subprocess must run under. The returned slice is gitutil.IsolatedEnv(): the parent environment with every repo-selection and config-injection variable stripped (GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_CONFIG_*, …) and the global/system config-file neutralisers appended.
Assign it to cmd.Env for each git command. It is safe to call once per test or once per git call — the HOME/XDG pin happens only on the first call within a test (see isolatedSentinel). A caller that needs a commit identity appends its own GIT_AUTHOR_*/GIT_COMMITTER_* (or sets git config) on top of the result; Env deliberately does NOT pin an identity, so config-based identity tests keep resolving the repo's own user.name/user.email.
If the test has ALREADY pointed HOME at a temp dir it owns (the common case for tests that stand up a hermetic ~/.abcd.noindex store), Env reuses that HOME rather than replacing it — replacing it would leave the process HOME and the test's captured home var pointing at different directories, so a store the test wrote under its own HOME would be invisible to the in-process production code under test. Env only mints a fresh temp HOME when HOME still points outside the test temp area.
func HideGHLogin ¶ added in v0.16.0
func HideGHLogin() (cleanup func(), err error)
HideGHLogin points gh, for the rest of the process, at an empty configuration directory and clears the token variables, so no test reaches the machine's own GitHub login. A test that did would pass on a developer's machine and fail on CI, which has no login: a landing test read the account behind an announcement that way and passed preflight, then failed in the merge queue. A package whose tests can reach gh calls it from TestMain before m.Run and runs the returned cleanup after; a test that wants a login of its own still sets one with t.Setenv.
func InitBare ¶ added in v0.14.0
InitBare creates an empty bare repository at path on branch main, with the same maintenance config NewRepo writes: a bare fixture is usually an origin the test pushes into, and a push spawns the origin's auto-gc. Every test makes its bare repositories here or through CloneBare, never with its own git init --bare.
func InitBareFormat ¶ added in v0.15.1
InitBareFormat is InitBare with git's object format named (NewRepoFormat).
func NeutralCaller ¶ added in v0.16.2
NeutralCaller points HOME at a fresh test-owned directory named for NeutralAccount and returns it, so a test that scans content judges the content and not whoever runs the suite. The identity scanner takes the caller's account name from HOME's last segment and flags every word-bounded occurrence of it, so an account named for a word the content holds fails a scan of a clean tree. Env reuses this HOME, since it is inside the test's temp area.
func NeutralHomeIn ¶ added in v0.16.2
NeutralHomeIn makes the directory NeutralCaller points HOME at, inside dir, for a TestMain that sets HOME for a whole package (it has no t to set it through, and removes dir itself). It is the account's folder, which HOME names, not abcd's home inside it: the code under test makes that one, at abcdhome.DirMode.
func PushEmptyTreeCommit ¶ added in v0.15.1
PushEmptyTreeCommit writes a commit of the empty tree carrying msg in the clone at dir and pushes it to ref on the clone's origin with no hook in the way: the shape a hand-made branch tip arrives in, a reservation among them. It returns the commit's name.
func RootCommit ¶ added in v0.16.0
RootCommit is gitutil.RootCommit for a fixture: the root commit of the repository at dir, "" for none, and a failed test when git did not answer. A fixture's identity is never in doubt, so a lookup that errors is the test machine's fault and is said as such rather than read as "no root commit".
func ShimGit ¶ added in v0.15.1
ShimGit puts a git first on PATH, for the length of t, that answers one kind of command itself: a git run with every word of when among its arguments prints out to stdout and exits code, and every other git command runs the git that was first on PATH before. Shims stack: a later one falls through to an earlier one.
It lets a test hand the code under test an answer real git never gives (a listing that stops partway, a line of an unexpected shape, a failure of one command) while every other git command behaves as git does. The fixture's own Repo.Git keeps the environment it was made with, so it is not shimmed when the Repo was made first. It cannot be used with t.Parallel.
func ShimGitNamingNoGitfileTarget ¶ added in v0.15.1
ShimGitNamingNoGitfileTarget puts a git first on PATH, for the length of t, that runs the git first on PATH before and reports a broken git file as Linux's git does: its "fatal: not a git repository: <path>" names the path as "(null)", where macOS's git names where the git file points. A reason that names that target only through git's stderr names it on one platform; under this shim a test sees what every Linux machine, CI's included, sees. It cannot be used with t.Parallel.
func SlowPipeGit ¶ added in v0.14.0
SlowPipeGit puts a `git` first on PATH that runs the real one and, for a call whose arguments contain match, leaves a background process holding its output pipes open for a second after it exits. A runner that let exec copy git's output under a WaitDelay saw exec.ErrWaitDelay ("WaitDelay expired before I/O complete") although git answered: the same error a heavily loaded machine produced when the copy of git's output missed the delay (iss-2610272041031418). It is the deterministic stand-in for that load, so no test has to generate CPU load to show git's answer is read whole.
The first hangs matching calls hold the pipe; later ones answer cleanly. A negative hangs holds it on every matching call. The returned function reports how many matching calls git has received so far.
Types ¶
type Abcd ¶ added in v0.15.1
type Abcd struct {
// contains filtered or unexported fields
}
Abcd is abcd built from this checkout, once for the whole test binary of one package. The git-hook and cloud-script fixtures run the real binary: as the attribution gate's outbound half, which a fixture clone cannot `go run`, and as the ABCD_BIN a script calls. Built afresh for every test, each a link of the whole module, the build cost those packages minutes of serial time.
A package declares one, and its TestMain removes the build after the tests:
var builtAbcd gittest.Abcd
func TestMain(m *testing.M) {
code := m.Run()
builtAbcd.Remove()
os.Exit(code)
}
The binary is shared, so a test reads it and never changes it.
type Person ¶ added in v0.7.1
type Person struct{ Name, Email string }
Person is one git author identity — the pair the redactors key on.
func SplitIdentity ¶ added in v0.7.1
SplitIdentity gives the test process a caller whose git identity differs by scope — the everyday shape of a work checkout, and the one the identity redactors must cover in full: a GLOBAL identity in a per-test HOME's .gitconfig and a REPO-LOCAL persona in repo's .git/config.
GIT_CONFIG_GLOBAL is pinned to that file and the system config to os.DevNull, so the production probe — which keeps global config in effect on purpose (gitutil.ScrubbedEnv) — resolves exactly these two people and nothing from the machine. repo is initialised when it is not a repository yet. A machine with no usable git skips the test.
type Repo ¶
type Repo struct {
// contains filtered or unexported fields
}
Repo is a hermetic throwaway git repository for tests that must exercise real git objects.
It exists because three packages needed the same fixture. The release derivation, the surface guardrail, and the ship verb all read their inputs out of git trees (tags, blobs, set-differences), so a stubbed git would prove nothing about the behaviour under test — each one has to build an actual history. internal/core/changelog and internal/surface/cli each grew a private copy of this helper; this is the promotion those copies asked for, so a fourth caller extends one implementation instead of writing a fourth.
Every command runs under Env(t): the ambient GIT_DIR/GIT_WORK_TREE and the developer's global config are stripped, so a test can never be redirected onto the real repository.
func NewRepo ¶
NewRepo initialises an empty repository on a fixed branch name under a per-test temp directory. A machine with no usable git skips the test rather than failing it: the fixture's subject is abcd's behaviour, not git's presence.
func NewRepoAt ¶ added in v0.16.2
NewRepoAt is NewRepo at root, a directory the caller made and owns, for a fixture that keeps its repository at a path of its own choosing.
func NewRepoFormat ¶ added in v0.15.1
NewRepoFormat is NewRepo with git's object format named ("sha1" or "sha256"; "" is git's default), for a test whose subject is how abcd reads and measures an object name of the longer form.
func OpenRepo ¶ added in v0.16.1
OpenRepo is a Repo over the working tree at root, which the caller made: a copy of a repository NewRepo built once, for a package whose every test starts from the same seeded history and copies it rather than building it again with git. The copy carries the config NewRepo wrote, maintenance off among it. Every command runs under Env(t), as NewRepo's do.
func (*Repo) AddSubmodule ¶ added in v0.13.4
AddSubmodule commits a checked-out submodule at rel: a second fixture repository holding one committed file, s.txt, added by path and committed in this one. It returns the submodule's own git directory (.git/modules/<rel>), whose config is the submodule's config, for a test that plants something a superproject command must not reach into.
func (*Repo) Commit ¶
Commit stages everything and records a commit. Empty commits are allowed so a fixture can advance history without touching a file.
func (*Repo) Env ¶
Env is the isolated environment the fixture's git commands run under, for a caller that must spawn git itself.
func (*Repo) Git ¶
Git runs one git command in the fixture and returns its trimmed output, failing the test on a non-zero exit. The identity is pinned per command rather than written into the repo's config, so a test that inspects the config sees only what it put there.
func (*Repo) MergeParentlessRoots ¶ added in v0.15.1
MergeParentlessRoots merges n new parentless commits into the current branch with an empty diff, in one n-way merge commit, so the branch's history holds n more root commits than it did. The commits are written through one fast-import, so the count costs one git process and not n. Each holds the empty tree and is dated in 2090, after any commit a test makes.
func (*Repo) Record ¶
Record writes a minimal record file carrying the given impact frontmatter — the shape the release derivation reads.
type Templates ¶ added in v0.16.2
type Templates struct {
// contains filtered or unexported fields
}
Templates keeps repositories a package's tests start from: each is built with git once in a test process and held in memory, and every test gets its own copy of the tree. A fixture of many commits costs a process per git command when built and only file writes when copied, and the copy is the same repository: the same objects, refs, config and working tree. Nothing outlives the test process, so a package has nothing to clean up.
A template must be a function of its key alone, since whichever test asks first builds it for all the others. A package declares one:
var fixtures gittest.Templates
func (*Templates) Repo ¶ added in v0.16.2
Repo is t's own copy of the repository kept under key, which build makes the first time the key is asked for. The copy is t's to change: it sits in its own temporary directory and shares nothing with the template or with any other test's copy. The first test gets a copy too, so no test is handed a repository of a different kind from the rest.
type Tree ¶ added in v0.16.2
type Tree struct {
// contains filtered or unexported fields
}
Tree is a directory's contents in memory, for a fixture that keeps more than one repository, or keeps one at a fixed place so that the paths its files hold stay true. It holds every entry's exact mode, which a store whose folder must be closed to other accounts depends on.