remote

package
v1.21.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: GPL-3.0 Imports: 11 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 remote drives GitHub operations (currently PR review) through the user's `gh` CLI. It performs no HTTPS calls itself — `gh` handles auth, host resolution, and the REST round-trips. See ADR-0016.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGHMissing — the `gh` binary is not on PATH.
	ErrGHMissing = errors.New("remote: gh binary not found on PATH")
	// ErrSelfPR — the authenticated user is the PR author (GitHub blocks
	// self-approval; we reject before fetching the diff).
	ErrSelfPR = errors.New("remote: cannot review your own pull request")
	// ErrTooVolatile — the PR head changed twice during review; aborted.
	ErrTooVolatile = errors.New("remote: pull request changed during review")
)

Sentinel errors let the CLI layer map failures to i18n catalog keys without string-matching. Wrap with %w where extra context helps.

Functions

func BuildCommentBody

func BuildCommentBody(f render.Finding, whoami string) string

BuildCommentBody renders one finding as an inline review comment body. Fixed English (ADR-0016 §10):

[SEVERITY] - Title
Description
💡 Suggestion @whoami by #commitbrief

A finding that carries a fingerprint also gets the identity marker on its own trailing line (ADR-0046); the visible text is unchanged.

func BuildReviewBody

func BuildReviewBody(v Verdict, whoami string) string

BuildReviewBody returns the fixed-English review body for a verdict (ADR-0016 §6.4).

func BuildUnanchoredSection added in v1.2.1

func BuildUnanchoredSection(findings []render.Finding) string

BuildUnanchoredSection renders the findings that fell back to the review body. Returns "" when there are none so callers can append it unconditionally.

func CommentText added in v1.20.0

func CommentText(f render.Finding, whoami string) string

CommentText renders the visible part of a finding's comment (no marker).

func EnsureGH

func EnsureGH() error

EnsureGH reports ErrGHMissing when the `gh` binary is not on PATH.

func FetchCompareDiff added in v1.20.0

func FetchCompareDiff(ctx context.Context, r Runner, slug, base, head string) (string, error)

FetchCompareDiff returns the unified diff of base...head. Large comparisons make the API fail; the caller then falls back to the full PR diff.

func FetchDiff

func FetchDiff(ctx context.Context, r Runner, id, repo string) (string, error)

FetchDiff returns the PR's unified diff (`gh pr diff <id>`).

func FetchLastOID

func FetchLastOID(ctx context.Context, r Runner, id, repo string) (string, error)

FetchLastOID re-reads only the commits to detect a head change cheaply between the diff fetch and the review submission (race check).

func FetchLastReviewedOID added in v1.20.0

func FetchLastReviewedOID(ctx context.Context, r Runner, slug string, number int) (string, error)

FetchLastReviewedOID returns the head OID recorded in the newest review the viewer authored that carries the K8 marker, looking at the PR's last 100 reviews only. An empty OID with a nil error means there is none.

func NormalizeText added in v1.20.0

func NormalizeText(s string) string

NormalizeText prepares comment text for the "is the body the same?" comparison: CRLF -> LF, trailing whitespace trimmed per line and overall.

func ParseReviewedMarker added in v1.20.0

func ParseReviewedMarker(body string) (string, bool)

ParseReviewedMarker extracts the head OID from a review body. When a body holds several markers the last one wins.

func PostComment

func PostComment(ctx context.Context, r Runner, c CommentRequest) error

PostComment posts a single inline review comment via the REST API. Side is chosen by the caller from the parsed diff (RIGHT for added / context lines, LEFT for removed ones); a finding whose line is outside the diff is filtered out upstream and never reaches here, so a 422 is now an unexpected GitHub error rather than the routine hallucinated-line case (ADR-0016 §9).

func ReplyToComment added in v1.20.0

func ReplyToComment(ctx context.Context, r Runner, slug string, number int, commentID int64, body string) error

ReplyToComment posts a reply into the thread rooted at commentID.

