github

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package github wraps the GitHub REST and GraphQL APIs used by gh-sweep.

Index

Constants

View Source
const (
	ConclusionSuccess = "success"
	ConclusionFailure = "failure"
	ConclusionSkipped = "skipped"
)

Terminal conclusion values reported by the GitHub Actions API.

View Source
const (
	ErrorTypeUnknown     = "unknown"
	ErrorTypeBuildError  = "build-error"
	ErrorTypeTestFailure = "test-failure"
	ErrorTypePanic       = "panic"
	ErrorTypeTimeout     = "timeout"
)

Error type classifications returned by classifyError.

View Source
const (
	FlakyPatternSameCommitFlip = "same-commit-flip"
	FlakyPatternIntermittent   = "intermittent"
	FlakyPatternConsistent     = "consistent"
)

Flaky patterns returned by classifyPattern.

View Source
const (
	SecretScopeOrg  = "org"
	SecretScopeRepo = "repo"
)

Secret scopes.

View Source
const DefaultOpenPRCap = 20

DefaultOpenPRCap bounds how many of the newest open PRs are scanned for review threads.

Variables

View Source
var (
	ErrDefaultBranchDeletion   = errors.New("cannot delete the default branch")
	ErrOpenPRBranchDeletion    = errors.New("branch has an open pull request")
	ErrProtectedBranchDeletion = errors.New("cannot delete a protected branch")
)

Sentinel errors returned by BranchStatus.DeleteBlocked.

View Source
var ErrBranchNotProtected = errors.New("branch not protected")

ErrBranchNotProtected means the branch has no protection rule configured yet.

View Source
var ErrJobLogFetchFailed = errors.New("unexpected status fetching job logs")

ErrJobLogFetchFailed indicates the GitHub API returned a non-200 status while fetching a job's logs.

View Source
var ErrPagesNotFound = errors.New("pages not configured for this repository")

ErrPagesNotFound means the repo has no GitHub Pages site configured.

View Source
var ErrRulesetNotFound = errors.New("ruleset not found")

ErrRulesetNotFound means the repo has no ruleset with the requested name.

View Source
var ErrUnexpectedFileEncoding = errors.New("unexpected file encoding")

ErrUnexpectedFileEncoding means a Contents API response came back in an encoding other than base64, which the API is not expected to send.

Functions

func CompareProtectionRules

func CompareProtectionRules(rules []*ProtectionRule) map[string][]string

CompareProtectionRules compares protection rules across repositories.

func ComputeBranchStats

func ComputeBranchStats(runs []RunTiming, baseBranch string) map[string]*BranchStats

ComputeBranchStats aggregates run timing per branch, including each non-base branch's average-duration delta against baseBranch.

func ComputeJobStats

func ComputeJobStats(runs []RunTiming) map[string]*JobStats

ComputeJobStats aggregates job timing per workflow:job key.

func ComputeWorkflowStats

func ComputeWorkflowStats(runs []RunTiming) map[string]*WorkflowStats

ComputeWorkflowStats aggregates run timing and success rate per workflow.

func FilterByCommit

func FilterByCommit(commits ...string) func(TestRun) bool

FilterByCommit creates a filter for specific commits Higher-order function for functional composition.

func FilterByRepository

func FilterByRepository(repos ...string) func(TestRun) bool

FilterByRepository creates a filter for specific repositories Higher-order function returning a filter predicate.

func FormatAsJSON

func FormatAsJSON(contexts []*ErrorContext) (string, error)

FormatAsJSON formats error context as JSON for AI consumption Pure function: serializes to JSON.

func FormatAsMarkdown

func FormatAsMarkdown(contexts []*ErrorContext) string

FormatAsMarkdown formats error context as Markdown for AI consumption Pure function: generates Markdown string.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration renders a duration as seconds, minutes, or hours depending on its magnitude.

func GroupSecretsByScope

func GroupSecretsByScope(secrets []Secret) map[string][]Secret

GroupSecretsByScope groups secrets by their scope (org/repo) Pure function: creates grouped map.

func ParseSinceDate

func ParseSinceDate(value string) (time.Time, error)

ParseSinceDate parses a YYYY-MM-DD date for --since filtering.

func ScanWorkflowForSecrets

func ScanWorkflowForSecrets(workflowContent string) []string

ScanWorkflowForSecrets extracts secret references from workflow YAML Pure function: parses YAML content for secrets.* references.

func SetDefaultCache added in v0.10.0

func SetDefaultCache(dir string, ttl time.Duration)

SetDefaultCache makes every later NewClient serve repeat reads from dir for ttl. Call it once at startup: threading the setting through each of the TUI's own client constructions would touch every view for one value.

func SetTestTransport

func SetTestTransport(rt http.RoundTripper) func()

SetTestTransport routes every client created afterward through rt so tests never reach the real GitHub API. It returns a restore function and panics when called outside `go test`.

func SortRunsByDate

func SortRunsByDate(runs []RunTiming, ascending bool)

