action

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 26 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 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. See specs/005-m6-action-cli/ for the full design corpus (plan.md / data-model.md / contracts/*).

Index

Constants

View Source
const DefaultRetries = 3

DefaultRetries is the default `retries` input value when none is supplied (action.yml + CLI both default to this). Spec FR-007.

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

func LoadYAMLConfig(path string) (map[string]any, error)

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

func ParseInputs(env map[string]string) (map[string]any, error)

ParseInputs builds the unified inputs map used by both Action mode and CLI mode. Priority (highest first):

  1. 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).
  2. 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). Spec FR-001.

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

func ResolveOutputWriter(filename, format string) (io.Writer, func() error, error)

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

func ResolveToken(cf *CLIFlags, envLookup func(string) string, inputToken string) (string, error)

ResolveToken applies the CLI token priority rules (contracts §4):

--token-env > --token (with warning) > INPUT_TOKEN > error

`envLookup` is dependency-injected (defaults to os.Getenv) so tests can run hermetically.

func Run

func Run(ctx context.Context) error

Run is the Action-mode entry point. Spec FR-001 / FR-002.

Pipeline:

  1. Skip detection — short-circuits when GITHUB_EVENT_PATH commit message contains "[Skip GitHub Action]" or "Auto-generated metrics for run #N".
  2. Input parsing — merges INPUTS JSON + INPUT_<UPPER>.
  3. Output_action validation — fail-fast on gist / markdown-*.
  4. Token validation — github_pat_* reject + scope check + quota check. Quota insufficient → exit 0 (skipped).
  5. Banner print (English fixed, slog-handler-agnostic).
  6. engine.Compute (wrapped in RetryPolicy).
  7. Write output to OutputDir/OutputFilename.
  8. Committer.Run (commit / pull-request*) unless Dryrun.
  9. SetOutput metrics_url + metrics_sha to $GITHUB_OUTPUT.

func RunCLI

func RunCLI(ctx context.Context, args []string) error

RunCLI is the CLI-mode entry point (spec FR-019). Pipeline:

  1. Parse flags (T034) + load --config YAML (T035).
  2. Merge inputs via CLIFlags.ToInvocation (T036).
  3. Resolve token (T037) — flag > env > error.
  4. newInvocation + output_action validation (shared with Action).
  5. Banner + engine.Compute + retry policy (shared).
  6. Write output to --filename or stdout (T038).
  7. Committer dispatch unless --dryrun.

func SetOutput

func SetOutput(key, value string) error

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

func WildcardFilename(template, format string) (string, error)

WildcardFilename resolves the `*` placeholder in a filename like `github-metrics.*` using the configured output format. Spec FR-008.

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. Spec data-model E-004 + contracts/cli-flags.md.

The fields map 1:1 onto action.yml inputs so the merged *Invocation produced by ToInvocation is interchangeable with the Action-mode pipeline (FR-019).

func ParseFlags

func ParseFlags(args []string) (*CLIFlags, error)

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

func (c *CLIFlags) ToInvocation(env map[string]string) (map[string]any, error)

ToInvocation merges CLI flags (highest priority), YAML config, env, and metadata defaults into a flat `map[string]any` suitable for newInvocation. Spec contracts/cli-flags.md §3.

Priority (highest first):

  1. CLI flag (--user, --plugin key=val, ...)
  2. --config <path>.yaml
  3. --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).
  4. INPUT_<UPPER> env variables (loaded via ParseInputs).
  5. 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. Spec FR-012 / FR-013.
	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 (T029-T031); for now the Committer rejects them with a clear error so the integration boundary is explicit.

func NewCommitter

func NewCommitter(rest *githubapi.REST, inv *Invocation, body []byte) (*Committer, error)

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.

func (*Committer) Run

func (c *Committer) Run(ctx context.Context) error

Run dispatches to the per-action sequence.

type CommitterAuthor

type CommitterAuthor struct {
	Name  string
	Email string
}

CommitterAuthor carries the commit author identity used by the Contents API call.

type ConfigError

type ConfigError struct {
	Key   string
	Value string
	Msg   string
}

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 — see contracts/retry-policy.md). 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

type InputError struct {
	Key string
	Msg string
}

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. Spec FR-015b + contracts/output-actions.md.

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 (FR-015b).

type PresetBundle

type PresetBundle struct {
	Path string         // source file path
	Q    map[string]any // input overrides
}

PresetBundle holds the inputs overlay loaded from a preset YAML file referenced via the `config_presets` input. Spec FR-006.

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 (see contracts/cli-flags.md §3).

type Quota

type Quota struct {
	REST    int
	GraphQL int
	Search  int
}

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

type RateBucket struct {
	Remaining int
	Limit     int
	Reset     time.Time
}

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.

const (
	// ModeAction = GitHub Actions runtime (GITHUB_ACTIONS=true).
	ModeAction RunMode = iota
	// ModeCLI = local / scripted CLI invocation.
	ModeCLI
)

func (RunMode) String

func (m RunMode) String() string

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 per contracts/token-validation.md.

  1. Format reject: github_pat_* + empty-no-mock paths.
  2. Scope check: HEAD / → X-OAuth-Scopes vs RequiredScopes. Missing scopes are returned as a warning (caller logs them); not an error.
  3. 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

type ValidationResult struct {
	MissingScopes   []string
	QuotaSufficient bool
	RateState       *RateState
}

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

Jump to

Keyboard shortcuts

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