git

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package git is the Git client of the Git extension (SPEC §10.30 "Running git", D35): it finds the user's git program, runs it safely and portably, and parses what it prints. It is plain Go (the standard library and rm4n0s/errors), with no UI and no Emetos import, and it is tested against the real git in isolated repositories (extensions/gitscm/gittest) and against recorded outputs.

Runner starts the commands: arguments as a list and never through a shell, a fixed environment, a process group per command that is stopped on cancellation, bounded or streamed output, the Git channel log and the classification of failures into the error tags of VS Code's GitErrorCodes. Queue orders the commands of one repository. The parsers (ParseStatus, ParseCommits, ParseRefs, ParseBlame and the others) read the output of status, log, for-each-ref, blame and the rest, as streams where git's format is a stream. Repo gathers the read commands of one repository; Init and Clone, on the Runner, are the only write commands of this step (the others are added by the steps that use them).

Ported from VS Code: extensions/git/src/git.ts (the parsers, the error classification, the commands), operation.ts (the kinds of operation that the queue orders) and util.ts (splitInChunks, versions). VS Code branches on git versions down to 2.13; Emetos requires 2.30 (D35) and drops those branches. VS Code's cache.ts (an LRU cache for blame and history) is not ported: no step needs it yet.

Index

Constants

View Source
const (
	// DefaultMaxOutput is the most standard output that Run keeps: 64 MiB.
	DefaultMaxOutput = 64 << 20
	// DefaultKillGrace is the time between SIGTERM and SIGKILL of a cancelled command.
	DefaultKillGrace = 3 * time.Second
	// StderrKept is the length of the error output kept in a Result and in the metadata of an error: the last 2 KiB.
	StderrKept = 2 << 10
)

Default limits (SPEC §10.30 "Running git").

View Source
const CommitFormat = "%H%n%aN%n%aE%n%at%n%ct%n%P%n%D%n%B"

CommitFormat is the --format of "git log -z" and "git show -s -z" that ParseCommits reads: hash, author name, author e-mail, author date, committer date (seconds since the epoch), parents, ref names and the raw message.

View Source
const DefaultMaxReads = 4

DefaultMaxReads is how many reads of one repository run at the same time.

View Source
const MaxBlobSize = 16 << 20

MaxBlobSize is the largest file content that ReadBlob returns: 16 MiB (SPEC §10.30 "Bounds"); above it the diff shows "The file is too large to compare".

View Source
const MaxCommandLineLength = 30000

MaxCommandLineLength is the most characters of paths put on one command line for the commands that cannot read a pathspec file (clean, mv, submodule update): VS Code's MAX_CLI_LENGTH.

View Source
const MaxConfigSize = 1 << 20

MaxConfigSize bounds a configuration file that Emetos reads itself: 1 MiB.

View Source
const MaxPathsOnTheCommandLine = 200

MaxPathsOnTheCommandLine is the number of paths past which a command that supports it gets them on its standard input (--pathspec-from-file=- --pathspec-file-nul) instead of after "--".

View Source
const RefsDetailsFormat = RefsFormat + "%00%(authorname)%00%(*authorname)%00%(subject)%00%(*subject)"

RefsDetailsFormat is RefsFormat with four more fields for the details a picker shows: the author's name and the subject of the commit, and the same two of the commit an annotated tag points at.

View Source
const RefsFormat = "" /* 185-byte string literal not displayed */

RefsFormat is the --format of "git for-each-ref" that ParseRefs reads, ten fields separated by NUL (%00): the full name, the object, the commit a tag points at, the upstream, the upstream track, the upstream's remote and remote ref, the commit date, the date of the commit a tag points at, and "*" for the checked out branch.

View Source
const StashFormat = "%H%n%P%n%gd%n%gs%n%at%n%ct"

StashFormat is the --format of "git stash list -z" that ParseStashes reads: hash, parents, "stash@{n}", the reflog subject, author date, commit date.

View Source
const StashLatest = -1

StashLatest as the index of a stash command means the newest stash: no stash@{n} is given to git.

Variables

View Source
var (
	RevParseGitDirArgs   = []string{"rev-parse", "--git-dir", "--git-common-dir", "--is-inside-work-tree", "--is-bare-repository", "--is-shallow-repository"}
	RevParseTopLevelArgs = []string{"rev-parse", "--show-toplevel", "--show-superproject-working-tree"}
)

RevParseGitDirArgs and RevParseTopLevelArgs are the two "git rev-parse" commands that RepoInfo is made from. The first works in any repository, bare or not; the second only in a work tree, and prints the top level and, inside a submodule, the work tree of the super project.

View Source
var ErrStopStream = &errors.Error{Tag: "GitStreamStopped"}

ErrStopStream is what a consumer of RunStream returns to stop the command without an error: git is ended (SIGTERM to its process group) and RunStream returns nil. It is a sentinel (a struct literal), so the route of an error never starts here.

View Source
var MinVersion = Version{Major: 2, Minor: 30}

MinVersion is the oldest git that Emetos runs (SPEC §10.30, D35): 2.30.

Functions

func CloneFolderName

func CloneFolderName(source string) string

CloneFolderName is the name of the folder a clone of the URL gets: the last element of its path without ".git" (the part after the last colon of an scp-like address), unescaped, or "repository" when nothing usable is left.

Ported from VS Code: extensions/git/src/git.ts (Git.clone: baseFolderName)

func ConflictingTags

func ConflictingTags(stderr string) []string

ConflictingTags reads the names of the tags a pull refused to replace from its error output ("! [rejected] v1 -> v1 (would clobber existing tag)").

Ported from VS Code: extensions/git/src/repository.ts (handleTagConflict)

func FilterWorktreeSymlinkFolders

func FilterWorktreeSymlinkFolders(candidates []string, ignoredOutput, matchedOutput, directoryOutput string) []string

FilterWorktreeSymlinkFolders selects the candidate folders that are ignored themselves, match the patterns and contain no tracked file, and drops a folder that lies inside another one of the result (the link of the outer one covers it). The outputs are NUL separated lists of folders with a trailing slash: those "git check-ignore" says are ignored, those the patterns match, and "git ls-files --others --ignored --exclude-standard --directory" (the wholly ignored folders).

func LooksBinary

func LooksBinary(data []byte) bool

LooksBinary tells whether file content is not text: git's own test, a NUL byte in the first 8,000 bytes.

func MaskURLs

func MaskURLs(s string) string

MaskURLs replaces the userinfo of every URL in s by *** ("https://user:secret@host/x" becomes "https://***@host/x"), so that a password or a token in a URL is never logged (SPEC §10.30 "Output").

func ObjectName

func ObjectName(ref, path string) string