SortRunsByDate sorts runs in place by creation time.

Types

type Branch

type Branch struct {
	Name           string
	SHA            string
	Protected      bool
	Ahead          int
	Behind         int
	LastCommitDate time.Time
}

Branch represents a GitHub branch.

type BranchStats

type BranchStats struct {
	Branch         string
	TotalRuns      int
	AvgDuration    time.Duration
	WorkflowStats  map[string]*WorkflowStats
	DeltaVsBase    float64
	DeltaVsBasePct float64
}

BranchStats aggregates run timing for one branch, including its delta against a base branch.

type BranchStatus

type BranchStatus struct {
	Branch
	ComparedTo string
	IsDefault  bool
	PR         *PullRequest
}

BranchStatus extends Branch with default-branch and pull request context.

func (BranchStatus) DeleteBlocked

func (b BranchStatus) DeleteBlocked() error

DeleteBlocked reports why the branch must not be deleted, or nil when deletion is safe.

type BranchWithComparison

type BranchWithComparison struct {
	Branch
	ComparedTo string
}

BranchWithComparison extends Branch with comparison data.

type Client

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

Client wraps the GitHub API client.

func NewClient

func NewClient(ctx context.Context, opts ...Option) (*Client, error)

NewClient creates a new GitHub API client. It resolves gh CLI authentication when available and falls back to the GITHUB_TOKEN env var.

func NewClientWithRealAuthAndTransport added in v0.7.0

func NewClientWithRealAuthAndTransport(ctx context.Context, rt http.RoundTripper) (*Client, error)

NewClientWithRealAuthAndTransport creates a client that resolves real gh CLI auth (host and token) but routes requests through rt instead of the default transport. For cassette-recording tools only: it panics under `go test` so tests keep using the fake-token seam in NewClientWithTransport.

func NewClientWithToken

func NewClientWithToken(ctx context.Context, token string) (*Client, error)

NewClientWithToken creates a new GitHub API client with an explicit token.

func NewClientWithTransport

func NewClientWithTransport(ctx context.Context, rt http.RoundTripper) (*Client, error)

NewClientWithTransport creates a client whose requests are served by rt, bypassing gh CLI auth resolution. Intended for tests using httptest or in-memory round-trip fakes; no network is reached.

func (*Client) AddCollaborator

func (c *Client) AddCollaborator(owner, repo, username, permission string) error

AddCollaborator adds a collaborator to a repository.

func (*Client) CompareBranches

func (c *Client) CompareBranches(owner, repo, base, head string) (int, int, error)

CompareBranches compares two branches and returns ahead/behind counts.

func (*Client) Context

func (c *Client) Context() context.Context

Context returns the client's context.

func (*Client) CreatePullRequest

func (c *Client) CreatePullRequest(owner, repo, title, body, head, base string) (int, error)

CreatePullRequest creates a new pull request.

func (*Client) CreateRuleset added in v0.10.0

func (c *Client) CreateRuleset(owner, repo string, desired Ruleset) error

CreateRuleset creates a new ruleset on the repo.

func (*Client) Delete

func (c *Client) Delete(path string, response any) error

Delete performs a DELETE request to the GitHub API.

func (*Client) DeleteBranch

func (c *Client) DeleteBranch(owner, repo, branch string) error

DeleteBranch deletes a branch.

func (*Client) DeleteRepoSubscription

func (c *Client) DeleteRepoSubscription(owner, repo string) error

DeleteRepoSubscription removes the authenticated user's subscription to a repository, resetting it to the default (un-set) state.

func (*Client) FetchFailedJobLogs

func (c *Client) FetchFailedJobLogs(owner, repo string, runID int) ([]JobLog, error)

FetchFailedJobLogs downloads logs for each failed job of a workflow run. Jobs whose logs cannot be fetched are skipped.

func (*Client) FetchRunDetails

func (c *Client) FetchRunDetails(owner, repo string, runID int) (*RunTiming, error)

FetchRunDetails fetches job and step timing for a single workflow run.

func (*Client) FetchWorkflowRuns

func (c *Client) FetchWorkflowRuns(
	owner, repo string,
	opts FetchWorkflowRunsOptions,
) ([]RunTiming, error)

FetchWorkflowRuns fetches completed workflow runs matching opts.

func (*Client) FetchWorkflowRunsWithDetails

func (c *Client) FetchWorkflowRunsWithDetails(
	owner, repo string,
	opts FetchWorkflowRunsOptions,
) ([]RunTiming, error)

FetchWorkflowRunsWithDetails fetches workflow runs and enriches each with job timing details.

func (*Client) FindRulesetByName added in v0.10.0

func (c *Client) FindRulesetByName(owner, repo, name string) (*Ruleset, error)

FindRulesetByName returns the named ruleset with its rules, or ErrRulesetNotFound. Names are unique per repo in GitHub's UI but not enforced by the API, so the first match wins.

func (*Client) Get

func (c *Client) Get(path string, response any) error

