models

package
v0.0.0-...-ddec407 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package models holds the pivot data types used to convey data between the different internal package.

Index

Constants

View Source
const (
	StalenessActive  = "active"  // commits in the last 30 days
	StalenessRecent  = "recent"  // commits in the last 90 days
	StalenessStale   = "stale"   // commits in the last 360 days
	StalenessDormant = "dormant" // no commits in the last 360 days
)

Staleness classification constants.

View Source
const (
	RunnerKindGit = iota
	RunnerKindGitHub
)
View Source
const (
	SCMGitHub = "github"
	SCMGitLab = "gitlab"
	SCMOther  = "other"
	SCMNone   = "no-scm"
)

SCM provider constants.

View Source
const (
	RemoteOrigin   = "origin"
	RemoteUpstream = "upstream"
)

Well-known remote names.

Variables

This section is empty.

Functions

func CompareSemver

func CompareSemver(a, b Tag) int

CompareSemver returns:

-1 if a < b
 0 if a == b
+1 if a > b

Prerelease tags sort before the corresponding release (1.2.3-beta < 1.2.3).

func CountTagsInWindow

func CountTagsInWindow(tags []Tag, nDays int) int

CountTagsInWindow counts how many tags from the given list fall within the last nDays.

func DefaultPushRemote

func DefaultPushRemote(remotes []Remote) string

DefaultPushRemote returns the remote to push to for the given repo. For forks (upstream exists): push to upstream. For clones (origin only): push to origin.

func DeriveTagSummary

func DeriveTagSummary(tags []Tag) (lastTagDate time.Time, lastSemverTag string, lastSemverDate time.Time)

DeriveTagSummary computes LastTagDate, LastSemverTag, and LastSemverDate from a tag list.

func FormatBytes

func FormatBytes(b int64) string

FormatBytes returns a human-readable byte size.

func HasDistinctRemote

func HasDistinctRemote(remotes []Remote, normalizeURL func(string) string) (string, bool)

HasDistinctRemote reports whether the repo has a remote with a URL different from origin's URL (i.e. a potential upstream/fork source).

func OriginFetchURL

func OriginFetchURL(remotes []Remote) string

OriginFetchURL returns the fetch URL for the "origin" remote, or empty string.

func SortBranches

func SortBranches(branches []Branch, defaultBranch string)

SortBranches sorts branches for display:

Local branches first:

  • Default branch always first
  • Current branch second (if not default)
  • Other local branches by descending last commit date

Remote-only branches after locals:

  • Ordered by remote name (origin first, upstream second, others alphabetically)
  • Within same remote, by descending last commit date

func StripURLCredentials

func StripURLCredentials(rawURL string) string