func ResolveThread added in v1.20.0

func ResolveThread(ctx context.Context, r Runner, nodeID string) error

ResolveThread marks a review thread resolved.

func ReviewedMarker added in v1.20.0

func ReviewedMarker(oid string) string

ReviewedMarker returns the hidden marker recording that a review covered the PR up to head commit oid.

func SubmitReview

func SubmitReview(ctx context.Context, r Runner, id, repo string, v Verdict, body string) error

SubmitReview submits the review-level verdict via `gh pr review`.

func UnresolveThread added in v1.20.0

func UnresolveThread(ctx context.Context, r Runner, nodeID string) error

UnresolveThread reopens a resolved review thread.

func UpdateComment added in v1.20.0

func UpdateComment(ctx context.Context, r Runner, slug string, commentID int64, body string) error

UpdateComment replaces the body of one review comment (REST PATCH).

func ValidFingerprint added in v1.20.0

func ValidFingerprint(fp string) bool

ValidFingerprint reports whether fp is a 64-char lowercase hex digest, the only shape the identity marker accepts.

func Whoami

func Whoami(ctx context.Context, r Runner) (string, error)

Whoami returns the authenticated GitHub login (`gh api user -q .login`).

func WithReviewedMarker added in v1.20.0

func WithReviewedMarker(body, oid string) string

WithReviewedMarker appends the K8 marker for oid to a review body. An empty oid leaves the body unchanged.

Types

type Class added in v1.20.0

type Class int

Class is how a thread CommitBrief owns is currently classified (S1-S9).

const (
	// ClassActive is an open thread CommitBrief manages (S1).
	ClassActive Class = iota
	// ClassHeld is an open thread a human reopened or marked to keep (S2-S5).
	ClassHeld
	// ClassClosedByUs is a thread CommitBrief resolved and nobody touched since (S6).
	ClassClosedByUs
	// ClassClosedByHuman is a closed thread a human decided on (S7-S9).
	ClassClosedByHuman
)

func Classify added in v1.20.0

func Classify(t Thread, m Marker) (c Class, record string)

Classify applies the S1-S9 table to one thread. record is the state the run should write into the root marker ("reopened" for S2, "closed" for S7/S8) or "" when nothing is to be recorded.

type Comment added in v1.20.0

type Comment struct {
	ID              int64
	Body            string
	ViewerDidAuthor bool
	ViewerCanUpdate bool
}

Comment is one review comment as the sync layer sees it.

type CommentRequest

type CommentRequest struct {
	RepoSlug string
	PRNumber int
	CommitID string
	Path     string
	Line     int
	Side     string
	Body     string
}

CommentRequest is one inline comment to POST. RepoSlug is the PR's baseRepository ("owner/name", cross-fork correctness); CommitID is the head OID the diff was fetched at. Side is "RIGHT" (new file) or "LEFT" (old file); empty defaults to RIGHT.

type Compare added in v1.20.0

type Compare struct {
	Status       string          `json:"status"`
	TotalCommits int             `json:"total_commits"`
	Commits      []CompareCommit `json:"commits"`
}

Compare is the part of GET /repos/{o}/{r}/compare/{base}...{head} that the incremental review needs.

func FetchCompare added in v1.20.0

func FetchCompare(ctx context.Context, r Runner, slug, base, head string) (Compare, error)

FetchCompare compares two commits through the REST API. The commit list is paginated by GitHub, so every page is read and merged.

func (Compare) Ahead added in v1.20.0

func (c Compare) Ahead() bool

Ahead reports whether head is strictly ahead of base, i.e. base is an ancestor of head (no force-push in between).

func (Compare) Complete added in v1.20.0

func (c Compare) Complete() bool

Complete reports whether Commits lists every compared commit. The API caps the list; an incomplete one cannot prove the absence of merge commits.

func (Compare) HasMerge added in v1.20.0

func (c Compare) HasMerge() bool

