plugins

package
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 10 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 plugins defines the plugin contract that every github-metrics data source implements, together with the in-memory Data structure the engine builds up as it executes plugins. Concrete plugins live in internal/plugins/<name>/; the orchestration that walks them lives in internal/plugins/core/.

Index

Constants

View Source
const (
	ModeUser = "user"
	ModeRepo = "repo"
)

AggregationMode tags the per-plugin Result with which aggregation path it took: "user" when computing over data.User (the M2/M4 classic-template behavior) or "repo" when computing over the single-repository data populated by base.runRepository (M7).

Plugins call this helper from their Run() to keep the per-plugin branching contract in one place. Each of the 7 reused plugins (activity, contributors, languages, people, projects, sponsors, stargazers) imports plugins already; this constant + helper costs zero extra import edges.

Variables

This section is empty.

Functions

func AggregationMode

func AggregationMode(d *Data) string

AggregationMode returns ModeRepo when the engine has populated a single-repository payload (Data.Repo != nil), ModeUser otherwise. Plugins assign the returned value to Result.Mode at the end of their Run().

func Each

func Each(fn func(name string, p Plugin) error) error

Each iterates registered plugins in sort.Strings(name) order so test expectations stay deterministic. fn may return an error to stop.

func Register

func Register(p Plugin)

Register adds p to the registry. Duplicate names panic so that two init()s racing for the same plugin slug are caught at startup, not at request time.

func RegisterForTest

func RegisterForTest(t TB, p Plugin)

RegisterForTest temporarily replaces the registry entry for p.Name() with p, calling t.Cleanup to restore the previous value (or remove the entry) once the test completes.

func RequireRepoMode added in v1.1.0

func RequireRepoMode(pc *PluginContext, slug string) (string, bool)

RequireRepoMode is the mirror of RequireUserMode: it returns a descriptive Skipped reason and skip=true when the engine did NOT populate Data.Repo (i.e. we are rendering the classic / user template) for a plugin that only has meaning against a single repository (today: contributors).

func RequireUserMode added in v1.1.0

func RequireUserMode(pc *PluginContext, slug string) (string, bool)

RequireUserMode returns a descriptive Skipped reason and skip=true when the engine populated Data.Repo (i.e. we are rendering the repository template), since plugins that aggregate per-user signals have nothing meaningful to compute against a single repository. The helper logs one WARN line via pc.Logger (or slog.Default when Logger is nil) so operators see the mode mismatch in CI logs.

slug must be the canonical plugin name (e.g. "achievements"). The caller passes its own Name constant.

Usage:

if reason, skip := plugins.RequireUserMode(pc, Name); skip {
    return &Result{Skipped: true, SkippedReason: reason}, nil
}

func Reset

func Reset()

Reset clears the registry. Intended for tests that need a clean slate; production code MUST NOT call it.

Types

type AccountKind

type AccountKind string

AccountKind is the high-level shape of the account the engine is rendering metrics for. The base plugin branches on this value.

const (
	AccountUser         AccountKind = "user"
	AccountOrganization AccountKind = "organization"
	AccountRepository   AccountKind = "repository"
)

AccountKind values the engine branches on when deciding which plugin dispatch path to take (user / organization / repository).

type Computed

type Computed struct {
	Commits        int
	Repositories   ComputedRepositories
	RepositoryList []Repository

	// Indepth fields are populated by base.runIndepth when at least one
	// indepth-dependent plugin (isocalendar, calendar, habits, ...) is
	// enabled. They stay zero-value when indepth is not triggered, or
	// when the indepth GraphQL call returned an error (degraded path).
	TotalCommits         int
	TotalIssues          int
	TotalPullRequests    int
	ContributionCalendar *ContributionCalendar
}

Computed aggregates derived counters. Filled gradually by the base plugin (repositories) and individual plugins.

RepositoryList is the per-node accumulator the M4 base plugin produces via batch-halving paging; downstream P1/P2 plugins (languages, repositories, achievements, ...) consume it. Repositories holds the totals derived from the same connection (count, stargazers, forks, ...), kept separate so M1 / M2 code that only reads totals stays compiling.

type ComputedConfig

