Documentation
¶
Overview ¶
Package git contains shared git helpers used by both the skills importer (pkg/skills) and the MCP server source builder (pkg/builder).
The helpers are thin wrappers over go-git that factor out duplicated clone/fetch/checkout logic. They do not know anything about gridctl's cache layout or authentication strategy: callers compute destination paths and pass in a transport.AuthMethod (or nil).
Index ¶
- Variables
- func Checkout(repo *gogit.Repository, ref string) error
- func ClassifyError(err error) error
- func Clone(destPath string, opts CloneOptions, logger *slog.Logger) (*gogit.Repository, error)
- func DefaultBranch(repo *gogit.Repository) (string, error)
- func Fetch(repoPath string, opts FetchOptions, logger *slog.Logger) error
- func HTTPSEquivalent(raw string) (string, bool)
- func HeadCommit(repoPath string) (string, error)
- func ListTags(repoPath string) ([]string, error)
- func Open(repoPath string) (*gogit.Repository, error)
- func RedactError(err error) error
- func RedactString(s string) string
- func RedactURL(raw string) string
- func ResolveRemoteRef(repo *gogit.Repository, ref string) (string, error)
- func SSHAgentAvailable() error
- func SyncWorktree(repo *gogit.Repository, ref string) (string, error)
- type Auther
- type CloneOptions
- type FetchOptions
- type HTTPSTokenAuth
- type NoAuth
- type Protocol
- type SSHAgentAuth
- type SSHKeyFileAuth
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAuthRequired: the remote rejected the request because no // credentials were presented. ErrAuthRequired = errors.New("authentication required") // ErrAuthFailed: credentials were presented but rejected. ErrAuthFailed = errors.New("authentication failed") // ErrNotFound: the remote returned a "not found" response. On hosts // like GitHub this may also mean a private repository accessed without // sufficient credentials. ErrNotFound = errors.New("repository not found") // ErrHostKeyMismatch: the SSH host key did not match the local // known_hosts — a potential man-in-the-middle indicator. ErrHostKeyMismatch = errors.New("ssh host key mismatch") // ErrSSHAgentMissing: ssh-agent was unavailable (socket missing or // SSH_AUTH_SOCK unset) when SSH-agent auth was requested. ErrSSHAgentMissing = errors.New("ssh agent not available") // ErrEmptyToken: a token-based Auther was constructed with an empty // token. Reported eagerly rather than falling through to an // unauthenticated clone that then fails with a cryptic error. ErrEmptyToken = errors.New("token is empty") // ErrProtocolMismatch: an Auther was asked to produce credentials for // a URL whose protocol does not match the auth mechanism (e.g., an // HTTPS token against an SSH URL). ErrProtocolMismatch = errors.New("protocol mismatch") )
Sentinel errors classify git-operation failures so callers can render actionable UI messages without string-matching raw go-git output.
Functions ¶
func Checkout ¶
func Checkout(repo *gogit.Repository, ref string) error
Checkout lands the worktree on ref, trying in order: tag, local branch, remote branch (origin), commit hash. Force is used so uncommitted changes in the worktree (unlikely in a cache) are discarded.
func ClassifyError ¶
ClassifyError maps raw go-git (or network) errors to sentinels in this package, wrapping the original so errors.Is / errors.As still find it. Unknown errors are returned unchanged — the caller is free to wrap them with its own context.
func Clone ¶
func Clone(destPath string, opts CloneOptions, logger *slog.Logger) (*gogit.Repository, error)
Clone performs a plain git clone into destPath. When Ref is set it first attempts a single-branch clone of that ref (as a branch); if that fails it removes destPath and retries with a full clone. Callers are responsible for a subsequent Checkout when they need to land on a non-branch ref (tag, commit, remote branch) after the full-clone fallback.
func DefaultBranch ¶
func DefaultBranch(repo *gogit.Repository) (string, error)
DefaultBranch returns the short name of the remote's default branch. It consults, in order: the origin/HEAD symbolic ref (when the clone recorded one), the local HEAD's branch when a matching remote-tracking ref exists, and finally the remote-tracking branches themselves (a sole branch wins; otherwise "main" then "master"). It works from a detached HEAD, which is the resting state of a cache worktree after SyncWorktree.
func Fetch ¶
func Fetch(repoPath string, opts FetchOptions, logger *slog.Logger) error
Fetch updates the cached repository at repoPath from its remote. Returns nil if the remote had no new refs.
func HTTPSEquivalent ¶
HTTPSEquivalent rewrites an SSH git URL into the HTTPS URL for the same repository, reporting false when the input is not SSH or is too malformed to convert. Both SCP syntax (git@host:owner/repo.git) and ssh:// URLs convert.
This lives here rather than in a caller so the CLI, the REST layer, and the web UI all offer the same rewrite. A non-standard SSH port is dropped: it says nothing about where HTTPS is served.
func HeadCommit ¶
HeadCommit returns the HEAD commit hash for the repository at repoPath.
func Open ¶
func Open(repoPath string) (*gogit.Repository, error)
Open is a thin wrapper around gogit.PlainOpen. It lets callers avoid importing go-git directly for routine repository access.
func RedactError ¶
RedactError returns an error whose message has been scrubbed of credential-shaped content. The original error is preserved via Unwrap so errors.Is / errors.As continue to work as expected. Returns nil when err is nil, and returns err unchanged when the message does not contain any redactable content.
func RedactString ¶
RedactString scrubs known token patterns and URL userinfo from arbitrary text. Use it on strings whose construction you do not fully control, e.g. error messages returned from go-git.
func RedactURL ¶
RedactURL returns a version of raw with any userinfo stripped.
https://TOKEN@host/path → https://host/path git@host:path → git@host:path (SCP-style, unchanged) non-URL text → unchanged
func ResolveRemoteRef ¶
func ResolveRemoteRef(repo *gogit.Repository, ref string) (string, error)
ResolveRemoteRef resolves ref to a commit hash, preferring freshly fetched remote-tracking state over possibly-stale local refs: tag, remote branch (origin), local branch, raw commit hash. An empty ref resolves the remote default branch. Annotated tags are peeled to their target commit so the result is always checkout-able and comparable against HEAD commits.
func SSHAgentAvailable ¶
func SSHAgentAvailable() error
SSHAgentAvailable reports whether this process can reach an ssh-agent, returning ErrSSHAgentMissing when it cannot.
The distinction matters for error text: the shell a user types in usually does have an agent, so "no ssh-agent" reads as wrong. A daemonized gridctl inherits SSH_AUTH_SOCK only from the shell that started it, and a long-running daemon can outlive the agent it inherited, so the accurate statement is that this process has no reachable socket.
func SyncWorktree ¶
func SyncWorktree(repo *gogit.Repository, ref string) (string, error)
SyncWorktree lands the worktree on the commit ResolveRemoteRef finds for ref and returns its hash. Unlike Checkout, it never resolves through a stale local branch: after a Fetch, this is what actually surfaces new upstream commits in the worktree. Branch targets fast-forward the local branch and keep HEAD attached (the equivalent of `git checkout -B <branch> <sha>`) so default-branch resolution keeps working on later syncs; tag and raw-hash targets leave HEAD detached. Repeated syncs are idempotent.
Types ¶
type Auther ¶
type Auther interface {
AuthFor(url string) (transport.AuthMethod, error)
}
Auther returns a transport.AuthMethod appropriate for the given URL. A nil AuthMethod with a nil error means "no credentials required"; a non-nil error surfaces misconfiguration (wrong protocol, missing agent, empty token) so callers don't silently fall through to an unauthenticated clone that then fails with a cryptic "repository not found".
type CloneOptions ¶
type CloneOptions struct {
URL string
Ref string // if set and branch-style, attempted as single-branch clone first
Depth int // 0 = full history
AllTags bool // fetch all tags
Auth transport.AuthMethod // nil = unauthenticated
}
CloneOptions configures a Clone call.
type FetchOptions ¶
type FetchOptions struct {
AllTags bool
// AllBranches fetches every remote branch with an explicit refspec,
// overriding the refspec stored at clone time. A single-branch clone's
// remote config only covers its own branch, so without this a later
// fetch cannot see branches (or a default branch) added upstream.
AllBranches bool
Auth transport.AuthMethod
}
FetchOptions configures a Fetch call.
type HTTPSTokenAuth ¶
type HTTPSTokenAuth struct {
Token string
}
HTTPSTokenAuth sends a token as HTTP basic-auth using the literal username "x-access-token" with the token in the password slot — the shape required by GitHub App installation tokens and accepted uniformly by GitHub PATs, GitLab, and Bitbucket.
func (HTTPSTokenAuth) AuthFor ¶
func (a HTTPSTokenAuth) AuthFor(url string) (transport.AuthMethod, error)
AuthFor returns an *http.BasicAuth carrying the token, or an error if the token is empty or the URL is not HTTPS.
type NoAuth ¶
type NoAuth struct{}
NoAuth produces no credentials for any URL. Use it for public repositories or when ambient go-git mechanisms handle auth transparently.
type Protocol ¶
type Protocol string
Protocol describes how a git URL is accessed.
func DetectProtocol ¶
DetectProtocol classifies a git remote URL by its scheme.
type SSHAgentAuth ¶
type SSHAgentAuth struct {
User string
}
SSHAgentAuth delegates authentication to the user's running ssh-agent. The User field defaults to "git" when empty.
func (SSHAgentAuth) AuthFor ¶
func (a SSHAgentAuth) AuthFor(url string) (transport.AuthMethod, error)
AuthFor returns a PublicKeysCallback backed by the ambient ssh-agent, or ErrSSHAgentMissing if no agent socket is available.
type SSHKeyFileAuth ¶
type SSHKeyFileAuth struct {
User string
KeyPath string
Passphrase string
KnownHostsPath string // reserved for a follow-up change
}
SSHKeyFileAuth authenticates using an on-disk private key file. The User field defaults to "git" when empty.
Host-key verification uses go-git's default behavior for this PR; a stricter TOFU / accept-new host-key policy and explicit KnownHostsPath handling will be wired through in a follow-up change. KnownHostsPath is reserved for that future work.
func (SSHKeyFileAuth) AuthFor ¶
func (a SSHKeyFileAuth) AuthFor(url string) (transport.AuthMethod, error)
AuthFor loads the private key file and returns an SSH PublicKeys auth.