StripURLCredentials returns the URL with credentials removed from userinfo. The username is preserved (it's often needed for authentication), but the password/token is removed.

func URLHasCredentials

func URLHasCredentials(rawURL string) bool

URLHasCredentials reports whether a remote URL contains embedded credentials (password or token in the userinfo). SSH URLs with just a username (e.g. "git@github.com") are NOT flagged.

Flagged: https://user:token@github.com/... Not flagged: ssh://git@github.com/..., git@github.com:...

func UpstreamFetchURL

func UpstreamFetchURL(remotes []Remote) string

UpstreamFetchURL returns the fetch URL for the "upstream" remote, or empty string.

Types

type ActionKind

type ActionKind uint8

ActionKind identifies the provider of an action.

const (
	ActionKindGit    ActionKind = iota // git CLI action
	ActionKindGitHub                   // GitHub API action
	ActionKindCustom                   // external/custom action (Phase 3)
)

type ActionResult

type ActionResult struct {
	// OK is true if the action completed successfully.
	OK bool

	// Message describes what happened (success or failure).
	Message string

	// CommandLog records the commands executed during this action.
	CommandLog []string
}

ActionResult holds the outcome of a git backend action.

func (ActionResult) ToResult

func (r ActionResult) ToResult() Result

ToResult converts an ActionResult to a Result.

type ActionSubject

type ActionSubject struct {
	Subject string

	// Params is a parallel slice to Subjects (same length, index-aligned).
	// Each entry carries action-specific parameters for the corresponding subject.
	// nil or shorter than Subjects means no params for those subjects.
	Params []string
}

type ActionSuggestion

type ActionSuggestion struct {
	// ActionName is the registered name of the action to execute.
	ActionName string

	// SubjectKind identifies what kind of thing the subjects are.
	SubjectKind SubjectKind

	// Subjects lists the specific instances to act on
	// (e.g., branch names, tag names).
	Subjects []ActionSubject
}

ActionSuggestion links an alert to an executable action. The ActionName is a key in the ActionRegistry.

func (ActionSuggestion) SubjectNames

func (s ActionSuggestion) SubjectNames() []string

func (ActionSuggestion) SubjectParams

func (s ActionSuggestion) SubjectParams() iter.Seq2[string, []string]

SubjectParams returns the params for the subject at index i, or nil if no params are set.

type Activity

type Activity struct {
	// Commit counts over rolling windows.
	Commits7d   int
	Commits30d  int
	Commits90d  int
	Commits360d int

	// TagsLast360d is the number of tags on the default branch created in the last 360 days.
	TagsLast360d int

	// Staleness is derived from commit counts:
	//   "active"  - Commits30d > 0
	//   "recent"  - Commits90d > 0
	//   "stale"   - Commits360d > 0
	//   "dormant" - otherwise
	Staleness string

	// Authors is populated on-demand via LoadAuthors.
	Authors []AuthorActivity
}

Activity holds commit activity metrics for a repository.

All windows are rolling: 7d, 30d, 90d, 360d from now. Counts are on HEAD only (merged activity).

type Alert

type Alert struct {
	// CheckName is the name of the check that produced this alert.
	CheckName string

	// Severity indicates urgency. SeverityNone means no alert.
	Severity Severity

	// Summary is a one-line human-readable description.
	Summary string

	// Detail is a longer explanation (useful for custom/AI checks,
	// and for documentation during development/testing).
	Detail string

	// Suggestions lists zero or more suggested fix actions.
	Suggestions []ActionSuggestion
}

Alert is the outcome of a check. One alert per SubjectKind per check invocation: if a check finds 5 lagging branches, that is one alert with 5 subject instances spread across the suggestions.

The zero value (Severity == SeverityNone) means "check ran, nothing wrong.".

type Assignment

type Assignment struct {
	// Suggestion is the action to execute.
	Suggestion ActionSuggestion

	// RepoPath is the repository this assignment targets.
	RepoPath string
}

Assignment wraps an action suggestion for execution.

In Phase 1 this is a thin wrapper for synchronous execution. Phase 2 will add scheduling state (pending/running/done/failed), priority, and timestamps.

type AuthorActivity

type AuthorActivity struct {
	Name    string
	Email   string
	Commits int
}

AuthorActivity holds per-author commit counts.

type BlobEntry

type BlobEntry struct {
	Hash string
	Size int64
	Path string // may be empty for orphaned blobs
}

BlobEntry represents a blob object with its size and associated path.

type Branch

type Branch struct {
	// Name is the short branch name (e.g. "main", "feature/foo").
	Name string

	// IsRemote is true for remote-tracking branches (e.g. "origin/main").
	IsRemote bool

	// IsCurrent is true if this is the currently checked-out branch.
	IsCurrent bool

	// Upstream is the upstream tracking ref (e.g. "origin/main"), if configured.
	Upstream string

	// Ahead is the number of commits ahead of the upstream branch.
	Ahead int

	// Behind is the number of commits behind the upstream branch.
	Behind int

	// Gone is true when the upstream branch has been deleted from the remote.
	Gone bool

	// Merged is true when the branch tip is reachable from the default branch.
	Merged bool

	// MergeCheck reports whether the branch can be cleanly merged into the default branch.
	// nil means not yet checked.
	MergeCheck *MergeCheck

	// RebaseCheck reports whether the branch can be rebased onto the default branch.
	// nil means not yet checked.
	RebaseCheck *RebaseCheck

	// LastCommit is the author date of the most recent commit on this branch.
	LastCommit time.Time

	// Hash is the commit hash at the tip of the branch.
	Hash string

	// AheadOnly is true when the branch has commits ahead of the default branch
	// but the default branch is an ancestor (no divergence). Set for remote branches
	// during full collection. False means the branch has diverged.
	AheadOnly bool

	// UniqueBytes is the on-disk size of objects (commits, trees, blobs)
	// reachable from this branch tip but not from any other ref. This is
	// the storage that deleting this branch would make unreachable, and
	// that a subsequent deep-clean could reclaim.
	//
	// -1 means not computed. 0 means the branch holds no unique objects
	// (fully subsumed by other refs). Populated only for local,
	// non-default branches during full collection.
	UniqueBytes int64

	// Detail is populated on demand by CollectDetails (nil until requested).
	Detail *BranchDetail
}

Branch represents a git branch.

func (Branch) HasUpstream

func (b Branch) HasUpstream() bool

HasUpstream reports whether this branch tracks a remote branch.

type BranchDetail

type BranchDetail struct {
	// LastCommitMessage is the subject line of the tip commit.
	LastCommitMessage string

	// DiffStat is the output of git diff --shortstat <default>...<branch>.
	DiffStat string
}

BranchDetail holds on-demand detail information for a branch.

type CheckKind

type CheckKind uint8

CheckKind identifies the provider of a check.

const (
	CheckKindGit    CheckKind = iota // git CLI check
	CheckKindGitHub                  // GitHub API check
	CheckKindGitLab                  // GitLab API check (future)
	CheckKindCustom                  // external/custom check (Phase 3)
)

type CollectLevel

type CollectLevel uint8

CollectLevel indicates the depth of data collection performed.

const (
	// CollectLevelFast is a quick collection that skips expensive operations
	// (fsck, file stats, health, merge/rebase checks, activity).
	CollectLevelFast CollectLevel = iota

	// CollectLevelFull is a complete collection with all diagnostics.
	CollectLevelFull
)

type CollectOption

type CollectOption uint8
const (
	CollectNone CollectOption = iota
	CollectFast
	CollectForceRefresh
	CollectSecurityAlerts
	CollectPlatform // collect hosting-platform metadata (GitHub/GitLab API)
)

type ConfigEntry

type ConfigEntry struct {
	// Key is the config key (e.g. "user.email").
	Key string

	// Value is the effective value. Empty if unset.
	Value string

	// Scope indicates where the value is defined (global, local, etc.).
	Scope ConfigScope

	// IsLocal reports whether this value is set in the repo's local config.
	IsLocal bool
}

ConfigEntry holds a single git config value with its origin scope.

type ConfigScope

type ConfigScope string

ConfigScope indicates where a git config value is defined.

const (
	ScopeSystem   ConfigScope = "system"
	ScopeGlobal   ConfigScope = "global"
	ScopeLocal    ConfigScope = "local"
	ScopeWorktree ConfigScope = "worktree"
	ScopeCommand  ConfigScope = "command"
	ScopeUnset    ConfigScope = ""
)

type Describer

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

Describer provides Name and Description for embedding into concrete check and action types.

func NewDescriber

func NewDescriber(name, description string) Describer

func (Describer) Description

func (d Describer) Description() string

Description returns the human-readable description.

func (Describer) Name

func (d Describer) Name() string

Name returns the registered name.

type EvaluateOption

type EvaluateOption uint8
const (
	EvaluateAll EvaluateOption = iota
)

type FileEntry

type FileEntry struct {
	Path string
	Size int64
}

FileEntry represents a file in the current tree with its size.

type FileStats

type FileStats struct {
	// LargeFiles lists files in HEAD that exceed the size threshold,
	// sorted by size descending.
	LargeFiles []FileEntry

	// LargeBlobs lists the largest blob objects across all history,
	// sorted by size descending.
	LargeBlobs []BlobEntry

	// BinaryFiles lists files in HEAD that git considers binary.
	BinaryFiles []string
}

FileStats holds information about large and binary files in the repository.

type HealthReport

type HealthReport struct {
	// FSCKErrors lists corruption issues found by git fsck --connectivity-only.
	FSCKErrors []string

	// OK is true when no integrity issues are found.
	OK bool

	// LooseObjects is the number of unpacked loose objects.
	LooseObjects int

	// LooseSizeKB is the total size of loose objects in kilobytes.
	LooseSizeKB int

	// PackedObjects is the number of objects in pack files.
	PackedObjects int

	// Packs is the number of pack files.
	Packs int

	// PackSizeKB is the total size of all pack files in kilobytes.
	PackSizeKB int

	// PrunePackable is the number of loose objects also present in a pack.
	PrunePackable int

	// Garbage is the number of garbage files in the object store.
	Garbage int

	// GarbageSizeKB is the total size of garbage files in kilobytes.
	GarbageSizeKB int

	// GCAdvised is true when conditions suggest git gc would be beneficial.
	GCAdvised bool

	// GCReasons lists human-readable reasons why GC is advised.
	GCReasons []string
}

HealthReport holds the result of a repository health check.

type HistoryEntry

type HistoryEntry struct {
	Timestamp  time.Time
	RepoPath   string
	ActionName string
	Subjects   []string
	Params     []string // user-provided input parameters (e.g. description text)
	Result     Result
}

HistoryEntry records a single executed action and its result.

type Issue

type Issue struct {
	Number    int
	Title     string
	State     string // "open", "closed"
	Author    string
	Labels    []string
	CreatedAt time.Time
	UpdatedAt time.Time
	HTMLURL   string
	Detail    *IssueDetail // nil until requested via CollectDetails
}

Issue represents a GitHub issue summary.

type IssueDetail

type IssueDetail struct {
	Body         string
	CommentCount int
	Assignees    []string
	Tags         []string
}

IssueDetail holds on-demand detail information for an issue.

type MergeCheck

type MergeCheck struct {
	// Clean is true if the merge would succeed without conflicts.
	Clean bool

	// Conflicts lists the file paths with merge conflicts (empty if Clean).
	Conflicts []string
}

MergeCheck holds the result of a dry-run merge check (git merge-tree).

type PlatformInfo

type PlatformInfo struct {
	// Identity.
	Owner    string
	Repo     string
	FullName string // "owner/repo"
	HTMLURL  string

	// Metadata.
	Description   string
	DefaultBranch string
	Topics        []string
	License       string // SPDX identifier or ""
	IsFork        bool
	IsArchived    bool
	IsPrivate     bool

	// Permissions (from API).
	HasAdminAccess bool
	HasPushAccess  bool

	// Counts.
	OpenIssues int // includes PRs on GitHub
	OpenPRs    int // accurate count
	StarCount  int
	ForkCount  int

	// Fork lineage.
	ParentFullName string // "" if not a fork

	// Timestamps.
	CreatedAt time.Time
	UpdatedAt time.Time
	PushedAt  time.Time

	// Expensive fields (populated only when corresponding checks are enabled).
	UnrespondedIssues int // -1 = not fetched
	PendingReviewPRs  int // -1 = not fetched

	// Security alerts (-1 = not fetched / no access, -2 = not queried by config).
	DependabotAlerts     int
	CodeScanningAlerts   int
	SecretScanningAlerts int
	SecuritySkipped      bool // true when config says securityAlerts: false

	// Token scopes (from X-OAuth-Scopes header). Empty for fine-grained tokens.
	TokenScopes string

	// Branch protection (-1 = not fetched, 0 = no protection, 1 = protected).
	DefaultBranchProtected int

	// DeleteBranchOnMerge tracks the "Automatically delete head branches" setting.
	// For forks, this is checked on the parent (upstream) repo.
	// -1 = not fetched, 0 = disabled, 1 = enabled.
	DeleteBranchOnMerge int

	// ActionsEnabled tracks whether GitHub Actions (CI) is enabled on the fork.
	// -1 = not fetched, 0 = disabled, 1 = enabled.
	ActionsEnabled int

	// Activity data (populated on demand via CollectDetails).
	Issues       []Issue
	PullRequests []PullRequest
	WorkflowRuns []WorkflowRun

	// Cross-check field: injected from git data.
	LocalDefaultBranch string

	// Err is non-nil if the API call failed.
	Err error
}

PlatformInfo holds hosting-platform metadata for a repository.

This covers GitHub, GitLab, Gitea, etc. Provider-specific fields that don't generalize across platforms are nil/zero when not applicable.

func NewPlatformInfo

func NewPlatformInfo(owner, repo string) *PlatformInfo

NewPlatformInfo returns a PlatformInfo with expensive fields initialized to -1 (not fetched).

func (*PlatformInfo) SecurityAlerts

func (d *PlatformInfo) SecurityAlerts() int

SecurityAlerts returns the total count of open security alerts, or -1 if none of the security APIs were queried.

type PullRequest

type PullRequest struct {
	Number    int
	Title     string
	State     string // "open", "closed", "merged"
	Author    string
	Branch    string // head branch
	Base      string // base branch
	Draft     bool
	CreatedAt time.Time
	UpdatedAt time.Time
	HTMLURL   string
	Detail    *PullRequestDetail // nil until requested via CollectDetails
}

PullRequest represents a GitHub pull request summary.

type PullRequestDetail

type PullRequestDetail struct {
	Body         string
	CommentCount int
	ReviewState  string // "approved", "changes_requested", "pending"
	Mergeable    bool
	Additions    int
	Deletions    int
	ChangedFiles int
	Tags         []string
}

PullRequestDetail holds on-demand detail information for a pull request.

type RebaseCheck

type RebaseCheck struct {
	// CanRebase is true if replaying each commit one by one onto target succeeds.
	CanRebase bool

	// CanRebaseSquashed is true if squashing all commits first and then rebasing
	// onto target succeeds.
	CanRebaseSquashed bool

	// Conflicts lists file paths from whichever strategy was attempted last.
	Conflicts []string

	// FailedStep is the 1-based index of the commit that caused a conflict
	// during the direct per-commit rebase. 0 if direct rebase is clean.
	FailedStep int

	// TotalSteps is the number of commits between the merge-base and the branch tip.
	TotalSteps int
}

RebaseCheck holds the result of a dry-run rebase analysis.

type Remote

type Remote struct {
	Name     string
	FetchURL string
	PushURL  string
}

Remote represents a git remote with its name and URL.

func FindRemote

func FindRemote(remotes []Remote, name string) *Remote

FindRemote returns the Remote with the given name, or nil if not found.

type RepoConfig

type RepoConfig struct {
	UserEmail  ConfigEntry
	UserName   ConfigEntry
	SigningKey ConfigEntry
	CommitSign ConfigEntry
	TagSign    ConfigEntry
}

RepoConfig holds a curated set of git config values for a repository.

type RepoInfo

type RepoInfo struct {
	// RootIndex identifies which configured root this repo belongs to.
	// -1 means unknown/unset. The engine uses this to look up per-root
	// config (enabled checks, GitHub settings, etc.).
	RootIndex int

	// Core git data.
	Path              string
	IsGit             bool
	Status            Status
	Branches          []Branch
	Remotes           []Remote
	Stashes           []Stash
	DefaultBranch     string
	SCM               RepoSCM  // github, gitlab, other, no-scm
	Kind              RepoKind // clone, fork, not-git
	LastCommit        time.Time
	LastCommitMessage string    // subject line of the most recent commit on HEAD
	LastLocalUpdate   time.Time // most recent local activity: last commit if clean, newest dirty file mtime if dirty
	CommitCount       int       // total number of commits reachable from HEAD; 0 when unavailable or shallow
	FirstCommit       time.Time // author date of the earliest commit reachable from HEAD; zero when unavailable or shallow
	Worktrees         []Worktree
	IsShallow         bool
	HasSubmodules     bool
	HasLFS            bool

	// StaleSubmoduleDirs lists orphan directories under .git/modules/
	// whose name is no longer referenced by .git/config. Nil when the
	// repository has no .git/modules/ tree.
	StaleSubmoduleDirs  []StaleSubmoduleDir
	Tags                []Tag
	LastTagDate         time.Time // most recent tag date (any tag)
	LastSemverTag       string    // latest semver tag by version ordering
	LastSemverDate      time.Time // date of LastSemverTag
	CommitsSinceLastTag int       // commits on HEAD since LastSemverTag; 0 when there is no tag

	// Cache metadata.
	CollectedAt  time.Time    // when this info was last collected (for cache TTL)
	CollectLevel CollectLevel // fast or full (for cache validity)

	// Git diagnostics (optional, nil when not collected).
	Health    *HealthReport
	Size      *RepoSize
	Config    *RepoConfig
	FileStats *FileStats
	Activity  *Activity

	// Platform metadata (optional, nil when not collected).
	// Platform is collected from the origin remote.
	Platform *PlatformInfo

	// UpstreamPlatform is collected from the upstream remote (if present).
	// Used by fork-aware checks that need data about the user's fork.
	UpstreamPlatform *PlatformInfo

	// UpstreamDefaultBehindLocal is true when the upstream remote's default
	// branch is strictly behind the local default branch.
	// Only populated for fork-kind repos that have an upstream remote.
	UpstreamDefaultBehindLocal bool

	// UpstreamDefaultBehindOrigin is true when the upstream remote's default
	// branch is strictly behind the origin remote's default branch.
	// Only populated for fork-kind repos that have both remotes.
	UpstreamDefaultBehindOrigin bool

	// Errors.
	Err      error // fatal collection error
	FetchErr error // non-fatal fetch failure (local data still valid)
}

RepoInfo holds the consolidated data for a single repository, combining git-derived data and optional hosting-platform metadata.

func NewRepoInfo

func NewRepoInfo(pth string) *RepoInfo

NewRepoInfo creates a minimal RepoInfo seeded with a path. Use this as input to [ifaces.Engineer.Collect] when no prior data exists.

func NewRepoInfoForRoot

func NewRepoInfoForRoot(pth string, rootIndex int) *RepoInfo

NewRepoInfoForRoot creates a minimal RepoInfo seeded with a path and root index.

func NoGit

func NoGit(pth string) *RepoInfo

NoGit creates a RepoInfo for a non-git directory.

func (*RepoInfo) DefaultBranchHash

func (r *RepoInfo) DefaultBranchHash() string

DefaultBranchHash returns the commit hash of the default branch, or an empty string if the default branch is not found.

func (*RepoInfo) IsEmpty

func (r *RepoInfo) IsEmpty() bool

IsEmpty reports whether the RepoInfo has no data.

func (*RepoInfo) RepoErr

func (r *RepoInfo) RepoErr() error

RepoErr returns the fatal error, if any.

type RepoItem

type RepoItem struct {
	Path      string
	Name      string
	Namespace string // slash-separated parent path relative to the root
	IsGit     bool   // true if a .git directory was found
}

RepoItem represents a repository entry in the list.

Namespace is the slash-separated relative parent directory from the configured root, used to express GitLab-style nested groups. It is empty for top-level repositories (the GitHub-style flat layout).

func (RepoItem) Depth

func (i RepoItem) Depth() int

Depth returns the nesting level of the repo within its root: 0 for a top-level repo, 1 for "group/repo", 2 for "group/sub/repo", etc.

func (RepoItem) Description

func (i RepoItem) Description() string

Description implements the list.DefaultItem interface.

func (RepoItem) DisplayKey

func (i RepoItem) DisplayKey() string

DisplayKey returns a stable, lowercased sort key combining the namespace and the leaf name. Sorting by this key clusters siblings under the same group regardless of os.ReadDir order.

func (RepoItem) FilterValue

func (i RepoItem) FilterValue() string

FilterValue implements the list.Item interface. It includes the namespace so the regexp filter naturally matches "group/sub/repo".

func (RepoItem) Title

func (i RepoItem) Title() string

Title implements the list.DefaultItem interface.

Title returns just the leaf name; the panel delegate is responsible for indenting the row according to RepoItem.Depth.

type RepoKind

type RepoKind string
const (
	RepoKindNone    RepoKind = ""
	RepoKindClone   RepoKind = "clone"
	RepoKindFork    RepoKind = "fork"
	RepoKindTracked RepoKind = "tracked"
	RepoKindNotGit  RepoKind = "not-git"
)

func (RepoKind) String

func (e RepoKind) String() string

type RepoSCM

type RepoSCM string

func (RepoSCM) String

func (e RepoSCM) String() string

type RepoSize

type RepoSize struct {
	// GitDirBytes is the total size of the .git directory on disk.
	GitDirBytes int64

	// ReachableBytes is the total size of all reachable objects.
	ReachableBytes int64

	// RepackAdvised is true when conditions suggest git repack would be beneficial.
	// Triggered by pack count, loose/packed ratio, or oversized .git.
	// A standard aggressive gc fixes these.
	RepackAdvised bool

	// RepackReasons lists human-readable reasons why repack is advised.
	RepackReasons []string

	// UnreachableBloat is true when the .git directory is significantly
	// larger than reachable objects, indicating unreachable objects held
	// alive by reflog entries or kept by the default grace period.
	// A standard gc does not reclaim this space; a deep clean is required
	// (reflog expiry + gc --prune=now).
	UnreachableBloat bool

	// UnreachableBloatReasons lists human-readable reasons why deep clean
	// is advised.
	UnreachableBloatReasons []string
}

RepoSize holds size metrics for a repository.

type Result

type Result struct {
	// OK is true if the action completed successfully.
	OK bool

	// Message describes what happened (success or failure).
	Message string

	// CommandLog records the commands (git CLI or API calls) executed
	// during the action, in order. Each entry is a human-readable
	// command string (e.g. "git stash apply stash@{3}").
	CommandLog []string
}

Result holds the outcome of an executed action.

type RunnerKind

type RunnerKind uint8

type Severity

type Severity uint8

Severity levels for alerts. The zero value (SeverityNone) means "check ran, nothing wrong.".

const (
	SeverityNone     Severity = iota // check passed, no alert
	SeverityInfo                     // informational, no action needed
	SeverityLow                      // minor housekeeping
	SeverityMedium                   // should address soon
	SeverityHigh                     // needs attention now
	SeverityCritical                 // needs manual repair
)

func (Severity) String

func (s Severity) String() string

String returns the human-readable name of a Severity.

type StaleSubmoduleDir

type StaleSubmoduleDir struct {
	// Name is the submodule name (path under .git/modules/, may contain slashes).
	Name string

	// Path is the absolute filesystem path to the orphan module directory.
	Path string

	// SizeBytes is the total on-disk size of the orphan directory.
	SizeBytes int64
}

StaleSubmoduleDir is an orphan directory under .git/modules/ whose submodule name is not referenced by any [submodule "..."] stanza in the repository's .git/config. These are historical leftovers (removed submodules, renamed paths) that a standard git gc does not reclaim.

type Stash

type Stash struct {
	// Ref is the stash reference (e.g. "stash@{0}").
	Ref string

	// Branch is the branch the stash was created on.
	Branch string

	// Message is the stash description.
	Message string

	// LastUpdatedAt is the timestamp of the stash entry.
	LastUpdatedAt time.Time

	// Detail is populated on demand by CollectDetails (nil until requested).
	Detail *StashDetail
}

Stash represents a single stash entry.

type StashDetail

type StashDetail struct {
	// DiffStat is the output of git stash show --include-untracked <ref>.
	DiffStat string
}

StashDetail holds on-demand detail information for a stash entry.

type Status

type Status struct {
	// Branch is the current branch name (empty if detached HEAD).
	Branch string

	// OID is the commit hash of HEAD.
	OID string

	// Upstream is the upstream tracking branch (e.g. "origin/main").
	Upstream string

	// AheadBehind holds the ahead/behind counts relative to upstream.
	Ahead  int
	Behind int

	// Entries are the changed/untracked files.
	Entries []StatusEntry
}

Status holds the parsed output of git status.

func (Status) IsDirty

func (s Status) IsDirty() bool

IsDirty reports whether the working tree has any changes.

type StatusEntry

type StatusEntry struct {
	// XY is the two-character status code (e.g. "M.", ".M", "A.", "??").
	XY string

	// Path is the file path relative to the repo root.
	Path string

	// OrigPath is set for renames/copies (the source path).
	OrigPath string
}

StatusEntry represents a single entry from git status --porcelain=v2.

func (StatusEntry) IsIgnored

func (e StatusEntry) IsIgnored() bool

IsIgnored reports whether the entry is an ignored file.

func (StatusEntry) IsUntracked

func (e StatusEntry) IsUntracked() bool

IsUntracked reports whether the entry is an untracked file.

type SubjectKind

type SubjectKind uint8

SubjectKind categorizes what a check or action operates on.

const (
	SubjectNone         SubjectKind = iota // no specific subject (repo-level)
	SubjectRepo                            // the repository itself
	SubjectRemote                          // a git remote
	SubjectBranch                          // a git branch
	SubjectStash                           // a git stash entry
	SubjectTag                             // a git tag
	SubjectFile                            // a git file object
	SubjectWorktree                        // a git worktree (main or linked)
	SubjectIssues                          // GitHub issues (paginated list)
	SubjectPullRequests                    // GitHub pull requests (paginated list)
	SubjectWorkflowRuns                    // GitHub workflow runs (paginated list)
	SubjectIssueDetail                     // a single GitHub issue, identified by number
)

func ParseSubjectKind

func ParseSubjectKind(s string) (SubjectKind, bool)

ParseSubjectKind converts a string (e.g. from YAML config) into a SubjectKind. It is case-insensitive and trims whitespace. Returns false for unrecognized values.

func (SubjectKind) String

func (s SubjectKind) String() string

String returns the human-readable name of a SubjectKind.

type Tag

type Tag struct {
	// Name is the tag name (e.g. "v1.2.3").
	Name string

	// Hash is the object hash the tag points to.
	Hash string

	// TargetHash is the commit hash the tag ultimately points to.
	TargetHash string

	// Date is the tagger date (annotated) or commit date (lightweight).
	Date time.Time

	// Message is the tag message (empty for lightweight tags).
	Message string

	// Annotated is true for annotated tags (objecttype == "tag").
	Annotated bool

	// Signed is true if the tag has a GPG/SSH signature.
	Signed bool

	// IsSemver is true if the tag matches semver pattern.
	IsSemver bool

	// HasVPrefix is true if the semver tag starts with "v".
	HasVPrefix bool

	// IsPrerelease is true if the semver tag has a prerelease suffix.
	IsPrerelease bool

	// OnDefaultBranch is true if the tagged commit is reachable from the default branch.
	OnDefaultBranch bool

	// LocalOnly is true if the tag exists locally but not on the origin remote.
	LocalOnly bool

	// RemoteOnly is true if the tag exists on the origin remote but not locally.
	RemoteOnly bool

	// SemverMajor, SemverMinor, SemverPatch hold the parsed version components.
	SemverMajor int
	SemverMinor int
	SemverPatch int

	// SemverPrerelease holds the prerelease suffix (e.g. "beta.1").
	SemverPrerelease string
}

Tag represents a git tag with metadata.

type WorkflowRun

type WorkflowRun struct {
	ID         int64
	Name       string
	Status     string // "queued", "in_progress", "completed"
	Conclusion string // "success", "failure", "cancelled", etc.
	Branch     string
	Event      string // "push", "pull_request", "schedule", etc.
	CreatedAt  time.Time
	HTMLURL    string
	Detail     *WorkflowRunDetail // nil until requested via CollectDetails
}

WorkflowRun represents a GitHub Actions workflow run summary.

type WorkflowRunDetail

type WorkflowRunDetail struct {
	RunNumber  int
	RunAttempt int
	Duration   time.Duration
}

WorkflowRunDetail holds on-demand detail information for a workflow run.

type Worktree

type Worktree struct {
	// Path is the absolute filesystem path of the worktree.
	Path string

	// HEAD is the commit hash at the tip of the worktree.
	HEAD string

	// Branch is the checked-out branch (e.g. "refs/heads/main").
	// Empty if the worktree is in detached HEAD state.
	Branch string

	// Detached is true if the worktree is in detached HEAD state.
	Detached bool

	// Bare is true if this is the bare repository entry.
	Bare bool

	// Prunable is true if the worktree path is missing and can be pruned.
	Prunable bool

	// PrunableReason describes why the worktree is prunable, when known
	// (e.g. "gitdir file points to non-existent location"). May be empty.
	PrunableReason string

	// Locked is true if the worktree is locked against pruning / moving.
	Locked bool

	// LockReason is the reason recorded when the worktree was locked.
	// May be empty.
	LockReason string

	// Dirty reports whether the worktree's working tree has any uncommitted
	// changes (staged, unstaged, or untracked). Populated only during full
	// collection and only for worktrees with an accessible path.
	Dirty bool

	// LastCommit is the author date of the commit at the worktree's HEAD.
	// Zero when the worktree is bare, prunable, or collection failed.
	LastCommit time.Time

	// LastCommitMessage is the subject line of the commit at the worktree's HEAD.
	// Empty when the worktree is bare, prunable, or collection failed.
	LastCommitMessage string
}

Worktree represents a git worktree linked to a repository.

func (Worktree) BranchShort

func (w Worktree) BranchShort() string

BranchShort returns the short branch name (e.g. "main" from "refs/heads/main").

func (Worktree) IsMain

func (w Worktree) IsMain() bool

IsMain reports whether this is the main worktree (the original checkout).

Jump to

Keyboard shortcuts

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