type ComputedConfig struct {
	Timezone   TimezoneConfig
	Animations bool
	Display    string
	Base64     bool
	DebugFlags []string
}

ComputedConfig captures the core plugin's resolved settings.

type ComputedRepositories

type ComputedRepositories struct {
	Count             int
	Stargazers        int
	Forks             int
	Releases          int
	Packages          int
	DiskUsage         int
	Watchers          int
	Issues            int
	PullRequests      int
	Languages         map[string]int
	LicensePreference []LicenseShare
}

ComputedRepositories carries the repository-level totals base/run produces.

429 Phase 2: Releases / Packages / DiskUsage / LicensePreference surface the per-repo aggregate fields upstream `base.repositories.ejs` renders. DiskUsage is in KB (GitHub GraphQL convention); the partial promotes to MB / GB / TB via format.FormatDiskKB. LicensePreference is the top-N license share, sorted by Count descending.

type ContributionCalendar

type ContributionCalendar struct {
	TotalContributions int
	Weeks              []ContributionWeek
}

ContributionCalendar mirrors GitHub's contributionCalendar payload as surfaced by base.runIndepth. Downstream plugins (isocalendar, calendar) consume it to compute weekly / yearly summaries.

type ContributionDay

type ContributionDay struct {
	Date              string
	ContributionCount int
	Weekday           int
	Color             string
}

ContributionDay is a single calendar day's contribution count.

type ContributionWeek

type ContributionWeek struct {
	FirstDay string
	Days     []ContributionDay
}

ContributionWeek holds the seven daily contribution counts for one ISO week.

type Data

type Data struct {
	Account      AccountKind
	User         *User
	Organization *Organization
	Repo         *Repo // M7: populated when AccountKind == AccountRepository; nil otherwise. Guarded by mu when accessed off the base-plugin goroutine — use RepoRef.
	Config       ComputedConfig
	Computed     Computed
	Plugins      map[string]any
	Errors       []error
	// contains filtered or unexported fields
}

Data is the central state object passed through engine.Compute. The base plugin populates User; core fills Config and zero-initializes Computed; downstream plugins append their results under Plugins.

The structure is intentionally minimal in M1: fields land incrementally as later phases need them. Access is goroutine-safe through the embedded mutex.

func NewData

func NewData() *Data

NewData returns a zero-value Data with the Plugins map initialised.

func (*Data) AppendError

func (d *Data) AppendError(err error)

AppendError records a non-fatal error. Goroutine-safe.

func (*Data) GetPlugin

func (d *Data) GetPlugin(name string) (any, bool)

GetPlugin returns the entry under name, if any.

func (*Data) RepoRef

func (d *Data) RepoRef() *Repo

RepoRef returns a goroutine-safe snapshot of d.Repo. nil when the engine did not request the repository template (M2/M4 classic flow) or when the base plugin's repository fetch failed. Callers must not mutate the returned *Repo — the M7 contract treats it as write-once-read-many.

func (*Data) SetPlugin

func (d *Data) SetPlugin(name string, result any)

SetPlugin stores result under name. Goroutine-safe.

func (*Data) SetRepo

func (d *Data) SetRepo(r *Repo)

SetRepo stores the resolved repository payload. Goroutine-safe; intended to be called once by the base plugin before plugin dispatch fans out.

func (*Data) SnapshotErrors

func (d *Data) SnapshotErrors() []error

SnapshotErrors returns a copy of the currently recorded non-fatal errors. Goroutine-safe; the returned slice is independent of d.Errors so callers can extend or sort it without affecting future appenders.

type LanguageStat

type LanguageStat struct {
	Name  string
	Color string
	Size  int
	Count int
	Value float64
}

LanguageStat is the primary-language summary surfaced per repository. Plugins that need full per-byte language breakdowns (T-041 languages standard mode) compute their own from this and additional fetches.

type LicenseShare added in v1.1.0

type LicenseShare struct {
	Name    string
	Count   int
	Percent float64
}

LicenseShare is one entry in the License-preference top-N. Percent is the share of owned repositories whose `licenseInfo.name` matches Name (0..100, never normalised against unlicensed repositories — so the figures sum to <= 100 when some repos have no license).

type OrgMember

type OrgMember struct {
	Login     string
	Name      string
	AvatarURL string
}

