git

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package git is Githome's read access to the bare repositories on disk. M2 implements the read surface (refs, commits, trees, blobs, and path lookups) on a pure-Go go-git backend; writes and the smart-HTTP transport build on the same layout in later milestones. The on-disk layout is a sharded tree of bare repositories under a single root, addressed by the repository's internal pk.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRepoNotFound is returned when no bare repository exists on disk for
	// the requested handle.
	ErrRepoNotFound = errors.New("git: repository not found")

	// ErrObjectNotFound is returned when a ref, revision, or object id does not
	// resolve in the repository.
	ErrObjectNotFound = errors.New("git: object not found")

	// ErrEmptyRepository is returned by HEAD-dependent reads on a repository
	// that has no commits yet.
	ErrEmptyRepository = errors.New("git: repository is empty")

	// ErrPathNotFound is returned when a path does not exist at the given ref.
	ErrPathNotFound = errors.New("git: path not found")

	// ErrRefExists is returned by CreateRef when the reference already exists.
	ErrRefExists = errors.New("git: reference already exists")

	// ErrRefNotFound is returned when a named reference does not resolve.
	ErrRefNotFound = errors.New("git: reference not found")

	// ErrNotFastForward is returned by UpdateRef when a non-force update would
	// not be a fast-forward (the new commit is not a descendant of the old).
	ErrNotFastForward = errors.New("git: update is not a fast-forward")

	// ErrBlobTooLarge is returned when a blob's size exceeds the configured
	// ceiling, before its bytes are read into memory. Callers translate it into a
	// 403 too_large at the API edge, matching GitHub's contents and blob limits.
	ErrBlobTooLarge = errors.New("git: blob exceeds size limit")
)

The sentinel errors the git layer returns. Callers (the domain repo service) translate these into the right REST and GraphQL status: a missing repository or object is a 404, an empty repository yields an empty ref set rather than an error at the API edge.

Functions

This section is empty.

Types

type AnnotatedTag

type AnnotatedTag struct {
	SHA        SHA
	Tagger     Signature
	Message    string
	Target     SHA
	TargetType ObjectType
}

AnnotatedTag is the metadata of an annotated tag object.

type Blob

type Blob struct {
	SHA     SHA
	Size    int64
	Content []byte
}

Blob is a git blob with its raw content.

type Branch

type Branch struct {
	Name   string
	Commit SHA
}

Branch is a branch ref reduced to its name and head commit.

type Commit

type Commit struct {
	SHA       SHA
	Tree      SHA
	Parents   []SHA
	Author    Signature
	Committer Signature
	Message   string
}

Commit is the parsed git commit object behind the git/commits and commits endpoints.

type FileChange

type FileChange struct {
	Path      string
	PrevPath  string // set for a rename or copy
	Status    string
	Additions int
	Deletions int
	SHA       SHA
	Patch     string
}

FileChange is one file's diff between two commits, the shape the pull request files endpoint renders. Status is GitHub's vocabulary (added, removed, modified, renamed, copied, changed). SHA is the blob id of the new side, or the old side for a deletion. Patch is the unified hunk text for that file, empty for a binary file.

type LogOpts

type LogOpts struct {
	From SHA    // starting commit (required)
	Path string // when set, only commits touching this path
	Max  int    // cap on returned commits; zero means a sensible default
}

LogOpts controls a commit history walk.

type MergeMethod

type MergeMethod string

MergeMethod is one of GitHub's three ways to land a pull request.

const (
	MergeCommit MergeMethod = "merge"
	MergeSquash MergeMethod = "squash"
	MergeRebase MergeMethod = "rebase"
)

The merge strategies. merge writes a two-parent merge commit; squash collapses the head into one commit on the base; rebase replays the head's commits onto the base tip.

type ObjectType

type ObjectType string

ObjectType is a git object kind as it appears in the REST git-data models.

