vcs

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package vcs ports orchestrator/vcs/ (protocol.py, github.py, gitlab.py): opening a PR/MR, polling its CI status, fetching failed-job logs, and merging it, all through the `gh` / `glab` CLIs rather than a REST client.

Polling contract (for internal/engine, not yet built)

CIStatus is a single poll, not a loop: Python's ci_poll_interval_s wait and ci_max_retries retry count live in orch.py's dispatch loop (_check_ci_once), which has no Go equivalent yet. Whoever writes internal/engine owns calling CIStatus on a timer and deciding when the retry budget is spent — this package only answers "what does CI say right now".

Error handling deliberately improves on Python here

Python's three provider methods that can fail return a zero value on ANY failure — create_pr returns None, get_ci_status returns "pending", merge_pr returns False — whether the cause is "CI is still running" or "gh isn't even installed". That hides a structural setup problem behind what looks like ordinary polling. This port keeps the same zero-value behavior for a normal, expected outcome (CI genuinely pending, a PR that didn't get created this attempt), but a missing CLI binary always surfaces as a typed *CLIError — checked once, cheaply, via exec.LookPath, on every call — and CreatePR/MergePR (called once per task, not polled, so the extra cost is negligible) additionally probe `gh|glab auth status` on failure to tell "not authenticated" apart from an ordinary business failure (PR already exists, not mergeable yet). CIStatus/CILogs stay poll-loop-cheap and do not make that extra call.

Index

Constants

View Source
const FreeMinutesNote = "GitHub Free includes 2,000 Actions minutes a month for private repositories, Pro and Team 3,000"

FreeMinutesNote is what GitHub's plans include for private repositories; public ones are not billed.

View Source
const NoCILogNote = "No failure log could be captured (possible infra, cancelled or timed-out failure). " +
	"Check the run or PR URL above; if the failure is unrelated to your change, say so in your status note."

NoCILogNote is what the agent's CI feedback says when a failing check left no log to show: a job cancelled, timed out or never started prints nothing to `gh run view --log-failed` (#598).

Variables

View Source
var ErrMergeFailed = errors.New("vcs: merge did not succeed")

ErrMergeFailed is MergePR's error when the CLI ran (and is authenticated) but the merge itself didn't happen — not mergeable yet, conflicts, branch protection, or a MR/PR that doesn't exist. Ports Python's merge_pr returning False for the same set of outcomes; wrapped so a caller can tell "merge genuinely didn't happen" apart from a *CLIError with errors.Is/errors.As.

View Source
var ErrPRStateUnsupported = errors.New("vcs: reading a PR's state is not supported for this provider")

ErrPRStateUnsupported is PRState's error for a provider that cannot tell yet. The caller treats it as "unknown" and carries on as before.

Functions

func CheckAuth

func CheckAuth(binary, host string) error

CheckAuth reports whether binary ("gh" or "glab") is installed and authenticated, as a *CLIError when it isn't. host, when non-empty, is passed as GITLAB_HOST (glab reads it the same way GitLabProvider does); ignored for gh. Exported for internal/doctor's readiness check (G4.5), which needs this exact probe independent of opening or merging anything.

func RepoVisibility

func RepoVisibility(dir string) (string, error)

RepoVisibility is the GitHub repository of dir's remote: "public", "private" or "internal".

func UpsertComment

func UpsertComment(repo string, number int, marker, body string) (url string, created bool, err error)

UpsertComment makes body the one comment on issue or pull request number whose body contains marker: it edits that comment when there is one and creates it otherwise. gh authenticates itself (GH_TOKEN on a runner). It returns the comment's URL and whether it was created.

Types

type ActionsUsage

type ActionsUsage struct {
	Since time.Time `json:"since"`
	Runs  int       `json:"runs"`
	// Minutes is billable minutes: each job's duration rounded up to the
	// minute, as GitHub bills Linux runners. macOS and Windows runners cost
	// more per minute; orch's workflow uses neither.
	Minutes    int            `json:"minutes"`
	ByWorkflow map[string]int `json:"by_workflow"`
	// PullRequests counts the pull-request branches that ran;
	// MinutesPerPR is their average, what one more task's PR costs.
	PullRequests int     `json:"pull_requests"`
	MinutesPerPR float64 `json:"minutes_per_pr"`
}

ActionsUsage is what a repository's GitHub Actions runs took since a date.

func ActionsMinutes

func ActionsMinutes(dir string, since time.Time) (ActionsUsage, error)

ActionsMinutes adds up the jobs of every workflow run since since. One API call per run: a month of an orch project is tens of runs, not thousands.

func (ActionsUsage) SortedWorkflows

func (u ActionsUsage) SortedWorkflows() []string

SortedWorkflows lists ByWorkflow's names, most minutes first.

type CIState

type CIState string

