git

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package git acquires repository metadata for the GraphLume indexer.

Three consumers shape everything here:

  1. Provenance — an IndexRun is stamped with the revision it describes, so a stale index can be recognised instead of silently trusted.
  2. Recency ranking — the context engine boosts code that changed recently, which needs per-file "when was this last touched" data.
  3. Incremental re-indexing — knowing exactly which paths changed between two revisions, including renames, is what makes re-indexing cheap. A rename reported as delete+add would make the indexer destroy and rebuild every symbol in the file rather than move it.

Two hard constraints

Pure Go. Everything goes through github.com/go-git/go-git/v5. GraphLume ships CGO_ENABLED=0 binaries, and it must not shell out to a `git` binary: the binary may be absent, it may behave differently across versions, and spawning subprocesses from a tool that runs over untrusted repositories is an attack surface this product declines to open.

Not being a git repository is normal, not an error. GraphLume indexes plain directories, extracted tarballs and vendored trees. Open therefore succeeds on a non-repository and reports IsRepo=false; callers branch on a boolean, never on the text of an error.

Performance

go-git is O(history) for anything resembling `git log`, and it has no index behind path-scoped queries. Every walk here takes an explicit limit, checks context.Context cancellation between commits, and bounds rename detection.

Measured on a synthetic 500-commit, 200-file repository (see bench_test.go; Apple M-series, go-git v5.19.2, ns/op converted to ms):

Open                          1 ms
Info (includes worktree scan) 15 ms
ChangedSince HEAD~1..HEAD     17 ms
ChangedSince HEAD~200..HEAD   93 ms
RecentCommitsMeta(50)         16 ms
RecentCommits(50) with paths  733 ms
RecentCommits(500) with paths 7.5 s
FileLastModified, recent file 3 ms
FileLastModified, absent path 635 ms   (full 500-commit walk)
go-git Blame, one file        2.0 s    — not exposed; see BenchmarkGoGitBlame

The single number that governs everything is the tree diff: roughly 8–17 ms per commit pair on a 200-file tree, and it is CPU-bound in go-git's tree decoding rather than I/O-bound — repacking the repository changes it by less than 10%. That is why RecentCommitsMeta exists (~50x cheaper than RecentCommits) and why callers that need per-commit paths for more than a few dozen commits should persist them rather than recompute them.

Blame is deliberately absent. Two seconds for one file on a 500-commit repository is not a per-file cost an indexer can pay, and it grows with history; the benchmark stays in the tree as the evidence, so the decision can be revisited against measurements rather than impressions.

Paths

Every path returned by this package is repo-relative and forward-slashed on every platform, matching model.File.Path. Callers may use returned paths as database keys directly.

Index

Constants

View Source
const MaxHistoryScan = 4096

MaxHistoryScan bounds path-scoped history searches. Without it, FileLastModified on a path that was never committed walks the entire history — the exact O(history) trap this package exists to avoid.

View Source
const MaxRecentCommits = 5000

MaxRecentCommits is the safety ceiling on a commit walk so unbounded caller arguments cannot exhaust memory or pin the CPU for minutes.

Variables

View Source
var (
	// ErrNotRepository is returned by the history and diff methods when the
	// Repo was opened on a directory that is not under git control. Info does
	// not return it — it reports IsRepo=false instead, because "is this a
	// repository?" is a question, not a failure.
	ErrNotRepository = errors.New("git: path is not a repository")

	// ErrUnboundedWalk is returned when a commit walk is requested without a
	// positive limit. Refusing is deliberate: an accidental unbounded walk on a
	// kernel-sized repository takes minutes, and a hang is a worse bug than a
	// loud error.
	ErrUnboundedWalk = errors.New("git: commit walk requires a positive limit")

	// ErrNoHistory means the reachable history was exhausted without finding
	// any commit that touched the requested path.
	ErrNoHistory = errors.New("git: no commit in history touched this path")

	// ErrScanLimit means the search stopped at MaxHistoryScan commits without
	// an answer. Distinct from ErrNoHistory on purpose: this one says "we gave
	// up", not "it isn't there", and callers may reasonably treat it as unknown
	// rather than as absent.
	ErrScanLimit = errors.New("git: history scan limit reached without a match")

	// ErrShallowHistory reports that an answer needs a commit this shallow
	// clone never fetched. FileLastModified returns it when the walk reached
	// the clone's boundary without finding a change to the path, and revision
	// resolution wraps it when a revision such as HEAD~20 names a commit older
	// than the boundary. The message carries the remedy because it reaches
	// the user unchanged.
	ErrShallowHistory = errors.New("git: this is a shallow clone and the commit needed is older than " +
		"the history that was fetched (run `git fetch --unshallow`, or fetch with a larger --depth)")
)