Get performs a GET request to the GitHub API.

func (*Client) GetAuthenticatedUser

func (c *Client) GetAuthenticatedUser() (string, error)

GetAuthenticatedUser returns the login of the user the client is authenticated as.

func (*Client) GetBranchProtection

func (c *Client) GetBranchProtection(owner, repo, branch string) (*ProtectionRule, error)

GetBranchProtection retrieves branch protection rules.

func (*Client) GetBranchesWithComparison

func (c *Client) GetBranchesWithComparison(
	owner, repo, baseBranch string,
) ([]BranchWithComparison, error)

GetBranchesWithComparison fetches branches and compares them to a base branch.

func (*Client) GetCNAMEFile added in v0.7.0

func (c *Client) GetCNAMEFile(owner, repo string) (string, error)

GetCNAMEFile reads a repo's root CNAME file, returning "" when the repo has none. A CNAME file can outlive Pages being disabled, which is the subdomain-takeover signal: DNS still points at GitHub while nothing serves the domain from this repo anymore.

func (*Client) GetDefaultBranch

func (c *Client) GetDefaultBranch(owner, repo string) (string, error)

GetDefaultBranch fetches the default branch for a repository.

func (*Client) GetDefaultBranchProtection

func (c *Client) GetDefaultBranchProtection(owner, repo string) (*ProtectionRule, error)

GetDefaultBranchProtection retrieves protection rules for the repo's default branch.

func (*Client) GetImmutableReleases added in v0.6.0

func (c *Client) GetImmutableReleases(owner, repo string) (*ImmutableReleases, error)

GetImmutableReleases retrieves whether release immutability is enabled for a repo.

func (*Client) GetLatestRelease

func (c *Client) GetLatestRelease(owner, repo string) (*Release, error)

GetLatestRelease returns the most recent release.

func (*Client) GetPagesInfo added in v0.7.0

func (c *Client) GetPagesInfo(owner, repo string) (*PagesInfo, error)

GetPagesInfo fetches a repo's GitHub Pages configuration. It returns ErrPagesNotFound when Pages isn't enabled for the repo (a 404 from the API).

func (*Client) GetPullRequestsForBranch

func (c *Client) GetPullRequestsForBranch(owner, repo, branch string) ([]PullRequest, error)

GetPullRequestsForBranch lists all pull requests (any state) whose head is owner/branch.

func (*Client) GetRepoSettings

func (c *Client) GetRepoSettings(owner, repo string) (*RepoSettings, error)

GetRepoSettings retrieves repository settings.

func (*Client) GetRuleset added in v0.10.0

func (c *Client) GetRuleset(owner, repo string, id int) (*Ruleset, error)

GetRuleset returns one ruleset with its rules populated.

func (*Client) ListBranchStatuses

func (c *Client) ListBranchStatuses(owner, repo, baseBranch string) ([]BranchStatus, error)

ListBranchStatuses lists branches enriched with default-branch, comparison, and PR data. An empty baseBranch compares against the repository default branch.

func (*Client) ListBranches

func (c *Client) ListBranches(owner, repo string) ([]Branch, error)

ListBranches lists all branches for a repository.

func (*Client) ListBranchesWithDates added in v0.10.0

func (c *Client) ListBranchesWithDates(owner, repo string) ([]Branch, error)

ListBranchesWithDates lists branches with LastCommitDate populated. The branches endpoint omits commit dates, so this costs one extra request per branch; callers that classify branches by age need it, and a caller that only needs names should use ListBranches.

func (*Client) ListCollaborators

func (c *Client) ListCollaborators(owner, repo string) ([]Collaborator, error)

ListCollaborators lists all collaborators for a repository.

func (*Client) ListNamespaceRepositories

func (c *Client) ListNamespaceRepositories(namespace string) ([]Repository, bool, error)

ListNamespaceRepositories lists repositories for a namespace that may be either an organization or a user, reporting which kind it resolved to.

func (*Client) ListOrgRepositories

func (c *Client) ListOrgRepositories(org string) ([]Repository, error)

ListOrgRepositories lists all repositories belonging to an organization.

func (*Client) ListOrgSecrets

func (c *Client) ListOrgSecrets(org string) ([]Secret, error)

ListOrgSecrets lists organization-level secrets.

func (*Client) ListPullRequests

func (c *Client) ListPullRequests(owner, repo, state string) ([]PullRequest, error)

ListPullRequests lists pull requests in a repository matching state ("open", "closed", or "all").

func (*Client) ListReleases

func (c *Client) ListReleases(owner, repo string) ([]Release, error)

ListReleases lists all releases for a repository.

func (*Client) ListRepoSecrets

func (c *Client) ListRepoSecrets(owner, repo string) ([]Secret, error)

ListRepoSecrets lists repository-level secrets.

func (*Client) ListRulesets added in v0.10.0

func (c *Client) ListRulesets(owner, repo string) ([]Ruleset, error)