OrgMember is a single organization member entry surfaced by runOrganization.

type Organization

type Organization struct {
	Login        string
	Name         string
	Description  string
	AvatarURL    string
	MembersCount int
	Members      []OrgMember
}

Organization is the organization-account payload populated by the base plugin's runOrganization branch. It mirrors the upstream `organization(login)` GraphQL fields the project consumes, including the paged member list and the paged repositories accumulator.

type Plugin

type Plugin interface {
	Name() string
	Metadata() *config.PluginMetadata
	Run(ctx context.Context, pc *PluginContext) (any, error)
}

Plugin is the contract every github-metrics data source implements.

func Get

func Get(name string) (Plugin, bool)

Get returns the registered Plugin. The second return value reports presence so callers can distinguish "missing" from "registered but nil" (which is forbidden by the contract anyway).

type PluginContext

type PluginContext struct {
	Settings   *config.Settings
	Inputs     map[string]any
	Logger     *slog.Logger
	HTTPClient *httpx.Client
	REST       *githubapi.REST
	GraphQL    *githubapi.GraphQL
	Data       *Data
	Metadata   *config.MetadataLoader
	Imports    PluginImports
	// Render carries the engine's renderer. Only the SVG -> PNG/JPEG
	// resize pipeline (engine.dispatch.go) consumes this field today;
	// plugins themselves never type-assert it. Tests inject a
	// *render.FakeRenderer to avoid launching chromium.
	Render render.Renderer
}

PluginContext groups everything a Run call needs. Engine constructs one per request and mutates Data only — every other field is treated as read-only by plugin code.

type PluginImports

type PluginImports interface {
	Get(name string) (any, bool)
}

PluginImports lets a plugin read another plugin's published result without depending on its package directly.

func NewImports

func NewImports(d *Data) PluginImports

NewImports returns a PluginImports backed by the given Data.

type Repo

type Repo struct {
	// Owner is the repository owner's login (the part before `/` in
	// `<owner>/<name>`).
	Owner string
	// OwnerAvatar is the avatar URL of the owner — sized for the
	// `base.header` partial's avatar slot.
	OwnerAvatar string
	// Name is the repository name (the part after `/`).
	Name string
	// Description is the repo's about/description text (may be empty).
	Description string
	// CreatedAt is `repository.createdAt` — backs the base.header
	// "Created N years ago" field (#464).
	CreatedAt time.Time
	// DiskUsageKB is `repository.diskUsage` (KiB, GitHub GraphQL
	// convention) — backs the base.header "N MB used" field (#464).
	DiskUsageKB int
	// Deployments is `repository.deployments.totalCount` — backs the
	// base.header "Deployed N times" field (#464).
	Deployments int
	// Environments is `repository.environments.totalCount` — backs the
	// base.header "N Environments" field (#464).
	Environments int
	// Calendar holds the trailing contribution days (copied from the
	// user payload) the base.header mini calendar renders (#464).
	Calendar []ContributionDay
	// Stargazers is `repository.stargazerCount`.
	Stargazers int
	// Watchers is `repository.watchers.totalCount`.
	Watchers int
	// Forks is `repository.forkCount`.
	Forks int
	// Contributors is the REST `listContributors` count (the GraphQL
	// API does not expose this directly).
	Contributors int
	// PrimaryLanguage is the GraphQL `primaryLanguage.name`; may be
	// empty for repos with no detected language.
	PrimaryLanguage string
	// PrimaryLanguageColor is `primaryLanguage.color` — used by the
	// languages partial to render the language dot.
	PrimaryLanguageColor string
	// LicenseName is the GraphQL `licenseInfo.name` (e.g. "MIT
	// License"); empty when no license is declared.
	LicenseName string
	// Languages is the full per-language byte breakdown for the
	// repository as reported by GraphQL `repository.languages`.
	Languages []LanguageStat
	// DefaultBranch is `defaultBranchRef.name` (e.g. "main"); used by
	// the committer when the workflow does not pin one explicitly.
	DefaultBranch string
	// IsArchived flips on for archived repos so partials can either
	// surface a badge or quietly skip the activity section.
	IsArchived bool
	// SponsorshipsAsMaintainer mirrors `template.mjs:21` —
	// `data.repo.sponsorshipsAsMaintainer = data.user.sponsorshipsAsMaintainer`.
	// Copied from the user payload by the base plugin.
	SponsorshipsAsMaintainer int
	// Activity carries the recent commits / open issues / open PRs
	// counts the `base.activity` and `activity` partials consume.
	Activity RepoActivity
}