HasMerge reports whether any compared commit is a merge commit.

type CompareCommit added in v1.20.0

type CompareCommit struct {
	SHA     string `json:"sha"`
	Parents []struct {
		SHA string `json:"sha"`
	} `json:"parents"`
}

CompareCommit is one commit of a comparison; Parents has more than one entry for a merge commit.

type Group added in v1.20.0

type Group struct {
	FP       string
	Rep      render.Finding
	Members  []render.Finding
	Severity render.Severity
	Side     string
	Anchored bool
	Text     string
}

Group is every finding that shares one fingerprint, folded into a single comment. Rep is the finding the comment is anchored on (lowest anchorable line); Text is the rendered comment without the identity marker. A group with an empty FP is unmanaged: it never matches a thread and is always posted fresh, like before comment sync existed.

type Marker added in v1.20.0

type Marker struct {
	FP    string
	Attrs []string
}

Marker is a parsed identity marker. Attrs holds every attribute token other than `v=1`, in document order — unknown keys and values included — so a rewrite preserves what it does not understand.

func NewMarker added in v1.20.0

func NewMarker(fp string) Marker

NewMarker returns a marker with no attributes (a thread CommitBrief manages and has not closed).

func SplitMarker added in v1.20.0

func SplitMarker(body string) (text string, m Marker, ok bool)

SplitMarker separates a comment body into its text and identity marker. ok is false when the body carries no valid v=1 marker. text is normalized for comparison (CRLF -> LF, trailing whitespace trimmed).

func (Marker) Last added in v1.20.0

func (m Marker) Last() int64

Last is the `last=` comment id; 0 when absent or malformed.

func (Marker) State added in v1.20.0

func (m Marker) State() string

State is the `state=` value, "" when absent.

func (Marker) String added in v1.20.0

func (m Marker) String() string

String renders the marker exactly as it is stored in a comment body.

func (Marker) WithState added in v1.20.0

func (m Marker) WithState(state string, last int64) Marker

WithState returns a copy with `state` (and `last`, when non-zero) replaced. An empty state removes both. Every other attribute is kept as is, in order. These are the only two keys CommitBrief ever rewrites.

type PRMeta

type PRMeta struct {
	Number         int      `json:"number"`
	Author         owner    `json:"author"`
	URL            string   `json:"url"`
	HeadRepository repoRef  `json:"headRepository"`
	Commits        []commit `json:"commits"`
}

PRMeta is the subset of `gh pr view --json ...` that remote pr consumes.

Note: gh does not expose a baseRepository field on PRs — the base repo is derived from the PR URL (which always points at the base repo) via BaseSlug.

func FetchPRMeta

func FetchPRMeta(ctx context.Context, r Runner, id, repo string) (PRMeta, error)

FetchPRMeta runs `gh pr view <id> --json number,author,url,headRepository,commits`.

func (PRMeta) AuthorLogin

func (m PRMeta) AuthorLogin() string

AuthorLogin returns the PR author's GitHub login.

func (PRMeta) BaseSlug added in v1.2.0

func (m PRMeta) BaseSlug() string