ListRulesets returns the repo's rulesets. GitHub omits each ruleset's rules from this summary, so a caller needing rules must fetch by ID.

func (*Client) ListUserRepositories

func (c *Client) ListUserRepositories(username string) ([]Repository, error)

ListUserRepositories lists all repositories belonging to a user.

func (*Client) ListWebhookDeliveries

func (c *Client) ListWebhookDeliveries(owner, repo string, hookID int) ([]WebhookDelivery, error)

ListWebhookDeliveries lists recent deliveries for a webhook.

func (*Client) ListWebhooks

func (c *Client) ListWebhooks(owner, repo string) ([]Webhook, error)

ListWebhooks lists all webhooks for a repository.

func (*Client) ListWorkflows

func (c *Client) ListWorkflows(owner, repo string) ([]WorkflowFile, error)

ListWorkflows lists the workflow files defined in a repository.

func (*Client) Patch

func (c *Client) Patch(path string, body, response any) error

Patch performs a PATCH request to the GitHub API.

func (*Client) Post

func (c *Client) Post(path string, body, response any) error

Post performs a POST request to the GitHub API.

func (*Client) Put

func (c *Client) Put(path string, body, response any) error

Put performs a PUT request to the GitHub API.

func (*Client) RemoveCollaborator

func (c *Client) RemoveCollaborator(owner, repo, username string) error

RemoveCollaborator removes a collaborator from a repository.

func (*Client) ScanRepoSecretRefs added in v0.7.0

func (c *Client) ScanRepoSecretRefs(owner, repo string) (map[string][]string, error)

ScanRepoSecretRefs fetches a repo's workflow files and returns which secret names each one references, keyed by secret name. Workflows that fail to fetch are skipped rather than failing the whole scan, since a partial reference map only risks a false "unused" positive, not a wrong action.

func (*Client) SetImmutableReleases added in v0.6.0

func (c *Client) SetImmutableReleases(owner, repo string, enabled bool) error

SetImmutableReleases enables or disables release immutability for a repo.

func (*Client) SetRepoSubscription

func (c *Client) SetRepoSubscription(
	owner, repo string,
	subscribed, ignored bool,
) (*Subscription, error)

SetRepoSubscription sets the authenticated user's watch/ignore subscription for a repository.

func (*Client) UpdateBranchProtection added in v0.6.0

func (c *Client) UpdateBranchProtection(owner, repo, branch string, desired ProtectionRule) error

UpdateBranchProtection replaces branch protection rules via PUT, which GitHub requires as a full replacement rather than a partial patch. Fields left at their zero value (e.g. no status checks) are sent as such, not omitted.

func (*Client) UpdateRepoSettings added in v0.6.0

func (c *Client) UpdateRepoSettings(owner, repo string, patch RepoSettingsPatch) error

UpdateRepoSettings applies a partial settings patch via PATCH /repos/{owner}/{repo}.

func (*Client) UpdateRuleset added in v0.10.0

func (c *Client) UpdateRuleset(owner, repo string, id int, desired Ruleset) error

UpdateRuleset replaces an existing ruleset. Like branch protection, GitHub treats this as a full replacement, so desired must carry every rule to keep.

func (*Client) UpdateSecurityAndAnalysis added in v0.6.0

func (c *Client) UpdateSecurityAndAnalysis(owner, repo, feature, status string) error

UpdateSecurityAndAnalysis toggles a single security_and_analysis feature. GitHub requires the full nested object per request, so callers pass the one feature they want changed; the rest are omitted and left untouched server-side.

type Collaborator

type Collaborator struct {
	Login      string
	Permission string
	Repository string
}

Collaborator represents a repository collaborator.

type CollaboratorGrant

type CollaboratorGrant struct {
	User       string
	Repository string
	Permission string
	GrantedBy  string
	GrantedAt  time.Time
	ExpiresAt  time.Time
	RevokedAt  *time.Time
}

CollaboratorGrant represents a time-boxed access grant.

type DuplicateSecret

type DuplicateSecret struct {
	Name   string
	Count  int
	Scopes []string // List of scopes where it appears
	Repos  []string // List of repositories (for repo-scoped secrets)
}

DuplicateSecret represents a secret name that appears multiple times.

func FindDuplicateSecrets

func FindDuplicateSecrets(secrets []Secret) []DuplicateSecret

FindDuplicateSecrets identifies secret names that appear in multiple scopes/repos Pure function: analyzes secret list for duplicates.

type ErrorContext

type ErrorContext struct {
	Repository   string    `json:"repository"`
	WorkflowName string    `json:"workflow_name"`
	JobName      string    `json:"job_name"`
	StepName     string    `json:"step_name,omitempty"`
	Conclusion   string    `json:"conclusion"`
	Timestamp    time.Time `json:"timestamp"`
	ErrorLines   []string  `json:"error_lines"`
	Context      []string  `json:"context_lines,omitempty"`
	ErrorType    string    `json:"error_type,omitempty"`
	Summary      string    `json:"summary"`
}