const (
	ObjectCommit ObjectType = "commit"
	ObjectTree   ObjectType = "tree"
	ObjectBlob   ObjectType = "blob"
	ObjectTag    ObjectType = "tag"
)

The git object kinds.

type PathEntry

type PathEntry struct {
	Name string
	Path string
	Type ObjectType // blob (file/symlink), tree (dir), commit (submodule)
	Mode string
	SHA  SHA
	Size int64
}

PathEntry is one item the contents lookup returns: a file, a directory, a symlink, or a submodule, with the metadata the Contents API renders.

type PathResult

type PathResult struct {
	IsDir bool
	Entry PathEntry   // the resolved path's own metadata (set for files)
	File  *Blob       // populated when !IsDir
	Dir   []PathEntry // populated when IsDir
}

PathResult is the result of resolving a path at a ref. Exactly one of File or Dir is populated: File for a blob (with Content), Dir for a tree listing.

type Ref

type Ref struct {
	Name   string
	Target SHA
	Type   ObjectType
}

Ref is a fully-qualified reference (refs/heads/main, refs/tags/v1.0). Target is the object the ref names directly: a commit for a branch or lightweight tag, or the tag object for an annotated tag. Type reports that object's kind.

type Repo

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

Repo is a single bare repository opened for reading.

func (*Repo) Blob

func (r *Repo) Blob(rev string) (Blob, error)

Blob loads a blob by any revision pointing at one (typically a blob sha).

func (*Repo) Branches

func (r *Repo) Branches() ([]Branch, error)

Branches lists the repository's branches in name order. An empty repository yields an empty slice, not an error.

func (*Repo) Commit

func (r *Repo) Commit(rev string) (Commit, error)

Commit loads a single commit by any revision.

func (*Repo) HEAD

func (r *Repo) HEAD() (Branch, error)

HEAD resolves the repository's default branch to its short name and head commit. It returns ErrEmptyRepository when the repository has no commits.

func (*Repo) Log

func (r *Repo) Log(opts LogOpts) ([]Commit, error)

Log walks commit history from opts.From, optionally filtered to a path.

func (*Repo) PathAt

func (r *Repo) PathAt(rev, path string) (PathResult, error)

PathAt resolves a path within the tree of rev. A blob yields a file result with content; a tree yields a directory listing. An empty path lists the root tree.

func (*Repo) RefByName

func (r *Repo) RefByName(name string) (Ref, error)

RefByName resolves a single reference. The name may be fully qualified (refs/heads/main) or carry just the suffix the REST API uses (heads/main, tags/v1.0).

func (*Repo) Refs

func (r *Repo) Refs() ([]Ref, error)

Refs lists every branch and tag ref fully qualified, in name order. The target is the object the ref names directly: a commit for branches and lightweight tags, the tag object for annotated tags.

func (*Repo) ResolveCommit

func (r *Repo) ResolveCommit(rev string) (SHA, error)

ResolveCommit resolves any revision (a sha, HEAD, a branch or tag name, or an expression like HEAD~2) to its commit sha.

func (*Repo) Tags

func (r *Repo) Tags() ([]Tag, error)

Tags lists the repository's tags in name order, peeling annotated tags to the commit they point at and carrying the tag object metadata alongside.

func (*Repo) Tree

func (r *Repo) Tree(rev string, recursive bool) (Tree, error)

Tree loads a tree by any revision (a tree sha, a commit, or a ref). When the revision names a commit it resolves to that commit's root tree. With recursive set it walks the whole subtree, stopping and reporting Truncated at the entry ceiling.

type SHA

type SHA = string

SHA is a 40-character lowercase hex object id. It is a string alias so call sites stay light while the type still documents intent.

type Signature

type Signature struct {
	Name  string
	Email string
	When  time.Time
}

Signature is the name, email, and timestamp of a commit or tag author.

type Store

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

