github

package
v0.109.1 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 28 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 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

View Source
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).

View Source
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).

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
const KeychainService = "dev.caprock.github"

KeychainService is the macOS Keychain item Caprock's token lives under.

View Source
const TokenFile = "github-token"

TokenFile is the file's name in the data directory.

Variables

View Source
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 UserHome

func UserHome(ctx context.Context) string

UserHome is the current user's home directory as the system records it (Directory Services on macOS), not $HOME, which a caller may have changed. "" when it cannot be read.

Types

type CI added in v0.108.0

type CI struct {
	Repo    string `json:"repo"`
	HeadSHA string `json:"head_sha"`
	// 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"`
	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 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"`
	HTMLURL    string   `json:"html_url,omitempty"`
	Steps      []CIStep `json:"steps"`
}

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 CIOS added in v0.108.0

type CIOS struct {
	OS string `json:"os"`
	MS int64  `json:"ms"`
}

CIOS is the runner time of the finished jobs on one OS.

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"`
	Jobs       []CIJob `json:"jobs"`
}

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"`
}

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.

func (*Error) Error

func (e *Error) Error() string

type ExistsError

type ExistsError struct {
	Err *Error
	PR  *PR
}

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

type Fallback struct {
	Keychain Keychain
	File     File
	// contains filtered or unexported fields
}

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.

func (*Fallback) Delete

func (f *Fallback) Delete(ctx context.Context) error

func (*Fallback) Get

func (f *Fallback) Get(ctx context.Context) (string, error)

func (*Fallback) Kind

func (f *Fallback) Kind() string

func (*Fallback) Note

func (f *Fallback) Note() string

Note says why the token is not where it would usually be, "" otherwise.

func (*Fallback) Set

func (f *Fallback) Set(ctx context.Context, token string) error

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).

func (File) Delete

func (f File) Delete(context.Context) error

func (File) Get

func (f File) Get(context.Context) (string, error)

func (File) Kind

func (File) Kind() string

func (File) Set

func (f File) Set(_ context.Context, token string) error

type FileWithNote

type FileWithNote struct {
	File
	Why string
}

FileWithNote is the file store with the reason the Keychain is not used.

func (FileWithNote) Note

func (f FileWithNote) Note() string

type GHCLI

type GHCLI struct {
	Env func() []string
	Bin string
}

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).

func (GHCLI) Found

func (g GHCLI) Found() bool

Found reports whether gh is installed, without running it.

func (GHCLI) Token

func (g GHCLI) Token(ctx context.Context) (string, error)

Token runs `gh auth token --hostname github.com`. The token is returned and nowhere kept by this call.

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.

func (Keychain) Delete

func (k Keychain) Delete(ctx context.Context) error

func (Keychain) Get

func (k Keychain) Get(ctx context.Context) (string, error)

func (Keychain) Kind

func (Keychain) Kind() string

func (Keychain) Set

func (k Keychain) Set(ctx context.Context, token string) error

type Label added in v0.103.0

type Label struct {
	Name  string `json:"name"`
	Color string `json:"color,omitempty"`
}

Label is an issue's label.

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 Repo

type Repo struct {
	Owner string `json:"owner"`
	Name  string `json:"name"`
}

Repo names a repository on github.com.

func ParsePullURL added in v0.107.0

func ParsePullURL(link string) (Repo, int, bool)

ParsePullURL reads a github.com pull request link: https://github.com/owner/name/pull/123.

func ParseRemote

func ParseRemote(remote string) (Repo, bool)

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).

func (Repo) FullName

func (r Repo) FullName() string

FullName is "owner/name".

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

type Runner func(ctx context.Context, args ...string) (stdout string, code int, err error)

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 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) CIBySHA added in v0.108.0

func (s *Service) CIBySHA(ctx context.Context, repo Repo, sha string) (CI, *Error)

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

func (s *Service) Connect(ctx context.Context, source, pasted string) (Status, *Error)

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) DeviceState

func (s *Service) DeviceState() *Device

DeviceState is the device flow's state, nil when none was started.

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context) (Status, error)

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

func (s *Service) Items(ctx context.Context, projectID int64, q string) (Items, error)

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

func (s *Service) JobLog(ctx context.Context, repo Repo, jobID int64) (CILog, *Error)

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

func (s *Service) Kick(projectID int64)

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) Owners

func (s *Service) Owners(ctx context.Context) (Owners, *Error)

Owners lists the account and the organizations it belongs to.

func (*Service) PRs

func (s *Service) PRs() []PR

PRs is every followed pull request.

func (*Service) PullByURL added in v0.107.0

func (s *Service) PullByURL(ctx context.Context, link string) (PR, *Error)

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) 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) Repos

func (s *Service) Repos(ctx context.Context, owner, query string, page int) (RepoPage, *Error)

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) SetNotify

func (s *Service) SetNotify(on bool) (Status, error)

SetNotify switches the CI and review notifications.

func (*Service) Start

func (s *Service) Start(ctx context.Context)

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

func (s *Service) StartDevice(ctx context.Context) (Device, *Error)

StartDevice begins the device flow: GitHub's code for the user to enter, then a background wait for the token.

func (*Service) Status

func (s *Service) Status() Status

Status is the connection as Settings shows it. It sends nothing.

func (*Service) Worktree

func (s *Service) Worktree(ctx context.Context, projectID int64, worktree string) (WorktreeInfo, error)

Worktree says what the Changes view shows about GitHub for one worktree. When GitHub has not been asked about this branch yet, it asks now.

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

type TokenSource interface {
	Token(ctx context.Context) (string, error)
	Found() bool
}

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).

Jump to

Keyboard shortcuts

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