ErrorContext represents extracted error information.

func BatchExtractErrors

func BatchExtractErrors(
	logs []JobLog,
	workflow string,
	config LogExtractionConfig,
) []*ErrorContext

BatchExtractErrors extracts errors from multiple logs Pure function: maps over logs.

func ExtractErrorContext

func ExtractErrorContext(log JobLog, workflow string, config LogExtractionConfig) *ErrorContext

ExtractErrorContext extracts actionable error information from job logs Pure function: deterministic, no side effects.

type FetchWorkflowRunsOptions

type FetchWorkflowRunsOptions struct {
	WorkflowFile string
	Branch       string
	Status       string
	Limit        int
	CreatedAfter time.Time
}

FetchWorkflowRunsOptions configures FetchWorkflowRuns.

type FlakyDetectionConfig

type FlakyDetectionConfig struct {
	MinFlips       int     // Minimum flips to be considered flaky
	MinFailureRate float64 // Minimum failure rate (0.0-1.0)
	TimeWindow     time.Duration
	SameCommitOnly bool // Only detect same-commit flips
	IncludeSkipped bool // Include skipped tests in analysis
}

FlakyDetectionConfig configures flaky test detection.

func DefaultFlakyConfig

func DefaultFlakyConfig() FlakyDetectionConfig

DefaultFlakyConfig returns sensible defaults.

type FlakyTest

type FlakyTest struct {
	Name         string
	FailureRate  float64
	FirstFailure time.Time
	LastFlip     time.Time
	FlipCount    int
	TotalRuns    int
	FailureCount int
	Pattern      string // one of the FlakyPattern* constants
}

FlakyTest represents a test that exhibits flaky behavior.

func DetectFlakyTests

func DetectFlakyTests(runs []TestRun, config FlakyDetectionConfig) []FlakyTest

DetectFlakyTests identifies flaky tests from test runs Pure function: no side effects, deterministic output.

type GQLClient

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

GQLClient wraps the GitHub GraphQL API for review thread queries.

func NewGQLClient

func NewGQLClient(opts ...Option) (*GQLClient, error)

NewGQLClient creates a GraphQL client using gh CLI auth or GITHUB_TOKEN.

func (*GQLClient) ListOpenPRReviewThreads

func (g *GQLClient) ListOpenPRReviewThreads(
	client *Client,
	owner, repo string,
	maxPRs int,
) ([]ReviewThread, error)

ListOpenPRReviewThreads fetches review threads across the newest open PRs, capped at maxPRs.

func (*GQLClient) ListPRReviewThreads

func (g *GQLClient) ListPRReviewThreads(owner, repo string, prNumber int) ([]ReviewThread, error)

ListPRReviewThreads fetches all review threads for a single pull request.

func (*GQLClient) ListRepoReviewThreads

func (g *GQLClient) ListRepoReviewThreads(
	client *Client,
	owner, repo string,
	prNumber, maxPRs int,
) ([]ReviewThread, error)

ListRepoReviewThreads fetches threads for one PR when prNumber > 0, otherwise across open PRs.

func (*GQLClient) ListViewerRepoWatchInfo

func (g *GQLClient) ListViewerRepoWatchInfo(includeOrgs bool) (string, []RepoWatchInfo, error)

ListViewerRepoWatchInfo fetches watch state and enrichment metadata for every repository owned by the authenticated user, paginated via GraphQL. Unlike the REST subscription endpoint, the query is atomic per page: a page either returns full data for every repo in it or fails outright, so there's no partial-failure state to silently misreport as "not watching".

Passing includeOrgs widens the query to repositories the viewer can reach as an organization member. It stays off by default because a member of a large org would otherwise page through thousands of repos to audit their own.

type ImmutableReleases added in v0.6.0

type ImmutableReleases struct {
	Repository      string
	Enabled         bool
	EnforcedByOwner bool
}

ImmutableReleases represents a repository's release-immutability status.

type JobLog

type JobLog struct {
	JobID      int
	JobName    string
	WorkflowID int
	Repository string
	Conclusion string
	Lines      []string
	Timestamp  time.Time
}

JobLog represents a GitHub Actions job log.

type JobStats

type JobStats struct {
	WorkflowJob string
	TotalRuns   int
	AvgDuration time.Duration
	MinDuration time.Duration
	MaxDuration time.Duration
}

JobStats aggregates timing for one workflow job across runs.

func GetTopJobsByDuration

func GetTopJobsByDuration(stats map[string]*JobStats, limit int) []*JobStats

GetTopJobsByDuration returns the jobs with the highest average duration, capped at limit (0 means unlimited).

type JobTiming

type JobTiming struct {
	Name            string        `json:"name"`
	DurationSeconds float64       `json:"duration_seconds"`
	Status          string        `json:"status"`
	Conclusion      string        `json:"conclusion"`
	StartedAt       time.Time     `json:"started_at"`
	CompletedAt     time.Time     `json:"completed_at"`
	Duration        time.Duration `json:"-"`
	Steps           []StepTiming  `json:"steps"`
}