Sentinel errors. They are values, not message text: callers use errors.Is, never string matching. See the package comment on why "not a repository" is reported through Info.IsRepo rather than through one of these.

Functions

func ReachedShallowBoundary

func ReachedShallowBoundary(commits []Commit) bool

ReachedShallowBoundary reports whether a walk ran into a shallow clone's boundary: older commits exist upstream and were not available to read.

It is false for a shallow clone whose boundary lies beyond the walk's limit. That walk was cut by the limit, and the caller already says so.

Types

type Change

type Change struct {
	// Path is the path after the change. For ChangeDeleted it is the path the
	// file had when it was removed, so Path is never empty.
	Path string `json:"path"`

	// OldPath is set only for ChangeRenamed, and holds the pre-rename path.
	OldPath string `json:"old_path,omitempty"`

	Kind ChangeKind `json:"kind"`
}

Change is one path's fate between two revisions.

type ChangeKind

type ChangeKind string

ChangeKind classifies what happened to a path between two revisions.

const (
	ChangeAdded    ChangeKind = "added"
	ChangeModified ChangeKind = "modified"
	ChangeDeleted  ChangeKind = "deleted"

	// ChangeRenamed carries both names. The indexer relies on this to *move*
	// a file's symbols and their inbound edges; treating a rename as
	// delete+add would discard every edge pointing into that file and rebuild
	// them at lower confidence.
	ChangeRenamed ChangeKind = "renamed"
)

type Commit

type Commit struct {
	SHA         string `json:"sha"`
	AuthorName  string `json:"author_name"`
	AuthorEmail string `json:"author_email"`

	// When is the author timestamp in Unix seconds. Author time, not commit
	// time, because rebases and cherry-picks rewrite commit time and would make
	// untouched code look freshly changed to the recency ranker.
	When int64 `json:"when"`

	// Subject is the first line of the message, trimmed.
	Subject string `json:"subject"`

	// Constraints holds high-entropy defensive phrases extracted from commit
	// bodies (e.g. "FIX: race in pool", "WORKAROUND: issue #123", "DO NOT REMOVE").
	Constraints []string `json:"constraints,omitempty"`

	// Paths are the repo-relative paths this commit touched, sorted. Populated
	// by RecentCommits and left nil by RecentCommitsMeta. Also nil for a
	// commit at a shallow clone's boundary whose first parent was never
	// fetched: what it changed cannot be computed without that parent, and
	// reporting every file in its tree as "changed here" (which is what
	// treating it as a root commit does) would credit one author with the
	// whole repository.
	Paths []string `json:"paths,omitempty"`

	// ShallowBoundary marks a commit at the edge of a shallow clone
	// (`git clone --depth`): at least one of its parents was never fetched, so
	// the walk could not continue past it. A walk that returns such a commit
	// is truncated by the clone, not by its limit and not by the repository's
	// first commit, and nothing drawn from it may be described as the whole
	// history. See ReachedShallowBoundary.
	ShallowBoundary bool `json:"shallow_boundary,omitempty"`

	// Merge marks a commit with more than one parent. Its Paths are the diff
	// against the first parent, so they repeat the changes of the commits the
	// merge brought in, which the walk also returns. A count of how often a
	// file changed must skip merges, as `git log --name-only` does, or each
	// merged change is counted twice.
	Merge bool `json:"merge,omitempty"`
}

Commit is one commit, reduced to what the indexer consumes.

The full message body is deliberately absent: the context engine ranks and displays subjects, and carrying bodies through the graph would spend agent context on prose nobody reads.

type FileRevision

type FileRevision struct {
	SHA  string `json:"sha"`
	When int64  `json:"when"` // author timestamp, Unix seconds
}

FileRevision identifies the commit that last changed a path.

type Info

type Info struct {
	// IsRepo is false when the opened path is not under git control. All other
	// fields are then zero. This is a supported, non-error state.
	IsRepo bool `json:"is_repo"`

	// Root is the absolute path of the worktree root (or of the opened
	// directory when IsRepo is false). Returned paths are relative to it.
	Root string `json:"root"`

	// HeadSHA is the full 40-character revision of HEAD, or "" in a repository
	// with no commits yet.
	HeadSHA string `json:"head_sha"`

	// Branch is the current branch name, or "" when HEAD is detached. A
	// freshly-initialised repository with no commits still reports its branch,
	// because HEAD is a symbolic ref before it is a hash.
	Branch string `json:"branch"`

	// Detached reports that HEAD points straight at a commit. Distinguishing
	// this from an empty repository matters: both have Branch=="", but only one
	// has a HeadSHA.
	Detached bool `json:"detached"`

	// Dirty reports uncommitted changes anywhere in the worktree or index.
	// An index stamped with a dirty revision does not describe that revision,
	// so this must be recorded alongside HeadSHA, not inferred from it.
	Dirty bool `json:"dirty"`
}

