gitx

package
v0.29.2 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: 22 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 gitx provides a git wrapper via os/exec for the Agentic Wiki. No external git library: only CLI invocation.

Index

Constants

View Source
const (
	// RebaseStateNormal: a real rebase is in progress (a head-name or todo is
	// present), so someone is mid-operation and git owns the worktree.
	RebaseStateNormal = "rebase"
	// RebaseStateOrphanAutostash: the rebase directory exists but holds no
	// rebase — only an autostash. Observed after a process was killed mid
	// `pull --rebase --autostash`: from then on every write failed with "there is
	// already a rebase-merge directory", and the KB was frozen until the
	// directory was removed by hand (D155).
	RebaseStateOrphanAutostash = "orphan-autostash"
)

Rebase state kinds returned by RebaseInProgress.

View Source
const (
	// MaxRemoteLineRunes caps one quoted line.
	MaxRemoteLineRunes = 200
	// MaxRemoteTextBytes caps the whole quoted text.
	MaxRemoteTextBytes = 1024
)

Limits of the remote's words once they are quoted in an error: the text reaches /health, MCP results, the Atlas and the CLI, so a remote cannot make it long or carry anything a terminal or a reader would act on.

View Source
const DefaultBranch = "main"

DefaultBranch is the branch a freshly initialized KB is created on. Sync compares the checked-out branch against the remote's default one (D264), so inheriting the host's init.defaultBranch would make a KB unusable on any machine configured for "master".

View Source
const MaxIdentBytes = 256

MaxIdentBytes bounds an identity: a name and an email, not a document.

Variables

View Source
var (
	IndexLockWait = 3 * time.Second
	IndexLockPoll = 50 * time.Millisecond
)