JobTiming records the timing and outcome of a single workflow job.

type LogExtractionConfig

type LogExtractionConfig struct {
	TailLines         int      // Number of lines from end of log
	ContextLines      int      // Additional context lines around errors
	FilterNoise       bool     // Remove timestamps, ANSI codes
	ExtractStackTrace bool     // Include full stack traces
	IncludeSuccess    bool     // Include successful runs
	ErrorPatterns     []string // Custom regex patterns for errors
}

LogExtractionConfig configures log extraction behavior.

func DefaultLogConfig

func DefaultLogConfig() LogExtractionConfig

DefaultLogConfig returns sensible defaults for log extraction.

type Option added in v0.10.0

type Option func(*api.ClientOptions)

Option configures a Client at construction.

func WithCache added in v0.10.0

func WithCache(dir string, ttl time.Duration) Option

WithCache serves repeat GET and GraphQL responses from dir for ttl. Cached responses cost no rate-limit quota, which is what keeps a cross-repo sweep inside the hourly budget. A zero ttl leaves the cache off.

type PRRef

type PRRef struct {
	Ref  string
	SHA  string
	Repo string
}

PRRef identifies one side (head or base) of a pull request.

type PagesInfo added in v0.7.0

type PagesInfo struct {
	Repository     string
	CNAME          string
	HTMLURL        string
	HTTPSEnforced  bool
	Status         string
	DomainVerified bool
}

PagesInfo is a repository's GitHub Pages configuration.

type ProtectionRule

type ProtectionRule struct {
	Repository              string
	Branch                  string
	RequiredReviews         int
	RequireCodeOwnerReviews bool
	RequireStatusChecks     []string
	EnforceAdmins           bool
	RequireLinearHistory    bool
	AllowForcePushes        bool
	AllowDeletions          bool
}

ProtectionRule represents branch protection settings.

type PullRequest

type PullRequest struct {
	Number   int
	Title    string
	State    string
	Head     PRRef
	Base     PRRef
	MergedAt *time.Time
	ClosedAt *time.Time
}

PullRequest describes a GitHub pull request.

func MatchBranchPR

func MatchBranchPR(prs []PullRequest, repoFullName, branch string) *PullRequest

MatchBranchPR returns the open PR whose head is the branch, or the most recent closed one.

type PullRequestRule added in v0.10.0

type PullRequestRule struct {
	RequiredApprovals              int
	RequireCodeOwnerReview         bool
	RequireLastPushApproval        bool
	DismissStaleReviewsOnPush      bool
	RequiredReviewThreadResolution bool
	AllowedMergeMethods            []string
}

PullRequestRule is a ruleset's pull_request rule. Its presence is what requires a PR at all; RequiredApprovals of 0 requires the PR without requiring an approval, which classic branch protection cannot express.

type RateLimitError added in v0.10.0

type RateLimitError struct {
	RetryAt  time.Time
	Resource string
	Limit    int
}

RateLimitError reports an exhausted GitHub rate limit. Retrying before RetryAt burns nothing but still fails, so callers should surface the time rather than offering an immediate retry.

func (*RateLimitError) Error added in v0.10.0

func (e *RateLimitError) Error() string

type Release

type Release struct {
	ID          int
	Repository  string
	TagName     string
	Name        string
	Body        string
	Author      string
	CreatedAt   time.Time
	PublishedAt time.Time
	Draft       bool
	Prerelease  bool
}

Release represents a GitHub release.

type ReleaseComparison

type ReleaseComparison struct {
	Repositories   []string
	LatestReleases map[string]*Release
	OutdatedRepos  []string // Repos with no release in 90+ days
	NonSemVerRepos []string // Repos not following semver
}

ReleaseComparison compares releases across repositories.

func CompareReleases

func CompareReleases(releases map[string]*Release) ReleaseComparison

CompareReleases compares releases across multiple repositories.

type RepoBasic

type RepoBasic struct {
	Name     string
	FullName string
	Owner    string
	Private  bool
}

RepoBasic holds the minimal repository identity fields used by the watch/subscription APIs.

type RepoSettings

type RepoSettings struct {
	Repository          string
	DefaultBranch       string
	AllowMergeCommit    bool
	AllowSquashMerge    bool
	AllowRebaseMerge    bool
	AllowAutoMerge      bool
	AllowUpdateBranch   bool
	DeleteBranchOnMerge bool
	UseSquashPRTitle    bool
	SquashMergeMessage  string
	SquashMergeTitle    string
	MergeCommitMessage  string
	MergeCommitTitle    string
	HasIssues           bool
	HasProjects         bool
	HasWiki             bool
	HasDiscussions      bool
	IsTemplate          bool
	AllowForking        bool
	WebCommitSignoff    bool
	SecurityAndAnalysis SecurityAndAnalysis
}

RepoSettings represents repository settings.

type RepoSettingsPatch added in v0.6.0