Info is the summary of a repository's current state. It is cheap to describe and moderately expensive to compute: Dirty requires a full worktree status walk. See BenchmarkInfo.

type Repo

type Repo struct {
	// contains filtered or unexported fields
}

Repo is a handle on a repository (or on a directory that turned out not to be one). It is safe for concurrent reads; go-git's object storer is read-only here and none of these methods mutate the repository.

func Open

func Open(path string) (*Repo, error)

Open opens the repository containing path.

A directory that is not under git control is not an error: the returned Repo reports IsRepo()==false and Info returns IsRepo=false with a nil error. Only genuine failures (unreadable path, corrupt repository) produce an error.

Parent directories are searched for .git, matching what the git CLI does, so opening a subdirectory of a checkout yields the enclosing repository. Use Root to learn which repository was actually found.

func (*Repo) ChangedSince

func (r *Repo) ChangedSince(ctx context.Context, from, to string) (out []Change, err error)

ChangedSince reports the paths that differ between two revisions.

Both arguments accept anything `git rev-parse` would: a full or abbreviated SHA, a branch or tag name, HEAD, HEAD~3.

The empty string means different things on each side, and deliberately so:

from == ""  the empty tree — every file at `to` is reported as added. This
            is what a first-ever index run asks for.
to   == ""  HEAD. This is what "what changed since the last indexed
            revision?" asks for.

Rename detection is on, bounded by renameLimit. Results are sorted by Path.

func (*Repo) Degraded

func (r *Repo) Degraded() string

Degraded reports why full git support is unavailable, or "" when it is not.

Callers should surface this. A repository GraphLume cannot fully open still indexes — the code is on disk either way — but it loses history, and losing a feature silently is how a user ends up trusting an answer the tool never computed.

func (*Repo) FileLastModified

func (r *Repo) FileLastModified(ctx context.Context, path string) (rev FileRevision, err error)

FileLastModified reports the newest commit that changed the given path, walking back from HEAD.

This is the recency signal behind context ranking. It is path-scoped, not content-scoped: like `git log -- <path>` without --follow, a rename ends the trail at the commit that performed it. Following renames would require a full similarity diff at every commit, which is not affordable here.

A commit that deleted the path counts as having changed it, so callers asking about a removed file get the deletion rather than ErrNoHistory.

The walk stops after MaxHistoryScan commits and returns ErrScanLimit. That bound exists because go-git has no path index: asking about a path that was never committed would otherwise read every commit in the repository.

In a shallow clone, a path that did not change inside the fetched history returns ErrShallowHistory: its last change is in a commit that is not here.

func (*Repo) HeadSHA

func (r *Repo) HeadSHA(ctx context.Context) (string, error)

HeadSHA resolves HEAD without the worktree status scan Info performs.

Info's cost is dominated by Dirty, which requires a full worktree walk (~15ms on a synthetic 200-file repo — see the package benchmark comment). Callers that only need the commit HEAD points at, such as a live freshness comparison run on every request, should use this instead: it costs one ref read, not a tree walk.

Returns "" (not an error) for a non-repository or a repository with no commits yet — the same "unknown, not a failure" contract Info uses.

func (*Repo) HistoryAvailable

func (r *Repo) HistoryAvailable() bool

HistoryAvailable reports whether commit history can be read at all.

func (*Repo) HistorySource

func (r *Repo) HistorySource() string

HistorySource says how history is read: "go-git", "git binary" or "".

func (*Repo) Info

func (r *Repo) Info(ctx context.Context) (Info, error)

Info reports HEAD, branch and cleanliness.

It never returns ErrNotRepository; a non-repository yields Info{IsRepo:false} and a nil error, because callers must be able to keep working on plain directories without special-casing an error.

func (*Repo) IsRepo

func (r *Repo) IsRepo() bool

IsRepo reports whether the opened path is under git control.

func (*Repo) RecentCommits

func (r *Repo) RecentCommits(ctx context.Context, limit int) ([]Commit, error)

RecentCommits walks back from HEAD and returns at most limit commits, newest first, each with the paths it touched.

limit must be positive; see ErrUnboundedWalk. A repository with no commits returns an empty slice and a nil error, because that is the state `graphlume init` finds on a fresh project.

A shallow clone is read up to its boundary and no further. The commits at the boundary are returned with ShallowBoundary set, and the walk ends there without an error: CI checkouts are shallow by default, so "the history stops here because it was never fetched" is an ordinary answer, not a failure. Use ReachedShallowBoundary before describing the result as a whole history.

