Documentation
¶
Overview ¶
Package github is Caprock's GitHub integration (F14, .ai/21-app.md § GitHub): a small REST client in the daemon, the token sources it may use, the OAuth device flow, and the pull-request state each worktree shows.
The token never leaves the daemon. It is sent to the API host and nowhere else — not to git (a push uses the user's own credentials, through the Changes push), not to the interface, not to a log. Requests are conditional (ETag), so an unchanged answer is a 304 GitHub does not count; the rate-limit headers are read on every answer, and once a limit is hit nothing is asked until it lifts.
Index ¶
- Constants
- Variables
- func IsReleaseRun(event, headBranch, defaultBranch string) bool
- func UserHome(ctx context.Context) string
- type ActionsUsage
- type ActionsUsageSKU
- type BranchPR
- type CI
- type CICost
- type CIEstimate
- type CIJob
- type CILog
- type CIOS
- type CIRun
- type CIStep
- type Check
- type Checks
- type Config
- type CreatePRRequest
- type CreatePRResult
- type CreateRepoRequest
- type CreateRepoResult
- type Device
- type Draft
- type Error
- type ExistsError
- type Fallback
- type File
- type FileWithNote
- type GHCLI
- type Health
- type Item
- type Items
- type Keychain
- type Label
- type Owner
- type Owners
- type PR
- type PushFailure
- type Rate
- type ReleaseCI
- type ReleaseLink
- type Repo
- type RepoInfo
- type RepoPage
- type RepoRef
- type Review
- type Runner
- type RunnerCost
- type RunnerSKU
- type RunnerTable
- type Service
- func (s *Service) ActionsUsage(ctx context.Context, owner string) (ActionsUsage, *Error)
- func (s *Service) CIBySHA(ctx context.Context, repo Repo, sha string) (CI, *Error)
- func (s *Service) CancelDevice()
- func (s *Service) Connect(ctx context.Context, source, pasted string) (Status, *Error)
- func (s *Service) CreatePR(ctx context.Context, projectID int64, worktree string, req CreatePRRequest) (CreatePRResult, error)
- func (s *Service) CreateRepo(ctx context.Context, projectID int64, req CreateRepoRequest) (CreateRepoResult, error)
- func (s *Service) DefaultBranch(ctx context.Context, repo Repo) (string, *Error)
- func (s *Service) DeviceState() *Device
- func (s *Service) Disconnect(ctx context.Context) (Status, error)
- func (s *Service) Items(ctx context.Context, projectID int64, q string) (Items, error)
- func (s *Service) JobLog(ctx context.Context, repo Repo, jobID int64) (CILog, *Error)
- func (s *Service) Kick(projectID int64)
- func (s *Service) MainCI(ctx context.Context, repo Repo, branch string) (CI, *Error)
- func (s *Service) OpenPullCount(ctx context.Context, remote string) (n int, ok bool, reason string)
- func (s *Service) Owners(ctx context.Context) (Owners, *Error)
- func (s *Service) PRs() []PR
- func (s *Service) PullByURL(ctx context.Context, link string) (PR, *Error)
- func (s *Service) PullsByBranch(ctx context.Context, repo Repo) (map[string]BranchPR, *Error)
- func (s *Service) Refresh(ctx context.Context, projectID int64, worktree string) (WorktreeInfo, error)
- func (s *Service) ReleaseByRepo(ctx context.Context, repo Repo, defaultBranch string) (ReleaseCI, *Error)
- func (s *Service) RepoVisibility(ctx context.Context, repo Repo) string
- func (s *Service) Repos(ctx context.Context, owner, query string, page int) (RepoPage, *Error)
- func (s *Service) SetNotify(on bool) (Status, error)
- func (s *Service) Start(ctx context.Context)
- func (s *Service) StartDevice(ctx context.Context) (Device, *Error)
- func (s *Service) Status() Status
- func (s *Service) WithBaselines(ctx context.Context, repo Repo, runs []CIRun) []CIRun
- func (s *Service) Worktree(ctx context.Context, projectID int64, worktree string) (WorktreeInfo, error)
- type Sources
- type Status
- type TokenSource
- type TokenStore
- type User
- type WorktreeInfo
- type Worktrees
Constants ¶
const ( DefaultAPI = "https://api.github.com" DefaultWeb = "https://github.com" )
DefaultAPI and DefaultWeb are the only hosts the token or the device flow ever reach. Tests point a Client elsewhere (Service.API), and the daemon admits an override only for a loopback address (internal/daemon).
const ( KindNotConnected = "not_connected" // no source chosen, or it gives no token KindAuth = "auth" // 401: the token was revoked or expired KindScope = "scope" // 403: the token lacks a scope or a permission KindForbidden = "forbidden" // 403 for another reason (SSO, a blocked user) KindNotFound = "not_found" // 404: absent, or invisible to this token KindRateLimit = "rate_limit" // 403/429 with the limit spent, or a secondary limit KindExists = "exists" // 422: a pull request or repository already exists KindInvalid = "invalid" // 422 otherwise, or a bad request from us KindNetwork = "network" // GitHub could not be reached KindGitHub = "github" // 5xx, or an answer we could not read KindState = "state" // the worktree cannot do it (no branch, no remote) KindDisabled = "disabled" // device flow without a client id )
The kinds of failure, each with its own message and its own HTTP status on Caprock's side (internal/api/github.go). The interface shows every one of them with what was being done; none is swallowed (21-app.md principle 7).
const ( UnpricedSelfHosted = "self_hosted" // a self-hosted runner: not GitHub's minutes UnpricedUnknown = "unknown_runner" // labels that name no runner the table knows UnpricedUnfinished = "unfinished" // still queued or running UnpricedNoTable = "no_table" // the rate table did not load )
Why a job has no price.
const ( MatchLabel = "label" // a workflow label GitHub documents MatchName = "name" // a larger runner's chosen name stating the OS and core count )
How a SKU was found.
const ( VisibilityPublic = "public" VisibilityPrivate = "private" VisibilityUnknown = "unknown" )
Repository visibility as far as Caprock knows it.
const ( MinPoll = 60 * time.Second MaxPoll = 8 * time.Minute )
Polling bounds. A followed pull request is asked about at most once a minute, and less often while nothing changes (up to MaxPoll); a push, a new pull request or a person pressing Refresh asks sooner, never more often than kickGap.
const ( // SourceGH reuses the GitHub CLI's login: `gh auth token`, read when a // call needs it and kept in memory only. Caprock never writes it down. SourceGH = "gh" // SourceToken is a token the user pasted in Settings, kept in the // macOS Keychain (elsewhere a 0600 file in the data directory). SourceToken = "token" // SourceOAuth is a token from the OAuth device flow, kept like a pasted // one. Offered only when a client id is configured. SourceOAuth = "oauth" )
Where the token comes from (ADR-039). One source at a time; "" is not connected, and then nothing is ever sent to GitHub.
const ( UsageNotConnected = "not_connected" UsagePermission = "permission" // 403: the token may not read billing UsageNotFound = "not_found" // 404: no such account, or no enhanced billing UsageError = "error" // anything else; Error says what )
Why the usage is not available.
const DeviceScopes = "repo read:org"
DeviceScopes are what the device flow asks for: private repositories and pull requests, and the organizations the user belongs to.
const EnvSecretStore = "CAPROCK_SECRET_STORE"
EnvSecretStore forces the token store: "file" uses the 0600 file even on macOS. Tests and throwaway daemons set it, so nothing touches a keychain.
const FrameGitHub bus.FrameType = "github"
FrameGitHub is the live frame this package sends: {kind: "account", account: Status} when the connection changes, {kind: "pr", pr: PR} when a worktree's pull request does, {kind: "pr_gone", project_id, worktree} when one is no longer followed.
const KeychainService = "dev.caprock.github"
KeychainService is the macOS Keychain item Caprock's token lives under.
const TokenFile = "github-token"
TokenFile is the file's name in the data directory.
Variables ¶
var ErrGHMissing = errors.New("the GitHub CLI (gh) is not installed, or not on your login shell's PATH")
ErrGHMissing is `gh` not installed, or not on the login shell's PATH.
Functions ¶
func IsReleaseRun ¶ added in v0.110.0
IsReleaseRun reports whether a run was started by a release: a release event, or a push of a tag (a head_branch that reads as a tag and is not the default branch).
Types ¶
type ActionsUsage ¶ added in v0.110.0
type ActionsUsage struct {
Account string `json:"account"`
Org bool `json:"org"`
Year int `json:"year"`
Month int `json:"month"`
// Available is true when GitHub answered with the report.
Available bool `json:"available"`
// Reason says why not: not_connected, permission, not_found or error.
Reason string `json:"reason,omitempty"`
// Needs names what to grant the token when Reason is permission.
Needs []string `json:"needs,omitempty"`
// Minutes sums the Actions items billed in minutes; the dollars sum
// every Actions item (storage included). Net is after GitHub's discount,
// which is how the included minutes appear.
Minutes float64 `json:"minutes"`
GrossUSD float64 `json:"gross_usd"`
DiscountUSD float64 `json:"discount_usd"`
NetUSD float64 `json:"net_usd"`
BySKU []ActionsUsageSKU `json:"by_sku"`
// Endpoint is the GitHub path asked (no token, no host).
Endpoint string `json:"endpoint,omitempty"`
At int64 `json:"at"`
Error *Error `json:"error,omitempty"`
}
ActionsUsage is GET /v1/github/actions-usage.
type ActionsUsageSKU ¶ added in v0.110.0
type ActionsUsageSKU struct {
SKU string `json:"sku"`
UnitType string `json:"unit_type"`
Quantity float64 `json:"quantity"`
GrossUSD float64 `json:"gross_usd"`
DiscountUSD float64 `json:"discount_usd"`
NetUSD float64 `json:"net_usd"`
}
ActionsUsageSKU is one SKU's Actions usage this month.
type BranchPR ¶ added in v0.111.0
type BranchPR struct {
Number int `json:"number"`
URL string `json:"url"`
Title string `json:"title,omitempty"`
State string `json:"state"` // open | closed | merged
Draft bool `json:"draft,omitempty"`
Base string `json:"base,omitempty"`
HeadSHA string `json:"head_sha,omitempty"`
}
BranchPR is the pull request a branch is the head of.
type CI ¶ added in v0.108.0
type CI struct {
Repo string `json:"repo"`
HeadSHA string `json:"head_sha"`
// Branch is set on a branch's CI (MainCI), "" on a commit's.
Branch string `json:"branch,omitempty"`
// State: running (a run is queued or in progress), fail, pass, or none.
State string `json:"state"`
Runs []CIRun `json:"runs"`
RunnerMS int64 `json:"runner_ms"`
ByOS []CIOS `json:"by_os"`
// Cost sums every run's finished jobs at the runners' list rates: an
// estimate before a private repository's included minutes.
Cost *CICost `json:"cost,omitempty"`
At int64 `json:"at"`
Error *Error `json:"error,omitempty"`
}
CI is a commit's GitHub Actions: every workflow run, their jobs and steps, with what each took. RunnerMS sums the jobs that finished, measured from GitHub's own timestamps; a running job's time is the reader's clock minus its StartedAt. No billing multiplier is applied: ByOS says which runners the minutes were on, and nothing more.
type CICost ¶ added in v0.110.0
type CICost struct {
USD float64 `json:"usd"`
// MinutesBilled sums the priced jobs GitHub charges for; FreeMinutes the
// standard-runner minutes of a public repository; UnpricedMinutes those
// of finished jobs with no price (self-hosted, unknown runner).
MinutesBilled int64 `json:"minutes_billed"`
FreeMinutes int64 `json:"free_minutes"`
UnpricedMinutes int64 `json:"unpriced_minutes"`
PricedJobs int `json:"priced_jobs"`
UnpricedJobs int `json:"unpriced_jobs"`
UnfinishedJobs int `json:"unfinished_jobs"`
// Partial is true when a job is unfinished or could not be priced: the
// sum is less than the run will cost.
Partial bool `json:"partial"`
Visibility string `json:"visibility"`
TableVersion string `json:"table_version,omitempty"`
// TableSource is the page the table's rates were read from, for the
// deck's tooltip.
TableSource string `json:"table_source,omitempty"`
}
CICost is the sum over a run's, or a commit's, finished jobs.
type CIEstimate ¶ added in v0.110.0
CIEstimate is how long a release run usually takes: the median wall-clock span (updated_at - run_started_at, GitHub's own stamps) of the last Runs successful release runs of the same workflow. An estimate, labelled so.
type CIJob ¶ added in v0.108.0
type CIJob struct {
ID int64 `json:"id"`
RunID int64 `json:"run_id"`
Name string `json:"name"`
Status string `json:"status"`
Conclusion string `json:"conclusion,omitempty"`
StartedAt int64 `json:"started_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
Labels []string `json:"labels"`
// OS is read from the runner labels: linux, windows, macos, self-hosted,
// or "" when they name none of these.
OS string `json:"os,omitempty"`
RunnerName string `json:"runner_name,omitempty"`
// RunnerGroup is GitHub's runner_group_name: "GitHub Actions" for its
// standard hosted runners, the group's name for a larger or self-hosted one.
RunnerGroup string `json:"runner_group_name,omitempty"`
HTMLURL string `json:"html_url,omitempty"`
Steps []CIStep `json:"steps"`
// Baseline is the median duration of the job of this name in the
// workflow's last successful runs (WithBaselines); absent with fewer
// than two of them.
Baseline *CIEstimate `json:"baseline,omitempty"`
// Cost is what the job cost at the runner's list rate (runnercost.go).
Cost *RunnerCost `json:"cost,omitempty"`
}
CIJob is one job of a workflow run, with its steps.
type CILog ¶ added in v0.108.0
type CILog struct {
JobID int64 `json:"job_id"`
Lines []string `json:"lines"`
// ErrorLine is the index in Lines of the error the tail is built around,
// -1 when the log names none and Lines is simply its end.
ErrorLine int `json:"error_line"`
Truncated bool `json:"truncated,omitempty"` // the log was longer than was read
}
CILog is the end of a failed job's log: the lines around its last error.
type CIRun ¶ added in v0.108.0
type CIRun struct {
ID int64 `json:"id"`
Name string `json:"name"`
Event string `json:"event,omitempty"`
Status string `json:"status"`
Conclusion string `json:"conclusion,omitempty"`
Attempt int `json:"attempt,omitempty"`
HTMLURL string `json:"html_url,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
// StartedAt is when this attempt started (GitHub's run_started_at).
StartedAt int64 `json:"started_at,omitempty"`
// HeadBranch is the branch, or for a tag push or a release the tag.
HeadBranch string `json:"head_branch,omitempty"`
HeadSHA string `json:"head_sha,omitempty"`
WorkflowID int64 `json:"workflow_id,omitempty"`
Jobs []CIJob `json:"jobs"`
// Baseline is the median wall-clock span (run_started_at to updated_at)
// of the workflow's last successful runs (WithBaselines); absent with
// fewer than two of them.
Baseline *CIEstimate `json:"baseline,omitempty"`
// Cost sums the run's finished jobs (runnercost.go).
Cost *CICost `json:"cost,omitempty"`
}
CIRun is one workflow run of a commit.
type CIStep ¶ added in v0.108.0
type CIStep struct {
Number int `json:"number"`
Name string `json:"name"`
Status string `json:"status"` // queued | in_progress | completed
Conclusion string `json:"conclusion,omitempty"` // success | failure | skipped | cancelled …
StartedAt int64 `json:"started_at,omitempty"` // unix ms
CompletedAt int64 `json:"completed_at,omitempty"`
// DurationMS is CompletedAt - StartedAt, 0 until both are known.
DurationMS int64 `json:"duration_ms,omitempty"`
}
CIStep is one step of a job, as GitHub Actions reports it.
type Check ¶
type Check struct {
Name string `json:"name"`
State string `json:"state"` // pass | fail | pending | skipped
URL string `json:"url,omitempty"`
// Status is a check run's own: queued | in_progress | completed; "" for
// a commit status. The deck's mini pipeline tells running from queued by it.
Status string `json:"status,omitempty"`
StartedAt int64 `json:"started_at,omitempty"` // unix ms
CompletedAt int64 `json:"completed_at,omitempty"`
// JobID is the GitHub Actions job a check run is, read from its link
// (…/actions/runs/{run}/job/{job}); 0 for any other check.
JobID int64 `json:"job_id,omitempty"`
}
Check is one CI check on a pull request's head commit: a check run or a commit status.
type Checks ¶
type Checks struct {
State string `json:"state"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Items []Check `json:"items"`
}
Checks sums a head commit's checks: fail when any failed, else pending when any is still running, else pass; none when there are none.
type Config ¶
type Config interface {
Source() string
SetSource(string) error
ClientID() string
Notify() bool
SetNotify(bool) error
}
Config is where the choice of source and the client id live (config.json). The token itself is never there.
type CreatePRRequest ¶
type CreatePRRequest struct {
Title string `json:"title"`
Body string `json:"body"`
Base string `json:"base,omitempty"`
Draft bool `json:"draft"`
}
CreatePRRequest is POST /v1/projects/{id}/github/pr.
type CreatePRResult ¶
type CreatePRResult struct {
PR PR `json:"pr"`
Pushed bool `json:"pushed"`
Push *projects.RemoteResult `json:"push,omitempty"`
}
CreatePRResult is the new pull request, and the push that went first.
type CreateRepoRequest ¶
type CreateRepoRequest struct {
Name string `json:"name"`
Owner string `json:"owner,omitempty"` // an organization; empty is the account
Private *bool `json:"private,omitempty"`
Description string `json:"description,omitempty"`
Protocol string `json:"protocol,omitempty"` // https (default) | ssh: the remote's address
Push *bool `json:"push,omitempty"` // push the branch after (default true)
}
CreateRepoRequest is POST /v1/projects/{id}/github/repo.
type CreateRepoResult ¶
type CreateRepoResult struct {
Repo RepoInfo `json:"repo"`
Remote string `json:"remote"`
RemoteURL string `json:"remote_url"`
Pushed bool `json:"pushed"`
Push *projects.RemoteResult `json:"push,omitempty"`
PushError *PushFailure `json:"push_error,omitempty"`
Changes projects.Changes `json:"changes"`
}
CreateRepoResult says what was done: the repository, the remote, and the push, which can fail on its own after the first two succeeded.
type Device ¶
type Device struct {
State string `json:"state"` // pending | done | denied | expired | error
UserCode string `json:"user_code,omitempty"`
VerificationURI string `json:"verification_uri,omitempty"`
ExpiresAt int64 `json:"expires_at,omitempty"` // unix ms
Interval int `json:"interval,omitempty"` // seconds between polls
Error *Error `json:"error,omitempty"`
}
Device is the device flow's state, as Settings shows it.
type Draft ¶
type Draft struct {
Title string `json:"title"`
Body string `json:"body"`
Commits []string `json:"commits"`
}
Draft is a pull request's prefilled title and body: the one commit's subject, or the branch's name, and the commits' subjects.
type Error ¶
type Error struct {
Kind string `json:"kind"`
Status int `json:"status,omitempty"` // GitHub's HTTP status, 0 when none came back
Doing string `json:"doing"` // "Creating the pull request"
Message string `json:"message"`
// RetryAt is when a rate limit lifts, unix ms; 0 when not limited.
RetryAt int64 `json:"retry_at,omitempty"`
// Needs names the scopes or fine-grained permissions GitHub asked for.
Needs []string `json:"needs,omitempty"`
At int64 `json:"at"`
}
Error is a failed GitHub call, said so a person can act on it: what Caprock was doing, what GitHub answered, and when to try again.
type ExistsError ¶
ExistsError is a pull request already open from the branch: the 422, with the one GitHub has.
func (*ExistsError) Error ¶
func (e *ExistsError) Error() string
type Fallback ¶
Fallback is the Keychain with the 0600 file behind it: when the Keychain refuses (locked, missing, an error), the token goes to the file instead and Note says so — never a dialog.
type File ¶
type File struct {
Path string
}
File stores the token in a 0600 file in the data directory, where there is no Keychain (as the report bot's token and the paired devices are kept).
type FileWithNote ¶
FileWithNote is the file store with the reason the Keychain is not used.
func (FileWithNote) Note ¶
func (f FileWithNote) Note() string
type GHCLI ¶
GHCLI reads the GitHub CLI's token for github.com. Env is the login shell's environment, so `gh` and its keyring are found as in a terminal; Bin, when set, is the binary (tests).
type Health ¶
type Health struct {
LastOKAt int64 `json:"last_ok_at,omitempty"`
Error *Error `json:"error,omitempty"`
Rate *Rate `json:"rate,omitempty"`
PausedUntil int64 `json:"paused_until,omitempty"`
}
Health is the line Settings shows: when GitHub last answered, the last error with what was being done, the rate limit, and any pause.
type Item ¶ added in v0.103.0
type Item struct {
Number int `json:"number"`
Title string `json:"title"`
URL string `json:"url"`
Author string `json:"author,omitempty"`
Labels []Label `json:"labels"`
PR bool `json:"pr"`
Draft bool `json:"draft,omitempty"`
Body string `json:"body,omitempty"`
Comments int `json:"comments"`
UpdatedAt string `json:"updated_at,omitempty"`
}
Item is one open issue or pull request in the picker.
type Items ¶ added in v0.103.0
type Items struct {
Connected bool `json:"connected"`
Repo *RepoRef `json:"repo"`
// Reason says why there is nothing to list: no_remote | not_github.
Reason string `json:"reason,omitempty"`
Items []Item `json:"items"`
More bool `json:"more"`
// Search is true when the list came from GitHub's search for q.
Search bool `json:"search,omitempty"`
At int64 `json:"at"`
}
Items is GET /v1/projects/{id}/github/items: the repository, its open issues and pull requests, and whether there were more than shown.
type Keychain ¶
type Keychain struct {
Service string
Path string // the keychain file, e.g. ~/Library/Keychains/login.keychain-db
Run Runner // nil runs /usr/bin/security
}
Keychain stores the token as a generic password through the `security` tool, with the token as an argument (no shell, no file). Every call names the keychain file explicitly (Path, the user's login keychain): without one, `security` falls back to the default keychain and, when it cannot find that, macOS shows a "Keychain Not Found" dialog — which a daemon must never cause. DefaultStore only builds one for a Path that exists.
type Owner ¶
type Owner struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url,omitempty"`
Org bool `json:"org"`
}
Owner is the user or an organization repositories are listed for.
type Owners ¶
type Owners struct {
Owners []Owner `json:"owners"`
}
Owners is the user and their organizations.
type PR ¶
type PR struct {
ProjectID int64 `json:"project_id"`
Worktree string `json:"worktree"`
Branch string `json:"branch"`
Repo string `json:"repo"`
Number int `json:"number"`
URL string `json:"url"`
Title string `json:"title"`
State string `json:"state"` // open | closed | merged
Draft bool `json:"draft"`
Base string `json:"base"`
HeadSHA string `json:"head_sha"`
// Mergeable is null while GitHub is still working it out.
Mergeable *bool `json:"mergeable"`
MergeableState string `json:"mergeable_state,omitempty"`
Review string `json:"review"` // approved | changes_requested | review_required | commented | ""
Reviews []Review `json:"reviews"`
Checks Checks `json:"checks"`
At int64 `json:"at"` // when it was last read, unix ms
// Error is why the last read failed; the rest is the last good answer.
Error *Error `json:"error,omitempty"`
}
PR is a worktree's pull request as the sidebar and the Changes view show it.
type PushFailure ¶
type PushFailure struct {
Error string `json:"error"`
Kind string `json:"kind"`
Output string `json:"output,omitempty"`
}
PushFailure is a push that failed, as the Changes push reports one.
type Rate ¶
type Rate struct {
Resource string `json:"resource"`
Limit int `json:"limit"`
Remaining int `json:"remaining"`
ResetAt int64 `json:"reset_at"` // unix ms
Used int `json:"used"`
}
Rate is the last rate-limit reading, per resource ("core", "search").
type ReleaseCI ¶ added in v0.110.0
type ReleaseCI struct {
Repo string `json:"repo"`
Tag string `json:"tag,omitempty"`
// State: running, fail, pass, or none (no release run among the recent).
State string `json:"state"`
Run *CIRun `json:"run,omitempty"`
// Estimate is set while the run is unfinished and enough past runs exist.
Estimate *CIEstimate `json:"estimate,omitempty"`
// Release is set once the run finished and GitHub has a release for the tag.
Release *ReleaseLink `json:"release,omitempty"`
At int64 `json:"at"`
Error *Error `json:"error,omitempty"`
}
ReleaseCI is a repository's newest release run with its jobs and steps.
type ReleaseLink ¶ added in v0.110.0
type ReleaseLink struct {
URL string `json:"url"`
PublishedAt int64 `json:"published_at,omitempty"`
Draft bool `json:"draft,omitempty"`
}
ReleaseLink is the GitHub release published for a tag.
type Repo ¶
Repo names a repository on github.com.
func ParsePullURL ¶ added in v0.107.0
ParsePullURL reads a github.com pull request link: https://github.com/owner/name/pull/123.
func ParseRemote ¶
ParseRemote reads the repository a git remote URL points at on github.com: https://github.com/o/r(.git), git@github.com:o/r(.git), ssh://git@github.com/o/r(.git). Any other host is not GitHub's (false).
type RepoInfo ¶
type RepoInfo struct {
FullName string `json:"full_name"`
Name string `json:"name"`
Owner string `json:"owner"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Archived bool `json:"archived"`
Description string `json:"description,omitempty"`
CloneURL string `json:"clone_url"`
SSHURL string `json:"ssh_url"`
HTMLURL string `json:"html_url"`
DefaultBranch string `json:"default_branch,omitempty"`
PushedAt string `json:"pushed_at,omitempty"`
}
RepoInfo is one repository in the clone picker.
type RepoPage ¶
type RepoPage struct {
Repos []RepoInfo `json:"repos"`
Page int `json:"page"`
Next bool `json:"next"`
// Search is true when the list came from GitHub's search, which finds
// the repositories of the owners named and not those shared with you.
Search bool `json:"search,omitempty"`
}
RepoPage is one page of the picker.
type RepoRef ¶
type RepoRef struct {
Owner string `json:"owner"`
Name string `json:"name"`
FullName string `json:"full_name"`
HTMLURL string `json:"html_url"`
}
RepoRef is a worktree's repository on GitHub.
type Review ¶
type Review struct {
User string `json:"user"`
State string `json:"state"` // approved | changes_requested | commented | dismissed
At int64 `json:"at,omitempty"`
}
Review is one reviewer's latest verdict.
type Runner ¶
Runner runs the `security` tool with args and returns its stdout and exit status. Tests replace it: no test ever runs the real tool.
type RunnerCost ¶ added in v0.110.0
type RunnerCost struct {
Priced bool `json:"priced"`
// Reason says why a job is not priced: self_hosted, unknown_runner,
// unfinished or no_table.
Reason string `json:"reason,omitempty"`
SKU string `json:"sku,omitempty"`
Display string `json:"display,omitempty"`
Match string `json:"match,omitempty"` // label | name
Larger bool `json:"larger,omitempty"`
RateUSD float64 `json:"rate_usd_per_min,omitempty"`
MinutesBilled int64 `json:"minutes_billed"`
USD float64 `json:"usd"`
FreePublic bool `json:"free_public"`
}
RunnerCost is what one job cost: its SKU, the minutes GitHub bills (each job rounded up to the whole minute), and the dollars at the SKU's list rate. FreePublic: a standard runner in a public repository, which GitHub does not charge — USD is 0 and MinutesBilled says what it would have counted. The figure is before a private repository's included minutes: an estimate.
type RunnerSKU ¶ added in v0.110.0
type RunnerSKU struct {
SKU string `json:"sku"`
Display string `json:"display"`
OS string `json:"os"`
Arch string `json:"arch,omitempty"`
USDMin float64 `json:"usd_per_min"`
Larger bool `json:"larger,omitempty"`
GPU bool `json:"gpu,omitempty"`
}
RunnerSKU is one row of the runner rate table.
type RunnerTable ¶ added in v0.110.0
type RunnerTable struct {
Version string `json:"version"`
Source string `json:"source"`
FetchedAt string `json:"fetched_at"`
Currency string `json:"currency"`
Unit string `json:"unit"`
Notes []string `json:"notes"`
SKUs []RunnerSKU `json:"skus"`
Labels map[string]string `json:"labels"`
// contains filtered or unexported fields
}
RunnerTable is the parsed pricing/actions.json.
func EmbeddedRunnerTable ¶ added in v0.110.0
func EmbeddedRunnerTable() (*RunnerTable, error)
EmbeddedRunnerTable is the table compiled into the binary, parsed once.
func ParseRunnerTable ¶ added in v0.110.0
func ParseRunnerTable(b []byte) (*RunnerTable, error)
ParseRunnerTable decodes and validates a runner rate table: a version, rows with a SKU and a non-negative rate, no SKU twice, and every label naming a SKU the table has.
func (*RunnerTable) Cost ¶ added in v0.110.0
func (t *RunnerTable) Cost(job CIJob, visibility string) RunnerCost
Cost prices one job. visibility is the repository's (public | private | unknown); an unknown one is priced as private, at the list rate, and the sum says it was unknown.
type Service ¶
type Service struct {
API, Web string
HTTP *http.Client
Store TokenStore
GH TokenSource
Config Config
Projects Worktrees
Bus *bus.Bus
Log *slog.Logger
Now func() time.Time
// Sleep waits between device-flow polls; tests shorten it.
Sleep func(context.Context, time.Duration) bool
// contains filtered or unexported fields
}
Service is the integration. Fill the exported fields, then Start.
func (*Service) ActionsUsage ¶ added in v0.110.0
ActionsUsage reads this month's (UTC) Actions usage of owner — the account itself when owner is "" or its own login, else that organization — from GitHub's billing usage report, kept usageKept. A refusal is an answer (Available false, with the reason and what to grant), not an error; the error is only for a malformed owner. It does not mark the health line: a token without billing access is not a broken connection.
func (*Service) CIBySHA ¶ added in v0.108.0
CIBySHA is a commit's GitHub Actions runs with their jobs and steps, read from GitHub and kept for ciRunning while any run is unfinished, else for ciSettled. Nothing is sent while GitHub is not connected.
func (*Service) CancelDevice ¶
func (s *Service) CancelDevice()
CancelDevice abandons a device flow in progress.
func (*Service) Connect ¶
Connect switches to a source after proving its token works: the GitHub CLI's login, or a pasted token (stored only once GitHub accepted it).
func (*Service) CreatePR ¶
func (s *Service) CreatePR(ctx context.Context, projectID int64, worktree string, req CreatePRRequest) (CreatePRResult, error)
CreatePR opens a pull request from a worktree's branch: it pushes first when the branch is not published or has commits GitHub lacks (the Changes push), then asks GitHub.
func (*Service) CreateRepo ¶
func (s *Service) CreateRepo(ctx context.Context, projectID int64, req CreateRepoRequest) (CreateRepoResult, error)
CreateRepo makes a repository on GitHub for a local project that has no remote, sets it as origin, and pushes the checked-out branch through the Changes push (the user's own git credentials, never this token).
func (*Service) DefaultBranch ¶ added in v0.110.0
DefaultBranch is the repository's default branch as GitHub reports it, kept for defaultKept. Used when git does not know it locally.
func (*Service) DeviceState ¶
DeviceState is the device flow's state, nil when none was started.
func (*Service) Disconnect ¶
Disconnect stops using GitHub and removes what Caprock stored: the token it holds, if any. The GitHub CLI's own login is never touched.
func (*Service) Items ¶ added in v0.103.0
Items lists the open issues and pull requests of a project's repository, the most recently updated first; with q, GitHub's issue search in that repository, or the one numbered q ("123", "#123").
func (*Service) JobLog ¶ added in v0.108.0
JobLog is the end of one finished job's log: up to logBefore lines before its last "##[error]" line and logAfter after it, or the last lines when none is marked. GitHub answers the log request with a redirect to a signed address on its log storage; that address is fetched without the token (it carries its own signature), only over https, and only at the hosts GitHub keeps logs on (logHost). Kept for logKept: a finished log does not change.
func (*Service) Kick ¶
Kick asks about a project's pull requests soon (all projects for 0): a push, a new pull request, a reconnect. Never sooner than kickGap after the last time, so a burst of pushes is one request.
func (*Service) MainCI ¶ added in v0.110.0
MainCI is the CI of a repository's default branch: the newest run of each workflow on it (up to mainWorkflowsShown), with jobs and steps, kept for ciRunning while any runs and ciSettled after. HeadSHA is the newest run's commit. Nothing is sent while GitHub is not connected.
func (*Service) OpenPullCount ¶ added in v0.111.0
OpenPullCount is how many pull requests are open in the GitHub repository remote names (a git remote URL), for a multi-repo project's page (ADR-055). Asked only when that page asks, never polled; one conditional GET of the open pulls (at most 100) per repository, kept for itemsTTL. ok is false with the reason when there is no count: not connected, not on GitHub, or GitHub's own error.
func (*Service) PullByURL ¶ added in v0.107.0
PullByURL is one pull request a session opened, by its link: its state, checks and review, read from GitHub and kept for a while (byURLPending, byURLOpen, byURLDone) so a deck polling it costs nothing between reads. Nothing is sent while GitHub is not connected.
func (*Service) PullsByBranch ¶ added in v0.111.0
PullsByBranch is the pull request of each branch of repo, from one list of its 50 most recently updated, kept branchPullsKept. A failed read keeps the last answer, if any. Nothing is sent while GitHub is not connected.
func (*Service) Refresh ¶
func (s *Service) Refresh(ctx context.Context, projectID int64, worktree string) (WorktreeInfo, error)
Refresh reads one worktree's pull request now (the Refresh button), at most once per kickGap.
func (*Service) ReleaseByRepo ¶ added in v0.110.0
func (s *Service) ReleaseByRepo(ctx context.Context, repo Repo, defaultBranch string) (ReleaseCI, *Error)
ReleaseByRepo is the repository's newest release run — the newest run of a release event, or of a push whose head_branch reads as a tag — with its jobs and steps, kept for ciRunning while it runs and ciSettled after. While it runs, the estimate of how long it takes; once it finished, the GitHub release published for its tag, when there is one. Nothing is sent while GitHub is not connected.
func (*Service) RepoVisibility ¶ added in v0.110.0
RepoVisibility is public or private as GitHub reports the repository (GET /repos/{o}/{r}, the read DefaultBranch makes and keeps), or unknown when it could not be read — asked again after visibilityKept, not on every CI read.
func (*Service) Repos ¶
Repos lists repositories: every one the token can reach (owner ""), one owner's, or — with a query — a search by name among the account's and its organizations' (or one owner's).
func (*Service) Start ¶
Start reads whether a token is stored and starts following pull requests. Nothing is sent to GitHub unless a source was chosen.
func (*Service) StartDevice ¶
StartDevice begins the device flow: GitHub's code for the user to enter, then a background wait for the token.
func (*Service) WithBaselines ¶ added in v0.110.0
WithBaselines returns runs with Baseline set on each run and each job that has one: the median of the workflow's last baselineRuns successful runs (other than the runs shown), read once per workflow per baselineListKept; the jobs of a finished run are read once. The runs given are not changed. Without GitHub, or when a read fails, the runs come back as they were: a missing baseline is no figure, not an error. Called only by the deck's routes, so nothing is asked while the deck is closed.
type Sources ¶
type Sources struct {
GH bool `json:"gh"` // the GitHub CLI is installed
Stored bool `json:"stored"` // Caprock holds a token
Store string `json:"store"` // keychain | file
// StoreNote says why the token is in the file rather than the Keychain.
StoreNote string `json:"store_note,omitempty"`
OAuth bool `json:"oauth"` // a client id is configured
Client string `json:"client,omitempty"` // that client id (public)
}
Sources says which sources exist here, without reading a token.
type Status ¶
type Status struct {
Connected bool `json:"connected"`
Source string `json:"source,omitempty"`
User *User `json:"user,omitempty"`
// Scopes are a classic or OAuth token's; ScopesKnown is false for a
// fine-grained token, whose permissions GitHub does not list.
Scopes []string `json:"scopes"`
ScopesKnown bool `json:"scopes_known"`
TokenKind string `json:"token_kind,omitempty"`
CheckedAt int64 `json:"checked_at,omitempty"`
Sources Sources `json:"sources"`
Health Health `json:"health"`
Device *Device `json:"device,omitempty"`
Notify bool `json:"notify"`
Tracked int `json:"tracked"`
}
Status is GET /v1/github.
type TokenSource ¶
TokenSource is the GitHub CLI (GHCLI) or a test's stand-in.
type TokenStore ¶
type TokenStore interface {
Get(ctx context.Context) (string, error) // "" with no error when nothing is stored
Set(ctx context.Context, token string) error
Delete(ctx context.Context) error
Kind() string // "keychain" or "file"
}
TokenStore keeps the one token Caprock itself holds. Never the database, never config.json, never a log.
func DefaultStore ¶
func DefaultStore(dataDir, service, home string) TokenStore
DefaultStore picks where Caprock keeps its token: the user's login keychain on macOS when that file exists (with the 0600 file behind it), else the 0600 file in dataDir. home is the user's real home directory (UserHome), not $HOME.
type User ¶
type User struct {
Login string `json:"login"`
Name string `json:"name,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
HTMLURL string `json:"html_url,omitempty"`
}
User is the account the token belongs to.
type WorktreeInfo ¶
type WorktreeInfo struct {
Connected bool `json:"connected"`
Repo *RepoRef `json:"repo"`
// Reason says why there is no repository or no pull request to offer:
// no_remote | not_github | detached | default_branch.
Reason string `json:"reason,omitempty"`
Branch string `json:"branch"`
Base string `json:"base"`
Remote string `json:"remote,omitempty"`
Published bool `json:"published"`
Ahead int `json:"ahead"`
PR *PR `json:"pr"`
Draft *Draft `json:"draft,omitempty"`
// Primed is false until GitHub was asked whether a pull request exists.
Primed bool `json:"primed"`
}
WorktreeInfo is GET /v1/projects/{id}/github: whether the worktree can have a pull request, and the one it has.
type Worktrees ¶
type Worktrees interface {
List(ctx context.Context) ([]projects.View, error)
Changes(ctx context.Context, id int64, worktree string) (projects.Changes, error)
Push(ctx context.Context, id int64, worktree string) (projects.RemoteResult, projects.Changes, error)
AddRemote(ctx context.Context, id int64, name, url string) (projects.Changes, error)
Subjects(ctx context.Context, id int64, worktree, base string) ([]string, error)
}
Worktrees is what the service needs from the projects list (projects.Service).