Documentation
¶
Overview ¶
Package action implements the GitHub Action / CLI entry-point logic for the metrics-action binary.
The package exposes two top-level dispatch functions:
- Run(ctx) — Action mode. Reads INPUTS / INPUT_<UPPER> env vars, builds an *Invocation, runs engine.Compute, writes the output to /renders/<filename>, and optionally runs the configured output_action (commit / pull-request[-merge|-squash|-rebase]).
- RunCLI(ctx, args) — CLI mode. Parses CLI flags, optionally loads a YAML config file, builds the same *Invocation shape, and follows the same downstream pipeline. Action and CLI modes share the same input map / engine.Request / Committer paths so they produce byte-identical output for equivalent inputs (spec SC-009).
The package is internal because there is no expectation of external programmatic use — the metrics-action binary is the only consumer.
Index ¶
- Constants
- func CheckLatestRelease(ctx context.Context, rest *githubapi.REST, repo, currentVersion string) string
- func LoadYAMLConfig(path string) (map[string]any, error)
- func ParseInputs(env map[string]string) (map[string]any, error)
- func PrintBanner(w io.Writer, info BannerInfo)
- func ResolveOutputWriter(filename, format string) (io.Writer, func() error, error)
- func ResolveToken(cf *CLIFlags, envLookup func(string) string, inputToken string) (string, error)
- func Run(ctx context.Context) error
- func RunCLI(ctx context.Context, args []string) error
- func SetOutput(key, value string) error
- func WildcardFilename(template, format string) (string, error)
- type BannerInfo
- type CLIFlags
- type Committer
- type CommitterAuthor
- type ConfigError
- type HashComparator
- type InputError
- type Invocation
- type OutputActionRegistry
- type PresetBundle
- type Quota
- type RateBucket
- type RateState
- type RetryPolicy
- type RunMode
- type SkipReason
- type TokenValidator
- type ValidationResult
Constants ¶
const DefaultRetries = 3
DefaultRetries is the default `retries` input value when none is supplied (action.yml + CLI both default to this). Spec FR-007.
const DefaultRetryDelay = 300 * time.Millisecond
DefaultRetryDelay is the default `retries_delay` input value (ms) when none is supplied. Spec FR-007.
Variables ¶
This section is empty.
Functions ¶
func CheckLatestRelease ¶
func CheckLatestRelease(ctx context.Context, rest *githubapi.REST, repo, currentVersion string) string
CheckLatestRelease consults the upstream-style release feed of this repository and returns a notice message when a newer version is available. The result is intentionally a string (empty when no notice needed) so callers can do `if msg != "" { slog.Info(msg) }`.
Spec FR-021. Failures (network 5xx, missing repo) return "" with no error so the action does not fail on a notice-channel hiccup — notices are best-effort.
repo argument format: "owner/name" (e.g. "mjun0812/github-metrics").
func LoadYAMLConfig ¶
LoadYAMLConfig reads a YAML file at path and flattens its hierarchical `plugins:` / `config:` / `committer:` maps into the action.yml-flat key namespace expected by ParseInputs (prefixes `plugin_`, `config_`, `committer_`).
Top-level keys are passed through as-is. Returns nil + error if the file is missing or malformed.
func ParseInputs ¶
ParseInputs builds the unified inputs map used by both Action mode and CLI mode. Priority (highest first):
- INPUTS — a single env var holding a JSON object. Set by callers that want to pass a complete input set in one go (e.g., the composite GitHub Actions wrapper or programmatic CLI users).
- INPUT_<UPPER> — individual env vars per input. Set by GitHub Actions runner for each `with:` key in the workflow.
Keys are normalized to lowercase + underscores (matching the metadata.yml convention).
func PrintBanner ¶
func PrintBanner(w io.Writer, info BannerInfo)
PrintBanner writes the English-fixed startup banner to w. Format follows docs/design/13-appendix.md §E semantics: a top-bordered table block with key/value columns, suitable for grep'ing in GitHub Actions run logs and pinning via snapshot tests (SC-003).
The banner is intentionally written directly to w (bypassing slog) so handler choice (JSON / text) does not mangle the ASCII layout.
func ResolveOutputWriter ¶
ResolveOutputWriter returns the io.Writer + close func for the CLI output target. `-` returns os.Stdout (no close), with a warning when the format is non-text (png/jpeg). Other filenames are os.Create'd after mkdir -p of their parent.
func ResolveToken ¶
ResolveToken applies the CLI token priority rules:
--token-env > --token (with warning) > INPUT_TOKEN > error
`envLookup` is dependency-injected (defaults to os.Getenv) so tests can run hermetically.
func Run ¶
Run is the Action-mode entry point. Spec FR-001 / FR-002.
Pipeline:
- Skip detection — short-circuits when GITHUB_EVENT_PATH commit message contains "[Skip GitHub Action]" or "Auto-generated metrics for run #N".
- Input parsing — merges INPUTS JSON + INPUT_<UPPER>.
- Output_action validation — fail-fast on gist / markdown-*.
- Token validation — github_pat_* reject + scope check + quota check. Quota insufficient → exit 0 (skipped).
- Banner print (English fixed, slog-handler-agnostic).
- engine.Compute (wrapped in RetryPolicy).
- Write output to OutputDir/OutputFilename.
- Committer.Run (commit / pull-request*) unless Dryrun.
- SetOutput metrics_url + metrics_sha to $GITHUB_OUTPUT.
func RunCLI ¶
RunCLI is the CLI-mode entry point (spec FR-019). Pipeline:
- Parse flags (T034) + load --config YAML (T035).
- Merge inputs via CLIFlags.ToInvocation (T036).
- Resolve token (T037) — flag > env > error.
- newInvocation + output_action validation (shared with Action).
- Banner + engine.Compute + retry policy (shared).
- Write output to --filename or stdout (T038).
- Committer dispatch unless --dryrun.
func SetOutput ¶
SetOutput writes a `key=value` Action output line to the file at $GITHUB_OUTPUT (@actions/core v2 contract). When value contains a newline, a heredoc form is used with a random EOF delimiter that is guaranteed not to appear in value. See research R-003.
The function appends to the file (does not truncate). Returns nil + a warning-equivalent no-op when GITHUB_OUTPUT is unset (CLI mode without GitHub Actions); callers that require strict behavior should check GITHUB_OUTPUT themselves.
func WildcardFilename ¶
WildcardFilename resolves the `*` placeholder in a filename like `github-metrics.*` using the configured output format.
Examples:
WildcardFilename("github-metrics.*", "svg") → "github-metrics.svg"
WildcardFilename("github-metrics.*", "json") → "github-metrics.json"
WildcardFilename("custom.png", "svg") → "custom.png" (no wildcard)
Returns an error when the input contains more than one `*` since the upstream contract only defines a single wildcard placeholder.
Types ¶
type BannerInfo ¶
type BannerInfo struct {
Version string // semver tag or "dev"
Mode string // "action" or "cli"
Template string // e.g. "classic"
Plugins []string // enabled plugin slugs (sorted, deprecated entries suffixed " (deprecated)")
TokenMasked string // masked token string (config.Token.String() output)
GoVersion string // runtime.Version()
OSArch string // "darwin/arm64" etc.
}
BannerInfo carries the data the startup banner displays.
type CLIFlags ¶
type CLIFlags struct {
Config string // --config <path>.yaml
User string // --user <login>
Template string // --template <name>
Token string // --token <PAT>
TokenEnv string // --token-env <ENV_NAME>
Repo string // --repo <name> (M7 — repository template input)
Plugins map[string]string // --plugin key=value (repeatable)
Output string // --output svg|png|jpeg|json
Filename string // --filename <path-or-->
Dryrun bool // --dryrun
Preset string // --preset <path>.yaml
}
CLIFlags is the parsed result of `metrics-action <flags>` when the binary runs outside GitHub Actions.
The fields map 1:1 onto action.yml inputs so the merged *Invocation produced by ToInvocation is interchangeable with the Action-mode pipeline.
func ParseFlags ¶
ParseFlags parses the supplied args (typically os.Args[1:] after bootstrap flags are stripped in cmd/metrics-action) into a CLIFlags struct. Errors come from flag.FlagSet (continue on error).
func (*CLIFlags) ToInvocation ¶
ToInvocation merges CLI flags (highest priority), YAML config, env, and metadata defaults into a flat `map[string]any` suitable for newInvocation.
Priority (highest first):
- CLI flag (--user, --plugin key=val, ...)
- --config <path>.yaml
- --preset <path>.yaml (loaded by Run-side preset overlay; we just emit `config_presets` here so the unified pipeline runs it through LoadPreset like the Action path).
- INPUT_<UPPER> env variables (loaded via ParseInputs).
- metadata.yml defaults (applied by ParseInputs).
Returns the flat inputs map; the caller passes it through ParseInputs's metadata-default layer (newInvocation already does).
type Committer ¶
type Committer struct {
REST *githubapi.REST
Policy RetryPolicy
RepoOwner string
RepoName string
Branch string
Filename string
Message string
Author CommitterAuthor
Action string // "none", "commit", "pull-request[-merge|-squash|-rebase]"
// Condition controls the data-changed gate. "always" (default)
// commits unconditionally; "data-changed" runs HashComparator
// and skips when bytes are equivalent.
Condition string
// RunID is the GitHub Actions run id used to scope the
// pull-request head branch (`metrics-run-<RunID>`). Required for
// the pull-request* paths; ignored for commit / none.
RunID string
Body []byte
// Result fields populated by Run.
MetricsURL string // https://github.com/<owner>/<name>/blob/<branch>/<filename> (or PR URL for pull-request*)
Skipped bool // true when output_condition=data-changed and content matched
PRNumber int // populated for pull-request* paths after PR creation
}
Committer drives the output_action dispatch (commit / pull-request variants). The struct is populated by NewCommitter from an *Invocation; Run executes the configured action.
Phase 3 ships only the `commit` path. The `pull-request*` variants land in Phase 4; for now the Committer rejects them with a clear error so the integration boundary is explicit.
func NewCommitter ¶
NewCommitter constructs a Committer from an *Invocation + raw body. Returns nil + error when the invocation's RepoOwner/RepoName is missing for a path that requires GitHub API access (commit / pull-request). The caller is expected to fail fast on such errors.
type CommitterAuthor ¶
CommitterAuthor carries the commit author identity used by the Contents API call.
type ConfigError ¶
ConfigError flags a user-supplied input value that fails validation at startup. It is intentionally separate from xerrors.RetryableError (this error class is never retried). Callers should print the message verbatim + exit 1.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type HashComparator ¶
type HashComparator struct {
REST *githubapi.REST
RepoOwner string
RepoName string
Branch string
Filename string
NewBody []byte
}
HashComparator decides whether the freshly-rendered body matches the file already present in the target branch. When equal, the committer can skip the PUT /contents call so workflow runs that produce identical output don't pollute the commit log.
Spec FR-012 / FR-013. The comparison uses M3's render.Hash to avoid the per-byte differences (version literals, generated_at timestamps) that a raw bytes.Equal would mistake for "data changed".
func (*HashComparator) Equal ¶
func (c *HashComparator) Equal(ctx context.Context) (bool, error)
Equal returns true when the existing remote file's render.Hash matches the hash of NewBody. Returns (false, nil) when the remote file does not exist (404) so the committer treats first-runs as "data changed" and commits normally.
Transport errors and 5xx responses are wrapped as *xerrors.RetryableError so the RetryPolicy can retry them.
type InputError ¶
InputError signals a user-supplied input value that fails token / config validation at startup. Like ConfigError it is never retried; callers print the message + exit 1.
func (*InputError) Error ¶
func (e *InputError) Error() string
type Invocation ¶
type Invocation struct {
Mode RunMode
Inputs map[string]any
Token config.Token
Template string
Login string
Format string // "svg" / "png" / "jpeg" / "json"
Dryrun bool
OutputAction string
OutputCondition string
OutputFilename string
OutputDir string // "/renders" by default in Action mode; pwd in CLI
UseMockedData bool
NoticeReleases bool
RepoOwner string
RepoName string
RunID string // GITHUB_RUN_ID; used by pull-request* head branch naming
Branch string // committer_branch; empty = default
CommitterMessage string
CommitterAuthor string
CommitterEmail string
RetryPolicy RetryPolicy
GitHubAPIRest string
GitHubAPIGraphQL string
}
Invocation is the resolved per-run state Run / RunCLI hand off to the engine + committer pipeline. It is built from the merged inputs (INPUTS JSON / INPUT_<UPPER> / CLI flags / preset / env).
type OutputActionRegistry ¶
type OutputActionRegistry struct {
Supported []string
UnsupportedMigration map[string]string
// contains filtered or unexported fields
}
OutputActionRegistry holds the supported output_action values + the migration message map for unsupported values. The registry is returned by DefaultRegistry(); callers do not need to allocate their own.
func DefaultRegistry ¶
func DefaultRegistry() *OutputActionRegistry
DefaultRegistry returns the canonical registry for this M6 release.
Supported (6 values): none, commit, pull-request, pull-request-merge, pull-request-squash, pull-request-rebase.
Unsupported migration: gist + markdown-* + mixed forms get an explicit error message pointing at the adopted alternative.
func (*OutputActionRegistry) Validate ¶
func (r *OutputActionRegistry) Validate(value string) error
Validate returns nil iff value is one of the Supported entries. Otherwise it returns a *ConfigError suitable for fail-fast exit 1 with a migration-friendly message.
type PresetBundle ¶
PresetBundle holds the inputs overlay loaded from a preset YAML file referenced via the `config_presets` input.
func LoadPreset ¶
func LoadPreset(path string) (*PresetBundle, error)
LoadPreset reads the YAML at path and returns a PresetBundle. The expected schema is a single top-level `q:` map whose entries override individual inputs.
# example preset q: plugin_languages: true plugin_languages_limit: 5
func (*PresetBundle) MergeInto ¶
func (p *PresetBundle) MergeInto(inputs map[string]any)
MergeInto overlays the preset's q: entries onto the inputs map. Keys already present in inputs are NOT overwritten — preset values rank below CLI flag / INPUT_<UPPER> / INPUTS JSON in the priority chain.
type Quota ¶
Quota collects the per-API quota a request needs to succeed. Each plugin's metadata.yml can declare `quota_required_rest|graphql|search`; the validator sums those across the enabled plugin set.
type RateBucket ¶
RateBucket is a single API bucket's remaining + reset state.
type RateState ¶
type RateState struct {
REST RateBucket
GraphQL RateBucket
Search RateBucket
}
RateState mirrors `GET /rate_limit`'s salient fields.
type RetryPolicy ¶
type RetryPolicy struct {
Retries int // total attempts = Retries + 1
Delay time.Duration // wait between attempts
}
RetryPolicy controls retry-on-RetryableError behavior for fn calls (typically engine.Compute or committer API operations).
func (RetryPolicy) Do ¶
func (p RetryPolicy) Do(ctx context.Context, fn func() error) error
Do invokes fn up to (Retries + 1) times. It retries when fn's returned error is wrapped (anywhere in the chain) in *xerrors.RetryableError. Any other error class fails fast — no further attempts, return immediately.
errors.As is used (research R-002) so wrapped chains like fmt.Errorf("engine: %w", retryErr) are recognized correctly.
Context cancellation aborts the loop; ctx.Err() is returned even when fn's last call had not yet failed.
type RunMode ¶
type RunMode int
RunMode distinguishes Action mode (GITHUB_ACTIONS=true) from CLI mode. Set by Run / RunCLI before any business logic runs so the banner + log fields can record which path the invocation took.
type SkipReason ¶
type SkipReason string
SkipReason is the human-readable reason action.Run skipped without invoking engine.Compute. Returned by shouldSkip; logged by Run.
type TokenValidator ¶
type TokenValidator struct {
Token config.Token
REST *githubapi.REST
RequiredScopes []string
Quota Quota
UseMockedData bool
}
TokenValidator holds the inputs the 3-stage validation needs.
func (*TokenValidator) Validate ¶
func (v *TokenValidator) Validate(ctx context.Context) (ValidationResult, error)
Validate runs the 3 token-validation stages:
- Format reject: github_pat_* + empty-no-mock paths.
- Scope check: HEAD / → X-OAuth-Scopes vs RequiredScopes. Missing scopes are returned as a warning (caller logs them); not an error.
- Quota check: GET /rate_limit → compare against Quota. When remaining < required for any API, QuotaSufficient=false.
MOCKED_TOKEN (M1 convention) short-circuits past stages 2-3.
type ValidationResult ¶
ValidationResult carries the verdict of the 3 token-validation stages (format / scope / quota). Callers map it to exit codes:
- Reject* → exit 1
- QuotaSufficient=false → exit 0 (skipped)
- everything OK → continue