Store resolves repository handles to bare repositories under a single root directory. Reads go through go-git; the ref-write and object-inspection operations (repo_write.go) shell out to the git binary, matching the locked design decision for the write path. It is safe for concurrent use: it holds only immutable configuration and opens a fresh handle per call.

func NewStore

func NewStore(dir string) *Store

NewStore builds a Store rooted at dir (typically config.RepoRoot()).

func (*Store) AheadBehind

func (s *Store) AheadBehind(ctx context.Context, pk int64, base, head SHA) (ahead, behind int, err error)

AheadBehind reports how far head is ahead of and behind base: ahead counts the commits in head not reachable from base, behind the commits in base not reachable from head. It is the comparison the pull request and the BEHIND merge state read.

func (*Store) ChangedFiles

func (s *Store) ChangedFiles(ctx context.Context, pk int64, base, head SHA) ([]FileChange, error)

ChangedFiles returns the per-file diff between base and head over the three-dot range, parsed from a single full-index patch so each file carries its status, blob id, line counts, and hunk text in one pass.

func (*Store) Close added in v0.1.1

func (s *Store) Close()

Close shuts down the long-lived cat-file processes the pool holds. The server calls it on shutdown so the helper processes do not outlive the store.

func (*Store) CommitsBetween

func (s *Store) CommitsBetween(ctx context.Context, pk int64, base, head SHA) ([]Commit, error)

CommitsBetween returns the commits in head that are not in base, oldest first, the list the pull request commits endpoint pages over. It is empty when head is an ancestor of base.

func (*Store) CreateRef

func (s *Store) CreateRef(ctx context.Context, pk int64, ref string, sha SHA) error

CreateRef creates ref pointing at sha, failing with ErrRefExists when the reference already exists and ErrObjectNotFound when sha is not in the repository. The all-zero old value makes the update-ref create-only.

func (*Store) DeleteRef

func (s *Store) DeleteRef(ctx context.Context, pk int64, ref string) error

DeleteRef removes ref. ErrRefNotFound is returned when it does not exist.

func (*Store) DiffRaw

func (s *Store) DiffRaw(ctx context.Context, pk int64, base, head SHA) ([]byte, error)

DiffRaw returns the unified diff between base and head over the three-dot range, the body the .diff media type serves and gh pr diff prints.

func (*Store) DiffStat

func (s *Store) DiffStat(ctx context.Context, pk int64, base, head SHA) (additions, deletions, changed int, err error)

DiffStat totals the additions, deletions, and changed file count between base and head over the three-dot range (merge base to head), matching the counts a pull request reports.

func (*Store) Dir

func (s *Store) Dir(pk int64) string

Dir returns the on-disk path of the bare repository for pk. Repositories are sharded by pk%256 to keep any single directory from holding the whole fleet: root/{pk%256}/{pk}.git.

func (*Store) FormatPatch

func (s *Store) FormatPatch(ctx context.Context, pk int64, base, head SHA) ([]byte, error)

FormatPatch returns the head's commits as an mbox patch series, the body the .patch media type serves. The range is base..head so only the pull request's own commits appear.

func (*Store) Init

func (s *Store) Init(pk int64) (*Repo, error)

Init creates an empty bare repository for pk and returns it. It is used by tests and, from M3, by repository creation. An existing repository is opened rather than reinitialized.

func (*Store) IsAncestor

func (s *Store) IsAncestor(ctx context.Context, pk int64, ancestor, descendant SHA) (bool, error)

IsAncestor reports whether ancestor is reachable from descendant, the fast-forward test git itself uses (merge-base --is-ancestor: exit 0 yes, exit 1 no, anything else a real error).

func (*Store) Merge

func (s *Store) Merge(ctx context.Context, pk int64, method MergeMethod, base, head SHA, message string, author, committer Signature) (sha SHA, ok bool, err error)

Merge lands head into base by the given method and returns the new tip commit. It writes only objects, never a ref, so the caller advances refs/heads/<base> to the returned commit under its own locking. ok is false when the strategy cannot apply cleanly (a conflicting test merge, or a rebase over a merge commit), in which case no objects matter and no ref should move.