Repo carries the single-repository payload populated by the base plugin when the engine resolves a `repository` template request. It is the M7 analogue of User for the M2 classic template: nil when no repository template was requested, populated exactly once per run before plugin dispatch fans out so downstream consumers can read it lock-free (the M7 contract guarantees no writes after population).

Field names mirror upstream `template.mjs:13-21` semantics.

type RepoActivity

type RepoActivity struct {
	// RecentCommits is the count of commits in the last 30 days,
	// derived from REST `listCommits?per_page=100&since=<30 days ago>`.
	RecentCommits int
	// OpenIssues is the GraphQL `issues(states: OPEN).totalCount`.
	OpenIssues int
	// OpenPullRequests is the GraphQL `pullRequests(states: OPEN).totalCount`.
	OpenPullRequests int
}

RepoActivity is the per-repo activity rollup. Populated alongside Repo by the base plugin's repository fetch path.

type Repository

type Repository struct {
	NameWithOwner string
	Description   string
	URL           string
	Visibility    string
	IsFork        bool
	Stars         int
	Forks         int
	Watchers      int
	// CreatedAt is the repository creation timestamp. The repositories
	// plugin renders it as the humanised "created <date>" card label
	// (#466). Zero value means the field was not fetched (e.g. starred
	// repos sourced via REST).
	CreatedAt time.Time
	// Issues / PullRequests are the per-repository totalCount values the
	// repositories card info row surfaces (#466). They mirror upstream
	// repositories.ejs `repository.issues.totalCount` /
	// `repository.pullRequests.totalCount`.
	Issues       int
	PullRequests int
	// License is the per-repository license summary (#466). nil when the
	// repository reports no LICENSE file.
	License  *RepositoryLicense
	Language *LanguageStat
	// Languages is the per-language byte breakdown for this repository
	// as reported by GraphQL `repository.languages(first: 8).edges`.
	// Each entry has Size (bytes in this repo) and Name/Color from the
	// linguist palette. Downstream plugins (languages standard mode,
	// achievements) aggregate across all repositories.
	Languages []LanguageStat
}

Repository is the per-node entry produced by the base plugin's paging loop. Field set mirrors the M4 plugin data model.

type RepositoryLicense added in v1.1.0

type RepositoryLicense struct {
	Name     string
	SpdxID   string
	Nickname string
}

