Documentation
¶
Overview ¶
Package gitread is the read-side git plumbing layer for the /api/v1 git:read endpoints (docs/reference/http-api.md): ref resolution, ls-tree, log, diff, blame, grep, and tar.gz archive streaming over a hydrated bare cache repo.
FROZEN CONTRACT: the exported types and function signatures are the shared surface the phase-3 endpoint slices build on. gitread stays HTTP-agnostic (no status codes, no wire envelopes): handlers own parameter validation, cursoring, and response shaping. All plumbing is `os/exec git` over a repoPath produced by Materialize — consistent with the rest of the repo, no go-git.
Error mapping: ErrNotFound (wrapped) marks "the requested ref/object/path does not exist" outcomes that handlers turn into 404; every other error is internal (500).
Index ¶
- Constants
- Variables
- func Archive(ctx context.Context, repoPath, commit string, opts ArchiveOptions, w io.Writer) error
- func CatBlobTo(ctx context.Context, repoPath, sha string, w io.Writer) error
- func CheckBlobSize(ctx context.Context, path string, size int64) error
- func CheckSymlinkTarget(path string, size int64) error
- func CommitsBySHA(ctx context.Context, repoPath string, shas []string) (map[string]Commit, error)
- func Diff(ctx context.Context, repoPath, base, target string, opts DiffOptions) ([]FileDiff, DiffStats, error)
- func HeapLimitSupported() bool
- func IsBudgetError(err error) bool
- func LastCommits(ctx context.Context, repoPath, rev string, paths []string, maxDistinct int) ([]string, map[string]int, error)
- func LimitPath(err error) (path string, ok bool)
- func MatchGlob(pattern, p string) bool
- func Materialize(ctx context.Context, st ref.RefStore, bl blob.BlobStore, ...) (string, error)
- func Note(ctx context.Context, repoPath, notesRef, sha string) (string, error)
- func ReadSymlinkTarget(ctx context.Context, repoPath, sha string, size int64) (string, error)
- func ResolveRef(ctx context.Context, repoPath, spec string, ephemeral bool) (string, error)
- func Run(ctx context.Context, c Cmd) (string, error)
- func ValidArchivePrefix(prefix string) bool
- func WithBudget(ctx context.Context, b *Budget) context.Context
- type ArchiveOptions
- type BlameLine
- type BlobInfo
- type Budget
- type Class
- type Cmd
- type Commit
- type CommitDetail
- type DiffOptions
- type DiffStats
- type FileDiff
- type GitError
- type GrepFile
- type GrepLine
- type GrepOptions
- type Limits
- type LogOptions
- type PreparedArchive
- type Slots
- type Tag
- type TreeEntry
Constants ¶
const ( // HeavyHeapBytes caps the heap (RLIMIT_DATA, Linux) of a child whose // work grows with history length, tree size, blob size, or output size. // Measured peak VmData on a 300,000-commit linear history (git 2.55): // `log -1 -- <file from the root commit>` 184 MB, `blame` of that file // 126 MB, `merge-base <tip> <root>` 130 MB, `log --skip=299990` 75 MB. // So a 300k history fits; histories past roughly 400k commits can fail // the per-file walks. Read-only pack mappings are shared page cache and // are not counted. HeavyHeapBytes = gitlimit.HeavyHeapBytes // LightHeapBytes caps a child whose work is bounded by one object: // ref resolution and single-commit reads. A commit object larger than // this cannot be read through the API. LightHeapBytes int64 = 32 << 20 // DefaultOutputBytes is the buffered-stdout allowance of one request (a // Budget), shared by all of its children. Streaming children (CatBlobTo // into a caller's writer) are not counted; they never buffer in memory. DefaultOutputBytes int64 = 64 << 20 // MaxBlobBytes is the largest blob the API streams (file, archive). // git reads a blob below core.bigFileThreshold (512 MiB) fully into its // heap, and a deltified blob also needs its base, so larger blobs would // hit HeavyHeapBytes part-way; callers check sizes up front instead. MaxBlobBytes int64 = 100 << 20 )
Resource bounds for read-side git children (#313). Every git child that gitread starts runs through run, which applies them before git does any work. docs/reference/http-api.md ("Resource limits on git reads") is the client-facing description and ADR-049 the design; keep them in step.
const ( GrepLineMatch = "match" GrepLineContext = "context" )
Grep line types (docs/reference/http-api.md POST /repos/grep lines[].type).
const ( EntryBlob = "blob" EntryTree = "tree" EntrySymlink = "symlink" EntrySubmodule = "submodule" )
TreeEntry types (docs/reference/http-api.md GET /repos/files entry `type`): symlinks and submodules are surfaced distinctly from plain blobs/trees.
const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
EmptyTreeSHA is git's well-known empty tree object id (SHA-1 repos): the diff base for root commits (`git hash-object -t tree /dev/null`).
const MaxSymlinkTarget = 4095
MaxSymlinkTarget is the longest symlink target an archive carries: 4095 bytes, the longest that symlink(2) accepts on Linux (PATH_MAX is 4096, with the terminating NUL). XFS and macOS accept at most 1023. git 2.55's fsck has no check for the length of a target, so a repository can hold a longer one. The server reads a target in memory to write its tar header.
Variables ¶
var ( // ErrBusy: no admission slot freed up in time; git was not started. ErrBusy = gitlimit.ErrBusy // ErrTimeBudget: the request's git time budget ran out; the running // child (if any) was killed and reaped. ErrTimeBudget = errors.New("git reads exceeded the request time budget") // ErrOutputLimit: git's buffered output exceeded the request's // allowance; git was killed and reaped as soon as that happened. ErrOutputLimit = errors.New("git output exceeded the request output budget") // ErrBlobTooLarge: a blob is larger than MaxBlobBytes; git was not // started for it. ErrBlobTooLarge = errors.New("blob exceeds the API read size limit") // ErrSymlinkTooLong: a symlink's target is longer than MaxSymlinkTarget. // The size that the tree lists is checked before git starts. A blob // that git prints longer than listed (a broken object store: git reads // no replacement objects) ends git at the first byte over the limit. ErrSymlinkTooLong = errors.New("symlink target exceeds the API read size limit") // ErrMemoryLimit: git needed more heap than its class's cap and was // stopped by its own allocation failure (Linux only). ErrMemoryLimit = gitlimit.ErrMemoryLimit // ErrStop may be returned by a streaming Cmd.Stdout's Write to end git // early (a history walk that has seen enough): Run then kills and reaps // git and returns no error. ErrStop = errors.New("stop streaming git output") )
var ErrBadPattern = errors.New("grep pattern is not a valid regex")
ErrBadPattern: git grep could not compile the request's pattern.
var ErrBadRange = errors.New("blame range does not fit the file")
ErrBadRange: git blame refused a -L range of the request (bad syntax, past the end of the file, no match).
var ErrNotFound = errors.New("not found")
ErrNotFound marks a missing ref, object, or path (handlers map it to 404 per docs/reference/http-api.md, e.g. unknown branch and unborn-branch reads).
var ErrTooManyLastCommits = errors.New("too many distinct last commits")
ErrTooManyLastCommits reports that the files passed to LastCommits have more distinct last commits than its limit. It is not a budget error: the same request fails the same way every time.
var ErrUnsortedTree = errors.New("ls-tree listed entries out of order")
ErrUnsortedTree: git listed a tree's entries out of byte order (a tree that fsck rejects as treeNotSorted), so LsTreePage cannot page it.
Functions ¶
func Archive ¶
Archive is PrepareArchive + Stream in one call, for callers that do not need the resolve-before-stream split.
func CatBlobTo ¶
CatBlobTo streams the raw bytes of blob sha into w without buffering the whole blob in memory (file/archive streaming path). git itself runs as a Heavy child: a blob it must inflate or rebuild from deltas in its heap can hit HeavyHeapBytes, so callers check CheckBlobSize first.
func CheckBlobSize ¶
CheckBlobSize fails with ErrBlobTooLarge when a blob of size bytes is over the blob limit (MaxBlobBytes, or the Budget's in ctx). Streaming callers check before they start git or send response headers.
func CheckSymlinkTarget ¶ added in v0.20.0
CheckSymlinkTarget fails with ErrSymlinkTooLong when the target of the symlink at path, a blob of size bytes, is longer than MaxSymlinkTarget.
func CommitsBySHA ¶ added in v0.19.0
CommitsBySHA loads the given commits (resolved full SHAs, duplicates allowed) with one `git log --no-walk --stdin` child, keyed by SHA, with Subject set and Message empty (as LogOptions.SubjectOnly). It is Heavy: the output grows with the number of commits.
func Diff ¶
func Diff(ctx context.Context, repoPath, base, target string, opts DiffOptions) ([]FileDiff, DiffStats, error)
Diff computes the tree diff base..target (both resolved full SHAs; pass EmptyTreeSHA as base for root commits). Rename/copy detection is always on (-M) so renames surface as one R entry with OldPath, matching the docs/reference/http-api.md FileDiff shape.
func HeapLimitSupported ¶
func HeapLimitSupported() bool
HeapLimitSupported reports whether Run can cap a git child's heap on this platform (Linux: RLIMIT_DATA). Outside Linux, Run runs git without a heap cap, under the admission, time, and output limits only (ADR-049); it never refuses a read because the cap is unavailable.
func IsBudgetError ¶
IsBudgetError reports whether err is a resource-limit outcome (ErrBusy, ErrTimeBudget, ErrOutputLimit, ErrBlobTooLarge, ErrSymlinkTooLong, ErrMemoryLimit). Callers that turn git failures into "not found" or "no match" must check it first so a limit is never reported as missing data.
func LastCommits ¶ added in v0.19.0
func LastCommits(ctx context.Context, repoPath, rev string, paths []string, maxDistinct int) ([]string, map[string]int, error)
LastCommits returns, for every path in paths (entries of rev's tree), the commit that `git log -1 rev -- <path>` names, with literal pathspecs, in the order of paths (a slice, not a map: a listing can hold hundreds of thousands of paths). One difference: a submodule's `ignore` setting in .gitmodules never hides a gitlink change. It also returns the rank of each of those commits: its 0-based position in `git rev-list --topo-order rev` (files/metadata `order`). It fails with ErrTooManyLastCommits as soon as more than maxDistinct distinct commits are found.
One walk replaces a `git log -1` per path. `rev-list --topo-order --parents rev` is spooled to a temporary file and read one line, so one commit, at a time; the line number is the rank (--parents does not change the order). Each path waits at one commit, starting at rev, and moves the way git's default history simplification moves for that path alone. Topological order puts every commit before its parents, so a commit has collected every path waiting on it when its line is read. The walk asks one `diff-tree --stdin` child for the diff of such a commit against each parent in turn (first diffs are sent ahead within a window, see walk). The paths a diff leaves unchanged go to that parent (git follows the first TREESAME parent); the paths it changes stay for the next parent's diff. A root commit, or a commit whose diff against every parent changes the path, is the answer. So a commit that no path waits on is diffed only when the walk sent it ahead, against its first parent, and a merge's later parents are not diffed once no path is left: on a history with many merges, the diffs against second parents are most of the work (#576). The walk stops once every path has its commit.
Both children are Heavy and run under the request's budget (see Run).
func LimitPath ¶ added in v0.20.0
LimitPath returns the path that the CheckBlobSize or CheckSymlinkTarget call behind err was given. ok is false when err came from neither.
func MatchGlob ¶
MatchGlob matches a slash-separated path against one glob pattern:
- a pattern without "/" matches against the path's base name ("*.md" matches docs/x.md), gitignore-style;
- a pattern with "/" matches against the full path, segment by segment with path.Match semantics, where a "**" segment matches any number of segments (including zero).
Malformed patterns match nothing.
func Materialize ¶
func Materialize(ctx context.Context, st ref.RefStore, bl blob.BlobStore, cacheDir, repo, defaultBranch string) (string, error)
Materialize rebuilds the cache repo for repo from the ref/blob stores (githttp.Hydrate: ensure repo, hydrate packs, sync refs from the DB authority, point HEAD at defaultBranch) and returns its bare-repo path. Unlike the receive path, a ref-sync failure is fatal here: read plumbing over stale refs would serve wrong answers.
func Note ¶
Note reads the git note attached to object sha from notesRef in the repo at repoPath. Callers validate inputs: sha must be a full object id (ref.ValidSHA) and notesRef a refs/notes/ ref, so neither can smuggle options or rev expressions into git. A missing note wraps ErrNotFound — `git notes show` exits 1 for an unborn notes ref, an unknown object, and an object without a note alike (anything else is internal).
func ReadSymlinkTarget ¶ added in v0.20.0
ReadSymlinkTarget returns the target of the symlink whose blob is sha, size bytes long as the tree lists it. A target over MaxSymlinkTarget fails with ErrSymlinkTooLong. A listed size over the limit fails before git starts. A blob that git prints longer than it was listed (a broken object store: git reads no replacement objects) ends git after MaxSymlinkTarget+1 bytes, so the read holds at most 4 KiB whatever the blob is; file streaming goes through CatBlobTo. The target does not count against the output allowance, which the bound replaces.
func ResolveRef ¶
ResolveRef resolves a request ref to a full commit SHA in the repo at repoPath (docs/explanation/wire-compatibility.md, the revision row). The name candidates exclude each other:
- ephemeral: only the ephemeral namespace name (auth.EphemeralRefName)
- full ref: else <spec> verbatim when it starts with "refs/"
- else: refs/heads/<spec>, then refs/tags/<spec> (annotated tags peel to their commit)
Every case then tries a hex object name: a short or full SHA (no rev expressions; a full SHA may be uppercase, an abbreviation must be lowercase).
Everything unresolvable wraps ErrNotFound — including the empty spec and the unborn-branch case, where the DB knows no such ref yet (invariant 3: handlers map it to 404). Only git's own negative answer counts as unresolvable (gitSaidNo); any other git failure is returned as is. An existing ref, or an object, whose way to a commit git cannot read (a missing object, a broken tag) is an error too (resolveCommitObject).
func Run ¶
Run starts one read-side git child under the limits above and waits for it (git is always reaped before Run returns). Limit outcomes are returned as ErrBusy, ErrTimeBudget, ErrOutputLimit, or ErrMemoryLimit, and never wrap *exec.ExitError, so exit-status checks cannot mistake them for git's own "no match" or "not found" statuses. A ctx that ends (the caller gave up) returns ctx's error, also when git was killed for it. Other failures are a *GitError (see there).
func ValidArchivePrefix ¶
ValidArchivePrefix reports whether prefix is safe to prepend to tar entry names: no NUL bytes, no backslashes (Windows extractors treat them as separators), not absolute, and no "." or ".." segments — so extracted entries cannot escape the destination root (tar slip).
Types ¶
type ArchiveOptions ¶
type ArchiveOptions struct {
// Prefix is prepended verbatim to every entry name (callers include the
// trailing "/", e.g. "repo-main/"). It must satisfy ValidArchivePrefix;
// callers accepting untrusted input must validate it first.
Prefix string
// IncludeGlobs whitelists paths when non-empty; ExcludeGlobs always
// wins. See MatchGlob for the dialect.
IncludeGlobs []string
ExcludeGlobs []string
// MaxBlobSize (>0) skips file blobs larger than this many bytes —
// the reason this is a custom walk instead of `git archive`.
MaxBlobSize int64
}
ArchiveOptions tune one Archive stream. The zero value archives the whole tree with no prefix.
type BlameLine ¶
type BlameLine struct {
LineNumber int // 1-based line number in the file at the blamed commit
CommitSHA string // commit that introduced the line
OriginalLineNumber int // line number in CommitSHA's version of the file
OriginalPath string // path in CommitSHA (differs across renames)
PreviousCommitSHA string // CommitSHA's parent per blame ("" for root/boundary)
AuthorName string
AuthorEmail string
AuthorTime time.Time
CommitterName string
CommitterEmail string
CommitterTime time.Time
Summary string // commit subject line
}
BlameLine is one attributed line (docs/reference/http-api.md GET /repos/blame line objects).
func Blame ¶
func Blame(ctx context.Context, repoPath, commit, path string, ranges []string, detectMoves bool) ([]BlameLine, error)
Blame attributes every line of path at commit (a resolved full SHA). ranges are raw `git blame -L` specs (docs/reference/http-api.md: repeatable `range` params like "1,10" — the handler validates their shape); detectMoves adds -M. A path absent at commit wraps ErrNotFound.
type BlobInfo ¶
type BlobInfo struct {
SHA string // blob object id
Size int64 // bytes
Mode string // git octal mode string
Symlink bool // mode 120000: content is the link target
LastCommit Commit // most recent commit touching the path, reachable from commit
}
BlobInfo locates one blob at commit:path plus the last commit that touched the path — the /repos/file streaming metadata (X-Blob-Sha, X-Last-Commit-Sha, ETag, Last-Modified sources).
type Budget ¶
type Budget struct {
// contains filtered or unexported fields
}
Budget is one request's share of the read-side git limits. A handler middleware creates it, attaches it with WithBudget, and calls Close when the request has finished, including delivering its response. The request's first git child takes one admission slot, and the request keeps it until Close: the slot bounds everything the request retains (git children, buffered output, parsed results, spools), not just its git processes. Without a Budget in the context (write endpoints), Run applies none of these limits.
func BudgetFrom ¶
BudgetFrom returns the Budget attached to ctx, or nil.
func NewBudget ¶
NewBudget returns a request budget drawing admission from slots under key (the request's repository), with a git time budget of timeout (counted from the first child, so repository hydration before it is not included) and outputBytes of buffered output.
func (*Budget) Close ¶
func (b *Budget) Close()
Close ends the budget and releases its slot. Every child has been reaped by then (Run waits for git before returning).
func (*Budget) WithLimits ¶
WithLimits replaces the per-child caps (tests lower them). It returns b.
type Cmd ¶
type Cmd struct {
Class Class
Dir string // repository (or scratch) directory; required
Env []string // nil inherits the server's environment (see childEnv)
Stdin io.Reader // nil: no stdin
// Stdout, when set, receives git's output as it is produced and is not
// counted against the output allowance (streaming callers, such as a
// `rev-list` walk read incrementally). Its Write may return ErrStop to
// end git early. When nil, output is buffered, counted, and returned.
Stdout io.Writer
// Stderr, when set, also receives git's stderr, for a caller that must
// read git's messages when git exits 0.
Stderr io.Writer
Args []string
}
Cmd is one read-side git child for Run.
type Commit ¶
type Commit struct {
SHA string
TreeSHA string
ParentSHAs []string // empty (never nil) for root commits — invariant 2
AuthorName string
AuthorEmail string
AuthorDate time.Time
CommitterName string
CommitterEmail string
CommitterDate time.Time
Message string // full raw message (%B): subject + body, usually newline-terminated; "" under LogOptions.SubjectOnly
Subject string // subject line (%s), set only under LogOptions.SubjectOnly
}
Commit is one parsed commit — the docs/reference/http-api.md CommitInfo source data ({sha, parent_shas[], message, author_*, committer_*, date}).
type CommitDetail ¶
type CommitDetail struct {
Commit
Signature string // armored PGP/SSH signature; "" when unsigned
Payload string // exact signed bytes (raw commit minus the gpgsig header); "" when unsigned
}
CommitDetail is GET /repos/commit's payload: the commit plus, for signed commits only, the detached signature and the exact payload bytes it signs.
type DiffOptions ¶
type DiffOptions struct {
Paths []string // optional literal path filter (`-- :(literal)<path>...`, repeatable `path` params)
}
DiffOptions tune one Diff invocation. The zero value diffs the full trees.
type DiffStats ¶
type DiffStats struct {
Files int
Additions int
Deletions int
Changes int // Additions + Deletions
}
DiffStats aggregates a diff (docs/reference/http-api.md stats envelope). Binary files count toward Files but contribute 0 additions/deletions.
type FileDiff ¶
type FileDiff struct {
Path string // post-image path (the old path for deletions)
OldPath string // pre-image path for renames/copies; "" otherwise
Status string // "A", "M", "D", "R", "C", or "T"
Additions int // added lines; -1 for binary files (numstat "-")
Deletions int // deleted lines; -1 for binary files
Binary bool
// Patch is this file's slice of `git diff --patch` output, starting at
// its `diff --git` header line. Endpoint slices own the final `raw`
// formatting (hunks-only vs git-apply-compatible, docs/explanation/domain-model.md:93-95).
Patch string
}
FileDiff is one changed file between two trees. Status is git's raw status letter (A/M/D/R/C/T — docs/reference/http-api.md "state (raw letter)"); rename/copy similarity scores are stripped.
type GitError ¶ added in v0.20.0
type GitError struct {
Stderr string // git's stderr, trimmed
// contains filtered or unexported fields
}
GitError is Run's error for a git child that failed on its own (not a limit outcome or a canceled request). It wraps the error of the run: an *exec.ExitError when git exited with a status or died of a signal, or the error of a start that failed (exec refused the arguments). It keeps git's stderr. A caller that classifies a failure reads the exit status and Stderr, never the error text: that quotes the request's arguments.
type GrepFile ¶
GrepFile groups all matched/context lines of one file, ascending by line number (docs/reference/http-api.md matches[] entries).
func Grep ¶
Grep searches the tree at commit (a resolved full SHA). Binary blobs are skipped (-I). No matches is a successful empty result, not an error. Result limiting/pagination (docs/reference/http-api.md limits, incomplete_results) is the endpoint slice's job on top of this full result.
Match/context typing: `--null` (needed for unambiguous parsing of paths containing ':' or '-') erases git's ':' vs '-' delimiter distinction, so with context enabled Grep runs a second match-only pass and classifies every line by (path, line) membership in that match set.
type GrepOptions ¶
type GrepOptions struct {
Pattern string
CaseInsensitive bool // -i
Pathspecs []string // git pathspecs incl. :(glob)/:(exclude) magic; empty = whole tree
BeforeContext int // -B
AfterContext int // -A
}
GrepOptions tune one Grep invocation. Pattern is required (POSIX basic regex, git grep's default dialect).
type Limits ¶
type Limits struct {
HeavyHeap int64 // RLIMIT_DATA of Heavy children
LightHeap int64 // RLIMIT_DATA of Light children
MaxBlob int64 // CheckBlobSize limit
}
Limits are the per-child caps a Budget applies.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns HeavyHeapBytes, LightHeapBytes and MaxBlobBytes.
type LogOptions ¶
type LogOptions struct {
Path string // non-empty limits to commits touching Path (`-- :(literal)<path>`, no --follow)
Skip int // --skip offset (tip-anchored cursor pagination)
MaxCount int // >0 caps the returned commits (-n); 0 = unlimited
// SubjectOnly renders the subject line (%s: the first paragraph as one
// line) into Commit.Subject instead of the full message, so git prints
// no body.
SubjectOnly bool
}
LogOptions tune one Log invocation. The zero value lists the full history.
type PreparedArchive ¶
type PreparedArchive struct {
// contains filtered or unexported fields
}
PreparedArchive is a resolved, filtered archive plan. Everything that can fail without touching the output stream (commit lookup, tree walk, entry filtering) happens in PrepareArchive, so HTTP callers can commit response headers only after resolution succeeded and mid-stream failures are limited to blob streaming.
func PrepareArchive ¶
func PrepareArchive(ctx context.Context, repoPath, commit string, opts ArchiveOptions) (*PreparedArchive, error)
PrepareArchive resolves the tree at commit (a resolved full SHA) and applies the include/exclude globs and MaxBlobSize filters up front. A kept blob over the blob limit (CheckBlobSize) fails it with ErrBlobTooLarge, and a symlink whose target is over MaxSymlinkTarget fails it with ErrSymlinkTooLong, before any archive byte is written.
func (*PreparedArchive) Stream ¶
Stream writes the prepared entries as a tar.gz into w: regular blobs (mode 0644, or 0755 for git mode 100755) and symlinks (target = blob content); entry mtimes are the commit's committer time. Errors here can only truncate the stream — HTTP callers have already sent headers.
type Slots ¶
Slots is a process-wide pool of request admission slots. A request holds at most one slot, from its first git child until it ends (see Budget). One key (a repository) may hold at most perKey of them, so slow requests against one repository cannot take the whole pool from the others. It is gitlimit's pool type, shared with cache maintenance.
type Tag ¶
type Tag struct {
Name string // short tag name (refs/tags/ stripped)
SHA string // peeled commit sha
}
Tag is one refs/tags entry. SHA is the PEELED commit sha for annotated tags (invariant 10, docs/explanation/domain-model.md:78-80) and the target itself for lightweight tags.
func PeeledTags ¶
PeeledTags lists all tags of the repo at repoPath in lexical refname order (for-each-ref's default — the docs/reference/http-api.md GET /repos/tags order). Invariant 10 wants the peeled COMMIT sha, so tags that reference (or peel to) a non-commit object — trees or blobs, pushable with plain git — are skipped rather than surfaced with a non-commit sha.
type TreeEntry ¶
type TreeEntry struct {
Path string // full slash-separated path relative to the repo root
Mode string // git octal mode string, e.g. "100644", "100755", "120000"
Type string // EntryBlob | EntryTree | EntrySymlink | EntrySubmodule
SHA string // object id (blob sha for files — the X-Blob-Sha source)
Size int64 // blob size in bytes; -1 for trees and submodules
}
TreeEntry is one ls-tree row.
func LsTree ¶
func LsTree(ctx context.Context, repoPath, commit, path string, recursive bool) ([]TreeEntry, error)
LsTree lists the tree at commit (a resolved full SHA). path filters with git's `ls-tree <commit> -- <path>` semantics: "" lists the root, "dir/" lists a directory's contents, "dir" lists the entry itself. The path is literal: pathspec magic and wildcards match only their own name (#577). recursive descends into subtrees (blobs only, git -r semantics). A path that matches nothing yields an empty slice, NOT an error — the handler decides whether that is a 404.
func LsTreePage ¶ added in v0.19.0
func LsTreePage(ctx context.Context, repoPath, commit, path, after string, limit int) (page []TreeEntry, hasMore, found bool, err error)
LsTreePage returns one page of LsTree(ctx, repoPath, commit, path, true) sorted by Path: up to limit entries whose Path sorts after `after`, and whether more follow (#612). found reports whether path matched any entry.
Without a cursor it streams `ls-tree -r` and stops git one entry past the page, so its cost grows with the page. With a cursor it reads only the trees on the cursor's path and the ones after them (resumeTreePage, #615), so a deep cursor costs the folders it reads, each read whole, and not the listing before it. A tree that walk does not handle (see errDeclined), and a walk whose git fails, are paged by the stream, which reads the listing from its start up to the page.
git prints a recursive listing of a well-formed tree in byte order of the full paths. Only the page counts against the request's output allowance, and only once the page is complete, so a failed or refused page charges nothing. The stream returns ErrUnsortedTree for a listing out of order up to one entry past the page. An inversion after that is not read, so a tree stored out of order (fsck's treeNotSorted, which git's own path lookups do not handle either) can page in git's order. The walk reads no folder before the cursor, so nothing there fails a page that the walk answers: an inversion, a missing or unreadable object, or a tree nested past git's depth limit. A page left to the stream is read from the start and fails on them as before: with ErrUnsortedTree for an inversion, which the files handler answers by listing the tree sorted.