BaseSlug returns the base repository as "owner/name", parsed from the PR URL (https://<host>/<owner>/<repo>/pull/<n>). A PR's web URL always lives on the base repo, so this is correct even for cross-fork PRs. Returns "" if the URL is malformed.

func (PRMeta) LastOID

func (m PRMeta) LastOID() string

LastOID returns the head commit OID, or "" when the PR has no commits.

type Result added in v1.20.0

type Result struct {
	Posted     int
	PostFailed int
	Updated    int
	Unchanged  int
	Resolved   int
	Replied    int
	Held       int
	// StaleOpen counts duplicate (non-canonical) threads that could not be
	// resolved and were left open.
	StaleOpen int
	// StaleReason says why the duplicates stayed open: "permission" when the
	// viewer may not resolve (or record), otherwise the first API error.
	StaleReason string
	// Unanchored are findings that could not be given an inline comment and
	// must be listed in the review body instead.
	Unanchored []render.Finding
	Warnings   []Warning
	// OpenOurs counts CommitBrief threads that were already on the PR and are
	// still open once the sync is done: untouched, held and out-of-scope
	// ones, and threads left open by a failed resolve. Comments this run
	// posted are not counted: the verdict already weighs the findings they
	// carry. An incremental verdict that approves must not ignore OpenOurs
	// (ADR-0046 §A.7b).
	OpenOurs int
}

Result is the outcome of one Sync run.

func Sync added in v1.20.0

func Sync(ctx context.Context, p SyncParams) Result

Sync reconciles the PR's CommitBrief review threads with the current findings (ADR-0046). The decision logic is pure over the thread snapshot; all GitHub writes go through the small helpers in threads.go/comment.go.

type Runner

type Runner interface {
	Run(ctx context.Context, args ...string) ([]byte, error)
}

Runner executes a `gh` invocation and returns its stdout. Production uses execRunner; tests inject a fake to avoid live network and to script sequential responses (race-retry, failure paths).

func NewRunner

func NewRunner() Runner

NewRunner returns the production Runner backed by the `gh` binary.

type SyncParams added in v1.20.0

type SyncParams struct {
	Runner   Runner
	Slug     string
	PRNumber int
	CommitID string
	Threads  []Thread
	Groups   []Group
	Select   func([]render.Finding) []render.Finding
	// InScope reports whether a thread's file was part of this run's review.
	// A nil InScope means the whole PR was reviewed. Threads outside the
	// scope are never touched: a narrowed run (--file/--dir/--exclude-*) says
	// nothing about files it did not look at (ADR-0046 §Update 2026-10-18).
	InScope func(path string) bool
	// Incremental marks a --since-last-review run: only the delta since the
	// last review was re-reviewed, so a finding missing from Groups proves
	// nothing about code outside that delta. In that mode a thread whose
	// finding is gone is resolved only when it is active, outdated and its
	// file is in InDiff (ADR-0046 §A.7b); every other thread is left alone.
	Incremental bool
	// InDiff reports whether a file is part of the incremental diff. It is
	// consulted only when Incremental is set; nil then means no file is.
	InDiff func(path string) bool
}

SyncParams is the input of Sync. Select applies the loop cap (ADR-0016 §6) to the findings that need a brand-new inline comment.

type Thread added in v1.20.0

type Thread struct {
	NodeID       string
	Path         string
	Resolved     bool
	Outdated     bool
	CanResolve   bool
	CanUnresolve bool
	CanReply     bool
	Root         Comment
	Recent       []Comment
}

Thread is a review thread snapshot (GraphQL `reviewThreads`). Root is the first comment (it carries the identity marker); Recent is the tail of the thread, oldest first, so its last element is the thread's latest comment.

func FetchThreads added in v1.20.0

func FetchThreads(ctx context.Context, r Runner, slug string, number int) ([]Thread, error)

FetchThreads reads every review thread of a PR through GraphQL. `gh api graphql --paginate` emits one JSON document per page, back to back, so the output is decoded as a stream. Empty output is an empty snapshot.

func (Thread) LastID added in v1.20.0

func (t Thread) LastID() int64

LastID is the database id of the thread's most recent comment.

type Verdict

type Verdict int

Verdict is the review-level action submitted to GitHub.

const (
	// VerdictApprove — no findings reached the request-changes threshold.
	VerdictApprove Verdict = iota
	// VerdictComment — findings exist but none reached the threshold.
	VerdictComment
	// VerdictRequestChanges — at least one finding reached the threshold.
	VerdictRequestChanges
)

type Warning added in v1.20.0

type Warning struct {
	Op  string
	Ref string
	Err error
}

Warning is a non-fatal problem met while syncing. Err is nil when the operation was skipped for lack of permission.

Jump to

Keyboard shortcuts

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