type RepoSettingsPatch struct {
	AllowMergeCommit    *bool
	AllowSquashMerge    *bool
	AllowRebaseMerge    *bool
	AllowAutoMerge      *bool
	AllowUpdateBranch   *bool
	DeleteBranchOnMerge *bool
	UseSquashPRTitle    *bool
	HasIssues           *bool
	HasProjects         *bool
	HasWiki             *bool
	HasDiscussions      *bool
	AllowForking        *bool
	WebCommitSignoff    *bool
}

RepoSettingsPatch carries only the fields to change; nil pointers are left alone. Mirrors the subset of GitHub's PATCH /repos/{owner}/{repo} body gh-sweep can set.

type RepoWatchInfo

type RepoWatchInfo struct {
	RepoBasic
	IsArchived         bool
	IsFork             bool
	State              WatchState
	ViewerCanSubscribe bool
	StargazerCount     int
	WatcherCount       int
	PushedAt           time.Time
	UpdatedAt          time.Time
}

RepoWatchInfo is a repo's watch state plus metadata GitHub's REST subscription endpoint doesn't expose (activity, popularity, archival), fetched in a single paginated GraphQL query rather than one REST call per repo.

GitHub's "Custom" per-notification-type watch setting has no representation in either the REST or GraphQL API: a repo set to Custom on github.com reports the same viewerSubscription as one left at the default (see https://github.com/orgs/community/discussions/65099). State should be read as "the best this API can tell us," not as ground truth for Custom repos.

type Repository

type Repository struct {
	Name          string `json:"name"`
	FullName      string `json:"full_name"`
	Owner         string `json:"owner"`
	Private       bool   `json:"private"`
	Archived      bool   `json:"archived"`
	DefaultBranch string `json:"default_branch"`
}

Repository describes a GitHub repository.

type ReviewComment

type ReviewComment struct {
	Author    string
	Body      string
	CreatedAt time.Time
	URL       string
}

ReviewComment is a single comment within a PR review thread.

type ReviewThread

type ReviewThread struct {
	Repository string
	PRNumber   int
	PRTitle    string
	Path       string
	IsResolved bool
	IsOutdated bool
	Comments   []ReviewComment
}

ReviewThread is a review conversation on a pull request.

func FilterUnresolvedThreads

func FilterUnresolvedThreads(threads []ReviewThread) []ReviewThread

FilterUnresolvedThreads keeps only threads that are not resolved.

func (ReviewThread) FirstComment

func (t ReviewThread) FirstComment() (ReviewComment, bool)

FirstComment returns the thread's opening comment, if any.

func (ReviewThread) LastActivity

func (t ReviewThread) LastActivity() time.Time

LastActivity returns the creation time of the most recent comment.

type Ruleset added in v0.10.0

type Ruleset struct {
	ID                   int
	Name                 string
	Target               string
	Enforcement          string
	IncludeRefs          []string
	ExcludeRefs          []string
	BlockDeletion        bool
	BlockForcePush       bool
	RequireLinearHistory bool
	RequiredStatusChecks []string
	PullRequest          *PullRequestRule
	BypassActors         []json.RawMessage
	Unmanaged            []json.RawMessage
}

Ruleset is a repository ruleset flattened from GitHub's {type, parameters} rule array into the subset gh-sweep manages. Rules the policy does not model survive a round trip through Unmanaged, so updating a ruleset never silently drops a rule gh-sweep cannot express.

type RunTiming

type RunTiming struct {
	RunID           int           `json:"run_id"`
	Workflow        string        `json:"workflow"`
	WorkflowID      int           `json:"workflow_id"`
	Branch          string        `json:"branch"`
	HeadSHA         string        `json:"head_sha"`
	Conclusion      string        `json:"conclusion"`
	CreatedAt       time.Time     `json:"created_at"`
	UpdatedAt       time.Time     `json:"updated_at"`
	DurationSeconds float64       `json:"duration_seconds"`
	Duration        time.Duration `json:"-"`
	Jobs            []JobTiming   `json:"jobs"`
}

RunTiming records the timing and outcome of a single workflow run.

func FilterRunsByBranch

func FilterRunsByBranch(runs []RunTiming, branch string) []RunTiming

FilterRunsByBranch returns the runs matching branch, or all runs when branch is empty.

func FilterRunsByTimeRange

func FilterRunsByTimeRange(runs []RunTiming, since, until time.Time) []RunTiming

FilterRunsByTimeRange returns the runs created within [since, until], treating a zero bound as unbounded.

func FilterRunsByWorkflows

func FilterRunsByWorkflows(runs []RunTiming, workflows []string) []RunTiming

FilterRunsByWorkflows returns the runs whose workflow is in workflows, or all runs when workflows is empty.

type Secret

type Secret struct {
	Name       string
	Scope      string // SecretScopeOrg or SecretScopeRepo
	Repository string // Empty for org secrets
	CreatedAt  string
	UpdatedAt  string
}

Secret represents a GitHub Actions secret.