ObjectName is the name git knows a version of a file by (cat-file's "<object>"): the index version of path for ref "" (and "~", "index", which the diff of a file changed in the work tree reads), a stage of a conflicted file for "~1", "~2" and "~3" (":1:path"), and the version in a commit for any other ref (HEAD, a branch, a tag, a hash): "<ref>:<path>". The path is relative to the work tree, with slashes.

Ported from VS Code: extensions/git/src/fileSystemProvider.ts (sanitizeRef), extensions/git/src/git.ts (Repository.buffer).

func ParseIgnored

func ParseIgnored(data []byte) []string

ParseIgnored reads the output of "git check-ignore -v -z --stdin": for each path that matches, four NUL-terminated fields (the file with the pattern, its line, the pattern, the path). It returns the paths that are ignored: those whose pattern is not negated (a pattern that starts with "!" un-ignores the path).

Ported from VS Code: extensions/git/src/repository.ts (parseIgnoreCheck).

func ResolveWorktreeIncludePaths

func ResolveWorktreeIncludePaths(ignoredOutput, includedOutput, directoryOutput, worktreeOutput string, excludedFolders []string) []string

ResolveWorktreeIncludePaths selects the ignored paths to copy into a worktree from the NUL separated outputs of "git ls-files", and collapses a wholly ignored folder whose every ignored file is included into one recursive entry.

ignoredOutput is "git ls-files --others --ignored --exclude-standard -z" in the repository, includedOutput the same with "--exclude-from=<patterns>" in place of the standard sources, directoryOutput the first with "--directory --no-empty-directory", worktreeOutput "git ls-files -z" in the new worktree, and excludedFolders the folders (relative to the repository) that are linked into the worktree already. The paths are relative to the repository with forward slashes; a folder has no trailing slash.

func SanitizeWorktreeIncludePatterns

func SanitizeWorktreeIncludePatterns(patterns []string) []string

SanitizeWorktreeIncludePatterns removes the patterns that contain a line break. Each entry of git.worktreeIncludeFiles must stay one .gitignore line: a line break in it would inject more patterns (a "!" negation).

func SplitInChunks

func SplitInChunks(paths []string, maxChunkLength int) [][]string

SplitInChunks splits paths into groups whose total length is at most maxChunkLength (a path longer than that gets a group of its own), for the commands that cannot read their paths from a file.

Ported from VS Code: extensions/git/src/util.ts (splitInChunks).

func StreamCommits

func StreamCommits(r io.Reader, fn func(Commit) error) error

StreamCommits reads the output of git log from r and calls fn for each commit; when fn returns an error the reading stops and the error is returned.

func StreamLsFiles

func StreamLsFiles(r io.Reader, fn func(LsFilesEntry) error) error

StreamLsFiles reads the output of "git ls-files --stage -z" from r and calls fn for each entry; when fn returns an error the reading stops and the error is returned. A record that is cut short is dropped.

func StripCommitMessageComments

func StripCommitMessageComments(message string) string

StripCommitMessageComments removes the comment lines of a message and the white space around it. (core.commentChar is not read, as VS Code does not.)

func TrustedBy

func TrustedBy(store TrustStore) func(Location) bool

TrustedBy makes the Config.Trust function of a store: a repository is trusted when the store trusts its root, or the repository it belongs to as a submodule or a linked worktree (SPEC §10.30 "Trusting a repository": they are trusted with their parent).

func ValidateRemoteURL

func ValidateRemoteURL(s string) string

ValidateRemoteURL checks the URL or path a remote is added with and says what is wrong with it ("" when it is fine): a path (absolute, relative or starting with ~, and it may have spaces), a URL with the scheme file, http, https, ssh or git and a host (a file URL needs a path), or an scp-like address (user@host:path). It starts no process and touches no file.

func Within

func Within(path, dir string) bool

Within reports whether path is dir or below it, comparing whole path elements.

func WorktreeSymlinkFolderCandidates

func WorktreeSymlinkFolderCandidates(ignoredOutput, matchedOutput string) []string

WorktreeSymlinkFolderCandidates returns the ancestor folders of the files that are both ignored and matched by the patterns, nearest folder first for each file, each folder once. ignoredOutput and matchedOutput are NUL separated lists of files.

Types

type AddOptions

type AddOptions struct {
	// Update stages only the files git already tracks ("git add -u"); otherwise new files and deletions are staged too ("-A").
	Update bool
}

AddOptions are the options of Add.

type AddWorktreeOptions

type AddWorktreeOptions struct {
	// Path is the folder of the new work tree; one that is not absolute is relative to the root of the repository.
	Path string
	// Commitish is the branch, tag or commit the work tree starts at; HEAD when empty.
	Commitish string
	// Branch, when not empty, is a new branch made at Commitish and checked out in the work tree ("-b").
	Branch string
	// NoTrack makes the new branch track nothing ("--no-track").
	NoTrack bool
}

AddWorktreeOptions say what AddWorktree adds.

type BlameCommit

type BlameCommit struct {
	Hash        string
	Author      string
	AuthorEmail string
	AuthorTime  time.Time
	Summary     string
	Ranges      []LineRange
}

BlameCommit is a commit that is responsible for lines of a file, with the ranges of the lines (in the final file).

func ParseBlame

func ParseBlame(data []byte) []BlameCommit

ParseBlame parses a whole output of "git blame --incremental".

func StreamBlame

func StreamBlame(r io.Reader) ([]BlameCommit, error)

StreamBlame reads the output of git blame from r.

type BlameOptions

type BlameOptions struct {
	// Path is the file, relative to the root.
	Path string
	// Rev is the revision to blame; empty means the work tree's version.
	Rev string
	// IgnoreWhitespace adds -w.
	IgnoreWhitespace bool
}

BlameOptions are the options of Blame.

type BlameParser

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

BlameParser reads the output of "git blame --incremental" as a stream: Write it the chunks as they arrive, cut anywhere, and read Commits. A hunk is "<hash> <original line> <final line> <number of lines>", the author, author-mail, author-time and summary lines (only the first time git prints a commit), and "filename <path>", which ends the hunk. A hunk that is not complete yet waits for the next chunk. It implements io.Writer.

Ported from VS Code: extensions/git/src/git.ts (parseGitBlame).

func (*BlameParser) Commits

func (p *BlameParser) Commits() []BlameCommit

Commits returns the commits read so far, in the order they first appeared, each with its ranges.

func (*BlameParser) Write

func (p *BlameParser) Write(chunk []byte) (int, error)

Write adds a chunk of the output.

type CheckoutOptions

type CheckoutOptions struct {
	// Detached checks the ref out as a detached HEAD (--detach).
	Detached bool
	// Track makes a local branch that tracks a remote-tracking branch, named as git names it (--track): "origin/feature" gives
	// "feature".
	Track bool
	// Force throws away the local changes that the switch would overwrite (--force).
	Force bool
}

CheckoutOptions say how CheckoutRef switches.

type CloneOptions

type CloneOptions struct {
	// Recursive clones the submodules too ("--recursive").
	Recursive bool
	// Ref checks out that branch or tag ("--branch").
	Ref string
	// Bare makes a bare clone.
	Bare bool
	// TargetName, when it is not empty, is the name of the folder made in the parent folder; it is used as it is, and a folder of that
	// name that has files in it fails the clone with GitCloneTargetExists. When it is empty the folder is named after the repository,
	// and a name that is taken gets the next free "-1", "-2"... (VS Code's).
	TargetName string
	// Progress, when set, gets the progress of the transfer (--progress).
	Progress func(Progress)
}

CloneOptions are the options of Runner.Clone.

type CoAuthor

type CoAuthor struct {
	Name, Email string
}

CoAuthor is a "Co-authored-by: Name <email>" trailer of a message.

func ParseCoAuthors

func ParseCoAuthors(message string) []CoAuthor

ParseCoAuthors reads the "Co-authored-by: Name <email>" trailers of a message, without duplicates by e-mail (a squash merge repeats the trailers of what it squashed).

Ported from VS Code: extensions/git/src/git.ts (parseCoAuthors).

type Command

type Command struct {
	// Dir is the working directory (the repository). Empty means the root of the file system, outside any repository.
	Dir string
	// Args are the arguments after the program name, the command first (or "-c key=value" pairs before it): ["status", "-z",
	// "-uall"]. Never a shell line.
	Args []string
	// Paths are the paths the command works on. They go after "--" and, past MaxPathsOnTheCommandLine of them, for the
	// commands that can read them (add, rm, reset, restore, checkout, commit, stash), through --pathspec-from-file=-
	// --pathspec-file-nul on the standard input; Stdin must then be nil.
	Paths []string
	// Stdin is the standard input; nil means none (/dev/null).
	Stdin io.Reader
	// Background marks the commands that Emetos runs by itself (status, a refresh after a file change, blame, the graph, the
	// timeline, the originals of the quick diff): they get -c core.fsmonitor=false, -c core.pager=cat, GIT_OPTIONAL_LOCKS=0
	// and --no-ext-diff --no-textconv where the command has them.
	Background bool
	// Env are variables added last to the environment of this command.
	Env []string
	// AllowExit lists the exit statuses, besides 0, that are not failures for this command (1 for "git diff --quiet",
	// "check-ignore", "merge-base").
	AllowExit []int
	// Progress, when set, receives the progress lines git prints on its error output (the command must be given --progress): they are
	// taken out of the error output, which keeps git's messages. It is called from a goroutine of the Runner.
	Progress func(Progress)
}

Command is one git command.

type Commit

type Commit struct {
	// Hash is the object name (40 or 64 hexadecimal characters).
	Hash string
	// Message is the whole message, with the one final newline removed.
	Message string
	// Parents are the hashes of the parents, none for a root commit.
	Parents []string
	// AuthorName, AuthorEmail and AuthorDate come from the author line, CommitDate from the committer line.
	AuthorName, AuthorEmail string
	AuthorDate, CommitDate  time.Time
	// RefNames are the names of %D: "HEAD -> main", "tag: v1", "origin/main"; none when the commit has no decoration.
	RefNames []string
	// ShortStat is set when the log was asked for --shortstat and the commit changed files.
	ShortStat *ShortStat
	// CoAuthors are the trailers of the message, without duplicates by e-mail.
	CoAuthors []CoAuthor
	// FilePath is the path of the file at this commit, set by ParseFileLog for a followed file.
	FilePath string
}

Commit is one commit read from "git log" or "git show".

func ParseCommits

func ParseCommits(data []byte) []Commit

ParseCommits parses a whole output of "git log -z --format=CommitFormat". VS Code gives an empty name list as [""] for a commit with no decoration; RefNames is empty here.

func ParseFileLog

func ParseFileLog(data []byte) []Commit

ParseFileLog parses the output of "git log --numstat --shortstat -z --follow -- <file>": the commits, each with the path of the file at that commit (FilePath, which differs from the followed path before a rename). A commit without a numstat record has no FilePath.

Ported from VS Code: extensions/git/src/git.ts (parseGitFileLog).

type CommitChanges

type CommitChanges struct {
	// Commit is the commit.
	Commit Commit
	// Base is what the changes are against: the first parent of the commit, or the empty tree for a root commit (Root says which).
	Base string
	// Root says that the commit has no parent: Base is the empty tree.
	Root bool
	// Changes are the files that differ between Base and the commit, with git's rename detection.
	Changes []NameStatus
}

CommitChanges is what a commit changed: the commit, the tree it is compared with, and the files that differ.

type CommitOptions

type CommitOptions struct {
	// Message is the commit message, given to git on its standard input ("--file -"). Empty means no message: with UseEditor git asks
	// the editor, an Amend keeps the message it has ("--no-edit"), and otherwise the message is empty ("--allow-empty-message").
	Message string
	// UseEditor lets git start its editor when there is no Message (git.useEditorAsCommitInput); without it git never does.
	UseEditor bool
	// Verbose adds the diff to the message the editor shows ("--verbose"; git.verboseCommit, which VS Code reads only with the editor).
	Verbose bool
	// Amend replaces the last commit ("--amend").
	Amend bool
	// Signoff adds a Signed-off-by trailer ("--signoff").
	Signoff bool
	// Sign is -S when it points to true and --no-gpg-sign when it points to false; nil leaves the decision to the configuration
	// (commit.gpgsign). The passphrase is asked by the program git runs for the key, never by Emetos.
	Sign *bool
	// Empty allows a commit with no changes ("--allow-empty").
	Empty bool
	// NoVerify skips the pre-commit and commit-msg hooks ("--no-verify").
	NoVerify bool
	// RequireUserConfig makes git fail when user.name or user.email are not configured instead of guessing them from the system
	// ("-c user.useConfigOnly=true"; git.requireGitUserConfig).
	RequireUserConfig bool
}

CommitOptions are the options of Commit.

type CommitParser

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

CommitParser reads the output of "git log -z --format=CommitFormat [--shortstat]" as a stream. Each commit ends with a NUL; the shortstat of a commit follows that NUL, so a commit is handed to the callback when the next one starts (or at Close). A commit that is not complete (a stream cut short) is dropped; the shortstat of the last one is read only when its line is complete.

Ported from VS Code: extensions/git/src/git.ts (parseGitCommits).

func NewCommitParser

func NewCommitParser(emit func(Commit) error) *CommitParser

NewCommitParser makes a CommitParser that calls emit for each commit. When emit returns an error, Write returns it and the parser is finished.

func (*CommitParser) Close

func (p *CommitParser) Close() error

Close ends the stream: the text after the last NUL can still hold the shortstat of the last commit, which is then handed over.

func (*CommitParser) Write

func (p *CommitParser) Write(chunk []byte) (int, error)

Write adds a chunk of the output.

type Config

type Config struct {
	// Path is the git program (Find returns it).
	Path string
	// Version is the version of that git; it is only used by callers that branch on it.
	Version Version
	// Env is the base environment ("KEY=VALUE"). Nil means the environment of the process.
	Env []string
	// Extra are variables added to the environment of every command: the askpass and editor variables (GIT_ASKPASS,
	// SSH_ASKPASS, SSH_ASKPASS_REQUIRE, GIT_EDITOR, EMETOS_GIT_SOCKET, EMETOS_GIT_TOKEN) that the extension gives.
	Extra []string
	// ExtraFor, when set, gives more variables for a command: it is called, from the goroutine of the command, with the git command
	// ("fetch") and whether it is a background command, and its entries follow Extra. The extension starts the server of the askpass
	// and editor programs on the first command that can ask something, and gives it the socket and the token here (SPEC §10.30 "Passwords
	// and editors"); a background command never prompts and gets nothing.
	ExtraFor func(ctx context.Context, name string, background bool) []string
	// Logger gets the Git channel's lines; may be nil.
	Logger Logger
	// CommandsToLog lists the commands (git.commandsToLog) whose standard output is logged too, besides the command line and
	// the error output that are always logged.
	CommandsToLog []string
	// KillGrace is the time a cancelled command has between SIGTERM and SIGKILL; zero means DefaultKillGrace.
	KillGrace time.Duration
	// MaxOutput is the most standard output Run keeps; zero means DefaultMaxOutput.
	MaxOutput int64
	// Trust says whether git may be started in a repository (TrustedBy makes it from the store of the user's answers). A command
	// whose working directory, -C folder, --git-dir, --work-tree, GIT_DIR or GIT_WORK_TREE is in a repository that it does not trust is
	// refused with GitRepositoryNotTrusted before any process starts (SPEC §10.30 "Trusting a repository", D37). Nil trusts no
	// repository: only commands outside every repository run.
	Trust func(Location) bool
	// Now is the clock the durations of the log are measured with; nil means time.Now (a test gives a fake clock).
	Now func() time.Time
}

Config configures a Runner.

type ConfigEntry

type ConfigEntry struct {
	// Key is the name, "section.subsection.name" with the section and the name in lower case.
	Key string
	// Value is the value; empty for a key with no value.
	Value string
	// HasValue is false for a key written without "=" (a boolean true).
	HasValue bool
}

ConfigEntry is one setting printed by "git config --list -z".

func ParseConfigFile

func ParseConfigFile(text string) []ConfigEntry

ParseConfigFile reads the text of a git configuration file in git's syntax (git help config) and returns its settings in the order they are written: sections "[core]", "[remote "origin"]" and the deprecated "[remote.origin]", keys with or without "=", values in double quotes with the escapes \" \\ \n \t \b, comments with # and ;, a backslash at the end of a line continuing the value. Section and key names are lower case in the result (they are case-insensitive), a subsection keeps its case. Includes ("[include]", "[includeIf ...]") are not followed: this reader runs nothing and reads one file. A line it cannot understand is skipped, as git would stop at it.

func ParseConfigList

func ParseConfigList(data []byte) []ConfigEntry

ParseConfigList parses the output of "git config --list -z": records "key\nvalue\0", or "key\0" for a key with no value. A record that is cut short is dropped.

func ReadLocalConfig

func ReadLocalConfig(loc Location) ([]ConfigEntry, error)

ReadLocalConfig reads the configuration of the repository itself, without running anything (SPEC §10.30 "Trusting a repository"): the config of its git directory (of the common directory for a linked worktree, which shares it) and config.worktree. The settings come in file order; the global and system files are not read. A file that does not exist is empty, one that is too large fails with GitConfigTooLarge and one that cannot be read with GitConfigReadFailed.

type DiffSpec

type DiffSpec struct {
	// Cached compares the index with HEAD (or with Revs[0]).
	Cached bool
	// Revs are the revisions: none compares the work tree with the index, one the work tree (or the index) with it, two
	// compare them.
	Revs []string
	// Filter is the letters of --diff-filter ("ADMR"); empty means all.
	Filter string
	// SimilarityThreshold is passed as --find-renames=N% when it is not 0.
	SimilarityThreshold int
	// Paths limit the listing.
	Paths []string
}

DiffSpec describes a "git diff --name-status" listing.

type FetchOptions

type FetchOptions struct {
	// Remote is the remote to fetch from; empty fetches the upstream of the current branch, or origin (what "git fetch" does).
	Remote string
	// Ref, with Remote, is the ref to fetch: "main" or "main:main", which fast-forwards the local branch main when it can be.
	Ref string
	// All fetches every remote (--all); Remote is then ignored.
	All bool
	// Prune removes the remote-tracking branches the remote no longer has (--prune).
	Prune bool
	// Depth, when it is more than 0, limits the history fetched (--depth).
	Depth int
	// Silent marks a fetch the user did not ask for (the autofetch): it never asks for a password (SPEC §10.30 "Passwords and editors").
	Silent bool
	// Progress, when set, gets the progress of the transfer (--progress).
	Progress func(Progress)
}

FetchOptions say what Fetch fetches.

type FindOptions

type FindOptions struct {
	// Env is the environment of "git --version"; nil means the environment of the process. The PATH lookup uses the PATH of
	// the process.
	Env []string
	// Log receives a line for every candidate that was not usable (VS Code logs them to the Git channel); may be nil.
	Log func(line string)
}

FindOptions tune Find.

type ForcePushMode

type ForcePushMode int

ForcePushMode says how a push overwrites the remote's branch.

const (
	// NoForce is a push that git refuses when the remote has commits the branch lacks.
	NoForce ForcePushMode = iota
	// ForceWithLease is --force-with-lease: the push goes through when the remote-tracking branch is where the remote's branch is,
	// that is, nobody pushed since the last fetch.
	ForceWithLease
	// ForceWithLeaseIfIncludes is --force-with-lease with --force-if-includes: also refused when the remote-tracking branch has commits
	// the local branch does not include.
	ForceWithLeaseIfIncludes
	// ForceAlways is --force: the remote's branch is replaced whatever it has.
	ForceAlways
)

The modes of a force push.

type InitOptions

type InitOptions struct {
	// DefaultBranch is the name of the first branch ("-b"); empty leaves git's default.
	DefaultBranch string
	// Bare makes a repository with no work tree.
	Bare bool
}

InitOptions are the options of Runner.Init.

type Installation

type Installation struct {
	// Path is the program's path.
	Path string
	// Version is its version, at least MinVersion.
	Version Version
	// Raw is the output of "git --version".
	Raw string
}

Installation is a git program that was found and can be used.

func Find

func Find(ctx context.Context, hints []string, opts FindOptions) (Installation, error)

Find looks for git: the candidates in hints (the setting git.path: a string or an array, in order), then "git" on PATH. It runs "git --version" once for the candidate it takes, outside any repository, and returns the first one that is at least MinVersion (2.30). When some git was found but all are older the error has the tag GitTooOld with the path and the version of the first one; when none was found, GitNotFound with the candidates tried.

Ported from VS Code: extensions/git/src/git.ts (findGit, findSpecificGit).

type Kind

type Kind int

Kind says what a repository found on disk is.

const (
	// KindPlain is a repository with a .git folder, or a bare one.
	KindPlain Kind = iota
	// KindSubmodule is a work tree whose .git file points into the git directory of a super project (.git/modules/<name>).
	KindSubmodule
	// KindWorktree is a linked worktree: its .git file points into .git/worktrees/<name> of the main repository.
	KindWorktree
)

The kinds of repository.

func (Kind) String

func (k Kind) String() string

String is the name of the kind.

type LineRange

type LineRange struct {
	Start, End int
}

LineRange is a range of lines, counted from 1, both ends included.

type Location

type Location struct {
	// Root is the top level of the work tree, or the git directory of a bare repository, with symbolic links resolved: the key of
	// the repository.
	Root string
	// GitDir is the absolute git directory (the folder .git, or the folder a .git file points to).
	GitDir string
	// Bare says the repository has no work tree.
	Bare bool
	// Kind says whether the repository is a submodule or a linked worktree.
	Kind Kind
	// Parent is, for a submodule or a worktree, the root of the repository it belongs to (the super project, the main work
	// tree); empty for the others. Trust is inherited from it (SPEC §10.30 "Trusting a repository").
	Parent string
}

Location is a repository found by looking at the file system (SPEC §10.30 "Repositories": discovery runs no git command).

func FindRepository

func FindRepository(dir string) (Location, bool)

FindRepository looks for the repository that dir is in, from dir up to the root of the file system, by looking for a .git folder or file (and, in a folder that is a bare repository, for HEAD, objects and refs). It starts no process and reads no configuration. It reports false when there is none, or when the .git file cannot be read.

Ported from VS Code: extensions/git/src/git.ts (findGitRepo, getRepositoryRoot) in spirit; VS Code asks git, Emetos must not before the repository is trusted (D37).

func RepositoryAt

func RepositoryAt(dir string) (Location, bool)

RepositoryAt is FindRepository for a folder that must be the top level of the repository: it reports false for a folder that is only inside one.

type LogFileOptions

type LogFileOptions struct {
	// Path is the file: absolute, or relative to the root of the repository.
	Path string
	// Hash starts the log at this commit instead of at HEAD (a cursor of the Timeline view); empty for HEAD. It must be a full object
	// name.
	Hash string
	// MaxEntries is the most commits to list; 0 lists them all.
	MaxEntries int
	// Follow follows the file across renames.
	Follow bool
	// ShortStats adds the shortstat of each commit (the first-parent diff for merges).
	ShortStats bool
}

LogFileOptions are the options of LogFile.

type LogOptions

type LogOptions struct {
	// Range is a revision or a range ("main..feature"); empty means HEAD.
	Range string
	// MaxEntries is the most commits to list; zero means 32 (VS Code's default), a negative number means no limit.
	MaxEntries int
	// Skip skips that many commits first.
	Skip int
	// Path limits the log to the commits that changed the path.
	Path string
	// Author and Grep filter by author and by a case-insensitive extended regular expression in the message.
	Author, Grep string
	// ShortStats adds --shortstat (the first-parent diff for merges).
	ShortStats bool
	// Reverse lists the oldest first, along the ancestry path.
	Reverse bool
	// Revs are the revisions the log starts from (the Graph's references: hashes, or names), used instead of Range when set. A revision
	// that starts with "-" is refused with the tag GitRevisionInvalid.
	Revs []string
	// Decorate names the references of each commit in full ("refs/heads/main", "tag: refs/tags/v1") in Commit.RefNames; without it
	// they are short names.
	Decorate bool
	// TopoOrder lists the parents after all their children (--topo-order).
	TopoOrder bool
	// Fixed takes Author and Grep as plain text and not as regular expressions, and ignores case in both.
	Fixed bool
	// RootsOnly lists only the commits that have no parent.
	RootsOnly bool
	// NoWalk lists the commits of Revs themselves, in the order given, and not their ancestors.
	NoWalk bool
}

LogOptions are the options of Log.

type Logger

type Logger func(line string)

Logger receives the lines of the Git channel of the Output panel (SPEC §10.30 "Output"), without the final newline: "> git status -z -uall [34ms]", and the error output of a command. The userinfo of URLs is replaced by *** before.

type LsFilesEntry

type LsFilesEntry struct {
	Mode   string
	Object string
	// Stage is "0" for a normal entry and "1", "2", "3" for the base, ours and theirs of a conflict.
	Stage string
	Path  string
}

LsFilesEntry is one entry of "git ls-files --stage".

func ParseLsFiles

func ParseLsFiles(data []byte) []LsFilesEntry

ParseLsFiles parses the output of "git ls-files --stage -z": records "<mode> <object> <stage>\t<path>" ended by a NUL.

Ported from VS Code: extensions/git/src/git.ts (parseLsFiles).

type LsIgnoredOptions

type LsIgnoredOptions struct {
	// ExcludeStandard takes the ignore rules git reads on its own (.gitignore files, .git/info/exclude and core.excludesFile).
	ExcludeStandard bool
	// ExcludePatterns are .gitignore patterns used in their place or besides: git reads them as a file, so comments, blank lines and
	// trailing spaces are handled as in a .gitignore. None means the option is not given.
	ExcludePatterns []string
	// Directory shows a wholly ignored folder as one entry with a trailing slash, NoEmptyDirectory leaves out the folders with nothing in
	// them.
	Directory, NoEmptyDirectory bool
}

LsIgnoredOptions say what LsIgnored lists.

type LsTreeEntry

type LsTreeEntry struct {
	Mode   string
	Type   string
	Object string
	// Size is the size in bytes as git prints it: a number, or "-" for a tree.
	Size string
	Path string
}

LsTreeEntry is one entry of "git ls-tree -l".

func ParseLsTree

func ParseLsTree(data []byte) []LsTreeEntry

ParseLsTree parses the output of "git ls-tree -l -z": records "<mode> <type> <object> <size>\t<path>" ended by a NUL. The fields are separated by spaces, padded; the path is everything after the tab. VS Code reads the output without -z, one line a record; with -z a path with a newline is right.

Ported from VS Code: extensions/git/src/git.ts (parseLsTree).

type MergeFileOptions

type MergeFileOptions struct {
	// Diff3 puts the base between the two sides in the markers ("--diff3"); the others have "--no-diff3".
	Diff3 bool
	// Ours, Base and Theirs label the sections of the markers ("-L"): "HEAD", "base" and the name of the other side when empty.
	Ours, Base, Theirs string
}

MergeFileOptions are the options of MergeFile.

type MergeFileResult

type MergeFileResult struct {
	// Text is the merged file, with conflict markers where the sides disagree.
	Text string
	// Conflicts is the number of conflicts in Text; 0 when the merge was clean.
	Conflicts int
}

MergeFileResult is the file git merge-file made.

type NameStatus

type NameStatus struct {
	// Status is the letter: A added, M modified, D deleted, R renamed, C copied, T type changed, U unmerged.
	Status byte
	// Score is the similarity of a rename or a copy, 0 to 100; 0 for the others.
	Score int
	// Path is the path of the file (for a rename or a copy, the new path).
	Path string
	// OrigPath is the path a renamed or copied file came from.
	OrigPath string
}

NameStatus is one file of "git diff --name-status -z".

func ParseNameStatus

func ParseNameStatus(data []byte) []NameStatus

ParseNameStatus parses the output of "git diff --name-status -z": a status ("M", or "R100") and a path, or for a rename or a copy the old path and the new one, each ended by a NUL. A record that is cut short is dropped. Note that the old path comes first here, while "git status -z" prints the new path first.

Ported from VS Code: extensions/git/src/git.ts (parseGitChanges).

type ObjectDetails

type ObjectDetails struct {
	Mode   string
	Object string
	Size   int64
}

ObjectDetails is the mode, object and size of a path at a revision.

type Op

type Op struct {
	// Write says that the operation changes the repository: writes run one at a time per repository, in the order they were
	// asked. Reads run in parallel.
	Write bool
	// Scope is what a read reads or a write changes; zero means ScopeAll.
	Scope Scope
}

Op describes an operation of the queue.

type Operation

type Operation int

Operation is an operation that git can leave half done.

const (
	// OperationMerge is "git merge" (MERGE_HEAD).
	OperationMerge Operation = iota
	// OperationRebase is "git rebase" (rebase-merge/ or rebase-apply/).
	OperationRebase
	// OperationCherryPick is "git cherry-pick" (CHERRY_PICK_HEAD).
	OperationCherryPick
	// OperationRevert is "git revert" (REVERT_HEAD).
	OperationRevert
)

The operations.

func (Operation) Command

func (o Operation) Command() string

Command is the name of the git command of the operation.

type Program

type Program struct {
	// Key is the setting as it reads in a configuration file ("core.sshCommand", "alias.st", "filter.lfs.clean").
	Key string
	// Value is the command.
	Value string
}

Program is a setting of a repository's configuration that names a program git can run.

func Programs

func Programs(entries []ConfigEntry) []Program

Programs lists the settings of a repository's configuration that name programs git can run, in the order written (SPEC §10.30 "Trusting a repository"): core.fsmonitor other than a boolean, core.sshCommand, core.hooksPath, core.pager, core.editor, credential.helper starting with "!" or "/", diff.external, filter.*.clean and .smudge, diff.*.textconv and .command, and alias.* starting with "!". Keys are matched without regard to case; an empty value names nothing.

type Progress

type Progress struct {
	// Phase is what git is doing: "Counting objects", "Compressing objects", "Receiving objects", "Writing objects", "Resolving deltas",
	// "Unpacking objects", "Updating files", "Enumerating objects", "Checking out files".
	Phase string
	// Percent is the percentage of the phase that is done, 0 to 100; -1 for a phase that git counts without a percentage ("Enumerating
	// objects: 5").
	Percent int
	// Remote says that the line is the remote's ("remote: Counting objects: ...").
	Remote bool
}

Progress is one line of the progress git prints on its error output when it is given --progress ("Receiving objects: 45% (9/20)").

func ParseProgress

func ParseProgress(line string) (Progress, bool)

ParseProgress reads a line of --progress output. It reports false for a line that is not progress (a message, an error).

Ported from VS Code: extensions/git/src/git.ts (Git.clone: the lines of onSpawn)

func (Progress) Overall

func (p Progress) Overall() int

Overall is the progress of the whole command as a percentage, 0 to 100, from the phase it is in: the counting and the compressing of the sender are the first fifth, the transfer the next 40 percent and the resolving of the deltas the rest; a push, which has no resolving, spends the transfer's share and the rest on writing. A line with no percentage says nothing about the whole (-1).

Ported from VS Code: extensions/git/src/git.ts (Git.clone: totalProgress)

type PullOptions

type PullOptions struct {
	// Rebase rebases the local commits on the fetched ones instead of merging (-r).
	Rebase bool
	// Remote and Branch name what to pull ("origin", "main"); both empty pulls the upstream of the current branch. One of them alone is
	// ignored, as VS Code does.
	Remote, Branch string
	// Tags fetches every tag (--tags).
	Tags bool
	// Unshallow turns a shallow clone into a full one (--unshallow).
	Unshallow bool
	// AutoStash stashes the local changes before the pull and brings them back after it (--autostash; git 2.27 has it for merge and
	// rebase, and 2.30 is the oldest git Emetos runs).
	AutoStash bool
	// Progress, when set, gets the progress of the transfer (--progress).
	Progress func(Progress)
}

PullOptions say how Pull pulls.

type PushOptions

type PushOptions struct {
	// Remote and Refspec name the target ("origin", "main" or "main:main"); both empty pushes the current branch to its upstream (git
	// push, which fails with NoUpstreamBranch when it has none).
	Remote, Refspec string
	// SetUpstream makes the branch track the remote's (-u).
	SetUpstream bool
	// FollowTags pushes the annotated tags that point at the pushed commits (--follow-tags).
	FollowTags bool
	// Tags pushes every tag (--tags).
	Tags bool
	// Force is the force mode.
	Force ForcePushMode
	// Progress, when set, gets the progress of the transfer (--progress).
	Progress func(Progress)
}

PushOptions say what Push pushes.

type Queue

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

Queue orders the operations of one repository (SPEC §10.30 "Queue", ported from VS Code's Repository.run and the operation kinds of operation.ts): reads run in parallel, at most four at a time; writes run one at a time, in the order they were asked; a read that comes after a write that changes what it reads waits for that write. A read never waits for a write that came after it. The queue starts no goroutine of its own for Do; Coalesce starts one per coalesced key while it runs.

Ported from VS Code: extensions/git/src/operation.ts (OperationKind.readOnly) and repository.ts (run).

func NewQueue

func NewQueue(maxReads int) *Queue

NewQueue makes a Queue that runs at most maxReads reads at a time (DefaultMaxReads when maxReads is not positive).

func (*Queue) Coalesce

func (q *Queue) Coalesce(ctx context.Context, key string, op Op, fn func(ctx context.Context) error) error

Coalesce runs fn as an operation of the queue, merging the asks that come while it runs: the first ask starts a run; the asks that arrive while it runs (or while the next one waits) share one more run that starts when it ends. So many file changes during a status refresh give one more refresh, not many (SPEC §10.30 "Queue"). Every caller gets the error of the run it joined, and the run does not stop when one caller's ctx ends (it uses a context without the cancellation of the ask that started it); a caller whose ctx ends stops waiting and gets an error with the tag GitQueueCancelled. A run uses the fn of the first ask that joined it.

func (*Queue) Do

func (q *Queue) Do(ctx context.Context, op Op, fn func(ctx context.Context) error) error

Do waits for the turn of the operation and runs fn. When ctx ends while the operation waits, Do returns an error with the tag GitQueueCancelled and fn is not run. The error of fn is returned untouched.

type RebaseOptions

type RebaseOptions struct {
	// Onto is the commit the commits are put on ("--onto"); the branch itself when empty.
	Onto string
	// RebaseMerges keeps the merge commits ("--rebase-merges").
	RebaseMerges bool
	// Interactive lets the user edit the list of commits first ("-i"): git starts the editor of the Runner's configuration (the
	// sequence editor, then GIT_EDITOR) with the file git-rebase-todo.
	Interactive bool
}

RebaseOptions are the options of Rebase.

type Ref

type Ref struct {
	// Name is the short name: "main", "origin/main", "v1.0".
	Name string
	// FullName is the whole name: "refs/heads/main".
	FullName string
	// Type is the kind.
	Type RefType
	// Commit is the commit the ref names; for an annotated tag, the commit it points at.
	Commit string
	// Object is the object the ref itself names (for an annotated tag, the tag object).
	Object string
	// Remote is the remote of a remote-tracking branch.
	Remote string
	// Upstream is set for a local branch that tracks another.
	Upstream *Upstream
	// Ahead and Behind count the commits of a local branch against its upstream ("[ahead 1, behind 2]").
	Ahead, Behind int
	// Gone says that the upstream no longer exists ("[gone]").
	Gone bool
	// CommitDate is the committer date of the commit.
	CommitDate time.Time
	// Head says that the branch is checked out.
	Head bool
	// AuthorName and Subject are the author and the first line of the message of the commit; set by RefsDetailsFormat only (empty
	// otherwise). For an annotated tag they are those of the commit it points at.
	AuthorName, Subject string
}

Ref is a branch, a remote-tracking branch or a tag.

func ParseRefs

func ParseRefs(data []byte) []Ref

ParseRefs parses the output of "git for-each-ref --format=RefsFormat": one line a ref, the fields separated by NUL. Lines that are not branches, remote-tracking branches or tags (refs/stash, refs/notes) and lines that are cut short are skipped.

Ported from VS Code: extensions/git/src/git.ts (parseRefs, getBranch).

type RefQuery

type RefQuery struct {
	// Sort is "committerdate" (the newest commit first) or "alphabetically" (git's order); anything else is alphabetical.
	Sort string
	// Details adds the author and the subject of each commit (Ref.AuthorName, Ref.Subject).
	Details bool
	// Patterns are the ref prefixes ("refs/heads", "refs/remotes", "refs/tags"); none means all.
	Patterns []string
}

RefQuery says which refs RefsQuery lists.

type RefType

type RefType int

RefType is the kind of a reference.

const (
	// RefHead is a local branch.
	RefHead RefType = iota
	// RefRemoteHead is a remote-tracking branch.
	RefRemoteHead
	// RefTag is a tag.
	RefTag
)

The kinds of reference, as VS Code's RefType.

type Remote

type Remote struct {
	Name string
	// FetchURL and PushURL are the URLs; PushURL is the fetch URL when no pushurl is set.
	FetchURL, PushURL string
	// ReadOnly says that pushing is disabled (the push URL is "no_push", or there is none).
	ReadOnly bool
}

Remote is a configured remote.

func ParseRemoteVerbose

func ParseRemoteVerbose(out string) []Remote

ParseRemoteVerbose reads the output of "git remote -v": lines "name<TAB>url (fetch)" and "name<TAB>url (push)".

Ported from VS Code: extensions/git/src/git.ts (getRemotesGit).

func ParseRemotesConfig

func ParseRemotesConfig(raw string) []Remote

ParseRemotesConfig reads the [remote "name"] sections of the text of a .git/config file; it is the fast path that needs no git process.

Ported from VS Code: extensions/git/src/git.ts (parseGitRemotes).

func RemotesFromConfig

func RemotesFromConfig(entries []ConfigEntry) []Remote

RemotesFromConfig lists the remotes of a repository's configuration (remote.<name>.url and .pushurl) from the settings ReadLocalConfig returned.

type RemoteRef

type RemoteRef struct {
	// Name is the short name: "feature", "v1.0".
	Name string
	// Commit is the object the remote names.
	Commit string
}

RemoteRef is a branch or a tag as a remote has it.

func ParseRemoteTags

func ParseRemoteTags(data []byte) []RemoteRef

ParseRemoteTags reads the output of "git ls-remote --tags": "<object>\trefs/tags/<name>" per line, the peeled "<name>^{}" lines of annotated tags folded into the tag.

type Repo

type Repo struct {
	// Runner starts the commands.
	Runner *Runner
	// Queue orders them.
	Queue *Queue
	// Root is the top level of the work tree (the git directory of a bare repository).
	Root string
	// Info is what git rev-parse said when the repository was opened.
	Info RepoInfo
}

Repo is one repository: the Runner that starts its commands, the Queue that orders them, and what rev-parse said about it. The commands of its methods are reads; the commands of a user's action (stage, commit, checkout...) are added by the steps that need them, as methods that go through the same Queue as writes. A read of Repo is a background command (SPEC §10.30 "Running git"): it runs with core.fsmonitor=false, no pager, no external diff or textconv and no optional locks.

func Discover

func Discover(ctx context.Context, r *Runner, q *Queue, dir string) (*Repo, error)

Discover finds the repository that dir is in (the work tree's top level) and opens it. The error has the tags of Open except NotAtRepositoryRoot.

func Open

func Open(ctx context.Context, r *Runner, q *Queue, root string) (*Repo, error)

Open opens the repository whose work tree is rooted at root: it runs git rev-parse in it and returns the Repo. The error has the tag NotAtRepositoryRoot when root is a folder inside a repository but not its top level, and the tags of the commands (NotAGitRepository, UnsafeRepository...) when git refuses. q may be nil, which gives the repository a Queue of its own.

func (*Repo) Add

func (r *Repo) Add(ctx context.Context, paths []string, o AddOptions) error

Add stages the paths ("git add -A -- <paths>", with Update "git add -u"): a changed file, a new one, a deleted one and a whole folder. With no path it stages the whole tree.

func (*Repo) AddIntentToAdd

func (r *Repo) AddIntentToAdd(ctx context.Context, paths []string) error

AddIntentToAdd records that the untracked paths will be added later ("git add -N"): they show in the index as new files with no content, so their changes can be staged by ranges and a diff lists them.

func (*Repo) AddRemote

func (r *Repo) AddRemote(ctx context.Context, name, remoteURL string) error

AddRemote adds a remote ("git remote add <name> <url>"). A name or URL that is empty or starts with a dash is refused with the tag GitRemoteInvalid before git is started, and a name that exists is refused by git ("remote origin already exists").

Ported from VS Code: extensions/git/src/git.ts (Repository.addRemote)

func (*Repo) AddWorktree

func (r *Repo) AddWorktree(ctx context.Context, o AddWorktreeOptions) error

AddWorktree adds a linked work tree ("git worktree add [-b <branch>] [--no-track] -- <path> <commitish>"). The error has the tags WorktreeAlreadyExists (the path is taken), WorktreeBranchAlreadyUsed (the branch is checked out in another work tree), BranchAlreadyExists and InvalidBranchName.

Ported from VS Code: extensions/git/src/git.ts (Repository.addWorktree)

func (*Repo) AheadBehind

func (r *Repo) AheadBehind(ctx context.Context, a, b string) (ahead, behind int, err error)

AheadBehind counts the commits of a that b lacks (ahead) and of b that a lacks (behind), with "git rev-list --left-right --count a...b".

func (*Repo) Blame

func (r *Repo) Blame(ctx context.Context, o BlameOptions) ([]BlameCommit, error)

Blame runs "git blame --root --incremental" and parses it as a stream.

Ported from VS Code: extensions/git/src/git.ts (Repository.blame2).

func (*Repo) Branch

func (r *Repo) Branch(ctx context.Context, name string, checkout bool, ref string) error

Branch makes a branch at ref (HEAD when empty), and switches to it when checkout is set, with the changes of the work tree and the index kept and the branch tracking nothing ("git checkout -q -b <name> --no-track [<ref>]", else "git branch -q <name> [<ref>]"). The error has the tags BranchAlreadyExists and InvalidBranchName.

func (*Repo) CheckIgnore

func (r *Repo) CheckIgnore(ctx context.Context, paths []string) ([]string, error)

CheckIgnore returns the paths among the given ones that git ignores, with "git check-ignore -v -z --stdin" (a path matched by a negated pattern is not ignored). Paths outside the work tree make git fail; the error has the tag IsInSubmodule for a path inside a submodule.

Ported from VS Code: extensions/git/src/repository.ts (checkIgnore).

func (*Repo) CheckIgnoreFolders

func (r *Repo) CheckIgnoreFolders(ctx context.Context, folders []string) (string, error)

CheckIgnoreFolders says which of the folders (written with a trailing slash) the ignore rules of the repository match whatever the index says, NUL separated ("git check-ignore --no-index -z --stdin"). A folder inside an ignored folder is ignored.

func (*Repo) Checkout

func (r *Repo) Checkout(ctx context.Context, paths []string) error

Checkout puts the index version of the paths in the work tree ("git checkout -q -- <paths>"): modified files go back, deleted files come back. The error has the tag BranchNotYetBorn in a repository with no commit, where VS Code ignores it.

func (*Repo) CheckoutRef

func (r *Repo) CheckoutRef(ctx context.Context, ref string, o CheckoutOptions) error

CheckoutRef switches to a branch, a tag or a commit ("git checkout -q [--track] [--detach] [--force] <ref>"). A work tree whose changes the switch would overwrite fails with the tag DirtyWorkTree and an unborn branch with BranchNotYetBorn.

func (*Repo) CherryPick

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

CherryPick applies the changes of a commit on the current branch and commits them ("git cherry-pick <commit>"). A pick that has conflicts fails with the tag CherryPickConflict and stays in progress. A pick that leaves nothing to commit (the changes are in the branch already) is ended with "git cherry-pick --abort", as VS Code does, and fails with CherryPickEmpty.

func (*Repo) CherryPickAbort

func (r *Repo) CherryPickAbort(ctx context.Context) error

CherryPickAbort ends a cherry-pick that has conflicts ("git cherry-pick --abort").

func (*Repo) Clean

func (r *Repo) Clean(ctx context.Context, paths []string) error

Clean deletes untracked files ("git clean -f -q -- <paths>"); tracked files are never touched, nor are ignored ones. The paths go in several commands when they do not fit on one command line.

func (*Repo) Commit

func (r *Repo) Commit(ctx context.Context, o CommitOptions) error

Commit makes a commit of the index ("git commit --quiet ..."). The error has the tags UnmergedChanges (the index has unmerged paths), EmptyCommitMessage (the editor left an empty message), NoUserNameConfigured and NoUserEmailConfigured (with RequireUserConfig and no identity), and GitCommandFailed with the output of the hook that stopped the commit in its message and its stderr metadata.

func (*Repo) CommitAt

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

CommitAt is the commit that rev names, with its message and parents. The error has the tag GitNoCommit when rev names none.

func (*Repo) CommitChanges

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

CommitChanges reads the commit that id names and the files it changed against its first parent: a normal commit against its parent, a merge commit against its first parent, a root commit against the empty tree. A revision that starts with "-" would be read by git as an option and is refused with the tag GitRevisionInvalid; one that names no commit fails as git fails.

Ported from VS Code: extensions/git/src/commands.ts (viewCommit) and git.ts (Repository.getEmptyTree, diffBetweenWithStats)

func (*Repo) CommitTemplate

func (r *Repo) CommitTemplate(ctx context.Context, home string) string

CommitTemplate is the text of the file commit.template names, without its comment lines; "" when the setting is not set or the file cannot be read (VS Code ignores both). "~/" and "~user/" at the start of the path are expanded as git does, with home as the home folder; a relative path is relative to the root of the repository. It reads the setting with "git config --get", so the configuration of every scope counts.

func (*Repo) Config

func (r *Repo) Config(ctx context.Context, scope string) ([]ConfigEntry, error)

Config lists the settings of one scope ("local", "global", "system" or "worktree"; empty means local) with "git config --list -z".

func (*Repo) ConfigValue

func (r *Repo) ConfigValue(ctx context.Context, key string) (string, bool, error)

ConfigValue reads one setting as git sees it, from every scope ("git config --get <key>"): the value without its final newline, and false when no scope has the key.

func (*Repo) Continue

func (r *Repo) Continue(ctx context.Context, op Operation) error

Continue finishes the operation after its conflicts were resolved and staged ("git <command> --continue"), with the message the operation prepared and no editor (GIT_EDITOR=true). A rebase goes on to its next commit and may stop again on a conflict (the tag Conflict); files that are still unmerged fail with UnmergedChanges.

func (*Repo) CreateBranch

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

CreateBranch makes a branch at HEAD and switches to it, keeping the changes of the work tree and the index ("git checkout -q -b <name> --no-track"). The error has the tags BranchAlreadyExists and InvalidBranchName.

func (*Repo) DeleteBranch

func (r *Repo) DeleteBranch(ctx context.Context, name string, force bool) error

DeleteBranch deletes a local branch ("git branch -d <name>", "-D" with force). A branch whose commits no other branch has fails with the tag BranchNotFullyMerged unless force is set; the current branch is refused by git.

func (*Repo) DeleteRef

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

DeleteRef deletes a reference ("git update-ref -d <ref>"): "HEAD" on a branch with one commit leaves the branch with none.

func (*Repo) DeleteRemoteRef

func (r *Repo) DeleteRemoteRef(ctx context.Context, remote, ref string, force bool) error

DeleteRemoteRef deletes a branch or a tag at a remote ("git push <remote> --delete [--force] <ref>"); ref is the name at the remote ("feature", "v1.0"), not the remote-tracking name.

func (*Repo) DeleteTag

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

DeleteTag deletes a local tag ("git tag -d <name>").

func (*Repo) DiffPath

func (r *Repo) DiffPath(ctx context.Context, cached bool, path string) (string, error)

DiffPath returns the text of "git diff" (or "git diff --cached" for cached) for one path, which is what the diff of a submodule shows: the "Subproject commit" lines of the old and the new commit. The output is bounded by MaxBlobSize.

Ported from VS Code: extensions/git/src/git.ts (Repository.diffWithHEAD, diffIndexWithHEAD).

func (*Repo) EmptyTree

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

EmptyTree is the id of the empty tree of the repository's hash algorithm ("git hash-object -t tree" of nothing).

Ported from VS Code: extensions/git/src/git.ts (Repository.getEmptyTree)

func (*Repo) FastForwardBranch

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

FastForwardBranch moves a local branch that is not checked out to the commit its upstream has, when that is a fast-forward ("git fetch <remote> <upstream>:<branch>"). It does nothing for a branch with no upstream, and a branch with commits of its own is left alone (BranchFastForwardRejected is not an error here). The checkout of a branch calls it with git.pullBeforeCheckout.

Ported from VS Code: extensions/git/src/repository.ts (fastForwardBranch)

func (*Repo) Fetch

func (r *Repo) Fetch(ctx context.Context, o FetchOptions) error

Fetch runs git fetch. An error has the tags of the generic rules (AuthenticationFailed, CantAccessRemote, RepositoryNotFound...), NoRemoteRepositorySpecified, RemoteConnectionError and, for a ref that cannot be fast-forwarded, BranchFastForwardRejected.

Ported from VS Code: extensions/git/src/git.ts (Repository.fetch)

func (*Repo) FetchTags

func (r *Repo) FetchTags(ctx context.Context, remote string, tags []string, force bool) error

FetchTags fetches the tags by name from a remote, replacing the local ones when force is set ("git fetch <remote> refs/tags/<t>:refs/tags/<t>... [--force]"): the way out of a pull that stopped on tags that differ.

Ported from VS Code: extensions/git/src/git.ts (Repository.fetchTags)

func (*Repo) FindTrackingBranches

func (r *Repo) FindTrackingBranches(ctx context.Context, upstream string) ([]string, error)

FindTrackingBranches lists the local branches whose upstream is the remote-tracking branch ("origin/feature").

func (*Repo) HasCommit

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

HasCommit says whether HEAD points to a commit: false in a repository before its first commit.

func (*Repo) InputTemplate

func (r *Repo) InputTemplate(ctx context.Context, home string) string

InputTemplate is the text the commit box starts with: the message git prepared for a merge or a squash, else the commit template.

Ported from VS Code: extensions/git/src/repository.ts (getInputTemplate).

func (*Repo) LastCommit

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

LastCommit is the commit HEAD names, with its message and parents. The error has the tag GitNoCommit in a repository with no commit.

func (*Repo) Log

func (r *Repo) Log(ctx context.Context, o LogOptions) ([]Commit, error)

Log runs "git log -z" and parses it as a stream. A repository with no commit gives no commits.

Ported from VS Code: extensions/git/src/git.ts (Repository.log).

func (*Repo) LogFile

func (r *Repo) LogFile(ctx context.Context, o LogFileOptions) ([]Commit, error)

LogFile lists the commits that changed a file, newest first, each with the path the file had in it (Commit.FilePath, which differs from Path before a rename when Follow is set). A file that git does not know, and a repository with no commit, give no commits. The log is run in the background (SPEC §10.30 "Running git").

A merge commit that changed the file is listed with its path and its stat against its first parent (--diff-merges=first-parent, git 2.31), so that the Timeline can name the file of a merge.

Ported from VS Code: extensions/git/src/git.ts (Repository.logFile)

func (*Repo) LsFiles

func (r *Repo) LsFiles(ctx context.Context, paths ...string) ([]LsFilesEntry, error)

LsFiles lists the entries of the index for the paths (all when none) with "git ls-files --stage -z".

func (*Repo) LsFilesIn

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

LsFilesIn lists the tracked files of the work tree in dir, NUL separated ("git ls-files -z"): the files a new worktree has.

func (*Repo) LsIgnored

func (r *Repo) LsIgnored(ctx context.Context, o LsIgnoredOptions) (string, error)

LsIgnored lists the untracked files that are ignored, NUL separated ("git ls-files --others --ignored -z"). The patterns are written to a file in a private folder of the temporary files for the time of the command: git reads them from a file (a pipe is an empty file to it), so they are parsed as a .gitignore is. The error has the tag GitWorktreePatternsFailed when the file cannot be made.

Ported from VS Code: extensions/git/src/repository.ts (_getWorktreeIncludePaths, _getWorktreeSymlinkFolders)

func (*Repo) LsTree

func (r *Repo) LsTree(ctx context.Context, treeish, path string, recursive bool) ([]LsTreeEntry, error)

LsTree lists a tree with "git ls-tree -l -z".

func (*Repo) MaybeRebased

func (r *Repo) MaybeRebased(ctx context.Context, branch string) bool

MaybeRebased says that the upstream of the branch has commits with the same changes as commits of the branch ("git log --oneline --cherry <branch>...<branch>@{upstream}" starts with an equal commit, marked "="): the branch was probably rebased, and pulling merges the old commits and the new ones. A failure of the command (no upstream) is false.

Ported from VS Code: extensions/git/src/repository.ts (checkIfMaybeRebased)

func (*Repo) Merge

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

Merge merges the ref into the current branch ("git merge <ref>"). A merge that has conflicts fails with the tag Conflict and stays in progress; one that local changes would be overwritten by fails with DirtyWorkTree.

func (*Repo) MergeAbort

func (r *Repo) MergeAbort(ctx context.Context) error

MergeAbort ends a merge that has conflicts and puts the work tree back as it was ("git merge --abort").

func (*Repo) MergeBase

func (r *Repo) MergeBase(ctx context.Context, revs ...string) (hash string, ok bool, err error)

MergeBase returns the best common ancestor of the revisions with "git merge-base"; ok is false when they have none.

func (*Repo) MergeFile

func (r *Repo) MergeFile(ctx context.Context, path string, o MergeFileOptions) (MergeFileResult, error)

MergeFile does the three-way merge of the stages of a conflicted file again ("git merge-file -p"): stage 2 (ours), stage 1 (the base) and stage 3 (theirs) of the index, written to a temporary folder that is removed afterwards. A file that was added on both sides has no base and merges against an empty one, as git does. A stage that is missing on a side that matters (a file deleted on one side) fails with the tag MergeStageMissing. path is absolute or relative to the root.

Ported from VS Code: extensions/git/src/git.ts (Repository.mergeFile)

func (*Repo) MergeMessage

func (r *Repo) MergeMessage() string

MergeMessage is the message git prepared for the merge that is in progress, from MERGE_MSG; "" when there is none.

func (*Repo) Mv

func (r *Repo) Mv(ctx context.Context, from, to string) error

Mv renames a file or folder, in the work tree and the index ("git mv -- <from> <to>").

func (*Repo) NameStatus

func (r *Repo) NameStatus(ctx context.Context, d DiffSpec) ([]NameStatus, error)

NameStatus runs "git diff --name-status -z" and parses it.

Ported from VS Code: extensions/git/src/git.ts (Repository.diffFiles, diffBetween).

func (*Repo) ObjectDetails

func (r *Repo) ObjectDetails(ctx context.Context, treeish, path string) (ObjectDetails, error)

ObjectDetails describes a path at a revision: in the index when treeish is empty or ":1", ":2" or ":3" (the stages of a conflict), otherwise in that tree. The error has the tag UnknownPath when git does not know the path.

Ported from VS Code: extensions/git/src/git.ts (Repository.getObjectDetails).

func (*Repo) Pull

func (r *Repo) Pull(ctx context.Context, o PullOptions) (changed bool, err error)

Pull runs git pull. It reports false when git said that everything was up to date. An error has the tags Conflict (a merge or rebase that stopped on conflicts), DirtyWorkTree (local changes in the way, with "Cannot pull with rebase, you have unstaged changes" as VS Code words it), NoUserNameConfigured, CantLockRef, CantRebaseMultipleBranches, TagConflict (tags that would be replaced; the names are in the error output), NoRemoteRepositorySpecified, RemoteConnectionError and the generic ones.

Ported from VS Code: extensions/git/src/git.ts (Repository.pull)

func (*Repo) Push

func (r *Repo) Push(ctx context.Context, o PushOptions) error

Push runs git push. An error has the tags PushRejected, ForcePushWithLeaseRejected and ForcePushWithLeaseIfIncludesRejected (for the force modes that say why), PermissionDenied, RemoteConnectionError, NoUpstreamBranch and the generic ones; the remote may also refuse a push that the branch protection of the server does not allow, with the message it sends (the last line of the error output).

Ported from VS Code: extensions/git/src/git.ts (Repository.push)

func (*Repo) PushTags

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

PushTags pushes every tag to a remote ("git push --tags [<remote>]"); with no remote git uses the one of the current branch. A remote that has the tags already is not a failure; a rejected push has the tag PushRejected.

func (*Repo) ReadBlob

func (r *Repo) ReadBlob(ctx context.Context, object string) ([]byte, error)

ReadBlob returns the content of an object named like "HEAD:path/file", ":path/file" (the index) or ":2:path/file" (a stage of a conflict), read with "git cat-file blob". A file larger than MaxBlobSize is not read: the error has the tag GitContentTooLarge.

func (*Repo) ReadVersion

func (r *Repo) ReadVersion(ctx context.Context, ref, path string) (data []byte, found bool, err error)

ReadVersion reads a version of a file (ObjectName gives its name) with "git cat-file blob". found is false when git has no such version: the file is not in the index or the commit, the commit is unknown, or the path exists on disk but not there. A file larger than MaxBlobSize is not read: the error has the tag GitContentTooLarge. The content is raw, with no textconv and no filter.

func (*Repo) Rebase

func (r *Repo) Rebase(ctx context.Context, branch string, o RebaseOptions) error

Rebase puts the commits of the current branch on top of the branch ("git rebase [-i] [--rebase-merges] [--onto <commit>] <branch>"). A rebase that stops on a conflict fails with the tag Conflict and stays in progress; one that cannot start because of local changes fails with DirtyWorkTree; a branch with several heads fails with CantRebaseMultipleBranches.

func (*Repo) RebaseAbort

func (r *Repo) RebaseAbort(ctx context.Context) error

RebaseAbort ends a rebase and puts the branch back as it was ("git rebase --abort").

func (*Repo) RebaseSkip

func (r *Repo) RebaseSkip(ctx context.Context) error

RebaseSkip leaves out the commit the rebase stopped at ("git rebase --skip").

func (*Repo) Reflog

func (r *Repo) Reflog(ctx context.Context, ref string) ([]string, error)

Reflog lists the subjects of the reflog of a ref, newest first ("branch: Created from main", "checkout: moving from main to topic"); a ref with no reflog gives none.

Ported from VS Code: extensions/git/src/git.ts (Repository.reflog)

func (*Repo) Refs

func (r *Repo) Refs(ctx context.Context, patterns ...string) ([]Ref, error)

Refs runs "git for-each-ref" for the patterns ("refs/heads", "refs/remotes", "refs/tags"; none means all) and parses it.

Ported from VS Code: extensions/git/src/git.ts (Repository.getRefs).

func (*Repo) RefsQuery

func (r *Repo) RefsQuery(ctx context.Context, q RefQuery) ([]Ref, error)

RefsQuery lists the refs a query asks for, parsed as ParseRefs does.

Ported from VS Code: extensions/git/src/git.ts (Repository.getRefs)

func (*Repo) RemoteTags

func (r *Repo) RemoteTags(ctx context.Context, remote string) ([]RemoteRef, error)

RemoteTags lists the tags a remote has ("git ls-remote --tags <remote>"). An annotated tag is listed once, by its name. The command reaches the remote, so git may ask for a password and a failure can be AuthenticationFailed or RemoteConnectionError.

Ported from VS Code: extensions/git/src/git.ts (Repository.getRemoteRefs)

func (*Repo) Remotes

func (r *Repo) Remotes(ctx context.Context) ([]Remote, error)

Remotes lists the remotes with "git remote -v".

func (*Repo) RemoveRemote

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

RemoveRemote removes a remote and its remote-tracking branches ("git remote remove <name>").

Ported from VS Code: extensions/git/src/git.ts (Repository.removeRemote)

func (*Repo) RemoveWorktree

func (r *Repo) RemoveWorktree(ctx context.Context, path string, force bool) error

RemoveWorktree removes a linked work tree ("git worktree remove [--force] -- <path>"). One with changes or untracked files fails with the tag WorktreeContainsChanges unless force is set.

Ported from VS Code: extensions/git/src/git.ts (Repository.deleteWorktree)

func (*Repo) RenameBranch

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

RenameBranch renames the current branch ("git branch -m <name>"). The error has the tags InvalidBranchName and BranchAlreadyExists.

func (*Repo) Reset

func (r *Repo) Reset(ctx context.Context, paths []string) error

Reset unstages the paths: their index entries go back to HEAD and the work tree is not touched ("git reset -q HEAD -- <paths>"). Before the first commit there is no HEAD to go back to and the entries are removed from the index ("git rm --cached -r -q"). With no path it unstages everything. Unmerged paths are left as they are, which git reports with a status of 1 that is no failure.

Ported from VS Code: extensions/git/src/git.ts (Repository.revert).

func (*Repo) ResetSoft

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

ResetSoft moves HEAD, and the branch it names, to the commit, and leaves the index and the work tree as they are ("git reset --soft <commit>"): the changes of the commits it leaves behind stay staged.

func (*Repo) ResolveCommit

func (r *Repo) ResolveCommit(ctx context.Context, rev string) (hash string, ok bool, err error)

ResolveCommit finds the commit that a revision names ("a1b2c3" is the beginning of a hash); ok is false when it names none.

func (*Repo) RevList

func (r *Repo) RevList(ctx context.Context, o RevListOptions) ([]string, error)

RevList lists the hashes of the commits reachable from the revisions, newest first, with "git rev-list". It is the cheap way to ask which commits match a text: the Graph's search joins two lists with the order of a third.

func (*Repo) RevListCount

func (r *Repo) RevListCount(ctx context.Context, spec string) (int, error)

RevListCount counts the commits of a revision or a range with "git rev-list --count".

func (*Repo) Rm

func (r *Repo) Rm(ctx context.Context, paths []string, o RmOptions) error

Rm removes the paths from the work tree and the index ("git rm -q -- <paths>"). git refuses a file that has changes, staged or not.

func (*Repo) SetUpstream

func (r *Repo) SetUpstream(ctx context.Context, branch, upstream string) error

SetUpstream makes a local branch track a remote-tracking branch ("git branch --set-upstream-to=<upstream> <branch>"); the branch is the current one when empty.

Ported from VS Code: extensions/git/src/git.ts (Repository.setBranchUpstream)

func (*Repo) SquashMessage

func (r *Repo) SquashMessage() string

SquashMessage is the message git prepared for a squash merge, from SQUASH_MSG; "" when there is none.

func (*Repo) StageContent

func (r *Repo) StageContent(ctx context.Context, path string, data []byte) error

StageContent makes data the index version of the file at path, without touching the work tree ("git hash-object -w --stdin --path", then "git update-index --add --cacheinfo"): the way a part of a file is staged, so that staging a hunk cannot disturb the file the user is editing. The file keeps the mode the index has for it (an executable file stays one), a file that is not in the index is added with the mode 100644. hash-object applies the filters the attributes of the path name (the end of line conversion), as "git add" does.

Ported from VS Code: extensions/git/src/git.ts (Repository.stage).

func (*Repo) Stash

func (r *Repo) Stash(ctx context.Context, o StashOptions) error

Stash puts the changes aside ("git stash push [-u] [-S] [-m message]"). A repository with nothing to stash fails with the tag NoLocalChanges, and one before its first commit with git's own refusal.

Ported from VS Code: extensions/git/src/git.ts (Repository.createStash)

func (*Repo) StashApply

func (r *Repo) StashApply(ctx context.Context, index int, o StashApplyOptions) error

StashApply applies a stash and keeps it ("git stash apply [--index] [stash@{n}]"), failing as StashPop does.

Ported from VS Code: extensions/git/src/git.ts (Repository.applyStash)

func (*Repo) StashChanges

func (r *Repo) StashChanges(ctx context.Context, index int) (StashChanges, error)

StashChanges reads the stash stash@{index}: "git diff --name-status" of the commit it was made on against the stash for the tracked files, and the files of the commit of the untracked ones. It fails with the tag GitStashMissing when there is no such stash.

Ported from VS Code: extensions/git/src/git.ts (Repository.showStash) and commands.ts (_viewStash)

func (*Repo) StashChangesAt

func (r *Repo) StashChangesAt(ctx context.Context, hash string) (StashChanges, error)

StashChangesAt reads what the stash commit with this hash holds, as StashChanges does: the stash need not be in the list any more as long as git still has its commits (git keeps the commit of a dropped stash for a while), which is how a stash tab keeps showing a stash that was popped. The error has the tag GitStashHashInvalid for something that is not a full object name, and GitCommitNotFound for a commit git does not have.

func (*Repo) StashChangesOf

func (r *Repo) StashChangesOf(ctx context.Context, s Stash) (StashChanges, error)

StashChangesOf reads what a stash holds.

func (*Repo) StashClear

func (r *Repo) StashClear(ctx context.Context) error

StashClear removes every stash ("git stash clear").

Ported from VS Code: extensions/git/src/git.ts (Repository.dropStash without an index)

func (*Repo) StashDrop

func (r *Repo) StashDrop(ctx context.Context, index int) error

StashDrop removes the stash with the index ("git stash drop stash@{n}"); StashLatest is the newest. A missing one fails with the tag NoStashFound.

Ported from VS Code: extensions/git/src/git.ts (Repository.dropStash)

func (*Repo) StashPop

func (r *Repo) StashPop(ctx context.Context, index int, o StashApplyOptions) error

StashPop applies a stash and drops it ("git stash pop [--index] [stash@{n}]"); StashLatest is the newest. A stash that conflicts with the work tree fails with the tag StashConflict and is kept, a missing one with NoStashFound, and files that would be overwritten with LocalChangesOverwritten.

Ported from VS Code: extensions/git/src/git.ts (Repository.popStash)

func (*Repo) Stashes

func (r *Repo) Stashes(ctx context.Context) ([]Stash, error)

Stashes lists the stash with "git stash list -z".

func (*Repo) Status

func (r *Repo) Status(ctx context.Context, o StatusOptions) (StatusResult, error)

Status runs "git status -z" and parses it as a stream. At the limit the command is ended (SIGTERM to its process group) and the answer says so.

Ported from VS Code: extensions/git/src/git.ts (Repository.getStatus).

func (*Repo) SymbolicRef

func (r *Repo) SymbolicRef(ctx context.Context, ref string) (target string, ok bool, err error)

SymbolicRef reads where a symbolic ref points, short ("origin/main" for refs/remotes/origin/HEAD); ok is false when the ref is not a symbolic ref or does not exist.

func (*Repo) Tag

func (r *Repo) Tag(ctx context.Context, name, message, ref string) error

Tag makes a tag at ref (HEAD when empty): a lightweight one, or an annotated one ("-a -m") when the message is not empty.

func (*Repo) UpdateSubmodules

func (r *Repo) UpdateSubmodules(ctx context.Context, paths []string) error

UpdateSubmodules checks out the commit the index names in the submodules at the paths ("git submodule update -- <paths>"): the way to discard the changes of a submodule's HEAD.

func (*Repo) WorktreeDetails

func (r *Repo) WorktreeDetails(ctx context.Context) ([]Worktree, error)

WorktreeDetails is Worktrees with the subject of the commit each work tree has checked out.

Ported from VS Code: extensions/git/src/repository.ts (getWorktreeDetails)

func (*Repo) Worktrees

func (r *Repo) Worktrees(ctx context.Context) ([]Worktree, error)

Worktrees lists the work trees of the repository, the main one first ("git worktree list --porcelain"). It lists the same worktrees whichever of them the repository is.

type RepoInfo

type RepoInfo struct {
	// WorkTree is the top level of the work tree ("--show-toplevel"); empty for a bare repository.
	WorkTree string
	// GitDir is the git directory ("--git-dir"), absolute: the folder .git, or for a linked worktree a folder under
	// .git/worktrees of the main repository.
	GitDir string
	// CommonDir is the git directory that holds the objects and refs shared by the worktrees ("--git-common-dir"); equal to
	// GitDir for a repository that is not a linked worktree.
	CommonDir string
	// SuperProject is the work tree of the repository that holds this one as a submodule, empty when there is none.
	SuperProject string
	// InsideWorkTree says that the folder is inside the work tree (false inside the git directory).
	InsideWorkTree bool
	// Bare says that the repository has no work tree.
	Bare bool
	// Shallow says that the repository has an incomplete history.
	Shallow bool
}

RepoInfo is what "git rev-parse" tells about the repository a folder is in.

func ParseRevParse

func ParseRevParse(gitDirOutput, topLevelOutput, cwd string) (RepoInfo, error)

ParseRevParse builds the RepoInfo from the outputs of the two rev-parse commands run in cwd (topLevel is empty for a bare repository or a folder inside the git directory). Relative paths are made absolute against cwd. The error has the tag GitOutputUnexpected.

Ported from VS Code: extensions/git/src/git.ts (getRepositoryRoot, getRepositoryDotGit).

type Result

type Result struct {
	// ExitCode is the exit status; -1 when git was ended by a signal.
	ExitCode int
	// Stdout is the standard output kept by Run; RunStream leaves it empty.
	Stdout []byte
	// Stderr is the last 2 KiB of the error output.
	Stderr string
	// Duration is how long the command ran, by the clock of the Config.
	Duration time.Duration
}

Result is what a command left.

type RevListOptions

type RevListOptions struct {
	// Revs are the revisions the list starts from; none is HEAD. A revision that starts with "-" is refused with the tag
	// GitRevisionInvalid.
	Revs []string
	// TopoOrder lists the parents after all their children.
	TopoOrder bool
	// Author and Grep keep the commits whose author (name or address) or message has the text, as plain text and ignoring case.
	Author, Grep string
}

RevListOptions are the options of RevList.

type RmOptions

type RmOptions struct {
	// Cached removes the paths from the index and leaves the files ("--cached").
	Cached bool
	// Recursive allows folders ("-r").
	Recursive bool
	// Force removes a file that has changes ("-f"); with Cached it removes the index entry whatever the file holds.
	Force bool
}

RmOptions are the options of Rm.

type Runner

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

Runner starts git commands. It holds no state besides its Config and is safe for concurrent use.

func NewRunner

func NewRunner(cfg Config) *Runner

NewRunner makes a Runner.

func (*Runner) Clone

func (r *Runner) Clone(ctx context.Context, source, parentDir string, o CloneOptions) (string, error)

Clone clones the repository at source into a new folder of parentDir and returns the path of the folder. The folder is named after the repository (CloneOptions.TargetName), parentDir is made when it is missing, and the transfer is reported to o.Progress. It is a write command and not a background one: git may ask for a password through the askpass program of the Config, and the error has the tag AuthenticationFailed when none was given, RepositoryNotFound, CantAccessRemote and the other tags of the generic rules. The command runs outside every repository (a parentDir inside a repository that was not trusted is fine: git reads none of its files).

A clone that fails or is cancelled leaves no folder: the one this call made is removed, with what git put in it. A folder that existed (an empty one named by TargetName) is emptied. A source that is a path is read as git would from parentDir ("~" is the home folder of the Config's environment).

Ported from VS Code: extensions/git/src/git.ts (Git.clone)

func (*Runner) Init

func (r *Runner) Init(ctx context.Context, dir string, o InitOptions) error

Init makes a repository in dir with "git init". It is a write command and not a background one: the user asked for it.

Ported from VS Code: extensions/git/src/git.ts (Git.init).

func (*Runner) Path

func (r *Runner) Path() string

Path returns the git program of the Runner.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, c Command) (Result, error)

Run runs the command and returns its output, kept up to the limit of the Config (64 MiB; a command that prints more is stopped with the error GitOutputTooLarge). A failure is classified into the tags of VS Code's GitErrorCodes (classify) or is GitCommandFailed; the Result is returned with the error, so that the caller can read the output. Cancelling ctx sends SIGTERM to the whole process group and, after KillGrace, SIGKILL; the error has the tag GitCancelled.

Ported from VS Code: extensions/git/src/git.ts (Git.exec, _exec, spawn).

func (*Runner) RunStream

func (r *Runner) RunStream(ctx context.Context, c Command, consume func(stdout io.Reader) error) (Result, error)

RunStream runs the command and hands its standard output to consume as a stream. When consume returns ErrStopStream the command is ended and RunStream returns nil; when it returns another error the command is ended and that error is returned untouched; when it returns nil the rest of the output is read and dropped. The Result has no Stdout.

func (*Runner) Version

func (r *Runner) Version() Version

Version returns the version of the git of the Runner, as given in its Config.

type Scope

type Scope uint8

Scope is the part of a repository that an operation reads or changes. A read waits only for the earlier writes whose scope overlaps its own ("a read waits for a write that changes what it reads", SPEC §10.30 "Queue").

const (
	// ScopeIndex is the index (staging area).
	ScopeIndex Scope = 1 << iota
	// ScopeWorkTree is the files of the work tree.
	ScopeWorkTree
	// ScopeRefs is the branches, tags, HEAD and the commits.
	ScopeRefs
	// ScopeConfig is the configuration and the remotes.
	ScopeConfig
	// ScopeStash is the stash.
	ScopeStash
	// ScopeAll is everything; use it when unsure.
	ScopeAll = ScopeIndex | ScopeWorkTree | ScopeRefs | ScopeConfig | ScopeStash
)

The scopes.

type ShortStat

type ShortStat struct {
	Files, Insertions, Deletions int
}

ShortStat is the line "3 files changed, 2 insertions(+), 1 deletion(-)" of --shortstat.

type Stash

type Stash struct {
	Hash    string
	Parents []string
	// Index is the n of stash@{n}.
	Index int
	// Branch is the branch the stash was made on.
	Branch string
	// Description is the stash's message; "WIP (message)" for a stash made without one.
	Description string
	AuthorDate  time.Time
	CommitDate  time.Time
}

Stash is an entry of the stash.

func ParseStashes

func ParseStashes(data []byte) []Stash

ParseStashes parses the output of "git stash list -z --format=StashFormat". A record that is cut short is dropped.

Ported from VS Code: extensions/git/src/git.ts (parseGitStashes).

type StashApplyOptions

type StashApplyOptions struct {
	// ReinstateIndex puts back what was staged, not only the changes ("--index").
	ReinstateIndex bool
}

StashApplyOptions are the options of StashApply and StashPop.

type StashChange

type StashChange struct {
	NameStatus
	// Untracked says that the file was untracked when the stash was made: it is in the commit of the untracked files (the third
	// parent of the stash), not in the stash itself.
	Untracked bool
}

StashChange is a file a stash changed.

type StashChanges

type StashChanges struct {
	// Stash is the stash.
	Stash Stash
	// Base is the commit the stash was made on (its first parent): what the changes are against.
	Base string
	// Untracked is the commit that holds the untracked files (the third parent of the stash), empty when the stash has none.
	Untracked string
	// Changes are the files, tracked ones first with git's rename detection, then the untracked ones as added files.
	Changes []StashChange
}

StashChanges is what a stash holds: the files it changed against the commit it was made on, and the untracked files it saved.

type StashOptions

type StashOptions struct {
	// Message names the stash ("git stash push -m"); empty gives git's own "WIP on <branch>: <commit> <subject>".
	Message string
	// IncludeUntracked also stashes the untracked files ("-u").
	IncludeUntracked bool
	// Staged stashes only what is in the index ("-S", git 2.35 or newer).
	Staged bool
}

StashOptions are the options of Stash.

type Status

type Status int

Status is what a file's state is called in the Source Control view: the values of VS Code's Status enum, in its order (extensions/git/src/api/git.d.ts), so that the icons, letters, colors and sort orders can be ported unchanged.

const (
	// StatusNone is no status.
	StatusNone Status = iota - 1
	// StatusIndexModified is "M" in the first column: modified and staged.
	StatusIndexModified
	// StatusIndexAdded is "A" in the first column: added to the index.
	StatusIndexAdded
	// StatusIndexDeleted is "D" in the first column: deleted from the index.
	StatusIndexDeleted
	// StatusIndexRenamed is "R" in the first column: renamed in the index.
	StatusIndexRenamed
	// StatusIndexCopied is "C" in the first column: copied in the index.
	StatusIndexCopied
	// StatusModified is "M" in the second column: modified in the work tree.
	StatusModified
	// StatusDeleted is "D" in the second column: deleted in the work tree.
	StatusDeleted
	// StatusUntracked is "??".
	StatusUntracked
	// StatusIgnored is "!!".
	StatusIgnored
	// StatusIntentToAdd is "A" in the second column (git add -N).
	StatusIntentToAdd
	// StatusIntentToRename is "R" in the second column.
	StatusIntentToRename
	// StatusTypeChanged is "T" in the second column.
	StatusTypeChanged
	// StatusAddedByUs is "AU": unmerged, added by us.
	StatusAddedByUs
	// StatusAddedByThem is "UA": unmerged, added by them.
	StatusAddedByThem
	// StatusDeletedByUs is "DU": unmerged, deleted by us.
	StatusDeletedByUs
	// StatusDeletedByThem is "UD": unmerged, deleted by them.
	StatusDeletedByThem
	// StatusBothAdded is "AA": unmerged, added by both.
	StatusBothAdded
	// StatusBothDeleted is "DD": unmerged, deleted by both.
	StatusBothDeleted
	// StatusBothModified is "UU": unmerged, modified by both.
	StatusBothModified
)

The statuses. The zero value is StatusNone, which VS Code has no name for: "no status in this group".

type StatusEntry

type StatusEntry struct {
	// X is the status of the index (the first column), Y the status of the work tree (the second); a space is no change.
	X, Y byte
	// Path is the path of the file (for a rename, the new path).
	Path string
	// OrigPath is the path a renamed or copied file came from, empty for the others. VS Code calls the new path "rename" and
	// the old one "path" in its IFileStatus; here the names say what they are.
	OrigPath string
}

StatusEntry is one record of "git status -z" (porcelain version 1): the two status columns, the path, and for a rename or a copy the path it came from.

func ParseStatus

func ParseStatus(data []byte) []StatusEntry

ParseStatus parses a whole output of "git status -z".

func (StatusEntry) Statuses

func (e StatusEntry) Statuses() (merge, index, work Status)

Statuses maps the two columns to the statuses of the groups of the Source Control view, as VS Code's Repository.updateModelState does (extensions/git/src/repository.ts): merge is set for the seven unmerged codes (DD, AU, UD, UA, DU, AA, UU) and then the other two are StatusNone; untracked and ignored files have only work set; otherwise index is set by the first column (M A D R C) and work by the second (M D A R T). A column that gives no status is StatusNone.

type StatusOptions

type StatusOptions struct {
	// Untracked is how untracked files are listed.
	Untracked UntrackedMode
	// Ignored adds the ignored files ("--ignored").
	Ignored bool
	// IgnoreSubmodules adds --ignore-submodules (git.ignoreSubmodules).
	IgnoreSubmodules bool
	// SimilarityThreshold is git.similarityThreshold; it is passed as --find-renames=N% when it is not 0 or 50 (git's default).
	SimilarityThreshold int
	// Limit stops the command once more than Limit entries were read (git.statusLimit, 10000 by default in the extension);
	// zero means no limit.
	Limit int
}

StatusOptions are the options of Status.

type StatusParser

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

StatusParser reads the output of "git status -z" as a stream: Write it the chunks as they arrive, cut anywhere, and read Entries. A record that is not complete yet waits for the next chunk; one that never completes (a stream cut short) is dropped. It implements io.Writer, so io.Copy(parser, stdout) feeds it.

Ported from VS Code: extensions/git/src/git.ts (GitStatusParser).

func (*StatusParser) Entries

func (p *StatusParser) Entries() []StatusEntry

Entries returns the records read so far.

func (*StatusParser) Write

func (p *StatusParser) Write(chunk []byte) (int, error)

Write adds a chunk of the output.

type StatusResult

type StatusResult struct {
	// Entries are the records, at most Limit of them.
	Entries []StatusEntry
	// Total is the number of records read: more than Limit when the limit was hit (the command was stopped there).
	Total int
	// HitLimit says that the command was stopped because it printed more than Limit records.
	HitLimit bool
}

StatusResult is the answer of Status.

type Submodule

type Submodule struct {
	Name, Path, URL string
}

Submodule is an entry of .gitmodules.

func ParseGitmodules

func ParseGitmodules(raw string) []Submodule

ParseGitmodules reads the text of a .gitmodules file: the [submodule "name"] sections that have both a path and a url.

Ported from VS Code: extensions/git/src/git.ts (parseGitmodules).

type TrustStore

type TrustStore interface {
	// IsTrusted reports whether the repository with this root, or a folder above it that was trusted as a parent, is trusted.
	IsTrusted(root string) bool
}

TrustStore says which repositories the user trusted (extensions/gitscm/trust); the paths it is asked about are real paths, with symbolic links resolved.

type UntrackedMode

type UntrackedMode int

UntrackedMode is git.untrackedChanges: how untracked files are listed.

const (
	// UntrackedAll lists every untracked file ("-uall"): the modes "mixed" and "separate".
	UntrackedAll UntrackedMode = iota
	// UntrackedNone lists none ("-uno"): the mode "hidden".
	UntrackedNone
)

type Upstream

type Upstream struct {
	// Remote is the remote's name, "." for a branch of this repository.
	Remote string
	// Name is the branch at the remote ("main").
	Name string
	// Ref is the full name of the remote-tracking branch ("refs/remotes/origin/main").
	Ref string
}

Upstream is the branch a local branch tracks.

type Version

type Version struct {
	Major, Minor, Patch int
}

Version is the version of a git program: the numbers of "git version 2.43.0.windows.1" (2.43.0) or of "git version 2.56.0.rc1" (2.56.0). A pre-release compares like its final version; a missing patch number is 0.

func ParseVersion

func ParseVersion(raw string) (Version, error)

ParseVersion reads the output of "git --version" ("git version 2.30.1 (Apple Git-130)") or a bare version ("2.30"). The error has the tag GitVersionUnreadable.

func (Version) AtLeast

func (v Version) AtLeast(major, minor int) bool

AtLeast says whether v is at least major.minor.

func (Version) Compare

func (v Version) Compare(other Version) int

Compare returns -1, 0 or 1 when v is older than, equal to or newer than other.

func (Version) String

func (v Version) String() string

String formats the version as "2.43.0".

type Worktree

type Worktree struct {
	// Name is the name of the worktree's folder.
	Name string
	// Path is the absolute path of the work tree, as git records it.
	Path string
	// Head is the commit the work tree has checked out (HEAD).
	Head string
	// Ref is the full name of the branch the work tree has checked out ("refs/heads/feature"); empty for a detached HEAD.
	Ref string
	// Detached says that HEAD names a commit, not a branch.
	Detached bool
	// Main says that this is the main work tree, the one with the .git folder.
	Main bool
	// Locked says that "git worktree lock" protects the worktree from being pruned or removed; LockReason is the reason given.
	Locked     bool
	LockReason string
	// Prunable says that the worktree's folder is gone, so that "git worktree prune" would remove its record.
	Prunable bool
	// Subject is the first line of the message of the commit HEAD names, set by WorktreeDetails.
	Subject string
}

Worktree is a work tree of a repository, the main one or a linked one.

func FindWorktree

func FindWorktree(list []Worktree, path string) (Worktree, bool)

FindWorktree returns the work tree of the list whose folder is path, comparing the real paths of the two.

func ParseWorktrees

func ParseWorktrees(data []byte) []Worktree

ParseWorktrees reads the output of "git worktree list --porcelain": records of "worktree <path>", "HEAD <hash>", "branch <ref>" or "detached", "locked [<reason>]" and "prunable [<reason>]" lines, apart by an empty line. The first record is the main work tree; the record of a bare repository ("bare") is left out, as VS Code leaves it out.

func (Worktree) Branch

func (w Worktree) Branch() string

Branch is the short name of the branch the work tree has checked out, "" for a detached HEAD.

type WorktreeSymlinkStatus

type WorktreeSymlinkStatus string

WorktreeSymlinkStatus says what CreateWorktreeSymlink did.

const (
	// SymlinkCreated: the link was made.
	SymlinkCreated WorktreeSymlinkStatus = "created"
	// SymlinkSourceContainsWorktree: the folder holds the worktree, so a link to it would be a loop.
	SymlinkSourceContainsWorktree WorktreeSymlinkStatus = "sourceContainsWorktree"
	// SymlinkTargetExists: there is something at the place of the link.
	SymlinkTargetExists WorktreeSymlinkStatus = "targetExists"
)

The results of CreateWorktreeSymlink.

func CreateWorktreeSymlink(repositoryRoot, worktreeRoot, folder string) (WorktreeSymlinkStatus, error)

CreateWorktreeSymlink makes a symbolic link in the worktree to a folder of the repository. folder is relative to both, with forward slashes. It does nothing when the folder holds the worktree or the place of the link is taken. The error has the tags GitWorktreeSymlinkFailed (the paths could not be read or the link not made), GitWorktreeSymlinkParentLink and GitWorktreeSymlinkParentNotDir (a folder above the link in the worktree is a link or not a folder).

Jump to

Keyboard shortcuts

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