IndexLockWait is how long a restore after a failed commit waits for a foreign index.lock to clear before giving up (#2241); IndexLockPoll is the pause between two attempts. Variables so a test shortens them.

View Source
var AfterStage func(dir string)

AfterStage runs in Commit once the changes are staged and before git commit takes the index lock: a seam for the tests that need a foreign lock to appear in that window (#2241). Nil in production.

View Source
var CommitTimeout = 60 * time.Second

CommitTimeout bounds one git commit. Server commits are isolated from the user's commit-time configuration (serverConfig), so one that takes this long is stuck on something the isolation does not cover; it is stopped, process group included, rather than holding the KB's lock. A variable so tests can shorten it.

View Source
var ErrCloneTimeout = errors.New("git clone timed out")

ErrCloneTimeout reports that a clone was stopped by its context deadline rather than failing on its own. The caller owns the remedy, since only it knows the flag that changes the bound.

View Source
var ErrGitMissing = errors.New("installing a plugin from a git URL needs git on PATH; a local folder does not")

ErrGitMissing reports that git is not on PATH.

View Source
var ErrGitlink = errors.New("refusing to record a nested git repository")

ErrGitlink is the error of a commit that would record a gitlink (index mode 160000, a nested git repository). Nothing is committed and the index holds no gitlink change any more.

View Source
var ErrNotLinear = errors.New("gitx: the local commits are not a linear range")

ErrNotLinear means the commits above the upstream hold a merge or a root commit, which RealignCommitters leaves alone: the caller may log why the forge will still see the old committers.

View Source
var ErrNothingToCommit = errors.New("nothing to commit")

ErrNothingToCommit signals that there was nothing to commit.

View Source
var ErrProbeTimeout = errors.New("git ls-remote timed out")

ErrProbeTimeout reports that ProbeRemoteContent was stopped by its context deadline: the remote did not answer in time.

View Source
var ErrRangeTooLarge = errors.New("gitx: too many commits in range")

ErrRangeTooLarge is returned by LogNameStatusRange when more than MaxRangeCommits commits lie between the revision and HEAD.

View Source
var ErrRebaseConflict = errors.New("gitx: rebase conflict")

ErrRebaseConflict signals that a pull --rebase hit a conflict and was aborted.

View Source
var ErrUnknownRev = errors.New("gitx: unknown revision")

ErrUnknownRev is returned by LogNameStatusRange when the revision is not a commit reachable from HEAD: malformed, absent from the repository (a gc'd sha, a sha of another KB) or on a history a realign or reset left behind.

View Source
var FetchTimeout = 15 * time.Second

FetchTimeout bounds one git fetch. Without it a remote whose host drops packets (a VPN that is down) holds the fetch for the OS TCP connect timeout -- about 75s on macOS -- and every tool call waiting on the KB's git lock with it, past the client's 30s HTTP timeout (#348). The fetch is the operation that meets an unreachable remote first; pull and push run after a fetch has just succeeded. The deadline starts after netEnv, so one fetch takes at most FetchTimeout plus the separate core.sshCommand probe, bounded at 5s plus a 1s pipe wait (skipped when GIT_SSH_COMMAND or GIT_SSH is set). A variable so tests can shorten it.

View Source
var MaxRangeCommits = 5000

MaxRangeCommits bounds how many commits LogNameStatusRange reads, so a cursor far behind HEAD never walks the whole history. A variable so tests can shorten it.

View Source
var MoveHistoryTimeout = 15 * time.Second

MoveHistoryTimeout bounds one git call of the move history, like FetchTimeout bounds a fetch: the read runs under the KB's locks and on every review.

View Source
var MoveWalkCommits = 2000

MoveWalkCommits bounds how many commits (not only rename commits) a read of the move history examines: git log -n bounds the output, not the walk, and a KB with few renames would otherwise be diffed commit by commit to its root. A variable so tests can shorten it.

View Source
var PushTimeout = 60 * time.Second

PushTimeout bounds one git push. A push carries data, so it gets a longer bound than FetchTimeout, but it is bounded all the same: an unbounded push holds the KB's git lock, and every tool call behind it, for as long as the remote stalls. As for FetchTimeout, the deadline starts after netEnv: a push takes at most PushTimeout plus the core.sshCommand probe, bounded at 5s plus a 1s pipe wait. A variable so tests can shorten it.

Functions

func AddPath

func AddPath(dir, path string) error

AddPath stages a single path ("git add -- <path>").

func AddRemote

func AddRemote(dir, name, url string) error

AddRemote adds a remote with the given name and URL.

func AheadBehind added in v0.24.0

func AheadBehind(dir, remote, branch string) (ahead, behind int, known bool, err error)

AheadBehind returns how many commits HEAD is ahead of and behind <remote>/<branch> in one rev-list call. Behind is relative to the remote-tracking ref as the last fetch left it: no network is touched. known is false when the ref is absent or branch is empty.

func AheadCount added in v0.4.0

func AheadCount(dir, remote, branch string) (count int, known bool, err error)

AheadCount returns commits reachable from HEAD but not origin/<branch>. known is false when the remote-tracking ref is absent, so callers never mistake an unavailable comparison for zero unpushed commits.

func Ancestors added in v0.28.0

func Ancestors(dir, rev string, paths []string) (map[string]bool, error)

Ancestors returns the commits reachable from rev, rev itself included, that touch one of paths ("git rev-list --full-history rev -- paths"): one process answers "is this commit an ancestor of rev" for every commit of those paths' history, where IsAncestor costs one each, and the walk is bounded by the paths' history, not the repository's. --full-history keeps every commit that differs from a parent on a path, a superset of what `git log -- path` lists, so a commit of that history is in the set exactly when it is an ancestor. The "--" after rev keeps a file named like the rev from making it ambiguous.

func AnonymousEnv added in v0.29.0

func AnonymousEnv() []string

AnonymousEnv is the environment of a clone that must carry no identity of the operator: no global or system git config (so no credential helper, extra header, proxy or URL rewrite), no askpass program, no prompt, and no redirect followed (a redirect would leave the host that was checked). Layered after the process environment, it wins over it. For clones of a locator written by a KB writer (D1262), never for KB sync.

func AnonymousReadEnv added in v0.29.0

func AnonymousReadEnv(home string) []string

AnonymousReadEnv is AnonymousEnv for the commands run in an anonymous clone afterwards (HeadSHA, IsAncestor, TreeBlobs, DiffTree), with HOME and XDG_CONFIG_HOME also pointed at home, an empty directory the caller owns: GIT_CONFIG_GLOBAL needs git 2.32, and an older git would still read the operator's ~/.gitconfig and $XDG_CONFIG_HOME/git/config (D1262).

func AuthorIdent added in v0.4.0

func AuthorIdent(dir string, env ...string) (name, email string, err error)

AuthorIdent returns the identity resolved by Git itself (including local, global and ambient GIT_AUTHOR_* configuration). Empty values mean Git could not resolve a usable identity.

func Births added in v0.26.0

func Births(commits []CommitChanges, key func(path string) (string, bool)) map[string]time.Time

Births replays commits (newest first, as LogNameStatus returns them) from the oldest and returns when each key first entered the repository: the commit that added its file, carried across renames. key maps a file path to the identity being tracked; a path it rejects is ignored. A file deleted and added again is born again; one with no history is absent.

func BoundRemoteLines added in v0.29.0

func BoundRemoteLines(text string, n int) string

BoundRemoteLines is the first n non-empty lines of a remote's output, trimmed and joined on one line with " | ", with BoundRemoteText's guarantees.

func BoundRemoteText added in v0.29.0

func BoundRemoteText(text string) string

BoundRemoteText makes the output of a git remote safe to quote in an error: ANSI escape sequences are dropped, a carriage return ends a line, every other control character (C0, DEL, C1) is replaced by U+FFFD, every Unicode format character (category Cf: bidirectional controls, zero-width, tag characters) is dropped, each line is cut at MaxRemoteLineRunes and the whole at MaxRemoteTextBytes, a cut marked with an ellipsis. Line breaks are kept.

Redaction comes first: callers pass text already through RedactRemoteText, because a credential cut by the caps could no longer be recognised.

func Branch

func Branch(dir string) (string, error)

Branch returns the current branch name, or "" if detached HEAD.

func BranchExists

func BranchExists(dir, branch string) bool

BranchExists checks if a branch exists locally.

func CheckLinear added in v0.26.0

func CheckLinear(dir, upstream string) error

CheckLinear returns ErrNotLinear when upstream..HEAD holds a merge or a root commit, nil otherwise: the check a rewrite makes before it starts, for a caller that wants to refuse it up front.

func CheckRepo added in v0.28.0

func CheckRepo(dir string) (ok bool, err error)

CheckRepo tells "this is not a repository" apart from "git refused to look": IsRepo folds both into false, so a repository git declines to open (a changed owner, "dubious ownership") reads as one that has nothing to commit. ok is false with a nil error only when git says there is no repository.

func Checkout

func Checkout(dir, branch string) error

Checkout checks out an existing branch.

func CheckoutNewBranch added in v0.4.0

func CheckoutNewBranch(dir, branch, start string, env ...string) error

CheckoutNewBranch checks out branch at start. It never resets an existing branch; callers that see an existing branch must make an explicit, safe decision instead of discarding history.

func Clone

func Clone(ctx context.Context, remote, dest string, env ...string) error

Clone clones remote into dest ("git clone <remote> <dest>"), bounded by ctx. dest must not yet exist (or must be empty); git creates it. env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) layered on top of the process environment — see runGitEnv.

The child never prompts: GIT_TERMINAL_PROMPT=0, plus an SSH batch mode and connect timeout for ssh remotes. Without those, git blocks indefinitely on a credential or host-key prompt when stdin is not a usable terminal, and the caller shows nothing while it does. Host-key POLICY is left alone: StrictHostKeyChecking=accept-new would trade a hang for a silent trust-on-first-use decision on an operator's machine (D173).

Progress goes to stderr as it happens — a clone with no output is indistinguishable from a hang — while a copy is kept to translate a failure into something actionable.

func CloneAnonymous added in v0.29.0

func CloneAnonymous(ctx context.Context, remote, dest string) error

CloneAnonymous clones an https remote with AnonymousEnv and without the blobs of history (--filter=blob:none: the trees are what a listing reads, and the checkout fetches the blobs of HEAD). The caller bounds it with ctx.

HOME and XDG_CONFIG_HOME point at an empty directory made for the call (AnonymousReadEnv): GIT_CONFIG_GLOBAL needs git 2.32, and an older git would read the operator's ~/.gitconfig during the clone itself.

func Commit

func Commit(dir, message, authorName, authorEmail string, env ...string) error

Commit runs "git add -A" followed by a commit with the given message and author identity. The committer identity is taken from env (typically GIT_COMMITTER_NAME/GIT_COMMITTER_EMAIL, assembled per-KB by the caller); if env carries no committer variables, git falls back to its own config/ process environment, and when git cannot resolve one either the author becomes the committer (withCommitterFallback). If there is nothing to commit, returns ErrNothingToCommit (not a fatal error).

A KB never records a gitlink (a nested git repository, index mode 160000): the staging leaves a change to one out, and when the working tree holds a nested repository that is new it returns a *GitlinkError (ErrGitlink), nothing committed and nothing of it left in the index.

func CommitPaths added in v0.2.0

func CommitPaths(dir string, paths []string, message, authorName, authorEmail string, env ...string) error

CommitPaths creates one commit containing changes to paths only. It uses a temporary index seeded from HEAD, so pre-existing staged or unstaged work in the caller's real index is neither changed nor accidentally committed.

func CommitTime added in v0.29.0

func CommitTime(dir, sha string) (time.Time, error)

CommitTime returns the committer time of a commit (a tag peels to its commit). sha must be a full hex object name; anything else, or no such commit, is ErrUnknownRev. The errors carry no git output.

func DirtyPaths added in v0.29.0

func DirtyPaths(dir string) ([]string, error)

DirtyPaths lists the paths git status reports in dir (staged, modified, deleted or untracked, renames split in two), slash-separated.

func DiscardChanges added in v0.22.0

func DiscardChanges(dir string) error

DiscardChanges returns the working tree and index to HEAD, untracked files included (git reset --hard HEAD + git clean -fd). It is deliberately narrow, like ResetHardTo: the caller holds the KB lock and has checked the tree was clean before the write it undoes (D350). Ignored files are kept.

func Env added in v0.29.0

func Env() []string

Env is the environment a git command of the client runs with when it names the repository itself (-C): gitEnv without extras, so the variables that pin a repository (GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE, ...) are dropped. A sync run from a git hook inherits them, and the command would answer for the repository running the hook instead of the one asked about.

func Fetch

func Fetch(dir, remote string, env ...string) error

Fetch runs git fetch for a given remote (default "origin"). Returns error on failure. env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) — see runGitEnv.

func FetchNoTags added in v0.29.0

func FetchNoTags(dir, remote string, env ...string) error

FetchNoTags is Fetch without following tags: refs/tags/* is left as it was, for a caller that may have to undo the fetch (kb attach removes the remote again, which drops refs/remotes/<remote>/* but not tags).

func ForgeBoilerplateReadme added in v0.26.0

func ForgeBoilerplateReadme(repoName, text string) (boilerplate bool, description string)

ForgeBoilerplateReadme reports whether text, the README a forge's initial commit holds in a repository called repoName, is that forge's untouched boilerplate, and the one-line project description it carries when it has one. Only two shapes are recognised, whole-file, after normalising a BOM, CRLF line ends, trailing blanks and surrounding blank lines:

  • `# <repoName>`, optionally followed by one description line (GitHub, Gitea and Forgejo), with or without a blank line between;
  • `# <repoName>` and GitLab's "Getting started" template, identified by its three fixed markers (no description is carried over).

Anything else is the operator's text and reports false.

func ForgeInitialized added in v0.24.0

func ForgeInitialized(dir, ref string) (paths []string, ok bool, err error)

ForgeInitialized reports whether ref is what a forge writes when it creates a project with "initialize with README": exactly one commit whose tree holds only top-level README/LICENSE/COPYING/.gitignore/.gitattributes files (isForgeInitPath). It returns the tree's paths either way. A git failure is an error, never a silent false. "Exactly one branch" is the caller's condition (RemoteRefs.Branches).

func ForgeReadmeBoilerplate added in v0.26.0

func ForgeReadmeBoilerplate(dir, ref, path, remote string) (boilerplate bool, description string, err error)

ForgeReadmeBoilerplate reads the README at ref:path and applies ForgeBoilerplateReadme with the repository name of remote.

func ForgeReadmePath added in v0.26.0

func ForgeReadmePath(paths []string) (path string, ok bool)

ForgeReadmePath picks the README a forge's initial commit carries out of its top-level paths: the one file named README.md (case-insensitive). ok is false when there is none, or when another README file (README, README.rst, a second README.md in another case) sits beside it, so nothing is ever decided for an ambiguous tree.

func GlobalIdent added in v0.25.0

func GlobalIdent() (ident string, perFolder bool)

GlobalIdent returns the identity the global git config names, as "Name <email>", for a client entry every folder shares (D904). It is "" with perFolder true when the config includes files by condition (includeIf) and one of them may set an identity: a folder could then get another one, which a value written once into an entry cannot follow, and a KB must not receive the identity a per-folder setup keeps away from it. An includeIf whose files set no user, author or committer name or email (a per-organisation core.sshCommand, say) changes no identity and counts for nothing (#1910). Whatever cannot be shown to be harmless counts as an identity: an unreadable, missing or non-regular file, a nested includeIf, a key that is not a path. It is "" alone when the config names no valid identity or cannot be read. GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL are not read: they belong to one process, and the value goes into a file every later session reads.

func HasIndexLock added in v0.29.0

func HasIndexLock(dir string) string

HasIndexLock returns the path of the index.lock file present in the repository at dir, "" when there is none. It removes nothing and applies the guards of RemoveStaleIndexLock (dir is the root of its own repository).

func HeadSHA

func HeadSHA(dir string, env ...string) (string, error)

HeadSHA returns the SHA of the HEAD commit.

env is layered on the process environment like runGitEnv's; the poll passes AnonymousReadEnv for a clone of a locator a KB writer chose.

func HeadSHAAt added in v0.4.0

func HeadSHAAt(dir, ref string) (string, error)

HeadSHAAt returns the commit SHA for ref.

func HeadUnborn added in v0.17.0

func HeadUnborn(dir string) bool

HeadUnborn reports whether dir is a git repository whose HEAD names a branch with no commit yet: a fresh `git init`, or a clone of an empty remote.

func IgnoredFiles added in v0.25.0

func IgnoredFiles(dir, path string) ([]string, error)

IgnoredFiles lists the files under path (absolute, inside the repository at dir) that the repository's ignore rules exclude, as git prints them (relative to dir). Empty when there are none.

func IgnoredPaths added in v0.25.0

func IgnoredPaths(dir string, paths []string) ([]string, error)

IgnoredPaths returns those of paths (relative to dir, which need not exist yet) that the repository's ignore rules would exclude from a commit. It asks git with --no-index, so a tracked path is judged by the rules alone. The paths go to git on stdin, NUL-separated, so the call does not grow with them (argv has a hard limit) and a name is never quoted or split.

func Init

func Init(dir string) error

Init initializes a git repository in the directory, if one does not already exist. Pins the initial branch to DefaultBranch and configures merge.conflictStyle=zdiff3 locally. An existing repository whose HEAD is unborn (no commit yet) is pinned too: that is what `git clone` of an empty remote leaves, on a branch named by the host's git version and init.defaultBranch (often "master"), and a KB bootstrapped from it must land where `kb create` does (D264). Repositories with commits keep whatever branch they are on.

func InitOnBranch added in v0.20.0

func InitOnBranch(dir, branch string) error

InitOnBranch is Init with the unborn HEAD pinned to branch instead of DefaultBranch.

func IsAncestor added in v0.4.0

func IsAncestor(dir, ancestor, descendant string, env ...string) (bool, error)

IsAncestor reports whether ancestor is reachable from descendant. env as in HeadSHA.

func IsBareHookDecline added in v0.29.0

func IsBareHookDecline(output string) bool

IsBareHookDecline reports whether the output of a failed push carries no reason of the remote's own: besides git's framing ("git push ...: exit status", "To <url>", "error: failed to push some refs", hints) its only lines are the generic "pre-receive hook declined" / "hook declined" ones. GitLab's membership rule sometimes shows nothing else (D1063), so a caller that holds local evidence may infer an identity refusal from it; a line like "rejected by policy: protected" is the remote's reason and is not bare.

func IsIdentityRejection added in v0.26.0

func IsIdentityRejection(output string) bool

IsIdentityRejection reports whether the output of a failed push says the remote refused it because of who authored or committed a commit: GitLab's membership push rule ("GitLab: Author 'x' is not a member of team", and the "Committer" variant), GitHub's private-email protection ("GH007: Your push would publish a private email address"). It is a different refusal from a protected branch (IsProtectedBranchRejection) and needs a different fix: callers test it first, because the generic "pre-receive hook declined" line accompanies both. It never matches GH006 or a protected-branch wording.

func IsProtectedBranchRejection added in v0.25.0

func IsProtectedBranchRejection(output string) bool

IsProtectedBranchRejection reports whether the output of a failed push says the remote refused it because the branch is protected, or because a server-side hook declined it (D903). Forges word it differently (GitHub: "GH006: Protected branch update failed", GitLab: "You are not allowed to push code to protected branches", and "pre-receive hook declined" for both), so it is matched on those phrases and not tied to one provider. Retrying such a push repeats the refusal: the caller reports it and stops.

func IsPushCredentialVerdict added in v0.29.0

func IsPushCredentialVerdict(err error) bool

IsPushCredentialVerdict reports whether err, from ProbePushAccess, is the remote's verdict on the credential: a permanent rejection (PermanentPushRejection: no write access, a read-only deploy key, a rule), or a login refused or missing. Anything else that is not IsRemoteUnreachable (a TLS or host-key failure, an HTTP 429 or 5xx, a connection cut mid-way) says nothing about the credential: the caller reports that the check could not be made, never that the push is refused. No credential at all ("could not read Username", terminal prompts disabled) counts as a verdict: the server would not push either.

func IsRemoteUnreachable added in v0.29.0

func IsRemoteUnreachable(err error) bool

IsRemoteUnreachable reports whether err, from ProbePushAccess, says the remote did not answer: the probe's deadline passed, or git's own output names a network failure. A caller that probes for a verdict on a credential (doctor) skips the check on this and does not call the credential refused: the machine may simply be offline.

func IsRepo

func IsRepo(dir string) bool

IsRepo checks whether the directory is a valid git repository.

func LinkedWorktrees added in v0.29.0

func LinkedWorktrees(dir string) ([]string, error)

LinkedWorktrees returns the canonical absolute paths of the other working trees of the repository containing dir, sorted: the main working tree when dir is a linked one, and the linked ones otherwise. A bare record, a prunable one (its directory is gone), dir itself, a path with a control character and anything at or below another entry's `.git` are left out, and only existing directories are kept. A directory that is not in a repository, or a missing git, is not an error: the result is nil, nil. Any other failure of the listing (a timeout, a lock, a refusal over ownership, a git too old for `-z`) is returned: a caller must not read it as "no worktrees", because that would make every projection it knows look orphaned. It is not memoised (memo.go caches plain repositories only): a worktree added or removed is seen on the next call.

func ListFiles added in v0.19.0

func ListFiles(dir string) ([]string, error)

ListFiles returns the files git tracks in dir, plus the untracked ones it would add at the next commit (not ignored): "git ls-files --cached --others --exclude-standard", slash-separated and relative to dir. An error means dir is not inside a git work tree (or git is missing).

func MergeAbort

func MergeAbort(dir string) error

MergeAbort aborts an in-progress merge ("git merge --abort").

func MergeBase added in v0.19.0

func MergeBase(dir, a, b string) (string, error)

MergeBase returns the best common ancestor of a and b ("git merge-base").

func MergeFileUnion added in v0.19.0

func MergeFileUnion(base, ours, theirs string) (string, error)

MergeFileUnion returns the line-level union of ours and theirs against base ("git merge-file -p --union"): the content git's built-in merge=union driver produces, computed without touching the index or the working tree. It is how an append-only file such as log.md is reconciled when two clones added entries concurrently (D311). Only stdout is read: CombinedOutput would mix a warning into the merged content.

func MergeNoCommitNoFFEnv added in v0.26.0

func MergeNoCommitNoFFEnv(dir, ref string, env ...string) (conflicted bool, err error)

MergeNoCommitNoFFEnv runs "git merge --no-commit --no-ff <ref>" and reports whether the merge produced conflicts. A clean merge (conflicted=false) is left staged but uncommitted; a conflicting merge (conflicted=true) leaves the conflicting files unmerged for the caller to resolve. Any other failure is returned as err. env is layered on the git process environment. A merge needs a committer identity even with --no-commit, so a caller inside a KB passes kb.ServerGitEnv() or it fails with "empty ident name" on a host with no git identity.

func OldestUnpushedAt added in v0.29.0

func OldestUnpushedAt(dir, remote, branch string) (at time.Time, ok bool, err error)

OldestUnpushedAt is the committer time of the oldest commit in <remote>/<branch>..HEAD, the one that has waited longest to be pushed; ok is false when nothing is unpushed or the remote-tracking ref is absent. No network is touched.

func ParseIdent added in v0.25.0

func ParseIdent(raw string) (name, email, problem string)

ParseIdent validates the "Name <email>" identity a client sends as the author of a write (D904); problem says why a value is refused. The server applies it to the Cartographer-Author header and the client to what it is about to send, so a value one refuses the other never sends. TRAP: the value ends up in a commit's author line; control characters (newlines first) and angle brackets inside either part are refused, not cleaned.

func PermanentPushRejection added in v0.29.0

func PermanentPushRejection(output string) (remedy string, ok bool)

PermanentPushRejection reports whether the output of a failed push is a refusal that retrying only repeats, and the one-line remedy quoting the remote's own line: a credential without write access ("Permission to X denied", "write access", a read-only deploy key, GitLab's "not allowed to push code to this project", Gitea's "permission denied for writing"; a bare HTTP 403 is not enough, GitHub's secondary rate limit is one and heals), a credential the remote rejected ("Authentication failed", HTTP 401) or that git had none of to offer ("could not read Username": its own remedy), a repository rule or required signature (GitHub "GH013"), a file over the size limit ("GH001"), a server-side hook that declined. Only policy wording is permanent: a "[remote rejected]" for a lock, a ref update, an internal error or an unpacker error is a race or a server fault and is retried. Callers test the protected-branch and identity rejections first: their hook wording is also "hook declined". A non-fast-forward "[rejected]" is not matched either: it is retried through a rebase.

func PermanentPushRemedy added in v0.29.0

func PermanentPushRemedy(output string) string

PermanentPushRemedy is PermanentPushRejection for a surface that must not carry the remote's words (/health, status, doctor): only the rule's fixed sentence, "" when output is not a permanent refusal. It never returns any of output.

func ProbePushAccess added in v0.29.0

func ProbePushAccess(ctx context.Context, remote string, env ...string) error

ProbePushAccess asks remote whether this machine's credentials may push: "git push --dry-run" of a throw-away commit to a branch that does not exist, from a temporary repository. A dry run contacts the receiving side and writes nothing, so it catches a read-only credential (HTTP 403, a read-only deploy key) at once. A rule the remote evaluates only on a real push (required signatures, repository rules) is not seen here; SyncOut reports those on the first push. Failures come back with the permanent-rejection remedy, or remoteRemedy's, or ErrProbeTimeout (the deadline), or context.Canceled (the caller cancelled).

func PullRebaseAutostash

func PullRebaseAutostash(dir, remote, branch string, env ...string) error

PullRebaseAutostash runs "git pull --rebase --autostash <remote> <branch>". It talks to the network without FetchTimeout or a process-group kill, so the KB sync path does not use it: after Fetch it rebases locally with RebaseOntoAutostash (one round-trip, bounded). If the operation encounters a rebase conflict, it collects the list of unmerged files and the relevant SHAs, runs "git rebase --abort" (best-effort), and returns a *RebaseConflictError. errors.Is(err, ErrRebaseConflict) remains true for it. Other errors (e.g. remote unreachable) are returned as-is without abort. env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) — see runGitEnv.

func Push

func Push(dir, remote, branch string, env ...string) error

Push pushes the current branch to the remote. Never force-pushes. Returns error on non-fast-forward (caller should rebase and retry). env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) — see runGitEnv.

func PushSetUpstream added in v0.7.0

func PushSetUpstream(dir, remote, branch string, env ...string) error

PushSetUpstream pushes branch to remote and sets it as the branch's upstream ("git push -u"). Used once per KB: when its origin is first attached (kb create --remote), or by the local-profile SyncOut for the very first push of DefaultBranch to an empty remote (D264). Every other sync path in internal/kb uses Push, which must not touch tracking configuration. env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) — see runGitEnv.

func RealignCommitters added in v0.25.1

func RealignCommitters(dir, upstream, serverName, serverEmail, defName, defEmail string, env ...string) (int, error)

RealignCommitters rewrites the local commits above upstream (upstream..HEAD, never a published one) so that each one's committer is its author (D950). A rebase replays local commits with the committer of its environment, and a forge with a membership push rule checks committers too, so a commit whose writer is known must keep that writer as its committer. A commit authored by exactly the server identity (serverName <cartographer@any host>: no writer was known when it was made, possibly by another instance) is re-authored, and re-committed, as defName/defEmail when both are set, so a KB whose writer is registered later can still publish it. A commit authored "<token id> <serverEmail>" names the token that wrote it, is not that identity, and keeps its author.

It only rewrites a linear range (a merge or a root commit in it makes it return ErrNotLinear and change nothing), keeps every commit's message, tree and dates, and moves the checked-out branch with a compare-and-swap update-ref, so the working tree and the index are not touched. It returns how many commits it rewrote; 0 with a nil error when there is nothing to do.

func RebaseInProgress added in v0.9.0

func RebaseInProgress(dir string) (kind string, ok bool)

RebaseInProgress reports whether dir has a rebase state directory and what kind it is. A caller must not run git in the worktree while this returns true: the point is to refuse with an actionable message instead of letting git fail with one that names no way out.

func RebaseOntoAutostash added in v0.4.0

func RebaseOntoAutostash(dir, remote, branch string, env ...string) error

RebaseOntoAutostash rebases the checked-out branch onto remote/branch. It preserves a dirty tree with Git's autostash and returns the same structured conflict error used by PullRebaseAutostash.

func RebaseStateDir added in v0.9.0

func RebaseStateDir(dir string) string

RebaseStateDir returns the path of the rebase state directory in dir, or "". Named in the operator-facing message so the remedy points at a real path.

func RedactRemoteText added in v0.28.0

func RedactRemoteText(text, remote string) string

RedactRemoteText replaces every occurrence of the remote in text with its redacted form, so git output that echoes the URL cannot carry its credentials either. git echoes a URL in several shapes: as given, without its userinfo but with the query kept, already stripped, or cut at the host ("could not read Password for 'http://TOKEN@host'"): the first two are replaced whole, then each part of the userinfo (the token-only user, the password, with its percent-decoded form) wherever it still appears. A remote that is a name rather than a URL has nothing to replace here: callers that only hold the name use scrubRepoOutput. Text that never held the remote is returned unchanged.

func RedactRemoteURL added in v0.28.0

func RedactRemoteURL(raw string) string

RedactRemoteURL strips credential material from a remote URL. For http(s) (and any "+http"/"+https" transport such as git+https) the whole userinfo is dropped: a token can sit in either half (https://token@host/... as well as https://user:token@host/...). For other schemes only the password is dropped — an ssh username is not a secret and identifies the remote. The query string and the fragment are dropped whole: a credential parameter can have any name (passwd, pat, jwt, a ";"-separated pair…). A value with "://" that url.Parse rejects (a stray %, #, / or space in a password) is never returned as it came: everything between "://" and the last "@" of its authority is cut. Values without "://" lose any "user:password@" prefix (scp-style bot:pw@host:owner/repo.git too); a plain git@host:owner/repo.git (a username, no password) and local paths are returned unchanged. A "helper::url" remote (ext::https://…) is redacted on the url after the "::".

func RemoteBranchExists added in v0.4.0

func RemoteBranchExists(dir, remote, branch string) bool

RemoteBranchExists reports whether refs/remotes/<remote>/<branch> exists. Call Fetch first when the answer must reflect the forge's current state.

func RemotePushURL added in v0.29.0

func RemotePushURL(dir, remote string) (string, error)

RemotePushURL is the URL a push to the named remote goes to: its remote.<name>.pushurl when set (and url.<base>.pushInsteadOf), else its URL.

func RemoteRemedy added in v0.29.0

func RemoteRemedy(output string) string

RemoteRemedy is remoteRemedy for a caller that holds a git error's text: the fixed one-line sentence for a known failure phrase in output, "" otherwise. It never returns any of output.

func RemoteText added in v0.29.0

func RemoteText(err error) string

RemoteText is the text of err to classify a remote's refusal on: the whole redacted output when the error (or one it wraps) quotes a bounded one, else its message. Never display it: Error() is the bounded form.

func RemoteTrackingBranches added in v0.27.1

func RemoteTrackingBranches(dir, remote string) ([]string, error)

RemoteTrackingBranches lists the branch names under refs/remotes/<remote>/ (HEAD excluded), from the local clone: no network.

func RemoteURL

func RemoteURL(dir, remote string) (string, error)

RemoteURL returns the URL of the given remote, or error if not configured.

func RemoveRemote added in v0.29.0

func RemoveRemote(dir, name string) error

RemoveRemote removes the named remote, with its remote-tracking refs and the tracking configuration of the branches that followed it.

func RemoveStaleIndexLock added in v0.29.0

func RemoveStaleIndexLock(dir string) (path string, age time.Duration, err error)

RemoveStaleIndexLock removes the index.lock a crash, a power loss or a kill left in the repository at dir, and returns its path and age (path "" when there was none). The caller must hold the KB's exclusive process lock and run it before serving: only then no git of this server runs in the clone, so a lock found is a leftover. dir must be the root of its own repository or linked worktree (a `.git` directory or file in it), never a folder inside a larger one, whose lock is not ours to clear: a bogus or empty `.git` there makes git walk up to the enclosing repository, so the top level git reports must be dir itself. The lock path comes from git itself (rev-parse --git-path), so a worktree or a `.git` file pointing elsewhere resolves to the right git dir. Only a regular file is removed.

func RenameBranch added in v0.24.0

func RenameBranch(dir, name string) error

RenameBranch renames the checked-out branch ("git branch -m <name>").

func RepoNameFromURL added in v0.26.0

func RepoNameFromURL(remote string) string

RepoNameFromURL is the repository name of a git remote URL: its last path segment without a trailing slash or ".git" suffix. It handles https://, ssh:// and scp-style (git@host:group/sub/name.git) URLs, and a local path.

func ResetHardTo added in v0.4.0

func ResetHardTo(dir, ref string, env ...string) error

ResetHardTo resets a clean working tree to ref. It is deliberately narrow: callers check cleanliness before using it.

func ResetPaths added in v0.25.0

func ResetPaths(dir string, paths ...string) error

ResetPaths resets the index entries of paths to HEAD ("git reset -q -- paths"), leaving the working tree alone. CommitPaths commits through a temporary index, so the real one still holds what it held before: after the commit, this brings the paths it committed back in line with HEAD, and git status shows them clean.

func ResolveCommit added in v0.19.0

func ResolveCommit(dir, ref string) (string, error)

ResolveCommit returns the full SHA of the commit that ref names, or an error when ref is not a commit of this repository.

func RestorePaths added in v0.29.0

func RestorePaths(dir string, paths []string) error

RestorePaths puts exactly paths back to HEAD: unstaged, then rewritten from HEAD when HEAD holds them, removed when it does not. It needs the index lock free (the unstaging writes the index) and fails otherwise, touching nothing.

func RestoreWithoutIndex added in v0.29.0

func RestoreWithoutIndex(dir string) error

RestoreWithoutIndex puts the working tree back to HEAD while a foreign index.lock refuses every index write: untracked files are removed, a modified or deleted tracked file is rewritten from HEAD's blob (git cat-file and status take no lock). It handles only the plain states a write leaves (modified, deleted, untracked) and refuses the rest, which a reset must settle.

func RevertNoCommit added in v0.19.0

func RevertNoCommit(dir, sha string, env ...string) error

RevertNoCommit applies the inverse of commit sha to the working tree and the index without committing, so the caller's own commit path records it. On a conflict it returns an error and leaves the tree for the caller to reset.

func RunCount added in v0.28.0

func RunCount() int64

RunCount returns how many git processes runGitEnv has started so far.

func ShowFile

func ShowFile(dir, ref, path string) (string, error)

ShowFile returns the contents of path at the given git ref ("git show <ref>:<path>"). Used to materialise the "ours"/"theirs" sides of a conflict by content, which avoids the inverted --ours/--theirs semantics that apply during a rebase.

func ShowFileIfExists added in v0.28.0

func ShowFileIfExists(dir, ref, path string) (text string, exists bool, err error)

ShowFileIfExists is ShowFile that tells a path absent from ref (exists=false, nil error) from every other failure (a bad ref, a damaged repository), which is returned: an error must never be read as absence.

func StageExecutable added in v0.28.0

func StageExecutable(dir string, paths ...string) error

StageExecutable stages paths (literal, relative to dir, existing files) with the execute bit set in the index ("git add --chmod=+x"), so the next commit records 100755 even where the filesystem cannot carry the bit. A later "git add -A" keeps the index mode of a file whose content it restages when core.fileMode is false, and sets the same one when the filesystem has it.

func StashDrop

func StashDrop(dir string, env ...string) error

StashDrop discards the last stash without applying it ("git stash drop").

func StashPop

func StashPop(dir string, env ...string) error

StashPop pops the last stash. Returns error if nothing to pop.

func StashPushAllEnv added in v0.26.0

func StashPushAllEnv(dir string, env ...string) error

StashPushAllEnv stashes every uncommitted change including untracked files, so the tree is at HEAD until StashPop (StashPushEnv leaves untracked files behind). env is layered on the git process environment; see StashPushEnv for why a caller passes the server identity.

func StashPushEnv added in v0.26.0

func StashPushEnv(dir string, env ...string) error

StashPushEnv stashes uncommitted changes, with env layered on the git process environment. git stash creates commits, so a host with no git identity needs the caller to pass one (kb.ServerGitEnv) or the stash fails with "Committer identity unknown".

func Status

func Status(dir string) (string, error)

Status returns the working tree status (short format).

func StatusPaths added in v0.25.0

func StatusPaths(dir string, paths ...string) (string, error)

StatusPaths is Status restricted to paths: empty when none of them has a change.

func TrackedModes added in v0.28.0

func TrackedModes(dir string, paths ...string) (map[string]string, error)

TrackedModes returns the index mode ("100644", "100755", ...) of every file git tracks at or below pathspecs (taken literally, slash-separated, relative to dir). It is the source of truth for the execute bit of a tracked file: a filesystem without the bit (NTFS) reads every file as non-executable, the index does not.

func TrackedPaths added in v0.27.1

func TrackedPaths(dir string, paths ...string) (map[string]bool, error)

TrackedPaths returns which of paths (taken literally, never as pathspecs) (slash-separated, relative to dir) git tracks in the index.

func TrackedPathsFold added in v0.29.0

func TrackedPathsFold(dir string, paths ...string) (map[string]bool, error)

TrackedPathsFold is TrackedPaths for a caller that must not be fooled by spelling: it returns which of paths (slash-separated, relative to dir, taken literally) git tracks in the index under any capitalisation, keyed by the path as asked. A case-insensitive filesystem (macOS and Windows by default) writes `CLAUDE.md` into the file a repository tracks as `claude.md`, and an exact question about `CLAUDE.md` answers "no". Asking per pathspec (`:(literal,icase)`, which the global --literal-pathspecs would turn off) folds the whole path, directories included, on every filesystem: on a case-sensitive one the answer errs toward "tracked", the safe side for a caller that withholds something from a shared file. git folds ASCII letters only: a non-ASCII directory that differs from the tracked one only by case is not matched.

Each path is asked on its own, with the GIT_*_PATHSPECS variables dropped, and a name git lists counts when it has as many components as the path asked: it is the file itself, not a file below a directory that folds to it. The names are not compared as strings, since git may spell them differently from the request (core.precomposeunicode returns a decomposed name composed).

func TreePaths added in v0.24.0

func TreePaths(dir, ref string) ([]string, error)

TreePaths returns the paths of every file in ref's tree, slash-separated ("git ls-tree -r --name-only -z <ref>").

func UnmergedFiles

func UnmergedFiles(dir string) ([]string, error)

UnmergedFiles returns the git-relative paths of files with unresolved conflicts (git diff --name-only --diff-filter=U).

func UnpublishedCommitCount added in v0.26.0

func UnpublishedCommitCount(dir, upstream string) (inRange, unpublished int, err error)

UnpublishedCommitCount counts the commits in upstream..HEAD, and how many of them are not reachable from any remote-tracking ref: the two are equal when the range holds only commits that exist nowhere else.

func Untrack added in v0.27.1

func Untrack(dir string, paths ...string) error

Untrack removes paths from the index and leaves the working tree alone ("git rm --cached"). The next commit records the removal.

func ValidateRemote added in v0.26.0

func ValidateRemote(remote string) error

ValidateRemote refuses an operator-supplied remote that git would read as an option (leading "-") or run as a transport helper ("ext::<command>"). It is an allow-list of forms, not a deny-list: scp-like (git@host:path), a URL with one of allowedRemoteSchemes, or a plain local path.

func WorkTreeIdent added in v0.25.0

func WorkTreeIdent(dir string) string

WorkTreeIdent returns the author git would record for a commit made in dir, as "Name <email>", or "" when there is none to send (D904). Only inside a work tree: outside one git applies no includeIf gitdir:, and would answer with the global identity a per-repository setup exists to keep away from a work KB. user.useConfigOnly stops git from making up user@host from the machine; GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL still apply, as for a commit. GIT_DIR and GIT_WORK_TREE are dropped so dir alone decides the repository. An identity ParseIdent refuses is not sent either.

Types

type CommitChanges added in v0.2.0

type CommitChanges struct {
	SHA     string
	At      time.Time
	Author  string
	Subject string
	// Agent is the value of the commit's Agent: trailer (D718), empty when
	// absent. With several trailers only the first is kept.
	Agent string
	// MovedTo and MovedFrom are the values of the commit's Moved-To: and
	// Moved-From: trailers (D760): the other KB of a concept_transfer, empty
	// when absent.
	MovedTo, MovedFrom string
	// Token is the value of the commit's Cartographer-Token: trailer (D904):
	// the id of the token that wrote it, appended by the server last. Empty when
	// absent (a commit that is not a write, or one made before it existed).
	Token string
	// Reason is the value of the commit's Reason: trailer (D272), empty when
	// absent. With several trailers only the first is kept.
	Reason string
	// AcceptedFindings are the values of the commit's Accepted-Finding:
	// trailers (D350), "<check>: <reason>" each, in commit order.
	AcceptedFindings []string
	Files            []FileChange
}

CommitChanges contains the files changed by one commit in git log order (newest first). Files retain git's name-status order.

func LogNameStatus added in v0.2.0

func LogNameStatus(dir string, since time.Time) ([]CommitChanges, error)

LogNameStatus returns commits since the supplied instant with their changed files. Renames are normalised to status "R", with OldPath and Path holding the source and destination respectively. A directory that is not a git repository, or a repository with no commits in range, returns an empty slice.

func LogNameStatusAt added in v0.29.0

func LogNameStatusAt(dir string, since time.Time) ([]CommitChanges, string, error)

LogNameStatusAt is LogNameStatus that also returns the head it read and starts the walk there, not at whatever HEAD is by the time git runs: the answer's commits and its head are one snapshot. A directory that is not a repository, or one with no commit yet, returns no commits and an empty head.

func LogNameStatusRange added in v0.29.0

func LogNameStatusRange(dir, fromSHA string) ([]CommitChanges, string, error)

LogNameStatusRange returns the commits in fromSHA..head, newest first, with their changed files, as LogNameStatus does, and the head it read: the range ends there, so a client that continues from that head loses no commit that lands later. fromSHA comes from a client, so it must be a full lower-case hex object name that is, or peels to (an annotated tag), a commit reachable from HEAD (a ref, a range or an option never reaches git); anything else, and HEAD itself unborn, is ErrUnknownRev. More than MaxRangeCommits commits is ErrRangeTooLarge. fromSHA equal to head is an empty range.

type CommitSummary added in v0.19.0

type CommitSummary struct {
	Subject string
	// Reason is the Reason: trailer (D272), empty when absent.
	Reason  string
	Parents int
}

CommitSummary is the part of a commit a revert guard reads.

func ShowCommit added in v0.19.0

func ShowCommit(dir, sha string) (CommitSummary, error)

ShowCommit reads the subject, the Reason trailer and the number of parents of one commit.

type FileChange

type FileChange struct {
	Status  string // "A", "M", "D", "R"
	Path    string
	OldPath string // set for renames; Path is the destination
}

FileChange represents a changed file in a diff.

func CommitFiles added in v0.28.0

func CommitFiles(dir, sha string) ([]FileChange, error)

CommitFiles is the files commit sha changed, renames detected (OldPath holds the source), the same shape LogNameStatus reports. A root commit lists all its files. It reads the whole commit: a visibility filter needs every path a commit touched, not only the one a history was asked for.

func StagedChanges added in v0.22.0

func StagedChanges(dir string) ([]FileChange, error)

StagedChanges stages every change of the working tree (stageAll: git add -A, leaving a gitlink out, a *GitlinkError for a new nested repository) and returns what differs from HEAD, renames detected (-M), parsed from the NUL-separated form so a path with spaces or unusual bytes survives (D350). The index is left staged; DiscardChanges or a commit clears it.

func StagedChangesEnv added in v0.29.0

func StagedChangesEnv(dir string, env []string) ([]FileChange, error)

StagedChangesEnv is StagedChanges with env layered on the git processes: the write gate passes a Quarantine's, so the blobs it stages never reach the repository's own object store.

type FileRevision added in v0.18.0

type FileRevision struct {
	SHA     string
	At      time.Time
	Author  string
	Subject string
	// Agent is the value of the commit's Agent: trailer (D718), empty when
	// absent (first value only, like Reason).
	Agent string
	// MovedTo and MovedFrom are the values of the commit's Moved-To: and
	// Moved-From: trailers (D760): the other KB of a concept_transfer, empty
	// when absent.
	MovedTo, MovedFrom string
	// Token is the value of the commit's Cartographer-Token: trailer (D904),
	// as in CommitChanges.
	Token string
	// Reason is the value of the commit's Reason: trailer (D272), empty when
	// absent.
	Reason string
	// AcceptedFindings are the commit's Accepted-Finding: trailer values (D350).
	AcceptedFindings []string
	// Path is the file's path in that commit (the destination for a rename),
	// relative to the repository root.
	Path string
	// Status is A, M, D or R.
	Status string
}

FileRevision is one commit that touched a single file, as reported by FileHistory.

func FileHistory added in v0.18.0

func FileHistory(dir, path string, limit int) ([]FileRevision, error)

FileHistory returns the commits that touched path (relative to the repository root), newest first. It never follows a rename by similarity (#1281: git log --follow paired a merely similar file and listed a commit of another concept). It lists the commits that touch the concept's two forms, "<id>.md" and the expanded "<id>/index.md" (a concept_expand stays one history), and continues behind a rename only when the commit is a concept_move: the old path is then walked from that commit's parent. At most limit entries are returned (limit <= 0 means no cap). A path with no history, a directory that is not a git repository and a repository with no commits all return an empty slice.

type GitlinkError added in v0.28.0

type GitlinkError struct {
	Paths []string
}

GitlinkError names the paths a refused commit would have recorded as gitlinks. It satisfies errors.Is(err, ErrGitlink).

func (*GitlinkError) Error added in v0.28.0

func (e *GitlinkError) Error() string

func (*GitlinkError) Unwrap added in v0.28.0

func (e *GitlinkError) Unwrap() error

Unwrap makes errors.Is(err, ErrGitlink) true.

type LocalCommit added in v0.26.0

type LocalCommit struct {
	SHA            string
	Author         string // name
	AuthorEmail    string
	Committer      string
	CommitterEmail string
	Subject        string
}

LocalCommit is one commit above the upstream, with who it is by.

func LocalCommits added in v0.26.0

func LocalCommits(dir, upstream string) ([]LocalCommit, error)

LocalCommits lists upstream..HEAD, oldest first.

type Quarantine added in v0.29.0

type Quarantine struct {
	// Env is the environment to pass to the git calls that must write into it.
	Env []string
	// contains filtered or unexported fields
}

Quarantine is a throwaway object directory layered over the repository's own (GIT_OBJECT_DIRECTORY plus an alternate pointing at the real one): git reads everything the repository holds but writes its new objects into the quarantine only. The write gate stages and stashes through it, so a write it refuses leaves no object behind, not even the blob of the refused text (#2186). It carries its own copy of the index (GIT_INDEX_FILE), so the repository's index never names an object the quarantine holds (#2222).

func NewQuarantine added in v0.29.0

func NewQuarantine(dir string) (*Quarantine, error)

NewQuarantine creates a quarantine next to the repository's objects.

func (*Quarantine) Close added in v0.29.0

func (q *Quarantine) Close()

Close deletes everything written into the quarantine.

type RebaseConflictError

type RebaseConflictError struct {
	Files     []string // git-relative paths of unmerged files (e.g. "data/notes/c.md")
	LocalSHA  string   // HEAD SHA captured before the rebase started
	RemoteSHA string   // SHA of <remote>/<branch> after fetch
	Remote    string   // remote name (e.g. "origin")
	Branch    string   // branch name (e.g. "main")
}

RebaseConflictError carries structured details about a rebase conflict. It satisfies errors.Is(err, ErrRebaseConflict) so existing callers are unaffected.

func (*RebaseConflictError) Error

func (e *RebaseConflictError) Error() string

Error implements the error interface.

func (*RebaseConflictError) Is

func (e *RebaseConflictError) Is(target error) bool

Is makes errors.Is(err, ErrRebaseConflict) return true for *RebaseConflictError values, preserving backward compatibility with all callers that use the sentinel.

type RemoteProbe added in v0.28.0

type RemoteProbe struct {
	HasRefs   bool
	ForgeInit bool
}

RemoteProbe is what `cartographer setup` learns about a remote before it plans: whether it has refs, and whether they are only a forge's initial commit (ForgeInitialized), which is an empty project to build a KB in, not a KB to mount (D710).

func ProbeRemoteContent added in v0.28.0

func ProbeRemoteContent(ctx context.Context, remote string) (RemoteProbe, error)

ProbeRemoteContent reports whether the remote has refs and what they hold: the question that distinguishes a repository to create a KB in from one that already holds something to clone. When ls-remote shows refs on exactly one branch it fetches that branch two commits deep, without blobs, into a temporary repository (two, so a root commit is told from a longer history) and applies ForgeInitialized to it. Anything else with refs is content to mount.

type RemoteRefs added in v0.17.0

type RemoteRefs struct {
	// HasRefs is false for an empty remote: no branch, no tag.
	HasRefs bool
	// Default is the branch the remote's HEAD points at, or "" when the
	// remote does not advertise one (empty, or HEAD naming a branch that does
	// not exist — common on a self-hosted `git init --bare` whose HEAD is
	// "master" while only "main" was pushed).
	Default string
	// Branches are the remote's branch names.
	Branches []string
}

RemoteRefs is what a remote advertises, as far as the canonical-branch check needs it (D264).

func LsRemote added in v0.17.0

func LsRemote(dir, remote string, env ...string) (RemoteRefs, error)

LsRemote asks remote for its branches and default branch ("git ls-remote --symref"), bounded by FetchTimeout like Fetch. It asks the remote every time rather than reading refs/remotes/<remote>/HEAD: that ref is written once by clone and never refreshed by fetch, so it goes stale when the forge's default branch changes (and is absent in a repository that was init'ed and then given a remote). On success, and when the default branch has a remote-tracking ref, <remote>/HEAD is re-pointed at it (local only, best-effort) so an operator's `git log origin/HEAD` agrees with Cartographer. env carries extra per-KB variables (e.g. GIT_SSH_COMMAND) — see runGitEnv.

func (RemoteRefs) HasBranch added in v0.17.0

func (r RemoteRefs) HasBranch(branch string) bool

HasBranch reports whether the remote has branch.

type RemoteTimeoutError added in v0.16.1

type RemoteTimeoutError struct {
	Remote string
	After  time.Duration
}

RemoteTimeoutError reports a git remote that did not answer in time. It is a distinct type so a caller can say "the remote is unreachable" rather than pass on a bare exit status.

func (*RemoteTimeoutError) Error added in v0.16.1

func (e *RemoteTimeoutError) Error() string

type Rename added in v0.29.0

type Rename struct {
	SHA     string
	At      time.Time
	Subject string
	OldPath string
	Path    string
}

Rename is one file rename a move tool committed: the concept file moved from OldPath to Path (git-relative) by the commit SHA.

func MoveRenames added in v0.29.0

func MoveRenames(dir string, limit int) ([]Rename, error)

MoveRenames returns the file renames of the last limit commits that contain a rename within the last MoveWalkCommits commits of HEAD, keeping the ones a move tool made (subject "<tool>" or "<tool>: ..." for concept_move, concept_archive or kb_repair; a hand git mv, "external changes" or concept_expand are not recorded moves). Oldest first. A directory that is not a repository, or has no commit, returns an empty slice. The pair is git's rename pairing (-M, 50 % similarity): a page rewritten a lot in the move can read as delete + add and is missed, and identical pages moved in one commit may be paired crosswise.

func MoveRenamesSince added in v0.29.0

func MoveRenamesSince(dir, since string, limit int) (renames []Rename, ok bool, err error)

MoveRenamesSince is MoveRenames over the commits after since (since..HEAD), for a caller that holds the moves up to since. ok is false when it cannot answer incrementally: since is not an ancestor of HEAD (a rewrite, a forced sync), is unknown, or more than MoveWalkCommits commits follow it; the caller then reads the whole bounded history.

type Rewritten added in v0.26.0

type Rewritten struct{ Old, New string }

Rewritten is one commit a history rewrite replaced: its id before and after.

func ReauthorCommits added in v0.26.0

func ReauthorCommits(dir, upstream, name, email string, env ...string) ([]Rewritten, error)

ReauthorCommits rewrites the local commits above upstream (upstream..HEAD, never a published one) so that name <email> is both the author and the committer of every one that is not already (D1063). Unlike RealignCommitters it replaces a token-authored commit's author too: it is the operator's explicit repair, not a sync step. It keeps messages (and so the Cartographer-Author, -Token and -Host trailers, the record of who really wrote), trees and both dates, and moves the checked-out branch with the same compare-and-swap update-ref, so a commit another process adds meanwhile makes it fail and nothing is lost. A merge or a root commit in the range returns ErrNotLinear and changes nothing. It returns the old → new ids of the commits it replaced; none, with a nil error, when there is nothing to do.

type TreeBlob added in v0.29.0

type TreeBlob struct{ Mode, ID, Path string }

TreeBlob is one entry of a tree listing: the file mode ("100644", "120000" for a symlink), the blob id and the path.

func TreeBlobs added in v0.29.0

func TreeBlobs(dir, ref string, env ...string) ([]TreeBlob, error)

TreeBlobs lists the blobs of ref's tree with their ids ("git ls-tree -r -z"). Submodule entries are left out. DiffNameStatus is not used for this family of reads: it splits on whitespace and has no -z, so a path with a space or a quoted non-ASCII name would be mangled (D1262). env as in HeadSHA.

type TreeChange added in v0.29.0

type TreeChange struct{ Status, Mode, ID, Path string }

TreeChange is one path that differs between two commits. Status is A, M, D or T; Mode and ID are the new ones (ID "" for D).

func DiffTree added in v0.29.0

func DiffTree(dir, from, to string, env ...string) ([]TreeChange, error)

DiffTree lists the paths that differ between two commits ("git diff-tree -r -z --no-renames --raw"): a rename is a D plus an A. -z for the reason given at TreeBlobs. env as in HeadSHA.

type TreeEntry added in v0.28.0

type TreeEntry struct {
	Path       string // slash form, relative to the repository root
	Content    []byte
	Executable bool // mode 100755
}

TreeEntry is a regular file of a commit's tree, read from the object database.

func FetchTree added in v0.28.0

func FetchTree(ctx context.Context, remote, ref, tmpParent string, lim TreeLimits) ([]TreeEntry, string, error)

FetchTree fetches ref of remote (a branch, a tag or a full commit sha; empty means HEAD) at depth 1 into a throwaway repository under tmpParent and returns the files of the commit's tree with the commit's 40-hex id.

The tree is read from the object database and never checked out, so the bytes returned are the committed ones whatever core.autocrlf, .gitattributes (eol, filter, export-subst) or the host OS would have done to a working copy. Credentials are the machine's own, as for `kb clone`. A symlink, a gitlink, a blob over MaxFileSize or more than MaxEntries entries is refused naming the path, before any blob is read; so is a listing whose blobs add up to more than MaxTotal (0: no cap). The fetch runs under the caller's deadline, else FetchTimeout.

type TreeLimits added in v0.28.0

type TreeLimits struct {
	MaxEntries  int
	MaxFileSize int
	MaxTotal    int // bytes in all the files kept; 0 means no cap
	Skip        func(path string) bool
}

TreeLimits bound what FetchTree reads. Skip names the paths the caller never wants: they are not counted and their blobs are not read.

Directories

Path Synopsis
Package gitxtest is a git smart-HTTP server for tests: the real git-http-backend behind basic authentication, in process, so a test meets what a forge's HTTPS endpoint does (a 401, a credential helper, a pre-receive hook's "remote:" lines) without a network.
Package gitxtest is a git smart-HTTP server for tests: the real git-http-backend behind basic authentication, in process, so a test meets what a forge's HTTPS endpoint does (a 401, a credential helper, a pre-receive hook's "remote:" lines) without a network.

Jump to

Keyboard shortcuts

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