type SecretUsage

type SecretUsage struct {
	Name         string
	Scope        string
	Repository   string
	ReferencedIn []string // Workflow files that reference this secret
	Unused       bool
}

SecretUsage tracks secret usage in workflows.

func DetectUnusedSecrets

func DetectUnusedSecrets(secrets []Secret, workflowRefs map[string][]string) []SecretUsage

DetectUnusedSecrets compares secrets against workflow references.

type SecurityAndAnalysis added in v0.6.0

type SecurityAndAnalysis struct {
	SecretScanning               string
	SecretScanningPushProtection string
	DependabotSecurityUpdates    string
	SecretScanningNonProvider    string
	SecretScanningValidityChecks string
}

SecurityAndAnalysis represents the repo's security_and_analysis feature toggles. Each field is "enabled" or "disabled"; an absent feature (e.g. secret scanning on a private repo without GHAS) surfaces as an empty string, not a diff target.

type SettingsDiff

type SettingsDiff struct {
	Field    string
	Baseline any
	Current  any
	Severity string // critical, warning, info
}

SettingsDiff represents differences between repository settings.

func CompareSettings

func CompareSettings(baseline, current *RepoSettings) []SettingsDiff

CompareSettings compares repository settings against a baseline.

type StepTiming

type StepTiming struct {
	Name            string        `json:"name"`
	DurationSeconds float64       `json:"duration_seconds"`
	Status          string        `json:"status"`
	Conclusion      string        `json:"conclusion"`
	StartedAt       time.Time     `json:"started_at"`
	CompletedAt     time.Time     `json:"completed_at"`
	Duration        time.Duration `json:"-"`
}

StepTiming records the timing and outcome of a single job step.

type Subscription

type Subscription struct {
	Repository string
	Subscribed bool
	Ignored    bool
	Reason     string
	CreatedAt  time.Time
	State      WatchState
}

Subscription describes the authenticated user's notification subscription to a repository.

type TestRun

type TestRun struct {
	Name   string
	Status string // one of the Conclusion* constants

	CommitSHA  string
	Timestamp  time.Time
	Duration   time.Duration
	Repository string
	WorkflowID int
}

TestRun represents a single test execution.

func ApplyFilters

func ApplyFilters(runs []TestRun, filters ...func(TestRun) bool) []TestRun

ApplyFilters applies a list of filters to test runs Functional composition helper.

func RunsToTestRuns added in v0.7.0

func RunsToTestRuns(repo string, runs []RunTiming) []TestRun

RunsToTestRuns adapts workflow runs for flaky detection, treating each workflow as a test keyed by its name. Runs without a terminal success/failure/skipped conclusion are dropped.

type ThreadFilter

type ThreadFilter struct {
	Author string
	Since  *time.Time
	Search string
}

ThreadFilter narrows review threads by author, activity date, and text.

func (ThreadFilter) Apply

func (f ThreadFilter) Apply(threads []ReviewThread) []ReviewThread

Apply returns the threads matching every set filter field.

type WatchState

type WatchState string

WatchState is a repository's notification subscription state for the authenticated user.

const (
	WatchStateSubscribed WatchState = "subscribed"
	WatchStateIgnored    WatchState = "ignored"
	// WatchStateDefault is GitHub's un-set subscription state ("Participating
	// and @mentions"), not an absence of any relationship to the repo.
	WatchStateDefault WatchState = ""
)

Subscription states as reported by the GitHub API.

type Webhook

type Webhook struct {
	ID         int
	Repository string
	URL        string
	Events     []string
	Active     bool
}

Webhook represents a repository webhook.

type WebhookDelivery

type WebhookDelivery struct {
	ID        int
	Event     string
	Status    int
	Duration  int // milliseconds
	Timestamp string
}

WebhookDelivery represents a webhook delivery.

type WebhookHealth

type WebhookHealth struct {
	WebhookID       int
	SuccessRate     float64
	TotalDeliveries int
	Failures        int
	AvgDuration     int
}

WebhookHealth represents webhook health metrics.

func AnalyzeWebhookHealth

func AnalyzeWebhookHealth(deliveries []WebhookDelivery) WebhookHealth

AnalyzeWebhookHealth analyzes webhook delivery health.

type WorkflowFile

type WorkflowFile struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Path  string `json:"path"`
	State string `json:"state"`
}

WorkflowFile identifies a workflow definition file in a repository.

type WorkflowStats

type WorkflowStats struct {
	Workflow     string
	TotalRuns    int
	AvgDuration  time.Duration
	MinDuration  time.Duration
	MaxDuration  time.Duration
	SuccessRate  float64
	FailureCount int
}

WorkflowStats aggregates run timing and outcomes for one workflow.

func AnalyzeRuns added in v0.7.0

func AnalyzeRuns(runs []RunTiming) WorkflowStats

AnalyzeRuns aggregates timing and success rate across all of the given runs, regardless of which workflow each belongs to.

Jump to

Keyboard shortcuts

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