func (*Store) MergeBase

func (s *Store) MergeBase(ctx context.Context, pk int64, a, b SHA) (sha SHA, ok bool, err error)

MergeBase returns the best common ancestor of a and b. ok is false when the two commits share no history, the case a cross-repository head with no merge base produces.

func (*Store) ObjectExists

func (s *Store) ObjectExists(ctx context.Context, pk int64, sha SHA) (bool, error)

ObjectExists reports whether the object id is present in the repository.

func (*Store) ObjectType

func (s *Store) ObjectType(ctx context.Context, pk int64, sha SHA) (string, error)

ObjectType returns the git type of the object ("commit", "tag", "tree", "blob"), or ErrObjectNotFound when it is absent. A reference's wire model reports the type of the object it points at.

func (*Store) Open

func (s *Store) Open(pk int64) (*Repo, error)

Open opens the bare repository for pk for reading. It returns ErrRepoNotFound when no repository exists at the resolved path.

func (*Store) RefSHA

func (s *Store) RefSHA(ctx context.Context, pk int64, ref string) (SHA, error)

RefSHA returns the object id the fully qualified reference points at, or ErrRefNotFound when it does not exist.

func (*Store) RefSnapshot

func (s *Store) RefSnapshot(ctx context.Context, pk int64) (map[string]SHA, error)

RefSnapshot returns every reference and its current object id, keyed by the fully qualified ref name. It backs the post-receive sink, which diffs the snapshot taken before a push against the one taken after to recover the ref-update batch. An empty repository yields an empty map.

func (*Store) SetGitBin

func (s *Store) SetGitBin(bin string)

SetGitBin overrides the git binary the write path execs. An empty value (the default) resolves "git" on PATH. The server sets this from configuration.

func (*Store) SetMaxBlobBytes added in v0.1.2

func (s *Store) SetMaxBlobBytes(n int64)

SetMaxBlobBytes overrides the blob size ceiling reads enforce. A positive value caps materialization at that many bytes; a negative value disables the cap; zero restores the built-in default. The server sets this from configuration.

func (*Store) TestMerge

func (s *Store) TestMerge(ctx context.Context, pk int64, base, head SHA) (tree SHA, clean bool, err error)

TestMerge performs a three-way merge of base and head in memory and reports whether it is conflict-free, writing the merged tree to the object store but touching no ref. clean is true when git produced a tree with no conflicts; tree is that merged tree's id. It is the heart of the mergeability worker.

func (*Store) UpdateRef

func (s *Store) UpdateRef(ctx context.Context, pk int64, ref string, sha SHA, force bool) error

UpdateRef moves an existing ref to sha. Unless force is set, the move must be a fast-forward: sha must be a descendant of the current target, otherwise ErrNotFastForward is returned and the ref is left untouched. ErrRefNotFound is returned when the ref does not exist and ErrObjectNotFound when sha is absent.

type Tag

type Tag struct {
	Name      string
	Commit    SHA
	Annotated *AnnotatedTag
}

Tag is a tag ref. Commit is the commit the tag ultimately points to. When the tag is annotated, Annotated carries the tag object's own metadata; it is nil for a lightweight tag.

type Tree

type Tree struct {
	SHA       SHA
	Entries   []TreeEntry
	Truncated bool
}

Tree is a git tree object. Truncated reports that the recursive walk hit the entry ceiling and stopped, matching GitHub's truncated flag.

type TreeEntry

type TreeEntry struct {
	Path string
	Mode string
	Type ObjectType
	SHA  SHA
	Size int64 // blob byte size; zero for tree and submodule entries
}

TreeEntry is one entry of a tree. Path is the entry name within its tree, or the full slash-joined path when the tree was listed recursively. Mode is the six-digit octal string git stores (100644, 100755, 120000, 040000, 160000).

Jump to

Keyboard shortcuts

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