CIState is a CI run's outcome as this package reports it — Python's get_ci_status docstring's exact three values. A GitHub check conclusion or GitLab pipeline status that doesn't map to a state below (see each provider's state map) is reported as CIPending: an unrecognized value is far more likely to be a new not-yet-terminal state than a green light.

const (
	CIPending CIState = "pending"
	CISuccess CIState = "success"
	CIFailure CIState = "failure"
	// CINone is a PR with no check (GitHub) or pipeline (GitLab) at all. Go
	// only: Python called it pending, which is true for a PR opened a moment
	// ago and never stops being "true" on a repo with no CI — #233. The
	// engine decides how long none may last.
	CINone CIState = "none"
	// CIConflict is a PR with no checks that conflicts with its base. GitHub
	// runs no workflow on a conflicting PR, so its checks are never coming
	// (#236). Only reported alongside no checks: a PR whose CI already ran
	// is judged by that run.
	CIConflict CIState = "conflict"
	// CINotStarted is a failed CI whose every failing job never ran: GitHub
	// gave it no runner (an Actions billing problem, a spending limit) (#501).
	// No change to the code can turn it green, so it is not CIFailure.
	CINotStarted CIState = "not_started"
)

type CLIError

type CLIError struct {
	Binary string // "gh" or "glab"
	Reason string // "not found in PATH" | "not authenticated"
	Err    error  // underlying error, if any
}

CLIError reports that gh/glab itself couldn't do its job — missing from PATH or not authenticated — as opposed to an ordinary CI/PR outcome. Never returned for "CI is pending" or "no PR yet"; see the package doc comment.

func (*CLIError) Error

func (e *CLIError) Error() string

func (*CLIError) Unwrap

func (e *CLIError) Unwrap() error

type Config

type Config struct {
	// Provider is "github" (default) or "gitlab".
	Provider string
	// Host is the GitLab instance host (e.g. "gitlab.com" or a self-hosted
	// domain); ignored for GitHub.
	Host string
}

Config is the subset of internal/config.Config a caller needs to build a Provider — small and duplicated here (rather than importing internal/config) so this package has no dependency on the config package's parsing/defaulting concerns, only the three values that decide which provider to build.

type GitHubProvider

type GitHubProvider struct{}

GitHubProvider drives PR creation, CI polling, and merges through the `gh` CLI. Ports GitHubProvider (orchestrator/vcs/github.py).

func NewGitHubProvider

func NewGitHubProvider() *GitHubProvider

NewGitHubProvider builds a GitHubProvider. gh reads its own authentication from its config directory; no host/token is threaded through here, matching Python (GitHubProvider takes no constructor args).

func (*GitHubProvider) CILogs

func (p *GitHubProvider) CILogs(prURL string) (string, error)

CILogs tells the agent what failed: the commit, each failing check with its verdict and URL, then the failed jobs' logs. A failure with no log to show (cancelled, timed out, an infra fault, gh refusing) still names the checks and says no log was captured, never an empty answer for a red PR (#598). It returns "" only when nothing in the rollup failed or gh could not be read.

func (*GitHubProvider) CIStatus

func (p *GitHubProvider) CIStatus(prURL string) (CIState, error)

func (*GitHubProvider) CloseIssue added in v0.31.0

func (p *GitHubProvider) CloseIssue(issueURL, comment string) error

CloseIssue closes the issue at issueURL with comment as its closing comment, in one `gh issue close <url> --comment <comment>`: the evidence and the close land together or not at all. The URL names the repository, so gh's working directory does not matter. A failure carries gh's own stderr; a missing or unauthenticated gh is a *CLIError.

func (*GitHubProvider) CommentIssue

func (p *GitHubProvider) CommentIssue(repo string, number int, body string) (string, error)

CommentIssue adds body as a new comment on issue number in repo and returns the comment's URL.

func (*GitHubProvider) CreateIssue

func (p *GitHubProvider) CreateIssue(repo, title, body string, labels []string) (string, error)

CreateIssue files an issue in repo and returns its URL, which is what `gh issue create` prints.

func (*GitHubProvider) CreatePR

func (p *GitHubProvider) CreatePR(head, base, title, body string) (string, error)

func (*GitHubProvider) IsCollaborator added in v0.31.0

func (p *GitHubProvider) IsCollaborator(dir, login string) (bool, error)

IsCollaborator reports whether login is a collaborator of the repository gh reads from dir: `gh api repos/{owner}/{repo}/collaborators/<login>` answers 204 (exit 0) for one and 404 for anyone else. Collaborators here include org members with access and owners, which is GitHub's own definition.

Any other failure (no push access to ask, no network) is an error, never a quiet "no": `orch sync issues` would otherwise skip every issue and report an up-to-date tracker.

func (*GitHubProvider) ListIssues

func (p *GitHubProvider) ListIssues(q IssueQuery) ([]Issue, error)

ListIssues returns the issues carrying a label.

Filtered by gh server-side rather than here: `--label` is gh's own flag, an unmatched label returns `[]` rather than an error, and filtering client-side would mean paging the whole tracker to throw most of it away.

func (*GitHubProvider) MergePR

func (p *GitHubProvider) MergePR(prURL string, squash, auto bool) error

func (*GitHubProvider) MergeQueueActive added in v0.31.0

func (p *GitHubProvider) MergeQueueActive(prURL, baseBranch string) (bool, error)

MergeQueueActive reports whether the base branch of prURL's repository has GitHub's merge queue on (#522): orch then leaves the order to GitHub and only runs its semantic checks. testdata/gh/2.101.0/graphql-merge-queue-*.json.

func (*GitHubProvider) PRState

func (p *GitHubProvider) PRState(prURL string) (PRState, error)

func (*GitHubProvider) SearchIssues

func (p *GitHubProvider) SearchIssues(repo, label, query string, limit int) ([]Issue, error)

SearchIssues returns up to limit issues in repo carrying label whose title matches the words of query, open and closed alike. gh's `--search` is GitHub's issue search, so the match is fuzzy by design: it is a list of candidates for a human or a model to judge, not a verdict.

func (*GitHubProvider) UpsertPRComment added in v0.31.0

func (p *GitHubProvider) UpsertPRComment(prURL, marker, body string) error

UpsertPRComment is UpsertComment on the pull request at prURL, https://github.com/<owner>/<repo>/pull/<n>: the one comment carrying marker is edited, or created. The engine posts a task's evidence with it (#520).

type GitLabProvider

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

GitLabProvider drives MR creation, CI polling, and merges through the `glab` CLI. Ports GitLabProvider (orchestrator/vcs/gitlab.py).

func NewGitLabProvider

func NewGitLabProvider(host string) *GitLabProvider

NewGitLabProvider builds a GitLabProvider talking to host (e.g. "gitlab.com" or a self-hosted instance).

func (*GitLabProvider) CILogs

func (p *GitLabProvider) CILogs(prURL string) (string, error)

func (*GitLabProvider) CIStatus

func (p *GitLabProvider) CIStatus(prURL string) (CIState, error)

func (*GitLabProvider) CreatePR

func (p *GitLabProvider) CreatePR(head, base, title, body string) (string, error)

func (*GitLabProvider) MergePR

func (p *GitLabProvider) MergePR(prURL string, squash, auto bool) error

func (*GitLabProvider) PRState

func (p *GitLabProvider) PRState(string) (PRState, error)

PRState is not implemented for GitLab: `glab mr view --output json` does carry the MR's `state`, but this package has no real glab capture to pin its spelling to (testdata/fakebin/glab is hand-written), and a guessed parser that misreads "merged" would finish tasks nobody accepted. The poller treats ErrPRStateUnsupported as "unknown" and keeps polling CI as before.

type Issue

type Issue struct {
	Number    int          `json:"number"`
	Title     string       `json:"title"`
	Body      string       `json:"body"`
	State     string       `json:"state"`
	URL       string       `json:"url"`
	CreatedAt string       `json:"createdAt"`
	Labels    []IssueLabel `json:"labels"`
	Author    IssueAuthor  `json:"author"`
}

Issue is one GitHub issue, in the shape `gh issue list --json …` returns.

Captured, not guessed: internal/vcs/testdata/gh/2.100.0/issue-list.json is a real payload from this repository. The field set is gh's to change, which is why the fixture carries its version in the path — and why the tests read it rather than a literal written from this struct (see the README there, and bug 27, which was a field nobody had ever seen gh emit).

func (Issue) LabelNames

func (i Issue) LabelNames() []string

LabelNames is the labels as plain strings, in gh's order.

type IssueAuthor added in v0.31.0

type IssueAuthor struct {
	Login string `json:"login"`
}

IssueAuthor is who opened an issue. gh also returns `id`, `name` and `is_bot`; the login is what `orch sync issues` checks against the repo's collaborators (#542).

type IssueComment

type IssueComment struct {
	ID      int64  `json:"id"`
	Body    string `json:"body"`
	HTMLURL string `json:"html_url"`
}

IssueComment is one entry of `gh api repos/{repo}/issues/{n}/comments`. Pull request conversation comments are issue comments to the API. Captured, not guessed: see testdata/gh/2.100.0/issue-comments-*.json.

type IssueLabel

type IssueLabel struct {
	Name string `json:"name"`
}

IssueLabel is one label on an issue. gh returns `id`, `name`, `description` and `color`; only the name is load-bearing here, and the rest are left off rather than carried unused.

type IssueQuery

type IssueQuery struct {
	// Label is required unless Search is set. A sync with no label would
	// ingest an entire issue tracker, which is never what anyone means.
	Label string
	// Search is a GitHub issue search (`label:orch milestone:v1`), passed to
	// gh's --search; what `orch atomize --from-issues` asks with (#525).
	Search string
	// State is "open" (the default), "closed" or "all", matching gh's own
	// vocabulary so an operator who knows gh needs no translation.
	State string
	// Limit caps how many gh returns. gh's own default is 30, which would
	// silently truncate a real backlog.
	Limit int
	// Dir is the working directory gh runs in, which is how gh decides
	// which repository it is reading. Should be the project root, not the
	// shell's cwd — see runIn. Empty means the process cwd.
	Dir string
}

IssueQuery narrows what ListIssues asks for.

type MergeError

type MergeError struct {
	// Detail is the CLI's own stderr (trimmed), or what went wrong around it.
	Detail string
	// MergeState is GitHub's mergeStateStatus read after the failure
	// (BEHIND, UNKNOWN, BLOCKED, DIRTY, ...), "" when it could not be read
	// or the provider has no such thing.
	MergeState string
	// Retryable reports that the failure looks transient — mergeability
	// still being computed after the base moved, the base changing under
	// the merge, a required check re-running — so the same merge may
	// succeed a little later. False for conflicts and drafts.
	Retryable bool
	// BranchUpdated reports that the PR was behind its base and MergePR
	// brought it up to date (`gh pr update-branch`). Its head moved, so CI
	// runs again; the merge is for after that run.
	BranchUpdated bool
}

MergeError is MergePR's error when the CLI ran but the merge did not happen, carrying what the CLI said and whether trying again can help. errors.Is(err, ErrMergeFailed) holds for every MergeError, so a caller that only cares "merged or not" is unaffected (#347).

Before it existed every failure was the bare ErrMergeFailed, which threw away gh's stderr: a PR left open by a base that had just moved read the same as one with conflicts, and the log line said neither.

func (*MergeError) Error

func (e *MergeError) Error() string

func (*MergeError) Is

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

Is makes errors.Is(err, ErrMergeFailed) true for a *MergeError.

type PRState

type PRState string

PRState is whether a PR/MR is still open, or settled one way or the other. Go only: Python never asked, and polled a merged or closed PR's CI forever (#255).

const (
	PROpen   PRState = "open"
	PRMerged PRState = "merged"
	PRClosed PRState = "closed" // closed without merging
)

type Provider

type Provider interface {
	// CreatePR opens a PR/MR from head into base and returns its URL.
	// Returns ("", nil) — never an error — when the CLI ran but didn't
	// produce a PR (Python's None); see the package doc comment for when
	// this instead becomes a typed error.
	CreatePR(head, base, title, body string) (string, error)

	// CIStatus reports head's current CI state for the PR/MR at prURL. A
	// single poll — see the package doc comment's "Polling contract".
	CIStatus(prURL string) (CIState, error)

	// PRState reports whether the PR/MR at prURL is open, merged or closed
	// without merging. ErrPRStateUnsupported when the provider cannot tell.
	PRState(prURL string) (PRState, error)

	// CILogs returns failed CI job logs as plain text, truncated to 8000
	// chars, or "" when there is nothing failed to show.
	CILogs(prURL string) (string, error)

	// MergePR merges prURL. squash requests a squash merge; auto requests
	// merge-when-checks-pass instead of merging immediately (GitHub's
	// `--auto`, GitLab's `--when-pipeline-succeeds`) — see the package doc
	// comment for why these are parameters here when Python hardcodes them.
	// Returns a *MergeError (errors.Is ErrMergeFailed; never a plain
	// nil-vs-non-nil ambiguity) when the CLI ran but the merge itself didn't
	// happen. One attempt: retrying, and when, is the caller's decision.
	MergePR(prURL string, squash, auto bool) error
}

Provider opens, polls, and merges a PR (GitHub) or MR (GitLab).

func NewProvider

func NewProvider(cfg Config) Provider

NewProvider builds the Provider cfg selects. Ports get_vcs_provider.

type Repo

type Repo struct {
	// Remote is origin's URL with any credentials removed; "" without an
	// origin.
	Remote string `json:"remote"`
	// Host is the remote's host ("github.com"), Slug its path without .git
	// ("owner/name"); both "" when the URL has neither.
	Host string `json:"host"`
	Slug string `json:"slug"`
	// Branch is the checked-out branch; "" when HEAD is detached.
	Branch string `json:"branch"`
}

Repo is what the share panel says about the checkout a dashboard serves: which repository and which branch.

func DescribeRepo

func DescribeRepo(dir string) Repo

DescribeRepo reads dir's origin and branch. A directory that is not a repository, or has no origin, answers what it has rather than an error: the panel shows the fields it can.

Jump to

Keyboard shortcuts

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