Filling Paths costs one tree diff per commit and still dominates this call, but by a factor rather than by three orders of magnitude: on a 767-commit repository, 200 commits take 184 ms with paths against 98 ms without. Without pooled packfile reads it takes 10.4 s, for the reason objectview.go documents. Use RecentCommitsMeta when only recency and authorship are needed, and persist the paths rather than recomputing them for the same commits.

Those figures hold for a repository with a handful of packfiles. On one with a hundred or more (a large, never-repacked monorepo) go-git took 19 s for 50 commits and 46 s for 200, while `git log --name-only` read 500 in under 2 s; so the walk uses the git binary whenever one is on PATH (see walkViaBinary). The result is also remembered per HEAD on this Repo, so a server answering several questions about one revision walks once.

func (*Repo) RecentCommitsMeta

func (r *Repo) RecentCommitsMeta(ctx context.Context, limit int) ([]Commit, error)

RecentCommitsMeta is RecentCommits without the per-commit tree diff. Paths is nil on every returned Commit.

func (*Repo) RecentCommitsWithin

func (r *Repo) RecentCommitsWithin(ctx context.Context, limit int, opts WalkOptions) (commits []Commit, complete bool, err error)

RecentCommitsWithin is RecentCommits under WalkOptions. complete is false only when the budget ran out before limit commits were read and before the history ended: the commits returned are then the newest part of the window, in order, and a later call with Skip=len(commits) reads the rest.

A walk from HEAD (Skip zero) is answered from, and when complete kept in, the Repo's per-HEAD memo; see walkMemo.

func (*Repo) ResolveRevision

func (r *Repo) ResolveRevision(ctx context.Context, rev string) (string, error)

ResolveRevision turns anything `git rev-parse` accepts into a full commit SHA.

It exists so a caller can decide whether two revision NAMES designate the same commit. Comparing the strings cannot answer that: "HEAD", "main" and "9685bd8" are routinely the same commit and never the same string, and a staleness check built on string equality would either warn on every correct index or, worse, miss a genuinely unrelated one.

An empty revision resolves to "" with a nil error, matching ChangedSince's convention that the empty string is a position (the empty tree) rather than a name. A revision that does not resolve is an error, not "": not knowing and knowing-it-is-nothing are different answers, and only the caller can decide what to do about the first.

func (*Repo) Root

func (r *Repo) Root() string

Root is the absolute worktree root, or the opened directory when !IsRepo.

func (*Repo) Shallow

func (r *Repo) Shallow() bool

Shallow reports whether the repository was cloned with truncated history (`git clone --depth`, which is what most CI checkouts do).

A history walk cannot tell this from the commits it returns: a shallow clone's oldest commit looks exactly like a repository's first one. Anything that draws a conclusion from how much history exists has to ask, or it reports "the whole history is three commits" for a repository with ten thousand.

False for a directory that is not a repository, and false when the answer cannot be read: "not known to be shallow" is the only safe default, since the callers use true to add a warning.

func (*Repo) Status

func (r *Repo) Status(ctx context.Context) (WorktreeStatus, error)

Status reports the current worktree and index state.

All slices are sorted so that callers producing digests or diffs of the result get stable output.

type WalkOptions

type WalkOptions struct {
	// Skip passes over this many commits, newest first, before collecting any.
	// The order is the walk's own, so Skip=len(previous) continues a walk that
	// an earlier call stopped short, without diffing its commits again.
	Skip int

	// Budget is the wall-clock time the walk may spend. When it runs out the
	// commits read so far are returned with complete=false, rather than the
	// caller's deadline expiring with nothing to show for it. Zero means no
	// budget beyond the context.
	Budget time.Duration
}

WalkOptions bounds and positions a commit walk with paths. The zero value is RecentCommits: from HEAD, without a time budget.

type WorktreeStatus

type WorktreeStatus struct {
	// Modified are tracked files whose worktree content differs from the index.
	Modified []string `json:"modified"`
	// Staged are files whose index entry differs from HEAD.
	Staged []string `json:"staged"`
	// Untracked are files present on disk and unknown to git, after applying
	// .gitignore.
	Untracked []string `json:"untracked"`
	// Deleted are tracked files missing from the worktree. Listed separately
	// because the indexer must drop their symbols rather than re-read them.
	Deleted []string `json:"deleted"`
}

WorktreeStatus is the set of paths that differ from the committed tree, grouped by where the difference lives.

The groups overlap by design: a file staged and then edited again appears in both Staged and Modified, which is exactly what git reports and what the indexer needs in order to decide what to re-read from disk.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL