config

package
v1.2.13 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 12 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 config holds settings, metadata, and inputs loaders for github-metrics. The Token type in this file is the opaque wrapper for credentials that the rest of the codebase must use instead of bare strings, so leaking a raw token via fmt.Sprintf, log output, or JSON marshalling becomes impossible by construction.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalizeInput

func NormalizeInput(def InputDef, raw any) (any, error)

NormalizeInput converts raw (typically a string from env or YAML decoding) into the Go value implied by def.Type. The supported types are the set declared in [allowedInputTypes]. Unsupported types return an InputError-style error; type-coercion failures likewise return an error so callers can surface them on the upstream-compatible warning path.

Empty / nil raw plus a non-empty Default node falls back to the default value rendered through the same normalization.

Types

type APISettings

type APISettings struct {
	REST    string `json:"rest"`
	GraphQL string `json:"graphql"`
}

APISettings overrides the default GitHub REST and GraphQL endpoints.

type ActionInputDef

type ActionInputDef struct {
	Description string `yaml:"description"`
	Default     string `yaml:"default"`
	Required    bool   `yaml:"required"`
}

ActionInputDef is the simpler shape used by action.yml.

type ActionMetadata

type ActionMetadata struct {
	Name        string                    `yaml:"name"`
	Description string                    `yaml:"description"`
	Author      string                    `yaml:"author"`
	Branding    map[string]string         `yaml:"branding"`
	Runs        map[string]any            `yaml:"runs"`
	Inputs      map[string]ActionInputDef `yaml:"inputs"`
}

ActionMetadata is the parsed action.yml at the repository root.

type CommunitySettings

type CommunitySettings struct {
	Templates []string `json:"templates"`
}

CommunitySettings enumerates the community-template names a Web instance is willing to download. Unused by M1.

type Control

type Control struct {
	Token string `json:"token"`
}

Control holds the upstream control-plane token (Web feature).

type DataView

type DataView struct {
	UserLogin      string
	UserName       string
	RepositoryName string
	RepositoryFull string
}

DataView is the minimal subset of engine data needed to resolve inputs placeholders. The engine package wraps a richer Data into a DataView before calling Inputs.ForData, so internal/config does not import internal/engine.

type Extras

type Extras struct {
	Default  bool            `json:"default"`
	Features json.RawMessage `json:"features"`
	Logged   []string        `json:"logged"`
}

Extras retains the upstream JSON shape (features can be bool or []string).

type Hosted

type Hosted struct {
	By   string `json:"by"`
	Link string `json:"link"`
}

Hosted records the optional "hosted by" attribution displayed in the upstream web instance footer.

type InputDef

type InputDef struct {
	Description string     `yaml:"description"`
	Type        string     `yaml:"type"`
	Format      StringList `yaml:"format"`
	Default     yaml.Node  `yaml:"default"`
	Values      []string   `yaml:"values"`
	Min         *float64   `yaml:"min"`
	Max         *float64   `yaml:"max"`
	Global      bool       `yaml:"global"`
	Preset      *bool      `yaml:"preset"`
	Extras      []string   `yaml:"extras"`
}

InputDef captures the relevant fields of an input definition inside a plugin or template metadata.yml. Default is kept as a yaml.Node so the loader does not have to commit to a Go type at parse time — the input normalizer ([Inputs.Normalize]) interprets it against the declared type at use site.

type Inputs

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

Inputs is the per-scope normalized view of inputs keyed by metadata input name.

func NewInputs

func NewInputs(defs map[string]InputDef) *Inputs

NewInputs returns an Inputs ready to ingest values for the provided definition map. The defs typically come from [MetadataLoader.Plugins[...].Inputs] merged with the corresponding template inputs.

func (*Inputs) ForAction

func (i *Inputs) ForAction(env map[string]string, preset map[string]any) (map[string]any, error)

ForAction reads action-style inputs (INPUTS JSON + INPUT_<UPPER> environment variables), applies any preset overrides, normalizes each value against the input definition, and returns a flat map ready for PluginContext consumption.

Resolution order (from highest to lowest precedence):

  1. INPUTS JSON keys (when present)
  2. INPUT_<UPPER> environment values
  3. preset overrides
  4. metadata default

The function leaves placeholders (`.user.login`, `.repository.name`, ...) intact unless an explicit data context has been wired in via [Inputs.WithData]; the engine resolves them later.

func (*Inputs) ForData

func (i *Inputs) ForData(q map[string]any, data *DataView, account string) map[string]any

ForData is invoked once `data.User` (and friends) are populated; the resolver knows how to substitute `.user.login` and similar placeholders. M1 callers may pass nil for data — placeholders then pass through unchanged.

func (*Inputs) ForWeb

func (i *Inputs) ForWeb(query map[string][]string) (map[string]any, error)

ForWeb reads a url.Values-like map (web instance flow); the upstream behavior is mostly identical to ForAction without the INPUTS JSON hop. Implemented here for parity even though Web is not part of M1 scope (constitution principle III honors the input contract).

type LoadOptions

type LoadOptions struct {
	// ActionPath is the path inside fsys for action.yml. Empty value
	// disables action.yml parsing (useful in tests that only exercise
	// plugin/template metadata).
	ActionPath string
	// VersionPath is the path inside fsys for version.txt. Empty value
	// skips version capture.
	VersionPath string
	// Logger is used for warn-level messages (e.g. unknown input type).
	// nil falls back to slog.Default().
	Logger *slog.Logger
}

LoadOptions controls non-default Load behavior.

type MetadataLoader

type MetadataLoader struct {
	Plugins   map[string]*PluginMetadata
	Templates map[string]*TemplateMetadata
	Action    *ActionMetadata
	Package   *PackageMetadata
}

MetadataLoader aggregates every metadata.yml-shaped artifact the engine needs at runtime. It is read-only after [Load] completes.

func LoadMetadata

func LoadMetadata(fsys fs.FS, opts LoadOptions) (*MetadataLoader, error)

LoadMetadata walks the embedded filesystem rooted at fsys, reading every metadata.yml beneath plugins/ and templates/, plus an optional action.yml and version.txt. Unknown input types are logged at warn level and the offending input is dropped (constitution edge case for forward compatibility); other parse errors abort the load.

func (*MetadataLoader) Extras

func (m *MetadataLoader) Extras(scope, feature string) bool

Extras reports whether a given extras feature flag is enabled for the plugin/template named scope. Upstream encodes extras as a list of dotted feature names on PluginMetadata.Inputs[...].Extras; this helper keeps callers from reaching into the map.

func (*MetadataLoader) PluginNames

func (m *MetadataLoader) PluginNames() []string

PluginNames returns plugin keys sorted alphabetically (deterministic for golden file comparisons).

func (*MetadataLoader) TemplateNames

func (m *MetadataLoader) TemplateNames() []string

TemplateNames returns template keys sorted alphabetically.

func (*MetadataLoader) ToAction

func (m *MetadataLoader) ToAction(key string) string

ToAction returns the action.yml input key corresponding to a logical metadata key. Upstream collapses keys directly (no rewriting) — we preserve that behavior so existing user workflows remain compatible.

func (*MetadataLoader) ToQuery

func (m *MetadataLoader) ToQuery(key string) string

ToQuery returns the internal query map key for an input.

func (*MetadataLoader) ToWeb

func (m *MetadataLoader) ToWeb(key string) string

ToWeb returns the web query parameter for a key (alias of ToAction in upstream).

type MockFlag

type MockFlag struct {
	Enabled bool
	Force   bool
}

MockFlag accepts either a bool or the literal "force" string per upstream.

func (MockFlag) MarshalJSON

func (m MockFlag) MarshalJSON() ([]byte, error)

MarshalJSON mirrors UnmarshalJSON shape.

func (*MockFlag) UnmarshalJSON

func (m *MockFlag) UnmarshalJSON(b []byte) error

UnmarshalJSON parses bool or "force".

type OAuth

type OAuth struct {
	ID     string `json:"id"`
	Secret string `json:"secret"`
	URL    string `json:"url"`
}

OAuth carries upstream OAuth client credentials. Unused by M1 (Web is not adopted) but the keys are retained per constitution principle I.

type OptimizeFlag

type OptimizeFlag struct {
	Enabled bool
	Passes  []string
}

OptimizeFlag accepts either a bool or a list of optimization passes (e.g. ["css", "xml", "svg"]). The custom unmarshaller normalizes both shapes into the same struct so callers can branch with one check.

func (OptimizeFlag) MarshalJSON

func (f OptimizeFlag) MarshalJSON() ([]byte, error)

MarshalJSON keeps round-trip safety for the more expressive form.

func (*OptimizeFlag) UnmarshalJSON

func (f *OptimizeFlag) UnmarshalJSON(b []byte) error

UnmarshalJSON parses bool or []string per upstream conventions.

type PackageMetadata

type PackageMetadata struct {
	UpstreamVersion string
}

PackageMetadata carries the upstream version captured by sync-assets.sh in assets/version.txt.

type PluginMetadata

type PluginMetadata struct {
	Name        string              `yaml:"name"`
	Category    string              `yaml:"category"`
	Description string              `yaml:"description"`
	Index       int                 `yaml:"index"`
	Supports    []string            `yaml:"supports"`
	Scopes      []string            `yaml:"scopes"`
	Inputs      map[string]InputDef `yaml:"inputs"`
	Examples    map[string]string   `yaml:"examples"`
}

PluginMetadata is the parsed assets/plugins/<name>/metadata.yml shape.

type PluginSettings

type PluginSettings struct {
	Enabled bool           `json:"enabled"`
	Extra   map[string]any `json:"-"`
}

PluginSettings carries per-plugin overrides. Extra fields are captured verbatim so plugin-specific keys (tokens, API endpoints, etc.) round-trip unchanged.

func (*PluginSettings) UnmarshalJSON

func (p *PluginSettings) UnmarshalJSON(b []byte) error

UnmarshalJSON splits the canonical "enabled" key from everything else.

type Ratelimiter

type Ratelimiter struct {
	Max int `json:"max"`
	// Window keeps the upstream "windowMs" JSON tag (constitution
	// principle I) but uses an idiomatic Go field name without the
	// unit-specific suffix that staticcheck ST1011 flags.
	Window time.Duration `json:"windowMs"`
}

Ratelimiter mirrors the upstream express-rate-limit fields the project consumes.

type Settings

type Settings struct {
	Token          string                    `json:"token"`
	Modes          []string                  `json:"modes"`
	Restricted     []string                  `json:"restricted"`
	MaxUsers       int                       `json:"maxusers"`
	Cached         int                       `json:"cached"`
	Ratelimiter    *Ratelimiter              `json:"ratelimiter"`
	Port           int                       `json:"port"`
	Optimize       OptimizeFlag              `json:"optimize"`
	Debug          bool                      `json:"debug"`
	DebugHeadless  bool                      `json:"debug.headless"`
	Mocked         MockFlag                  `json:"mocked"`
	Repositories   int                       `json:"repositories"`
	Padding        []string                  `json:"padding"`
	Outputs        []string                  `json:"outputs"`
	Hosted         Hosted                    `json:"hosted"`
	OAuth          *OAuth                    `json:"oauth"`
	API            APISettings               `json:"api"`
	Control        Control                   `json:"control"`
	Community      CommunitySettings         `json:"community"`
	Templates      TemplatesSettings         `json:"templates"`
	Extras         Extras                    `json:"extras"`
	PluginsDefault bool                      `json:"plugins.default"`
	Plugins        map[string]PluginSettings `json:"plugins"`
	Sandbox        bool                      `json:"sandbox"`
	Web            *WebSettings              `json:"web,omitempty"`
}

Settings mirrors the upstream lowlighter/metrics settings.json schema (data-model E-001). The Web-only sub-structs (OAuth, Control, Hosted, Community, Web) are retained so the key set stays upstream-compatible (constitution principle I) even though M1 does not implement the Web instance.

func LoadSettings

func LoadSettings(path string) (*Settings, error)

LoadSettings reads settings.json from path (creating defaults when absent), strips // comment keys, applies Sandbox enforcement when requested, and returns the resulting Settings.

Absent path returns Settings{Port: defaultPort}.

func LoadSettingsReader

func LoadSettingsReader(r io.Reader) (*Settings, error)

LoadSettingsReader is the io.Reader variant of LoadSettings, mainly used by tests.

func (*Settings) NoToken

func (s *Settings) NoToken() bool

NoToken reports whether the explicit "NOT_NEEDED" sentinel is set. The bare empty string is intentionally treated as "absent" rather than "no token" to keep parity with upstream behavior.

type StringList

type StringList []string

StringList accepts either a single scalar or a YAML sequence and normalizes both into a slice. Some upstream metadata.yml fields (notably `format` and `values`) come in either shape.

func (*StringList) UnmarshalYAML

func (s *StringList) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type TemplateMetadata

type TemplateMetadata struct {
	Name        string              `yaml:"name"`
	Description string              `yaml:"description"`
	Index       int                 `yaml:"index"`
	Supports    []string            `yaml:"supports"`
	Formats     []string            `yaml:"formats"`
	Inputs      map[string]InputDef `yaml:"inputs"`
	Examples    map[string]string   `yaml:"examples"`
}

TemplateMetadata is the parsed assets/templates/<name>/metadata.yml shape.

type TemplatesSettings

type TemplatesSettings struct {
	Default string   `json:"default"`
	Enabled []string `json:"enabled"`
}

TemplatesSettings configures which named templates are enabled and which one is the engine's default.

type Token

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

Token is an opaque holder for a GitHub credential. Its zero value is safe to use and reports as empty in every observable surface (Stringer, GoStringer, MarshalJSON). Callers retrieve the underlying secret with Token.Reveal only at the network boundary (internal/githubapi).

func NewToken

func NewToken(raw string) Token

NewToken wraps a raw credential string. Empty input yields a zero- value token which subsequent calls treat as "absent".

func (Token) GoString

func (t Token) GoString() string

GoString mirrors String so %#v formatting is also safe.

func (Token) MarshalJSON

func (t Token) MarshalJSON() ([]byte, error)

MarshalJSON ensures encoding/json output never exposes the raw value; it surfaces the same placeholder used by String.

func (Token) Present

func (t Token) Present() bool

Present reports whether the token carries a non-empty credential.

func (Token) Reveal

func (t Token) Reveal() string

Reveal returns the raw credential. Call sites are intentionally limited to internal/githubapi and test helpers — grep for it during code review to keep the surface narrow.

func (Token) String

func (t Token) String() string

String reports a placeholder so accidental fmt.Print or slog logging cannot leak the credential. Empty tokens return an empty string so "(provided)" never appears for absent credentials.

type WebSettings

type WebSettings struct {
	Static string `json:"static"`
}

WebSettings is reserved for the Web instance (not implemented in M1).

Jump to

Keyboard shortcuts

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