RepositoryLicense is the per-repository license summary surfaced by the repositories plugin card (#466). It mirrors the GitHub GraphQL `licenseInfo` fields upstream `f.license` consumes: the human-friendly Nickname is preferred, falling back to SpdxId then Name.

func (*RepositoryLicense) Label added in v1.1.0

func (l *RepositoryLicense) Label() string

Label resolves the display string upstream `f.license` would render: when SpdxID is the catch-all "NOASSERTION" it returns Name, otherwise it prefers Nickname, then SpdxID, then Name. Returns "" only when all three fields are empty.

type TB

type TB interface {
	Helper()
	Cleanup(func())
	Fatalf(format string, args ...any)
}

TB matches the relevant subset of testing.TB so this file does not import "testing" at package level (which would pull the test runtime into production binaries).

type TimezoneConfig

type TimezoneConfig struct {
	Name  string
	Error error
}

TimezoneConfig records the resolved timezone or the error encountered while resolving an unknown IANA name (we keep both fields so the engine can surface a warning while still rendering in UTC).

type User

type User struct {
	Login                    string
	Name                     string
	AvatarURL                string
	CreatedAt                time.Time
	Followers                int
	Following                int
	Watching                 int
	SponsorshipsAsMaintainer int
	ContributedTo            int
	RecentContributions      []ContributionDay

	// 442: Activity-section counters surfaced by upstream
	// base.activity+community.ejs. Sourced from the always-fetched
	// User query's contributionsCollection aggregate fields and the
	// issueComments connection. They render in the base "Activity"
	// column regardless of whether an indepth-dependent plugin is
	// enabled (the upstream base run shows them unconditionally).
	Commits              int
	PullRequestsReviewed int
	PullRequestsOpened   int
	IssuesOpened         int
	IssueComments        int

	// 442: Community-stats counters surfaced by the same upstream
	// partial. Organizations / Sponsoring / Starred come from the
	// organizations / sponsorshipsAsSponsor / starredRepositories
	// connections; Following and Watching reuse the fields above.
	// Sponsoring renders even at zero to match upstream ("Sponsoring
	// 0 repositories").
	Organizations int
	Sponsoring    int
	Starred       int
}

User is the GraphQL-derived account payload populated by the base plugin's runUser branch.

429 Phase 1: CreatedAt / Followers / Following / Watching / SponsorshipsAsMaintainer surface the foundational counters that upstream `base.header.ejs` / `base.repositories.ejs` render. Zero values mean "GraphQL did not return the counter"; the partials hide rows whose source is zero so empty accounts do not gain noise lines.

429 Phase 2: ContributedTo carries the `user.repositoriesContributedTo(...).totalCount` counter rendered by upstream `base.header.ejs` as "Contributed to N repositories".

429 Phase 3: RecentContributions carries the last 14 calendar days used by the BaseHeader mini calendar. Sourced from `user.contributionsCollection.contributionCalendar.weeks`, flattened into a chronological day list and sliced to the trailing 14 by base.runUser — mirroring upstream `core/index.mjs`'s `slice(-14)`. Empty when GraphQL returned no calendar (e.g. a freshly-created account or a transient API failure) so the partial hides the block instead of rendering a row of empty cells.

Directories

Path Synopsis
Package achievements owns the M4 "achievements" plugin.
Package achievements owns the M4 "achievements" plugin.
Package activity owns the M4 "activity" plugin.
Package activity owns the M4 "activity" plugin.
Package base owns the special "base" plugin: it runs before every other plugin and populates the shared Data.User / Data.Organization / Data.Computed fields that downstream plugins depend on.
Package base owns the special "base" plugin: it runs before every other plugin and populates the shared Data.User / Data.Organization / Data.Computed fields that downstream plugins depend on.
Package calendar owns the M4 "calendar" plugin.
Package calendar owns the M4 "calendar" plugin.
Package contributors owns the M4 "contributors" plugin.
Package contributors owns the M4 "contributors" plugin.
Package core hosts the special "core" plugin.
Package core hosts the special "core" plugin.
Package habits owns the M4 "habits" plugin.
Package habits owns the M4 "habits" plugin.
Package isocalendar owns the M4 "isocalendar" plugin.
Package isocalendar owns the M4 "isocalendar" plugin.
Package languages — indepth.go implements the "languages.indepth" sub-mode of the M4 languages plugin.
Package languages — indepth.go implements the "languages.indepth" sub-mode of the M4 languages plugin.
Package notable owns the M4 "notable" plugin.
Package notable owns the M4 "notable" plugin.
Package people owns the M4 "people" plugin.
Package people owns the M4 "people" plugin.
Package projects owns the M4 "projects" plugin.
Package projects owns the M4 "projects" plugin.
Package reactions owns the M4 "reactions" plugin.
Package reactions owns the M4 "reactions" plugin.
Package repositories owns the M4 "repositories" plugin.
Package repositories owns the M4 "repositories" plugin.
Package sponsors owns the M4 "sponsors" plugin.
Package sponsors owns the M4 "sponsors" plugin.
Package sponsorships owns the M4 "sponsorships" plugin.
Package sponsorships owns the M4 "sponsorships" plugin.
Package stargazers owns the M4 "stargazers" plugin.
Package stargazers owns the M4 "stargazers" plugin.
Package starlists owns the M4 "starlists" plugin.
Package starlists owns the M4 "starlists" plugin.
Package stars owns the M4 "stars" plugin.
Package stars owns the M4 "stars" plugin.
Package topics owns the M4 "topics" plugin.
Package topics owns the M4 "topics" plugin.
Package traffic owns the M4 "traffic" plugin.
Package traffic owns the M4 "traffic" plugin.

Jump to

Keyboard shortcuts

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