Move facade to the root package

This commit is contained in:
2026-09-12 16:21:17 +00:00
parent 550f92d7c6
commit 7f46c947dd
84 changed files with 176 additions and 14739 deletions

View File

@@ -1,133 +0,0 @@
package configkit
import "gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
func fromEngineLocation(value engine.Location) Location {
return Location{SourceID: value.SourceID, Line: value.Line, Column: value.Column}
}
func toEngineLocation(value Location) engine.Location {
return engine.Location{SourceID: value.SourceID, Line: value.Line, Column: value.Column}
}
func fromEngineLocationPointer(value *engine.Location) *Location {
if value == nil {
return nil
}
result := fromEngineLocation(*value)
return &result
}
func toEngineLocationPointer(value *Location) *engine.Location {
if value == nil {
return nil
}
result := toEngineLocation(*value)
return &result
}
func fromEngineLocations(values []engine.Location) []Location {
if values == nil {
return nil
}
result := make([]Location, len(values))
for i := range values {
result[i] = fromEngineLocation(values[i])
}
return result
}
func toEngineLocations(values []Location) []engine.Location {
if values == nil {
return nil
}
result := make([]engine.Location, len(values))
for i := range values {
result[i] = toEngineLocation(values[i])
}
return result
}
func fromEngineSourceInfo(value engine.SourceInfo) SourceInfo {
return SourceInfo{ID: value.ID, Label: value.Label, Path: value.Path, Layer: Layer(value.Layer), ImportedFrom: fromEngineLocationPointer(value.ImportedFrom)}
}
func toEngineSourceInfo(value SourceInfo) engine.SourceInfo {
return engine.SourceInfo{ID: value.ID, Label: value.Label, Path: value.Path, Layer: engine.Layer(value.Layer), ImportedFrom: toEngineLocationPointer(value.ImportedFrom)}
}
func fromEngineOrigin(value engine.Origin) Origin {
return Origin{Layer: Layer(value.Layer), Locations: fromEngineLocations(value.Locations), Operation: ChangeKind(value.Operation)}
}
func toEngineOrigin(value Origin) engine.Origin {
return engine.Origin{Layer: engine.Layer(value.Layer), Locations: toEngineLocations(value.Locations), Operation: engine.ChangeKind(value.Operation)}
}
func fromEngineDiagnostic(value engine.Diagnostic) Diagnostic {
return Diagnostic{Code: Code(value.Code), Severity: Severity(value.Severity), Path: fromEnginePath(value.Path), Message: value.Message, Primary: fromEngineLocationPointer(value.Primary), Related: fromEngineLocations(value.Related)}
}
func toEngineDiagnostic(value Diagnostic) engine.Diagnostic {
return engine.Diagnostic{Code: engine.Code(value.Code), Severity: engine.Severity(value.Severity), Path: toEnginePath(value.Path), Message: value.Message, Primary: toEngineLocationPointer(value.Primary), Related: toEngineLocations(value.Related)}
}
func toEngineDiagnostics(values []Diagnostic) []engine.Diagnostic {
if values == nil {
return nil
}
result := make([]engine.Diagnostic, len(values))
for i := range values {
result[i] = toEngineDiagnostic(values[i])
}
return result
}
func fromEngineFieldInfo(value engine.FieldInfo) FieldInfo {
return FieldInfo{Explicit: value.Explicit, Null: value.Null, Origin: fromEngineOrigin(value.Origin)}
}
func fromEngineChange(value engine.Change) Change {
result := Change{Path: fromEnginePath(value.Path), Origin: fromEngineOrigin(value.Origin), Reasons: append([]string(nil), value.Reasons...)}
if value.Previous != nil {
result.Previous = make([]Origin, len(value.Previous))
for i := range value.Previous {
result.Previous[i] = fromEngineOrigin(value.Previous[i])
}
}
if value.Dependencies != nil {
result.Dependencies = make([]Path, len(value.Dependencies))
for i := range value.Dependencies {
result.Dependencies[i] = fromEnginePath(value.Dependencies[i])
}
}
return result
}
func fromEngineValueSnapshot(value engine.ValueSnapshot) ValueSnapshot {
return ValueSnapshot{Present: value.Present, Redacted: value.Redacted, YAML: value.YAML}
}
func fromEngineValueChange(value engine.ValueChange) ValueChange {
result := ValueChange{
Before: fromEngineValueSnapshot(value.Before),
After: fromEngineValueSnapshot(value.After),
Origin: fromEngineOrigin(value.Origin),
Reasons: append([]string(nil), value.Reasons...),
}
if value.Dependencies != nil {
result.Dependencies = make([]Path, len(value.Dependencies))
for index := range value.Dependencies {
result.Dependencies[index] = fromEnginePath(value.Dependencies[index])
}
}
return result
}
func fromEngineExplanation(value engine.Explanation) Explanation {
result := Explanation{
Path: fromEnginePath(value.Path),
Effective: fromEngineValueSnapshot(value.Effective),
Origin: fromEngineOrigin(value.Origin),
}
if value.History != nil {
result.History = make([]ValueChange, len(value.History))
for index := range value.History {
result.History[index] = fromEngineValueChange(value.History[index])
}
}
if value.SecretReference != nil {
result.SecretReference = &SecretReferenceInfo{Name: value.SecretReference.Name}
}
return result
}
func fromEngineSecretFileResult(value engine.SecretFileResult) SecretFileResult {
return SecretFileResult{Name: value.Name, Path: value.Path, Status: SecretFileStatus(value.Status), ExistingEmpty: value.ExistingEmpty}
}

View File

@@ -1,50 +0,0 @@
package configkit
import (
"io"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// LoadError reports safe structured diagnostics for a failed configuration load.
type LoadError struct{ value *engine.LoadError }
func (e *LoadError) Error() string {
if e == nil || e.value == nil {
return "configkit: configuration load failed"
}
return e.value.Error()
}
func (e *LoadError) Diagnostics() []Diagnostic {
if e == nil || e.value == nil {
return nil
}
values := e.value.Diagnostics()
if values == nil {
return nil
}
result := make([]Diagnostic, len(values))
for i := range values {
result[i] = fromEngineDiagnostic(values[i])
}
return result
}
func (e *LoadError) Sources() []SourceInfo {
if e == nil || e.value == nil {
return nil
}
values := e.value.Sources()
if values == nil {
return nil
}
result := make([]SourceInfo, len(values))
for i := range values {
result[i] = fromEngineSourceInfo(values[i])
}
return result
}
// WriteDiagnostics writes diagnostics in canonical order.
func WriteDiagnostics(output io.Writer, diagnostics []Diagnostic) error {
return engine.WriteDiagnostics(output, toEngineDiagnostics(diagnostics))
}

View File

@@ -1,272 +0,0 @@
package configkit_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"reflect"
"strings"
"testing"
configkit "gitea.maximumdirect.net/eric/ConfigKit/internal/facade"
)
var (
_ error = (*configkit.LoadError)(nil)
_ fmt.Formatter = configkit.Secret{}
_ fmt.Stringer = configkit.Path{}
_ json.Marshaler = configkit.Secret{}
)
func TestFacadeValuesRemainRootOwned(t *testing.T) {
t.Parallel()
const packagePath = "gitea.maximumdirect.net/eric/ConfigKit/internal/facade"
for _, candidate := range []reflect.Type{
reflect.TypeFor[configkit.Path](), reflect.TypeFor[configkit.Source](),
reflect.TypeFor[configkit.Secret](), reflect.TypeFor[configkit.Diagnostic](),
reflect.TypeFor[configkit.LoadError](), reflect.TypeFor[configkit.Metadata](),
reflect.TypeFor[configkit.Resolution](), reflect.TypeFor[configkit.Validation](),
reflect.TypeFor[configkit.Version](), reflect.TypeFor[configkit.VersionRule](),
reflect.TypeFor[configkit.FilesystemContext](), reflect.TypeFor[configkit.Override](),
reflect.TypeFor[configkit.Definition[struct{}]](), reflect.TypeFor[configkit.Options[struct{}]](),
reflect.TypeFor[configkit.Result[struct{}]](),
reflect.TypeFor[configkit.ValueSnapshot](), reflect.TypeFor[configkit.ValueChange](),
reflect.TypeFor[configkit.SecretReferenceInfo](), reflect.TypeFor[configkit.Explanation](),
reflect.TypeFor[configkit.SecretFileResult](), reflect.TypeFor[configkit.SecretsReport](),
reflect.TypeFor[configkit.SecretsError](),
} {
if candidate.PkgPath() != packagePath {
t.Fatalf("type %s belongs to %q", candidate, candidate.PkgPath())
}
}
secret := configkit.SecretEnv("SAFE_NAME")
formatted := fmt.Sprintf("%#v", secret)
encoded, err := json.Marshal(secret)
if formatted == "" || err != nil || string(encoded) != `"SAFE_NAME"` {
t.Fatalf("secret rendering = %q, %s, %v", formatted, encoded, err)
}
if got := configkit.Keys("a/b~").Index(0).String(); got != "/a~1b~0/0" {
t.Fatalf("path = %q", got)
}
if got := (&configkit.LoadError{}).Error(); got != "configkit: configuration load failed" {
t.Fatalf("zero LoadError = %q", got)
}
}
func TestFacadeInspectionUsesFrozenState(t *testing.T) {
t.Setenv("FACADE_INSPECTION_SECRET", "credential")
type configuration struct {
Value string `yaml:"value"`
Secret configkit.Secret `yaml:"secret"`
}
result, err := configkit.Load[configuration](configkit.Bytes("inspection.yml", []byte("value: original\nsecret: FACADE_INSPECTION_SECRET\n")))
if err != nil {
t.Fatal(err)
}
if !result.Config.Secret.IsResolved() || result.Config.Secret.Value() != "credential" {
t.Fatalf("secret = %#v", result.Config.Secret)
}
explanation, ok := result.Explain(configkit.Keys("value"))
if !ok || explanation.Effective.YAML != "original\n" {
t.Fatalf("explanation = %#v, %v", explanation, ok)
}
explanation.Effective.YAML = "mutated\n"
result.Config.Value = "mutated"
var effective bytes.Buffer
if err := result.WriteEffective(&effective); err != nil || !strings.Contains(effective.String(), "value: original\n") || strings.Contains(effective.String(), "credential") {
t.Fatalf("effective = %q, %v", effective.String(), err)
}
again, ok := result.Explain(configkit.Keys("value"))
if !ok || again.Effective.YAML != "original\n" {
t.Fatalf("inspection changed = %#v, %v", again, ok)
}
secret, ok := result.Explain(configkit.Keys("secret"))
if !ok || secret.SecretReference == nil || secret.SecretReference.Name != "FACADE_INSPECTION_SECRET" {
t.Fatalf("secret explanation = %#v, %v", secret, ok)
}
var explanationOutput bytes.Buffer
if err := result.WriteExplanation(&explanationOutput, configkit.Keys("value")); err != nil || !strings.Contains(explanationOutput.String(), `path: "/value"`) {
t.Fatalf("explanation output = %q, %v", explanationOutput.String(), err)
}
unknown := bytes.NewBufferString("unchanged")
if err := result.WriteExplanation(unknown, configkit.Keys("unknown")); err == nil || unknown.String() != "unchanged" {
t.Fatalf("unknown explanation = %q, %v", unknown.String(), err)
}
var nilResult *configkit.Result[configuration]
if _, ok := nilResult.Explain(configkit.Keys("value")); ok {
t.Fatal("nil result explained a path")
}
if err := nilResult.WriteEffective(io.Discard); err == nil {
t.Fatal("nil result rendered effective configuration")
}
}
func TestFacadeSecretsBootstrapUsesFacadeRecords(t *testing.T) {
const (
loadedName = "FACADE_BOOTSTRAP_LOADED"
existingName = "FACADE_BOOTSTRAP_EXISTING"
)
restore := func(name string) {
value, present := os.LookupEnv(name)
t.Cleanup(func() {
if present {
_ = os.Setenv(name, value)
} else {
_ = os.Unsetenv(name)
}
})
}
restore(loadedName)
restore(existingName)
if err := os.Unsetenv(loadedName); err != nil {
t.Fatal(err)
}
if err := os.Setenv(existingName, ""); err != nil {
t.Fatal(err)
}
directory := t.TempDir()
if err := os.WriteFile(directory+"/"+loadedName, []byte("bootstrap\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(directory+"/"+existingName, []byte("ignored\n"), 0o600); err != nil {
t.Fatal(err)
}
report, err := configkit.LoadSecretsDir(directory)
if err != nil {
t.Fatal(err)
}
entries := report.Entries()
if len(entries) != 2 || os.Getenv(loadedName) != "bootstrap" {
t.Fatalf("entries/environment = %#v / %q", entries, os.Getenv(loadedName))
}
status := map[string]configkit.SecretFileResult{}
for _, entry := range entries {
status[entry.Name] = entry
}
if status[loadedName].Status != configkit.SecretFileLoaded || status[existingName].Status != configkit.SecretFileSkippedExisting || !status[existingName].ExistingEmpty {
t.Fatalf("statuses = %#v", status)
}
entries[0].Name = "mutated"
if report.Entries()[0].Name == "mutated" {
t.Fatal("report entries share mutable state")
}
var rendered bytes.Buffer
if _, err := report.WriteTo(&rendered); err != nil || strings.Contains(rendered.String(), "bootstrap") || strings.Contains(rendered.String(), "ignored") {
t.Fatalf("report rendering = %q, %v", rendered.String(), err)
}
failedReport, err := configkit.LoadSecretsDir("")
var secretsError *configkit.SecretsError
if failedReport == nil || !errors.As(err, &secretsError) || len(secretsError.Diagnostics()) != 1 || secretsError.Diagnostics()[0].Code != configkit.CodeSecretsInvalidPath {
t.Fatalf("bootstrap failure = %#v / %#v", failedReport, err)
}
}
func TestFacadeLoadBridgesLifecycleCallbacks(t *testing.T) {
t.Setenv("FACADE_SECRET_NAME", "credential")
type configuration struct {
Version string `yaml:"version"`
Input int `yaml:"input"`
Derived int `yaml:"derived"`
Secret configkit.Secret `yaml:"secret"`
Labels map[string]string `yaml:"labels"`
}
var retainedResolution *configkit.Resolution
var retainedValidation *configkit.Validation
versionCalls, defaultsCalls, resolveCalls, validateCalls := 0, 0, 0, 0
definition := configkit.Definition[configuration]{
Version: &configkit.VersionRule{Path: configkit.Keys("version"), Check: func(version configkit.Version, validation *configkit.Validation) error {
versionCalls++
retainedValidation = validation
if !version.Present || version.Text != "1" {
validation.Error(configkit.Keys("version"), "unsupported version")
}
return nil
}},
Defaults: func() configuration {
defaultsCalls++
return configuration{Derived: 1, Labels: map[string]string{"default": "kept"}}
},
Resolve: func(configuration *configuration, resolution *configkit.Resolution) error {
resolveCalls++
retainedResolution = resolution
if !resolution.IsExplicit(configkit.Keys("input")) {
resolution.Error(configkit.Keys("input"), "input is required")
}
input, ok := resolution.InputInfo(configkit.Keys("input"))
if !ok || !input.Explicit {
resolution.Error(configkit.Keys("input"), "missing input provenance")
}
source, ok := resolution.Source("source-1")
if !ok || source.Label != "facade.yml" {
resolution.Error(configkit.Keys("input"), "missing source")
}
configkit.Default(resolution, configkit.Keys("derived"), &configuration.Derived, configuration.Input*2, "derived from input", configkit.Keys("input"))
return nil
},
Validate: func(configuration *configuration, validation *configkit.Validation) {
validateCalls++
retainedValidation = validation
if !configuration.Secret.IsResolved() || configuration.Secret.Value() != "credential" {
validation.Error(configkit.Keys("secret"), "secret did not resolve")
}
},
}
if versionCalls != 0 || defaultsCalls != 0 || resolveCalls != 0 || validateCalls != 0 {
t.Fatal("callbacks ran while constructing options")
}
result, err := configkit.Load(configkit.Bytes("facade.yml", []byte("version: 1\ninput: 3\nsecret: FACADE_SECRET_NAME\n")), configkit.Options[configuration]{Definition: definition})
if err != nil {
t.Fatal(err)
}
if versionCalls != 1 || defaultsCalls != 1 || resolveCalls != 1 || validateCalls != 1 || result.Config.Derived != 6 {
t.Fatalf("callback counts/configuration = %d/%d/%d/%d %#v", versionCalls, defaultsCalls, resolveCalls, validateCalls, result.Config)
}
derived, ok := result.Metadata().Lookup(configkit.Keys("derived"))
if !ok || derived.Explicit || derived.Origin.Operation != configkit.ChangeDerivedDefault {
t.Fatalf("derived metadata = %#v, %v", derived, ok)
}
if sources := result.Sources(); len(sources) != 1 || sources[0].Label != "facade.yml" {
t.Fatalf("sources = %#v", sources)
}
if result.Diagnostics() != nil {
t.Fatalf("diagnostics = %#v", result.Diagnostics())
}
for _, context := range []func(){
func() { retainedResolution.IsExplicit(configkit.Keys("input")) },
func() { retainedValidation.Warning(configkit.Keys("input"), "too late") },
} {
func() {
defer func() {
if recover() == nil {
t.Fatal("retained callback context remained active")
}
}()
context()
}()
}
}
func TestFacadeLoadReturnsFacadeLoadError(t *testing.T) {
t.Parallel()
type configuration struct {
Value int `yaml:"value"`
}
result, err := configkit.Load[configuration](configkit.Bytes("invalid.yml", []byte("value: wrong\n")))
if result != nil || err == nil {
t.Fatalf("result, err = %#v, %v", result, err)
}
var loadError *configkit.LoadError
if !errors.As(err, &loadError) || len(loadError.Diagnostics()) != 1 || loadError.Diagnostics()[0].Code != configkit.CodeDecodeType {
t.Fatalf("facade error = %#v", err)
}
}

View File

@@ -1,52 +0,0 @@
package configkit
import (
"errors"
"reflect"
"strings"
"testing"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
func TestWrappedSourcesPreserveEngineOwnership(t *testing.T) {
t.Parallel()
type config struct {
Value string `yaml:"value"`
}
data := []byte("value: retained\n")
source := Bytes("snapshot.yml", data)
data[7] = 'X'
result, err := engine.Load[config](source.toEngine(), engine.SecretBinding{})
if err != nil || result.Config.Value != "retained" {
t.Fatalf("snapshotted source = %#v, %v", result, err)
}
readerSource := Reader("reader.yml", strings.NewReader("value: once\n"))
first := readerSource
if _, err := engine.Load[config](first.toEngine(), engine.SecretBinding{}); err != nil {
t.Fatal(err)
}
_, err = engine.Load[config](readerSource.toEngine(), engine.SecretBinding{})
var loadError *engine.LoadError
if !errors.As(err, &loadError) || len(loadError.Diagnostics()) != 1 || loadError.Diagnostics()[0].Code != engine.CodeSourceReaderUsed {
t.Fatalf("copied reader source error = %#v", err)
}
}
func TestWrappedPathsRetainEngineSegmentIntent(t *testing.T) {
t.Parallel()
parsed, err := ParsePath("/0")
if err != nil {
t.Fatal(err)
}
keyed, indexed := Keys("0"), Path{}.Index(0)
if parsed.String() != "/0" || keyed.String() != "/0" || indexed.String() != "/0" {
t.Fatalf("path spellings = %q, %q, %q", parsed, keyed, indexed)
}
if reflect.DeepEqual(parsed.value, keyed.value) || reflect.DeepEqual(parsed.value, indexed.value) || reflect.DeepEqual(keyed.value, indexed.value) {
t.Fatal("path wrappers collapsed parsed, mapping-key, and index segments")
}
}

View File

@@ -1,70 +0,0 @@
package configkit
import (
"io"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// ValueSnapshot is a detached, deterministic YAML representation of one value.
// Present distinguishes absence or deletion from an explicit null value.
type ValueSnapshot struct {
Present bool
Redacted bool
YAML string
}
// ValueChange describes one explicit definition or audited domain operation.
type ValueChange struct {
Before ValueSnapshot
After ValueSnapshot
Origin Origin
Reasons []string
Dependencies []Path
}
// SecretReferenceInfo describes a successfully resolved effective reference.
// Name is the environment-variable name, never its value.
type SecretReferenceInfo struct {
Name string
}
// Explanation is a detached safe account of one effective or historical path.
type Explanation struct {
Path Path
Effective ValueSnapshot
Origin Origin
History []ValueChange
SecretReference *SecretReferenceInfo
}
// Explain returns safe effective and chronological values for a known final or
// historical path. Unknown and malformed paths return false.
func (r *Result[T]) Explain(path Path) (Explanation, bool) {
if r == nil {
return Explanation{}, false
}
value, ok := r.inspection.Explain(toEnginePath(path))
return fromEngineExplanation(value), ok
}
// WriteEffective writes deterministic redacted YAML from the frozen resolved
// snapshot. The output is intended for inspection and is not promised reloadable.
// Writer errors, including short writes, are returned and may leave partial output.
func (r *Result[T]) WriteEffective(output io.Writer) error {
if r == nil {
var inspection *engine.Inspection
return inspection.WriteEffective(output)
}
return r.inspection.WriteEffective(output)
}
// WriteExplanation writes a deterministic human-readable rendering of Explain.
// Unknown paths produce no output. Writer failures may leave partial output.
func (r *Result[T]) WriteExplanation(output io.Writer, path Path) error {
if r == nil {
var inspection *engine.Inspection
return inspection.WriteExplanation(output, toEnginePath(path))
}
return r.inspection.WriteExplanation(output, toEnginePath(path))
}

View File

@@ -1,254 +0,0 @@
package configkit
import (
"errors"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// Definition contains reusable application rules for a configuration type.
// Secret is a pure predicate that can add sensitivity to semantic paths.
// Definitions should be treated as read-only after being shared.
type Definition[T any] struct {
Defaults func() T
Resolve func(*T, *Resolution) error
Validate func(*T, *Validation)
Version *VersionRule
Secret func(Path) bool
}
// Options contains the application definition and per-load input selections.
// Imports enables explicit path and glob imports; Profile selects one fixed profile
// overlay; Overrides contains only values explicitly supplied by an application CLI.
type Options[T any] struct {
Definition Definition[T]
Imports bool
Profile string
Filesystem *FilesystemContext
Overrides []Override
}
// FilesystemContext supplies filesystem roots for imports and profiles.
type FilesystemContext struct {
BaseDir string
Root string
}
// Override describes one explicitly supplied application override. Value uses
// parser-neutral built-in scalars, nil, []any, or map[string]any; Flag is a safe
// display name and must not contain a raw argument or value.
type Override struct {
Path Path
Value any
Flag string
}
// Resolution exposes entry-state input provenance, surviving-input presence, and
// audited application resolution changes. A resolver must not retain or
// concurrently use the context.
type Resolution struct{ value *engine.Resolution }
// VersionRule declares the input path and application checker for a schema version.
// At that path, string and decimal-integer input is supplied as Version.Text.
type VersionRule struct {
Path Path
Check func(Version, *Validation) error
}
// Version preserves the absent, null, and textual states of a schema-version input.
// Text is the exact spelling of accepted string or decimal-integer input.
type Version struct {
Present bool
Null bool
Text string
}
// Validation collects safe application diagnostics during a supported callback.
// A callback must not retain the context or use it concurrently.
type Validation struct{ value *engine.Validation }
// Result is a successful independently owned configuration load.
type Result[T any] struct {
Config T
inspection *engine.Inspection
}
// Load parses and strictly decodes zero or one selected source, explicitly enabled
// imports, and one selected profile. It accepts at most one Options value and
// returns no result when any error is reported.
func Load[T any](source Source, supplied ...Options[T]) (*Result[T], error) {
options := make([]engine.Options[T], len(supplied))
for index := range supplied {
options[index] = toEngineOptions(supplied[index])
}
loaded, err := engine.Load(source.toEngine(), secretBinding(), options...)
if err != nil {
var loadError *engine.LoadError
if errors.As(err, &loadError) {
return nil, &LoadError{value: loadError}
}
return nil, &LoadError{}
}
return &Result[T]{Config: loaded.Config, inspection: loaded.Inspection}, nil
}
// Metadata returns detached effective presence, origin, and history records.
func (r *Result[T]) Metadata() Metadata {
if r == nil || r.inspection == nil {
return Metadata{}
}
return Metadata{value: r.inspection.Metadata()}
}
// Sources returns a detached list of sources used by the load.
func (r *Result[T]) Sources() []SourceInfo {
if r == nil || r.inspection == nil {
return nil
}
values := r.inspection.Sources()
if values == nil {
return nil
}
result := make([]SourceInfo, len(values))
for index := range values {
result[index] = fromEngineSourceInfo(values[index])
}
return result
}
// Diagnostics returns detached nonfatal diagnostics from the load.
func (r *Result[T]) Diagnostics() []Diagnostic {
if r == nil || r.inspection == nil {
return nil
}
values := r.inspection.Diagnostics()
if values == nil {
return nil
}
result := make([]Diagnostic, len(values))
for index := range values {
result[index] = fromEngineDiagnostic(values[index])
}
return result
}
// IsExplicit reports whether surviving input explicitly defined path.
func (r *Resolution) IsExplicit(path Path) bool { return r.value.IsExplicit(toEnginePath(path)) }
// InputInfo returns detached entry-state metadata for path. The entry state is
// the decoded configuration, including retained static defaults, immediately
// before resolution starts. It is fixed while resolution records mutate the
// working configuration; unknown or shape-mismatched paths return false.
//
// InputInfo is valid only during the resolution callback. See the configuration
// contract for source and provenance semantics.
func (r *Resolution) InputInfo(path Path) (FieldInfo, bool) {
value, ok := r.value.InputInfo(toEnginePath(path))
return fromEngineFieldInfo(value), ok
}
// Source returns a detached record for a source acquired by this load. Empty or
// unknown IDs return false and do not perform input, filesystem, or credential
// access. A source path is present only when that acquired source has one.
//
// Source is valid only during the resolution callback. See the configuration
// contract for source and provenance semantics.
func (r *Resolution) Source(id string) (SourceInfo, bool) {
value, ok := r.value.Source(id)
return fromEngineSourceInfo(value), ok
}
// Record declares the intent for a resolver mutation. A container path covers
// mutations to its descendants.
func (r *Resolution) Record(path Path, kind ChangeKind, reason string, dependencies ...Path) {
r.value.Record(toEnginePath(path), engine.ChangeKind(kind), reason, toEnginePaths(dependencies)...)
}
// Error reports a safe, value-free resolution error at path.
func (r *Resolution) Error(path Path, message string, related ...Path) {
r.value.Error(toEnginePath(path), message, toEnginePaths(related)...)
}
// Warning reports a safe, value-free resolution warning at path.
func (r *Resolution) Warning(path Path, message string, related ...Path) {
r.value.Warning(toEnginePath(path), message, toEnginePaths(related)...)
}
// Default assigns and records value only when path was absent from surviving
// input. Static defaults are not considered explicit.
func Default[V any](resolution *Resolution, path Path, target *V, value V, reason string, dependencies ...Path) {
engine.Default(resolution.value, toEnginePath(path), target, value, reason, toEnginePaths(dependencies)...)
}
// Normalize assigns and records value regardless of input presence.
func Normalize[V any](resolution *Resolution, path Path, target *V, value V, reason string, dependencies ...Path) {
engine.Normalize(resolution.value, toEnginePath(path), target, value, reason, toEnginePaths(dependencies)...)
}
// Error reports a value-free application error at path. Related paths are
// resolved to source locations when possible.
func (v *Validation) Error(path Path, message string, related ...Path) {
v.value.Error(toEnginePath(path), message, toEnginePaths(related)...)
}
// Warning reports a value-free application warning at path. Related paths are
// resolved to source locations when possible.
func (v *Validation) Warning(path Path, message string, related ...Path) {
v.value.Warning(toEnginePath(path), message, toEnginePaths(related)...)
}
func toEngineOptions[T any](options Options[T]) engine.Options[T] {
result := engine.Options[T]{
Definition: toEngineDefinition(options.Definition),
Imports: options.Imports,
Profile: options.Profile,
}
if options.Filesystem != nil {
result.Filesystem = &engine.FilesystemContext{BaseDir: options.Filesystem.BaseDir, Root: options.Filesystem.Root}
}
if options.Overrides != nil {
result.Overrides = make([]engine.Override, len(options.Overrides))
for index := range options.Overrides {
result.Overrides[index] = engine.Override{
Path: toEnginePath(options.Overrides[index].Path), Value: options.Overrides[index].Value, Flag: options.Overrides[index].Flag,
}
}
}
return result
}
func toEngineDefinition[T any](definition Definition[T]) engine.Definition[T] {
result := engine.Definition[T]{Defaults: definition.Defaults}
if definition.Resolve != nil {
result.Resolve = func(configuration *T, resolution *engine.Resolution) error {
return definition.Resolve(configuration, &Resolution{value: resolution})
}
}
if definition.Validate != nil {
result.Validate = func(configuration *T, validation *engine.Validation) {
definition.Validate(configuration, &Validation{value: validation})
}
}
if definition.Version != nil {
rule := definition.Version
result.Version = &engine.VersionRule{Path: toEnginePath(rule.Path), Check: func(version engine.Version, validation *engine.Validation) error {
return rule.Check(Version{Present: version.Present, Null: version.Null, Text: version.Text}, &Validation{value: validation})
}}
}
if definition.Secret != nil {
result.Secret = func(path engine.Path) bool { return definition.Secret(fromEnginePath(path)) }
}
return result
}
func toEnginePaths(paths []Path) []engine.Path {
if paths == nil {
return nil
}
result := make([]engine.Path, len(paths))
for index := range paths {
result[index] = toEnginePath(paths[index])
}
return result
}

View File

@@ -1,56 +0,0 @@
package configkit
import "gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
// Metadata provides detached effective presence/origin and chronological history
// queries for a load. Its zero value contains no paths.
type Metadata struct{ value engine.Metadata }
// Lookup returns information for an effective path. Unknown and invalid paths
// return false.
func (m Metadata) Lookup(path Path) (FieldInfo, bool) {
value, ok := m.value.Lookup(toEnginePath(path))
return fromEngineFieldInfo(value), ok
}
// IsExplicit reports whether a surviving input contribution explicitly defined
// path.
func (m Metadata) IsExplicit(path Path) bool {
return m.value.IsExplicit(toEnginePath(path))
}
// History returns detached definition and resolution records for path. A record's
// Path can be an ancestor when that container operation replaced or removed path.
// Removed historical paths can have history even though Lookup returns false.
// Unknown and invalid paths return nil.
func (m Metadata) History(path Path) []Change {
values := m.value.History(toEnginePath(path))
if values == nil {
return nil
}
result := make([]Change, len(values))
for index := range values {
result[index] = fromEngineChange(values[index])
}
return result
}
// HistoricalPaths returns the paths observed during loading, including effective
// paths and paths removed by overlays or recorded resolution. It includes default
// paths and the root, but not paths that never existed. The zero Metadata returns
// an empty slice.
//
// Paths are detached, unique by canonical JSON Pointer, and sorted by that
// spelling. Like ParsePath results, numeric tokens are resolved contextually;
// one pointer can identify a mapping key in an earlier layer and a sequence index
// in a later one. Use History to inspect definitions and Lookup to check whether
// a path remains effective. Enumeration exposes no configuration values and does
// not perform another load or resolve secrets.
func (m Metadata) HistoricalPaths() []Path {
values := m.value.HistoricalPaths()
result := make([]Path, len(values))
for index := range values {
result[index] = fromEnginePath(values[index])
}
return result
}

View File

@@ -1,33 +0,0 @@
package configkit
import (
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// Path identifies a configuration value using YAML field names. Its textual form
// is a JSON Pointer. Paths are immutable; the zero value is the root path.
type Path struct {
value engine.Path
}
// Keys constructs a path of mapping keys. Keys with no arguments returns the root path.
func Keys(keys ...string) Path { return Path{value: engine.Keys(keys...)} }
// ParsePath parses a JSON Pointer while preserving context-dependent numeric tokens.
func ParsePath(pointer string) (Path, error) {
value, err := engine.ParsePath(pointer)
return Path{value: value}, err
}
// Key returns a new path with key appended as a mapping-key segment.
func (p Path) Key(key string) Path { return Path{value: p.value.Key(key)} }
// Index returns a new path with index appended as a sequence-index segment.
func (p Path) Index(index int) Path { return Path{value: p.value.Index(index)} }
// String returns the path's canonical JSON Pointer spelling.
func (p Path) String() string { return p.value.String() }
func (p Path) clone() Path { return Path{value: p.value} }
func toEnginePath(path Path) engine.Path { return path.value }
func fromEnginePath(path engine.Path) Path { return Path{value: path} }

View File

@@ -1,286 +0,0 @@
package configkit
// Layer identifies the precedence layer responsible for a configuration value.
type Layer string
const (
LayerDefault Layer = "default"
LayerBase Layer = "base"
LayerProfile Layer = "profile"
LayerCLI Layer = "cli"
LayerResolution Layer = "resolution"
)
// ChangeKind identifies a recorded operation. The zero value is
// used for input and default origins.
type ChangeKind string
const (
// ChangeDecoding records the built-in transition to canonical typed values.
// It is inspection metadata, not an operation accepted by Resolution.Record.
ChangeDecoding ChangeKind = "decoding"
ChangeDerivedDefault ChangeKind = "derived_default"
ChangeNormalization ChangeKind = "normalization"
)
// Severity classifies a diagnostic.
type Severity string
const (
SeverityError Severity = "error"
SeverityWarning Severity = "warning"
)
// Code is a stable, machine-readable diagnostic classification.
type Code string
const (
CodeSourceInvalid Code = "source.invalid"
CodeSourceMissing Code = "source.missing"
CodeSourcePermission Code = "source.permission"
CodeSourceRead Code = "source.read"
CodeSourceNotRegular Code = "source.not_regular"
CodeSourceLimitExceeded Code = "source.limit_exceeded"
CodeSourceReaderUsed Code = "source.reader_used"
CodeYAMLInvalid Code = "yaml.invalid"
CodeYAMLEmpty Code = "yaml.empty"
CodeYAMLMultipleDocuments Code = "yaml.multiple_documents"
CodeYAMLRootType Code = "yaml.root_type"
CodeYAMLDuplicateKey Code = "yaml.duplicate_key"
CodeYAMLTag Code = "yaml.tag"
CodeYAMLAnchor Code = "yaml.anchor"
CodeYAMLAlias Code = "yaml.alias"
CodeYAMLMergeKey Code = "yaml.merge_key"
CodeYAMLScalar Code = "yaml.scalar"
CodeYAMLDepthLimit Code = "yaml.depth_limit"
CodeYAMLNodeLimit Code = "yaml.node_limit"
CodeSchemaRoot Code = "schema.root"
CodeSchemaUnsupportedType Code = "schema.unsupported_type"
CodeSchemaAmbiguousField Code = "schema.ambiguous_field"
CodeSchemaTag Code = "schema.tag"
CodeSchemaTextCodec Code = "schema.text_codec"
CodeSchemaInline Code = "schema.inline"
CodeSchemaCycle Code = "schema.cycle"
CodeSchemaProjectionLimit Code = "schema.projection_limit"
CodeSchemaCodec Code = "schema.codec"
CodeSchemaNonFinite Code = "schema.non_finite"
CodeSchemaDynamicType Code = "schema.dynamic_type"
CodeDecodeType Code = "decode.type"
CodeDecodeNull Code = "decode.null"
CodeDecodeRange Code = "decode.range"
CodeDecodeDuration Code = "decode.duration"
CodeDecodeText Code = "decode.text"
CodeDecodeUnknownField Code = "decode.unknown_field"
CodeDecodeArrayLength Code = "decode.array_length"
CodeOptionsInvalid Code = "options.invalid"
CodeOptionsUnavailable Code = "options.unavailable"
CodeImportDisabled Code = "import.disabled"
CodeImportInvalid Code = "import.invalid"
CodeImportMissing Code = "import.missing"
CodeImportPermission Code = "import.permission"
CodeImportRead Code = "import.read"
CodeImportOutsideRoot Code = "import.outside_root"
CodeImportCycle Code = "import.cycle"
CodeImportRepeated Code = "import.repeated"
CodeImportLimitExceeded Code = "import.limit_exceeded"
CodeImportVersion Code = "import.version"
CodeProfileInvalid Code = "profile.invalid"
CodeProfileMissing Code = "profile.missing"
CodeProfileOutsideRoot Code = "profile.outside_root"
CodeProfileRepeated Code = "profile.repeated"
CodeProfileDirective Code = "profile.directive"
CodeProfileVersion Code = "profile.version"
CodeProfileLimitExceeded Code = "profile.limit_exceeded"
CodeComposeInvalid Code = "compose.invalid"
CodeComposeConflict Code = "compose.conflict"
CodeVersionType Code = "version.type"
CodeVersionError Code = "version.error"
CodeVersionWarning Code = "version.warning"
CodeVersionHookFailed Code = "version.hook_failed"
CodeResolveError Code = "resolve.error"
CodeResolveWarning Code = "resolve.warning"
CodeResolveHookFailed Code = "resolve.hook_failed"
CodeResolveInvalidPath Code = "resolve.invalid_path"
CodeResolveInvalidKind Code = "resolve.invalid_kind"
CodeResolveInvalidRecord Code = "resolve.invalid_record"
CodeResolveInvalidTarget Code = "resolve.invalid_target"
CodeResolveInvalidValue Code = "resolve.invalid_value"
CodeResolveUnrecordedChange Code = "resolve.unrecorded_change"
CodeValidateError Code = "validate.error"
CodeValidateWarning Code = "validate.warning"
CodeValidateInvalidPath Code = "validate.invalid_path"
CodeValidateMutation Code = "validate.mutation"
CodeSecretsInvalidPath Code = "secrets.invalid_path"
CodeSecretsMissing Code = "secrets.missing"
CodeSecretsPermission Code = "secrets.permission"
CodeSecretsRead Code = "secrets.read"
CodeSecretsNotRegular Code = "secrets.not_regular"
CodeSecretsInvalidName Code = "secrets.invalid_name"
CodeSecretsLimitExceeded Code = "secrets.limit_exceeded"
CodeSecretsInvalidValue Code = "secrets.invalid_value"
CodeSecretsApplyFailed Code = "secrets.apply_failed"
CodeSecretRequired Code = "secret.required"
CodeSecretInvalidName Code = "secret.invalid_name"
CodeSecretUnset Code = "secret.unset"
CodeSecretEmpty Code = "secret.empty"
CodeOverrideInvalidPath Code = "override.invalid_path"
CodeOverrideInvalidLabel Code = "override.invalid_label"
CodeOverrideInvalidValue Code = "override.invalid_value"
CodeOverrideDuplicate Code = "override.duplicate"
CodeOverrideOverlap Code = "override.overlap"
CodeOverrideDirective Code = "override.directive"
CodeOverrideVersion Code = "override.version"
CodeOverrideLimitExceeded Code = "override.limit_exceeded"
CodeExplainLimitExceeded Code = "explain.limit_exceeded"
)
// Location identifies a position in a configuration source. Zero line and column
// values mean that coordinates are unavailable or synthetic.
type Location struct {
SourceID string
Line int
Column int
}
// SourceInfo describes a source discovered during a load. Path is a canonical
// local path when one exists. ImportedFrom identifies the declaration that
// included this source.
type SourceInfo struct {
ID string
Label string
Path string
Layer Layer
ImportedFrom *Location
}
// Diagnostic is a safe structured problem report. Message and source labels must
// never contain configuration values or other secrets.
type Diagnostic struct {
Code Code
Severity Severity
Path Path
Message string
Primary *Location
Related []Location
}
// Origin describes where an effective definition came from. Multiple locations
// represent a composite origin; resolution origins are synthetic and identify their
// operation instead of a file location.
type Origin struct {
Layer Layer
Locations []Location
Operation ChangeKind
}
// FieldInfo describes an effective configuration path.
type FieldInfo struct {
Explicit bool
Null bool
Origin Origin
}
// Change describes a definition or application-resolution operation. Path can name
// an ancestor operation affecting the queried descendant. Historical values are
// intentionally not exposed by this record.
type Change struct {
Path Path
Origin Origin
Previous []Origin
Reasons []string
Dependencies []Path
}
func cloneLocation(location *Location) *Location {
if location == nil {
return nil
}
cloned := *location
return &cloned
}
func cloneLocations(locations []Location) []Location {
if locations == nil {
return nil
}
return append([]Location(nil), locations...)
}
func cloneSourceInfo(source SourceInfo) SourceInfo {
source.ImportedFrom = cloneLocation(source.ImportedFrom)
return source
}
func cloneSourceInfos(sources []SourceInfo) []SourceInfo {
if sources == nil {
return nil
}
cloned := make([]SourceInfo, len(sources))
for i, source := range sources {
cloned[i] = cloneSourceInfo(source)
}
return cloned
}
func cloneOrigin(origin Origin) Origin {
origin.Locations = cloneLocations(origin.Locations)
return origin
}
func cloneFieldInfo(info FieldInfo) FieldInfo {
info.Origin = cloneOrigin(info.Origin)
return info
}
func cloneChange(change Change) Change {
change.Path = change.Path.clone()
change.Origin = cloneOrigin(change.Origin)
if change.Previous != nil {
previous := make([]Origin, len(change.Previous))
for i, origin := range change.Previous {
previous[i] = cloneOrigin(origin)
}
change.Previous = previous
}
change.Reasons = append([]string(nil), change.Reasons...)
if change.Dependencies != nil {
dependencies := make([]Path, len(change.Dependencies))
for i, path := range change.Dependencies {
dependencies[i] = path.clone()
}
change.Dependencies = dependencies
}
return change
}
func cloneDiagnostic(diagnostic Diagnostic) Diagnostic {
diagnostic.Path = diagnostic.Path.clone()
diagnostic.Primary = cloneLocation(diagnostic.Primary)
diagnostic.Related = cloneLocations(diagnostic.Related)
return diagnostic
}
func cloneDiagnostics(diagnostics []Diagnostic) []Diagnostic {
if diagnostics == nil {
return nil
}
cloned := make([]Diagnostic, len(diagnostics))
for i, diagnostic := range diagnostics {
cloned[i] = cloneDiagnostic(diagnostic)
}
return cloned
}

View File

@@ -1,52 +0,0 @@
package configkit
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// Secret is an opaque reference to an environment variable. Its name is public
// configuration; its resolved value is available only through Value.
type Secret struct {
name, value string
specified, resolved bool
}
// SecretEnv constructs an unresolved environment-backed secret reference.
func SecretEnv(name string) Secret { return Secret{name: name, specified: true} }
// EnvName returns the public environment-variable name.
func (s Secret) EnvName() string { return s.name }
// Value returns the resolved credential, or an empty string when unresolved.
func (s Secret) Value() string {
if !s.resolved {
return ""
}
return s.value
}
// IsResolved reports whether this reference resolved to a nonempty value during its configuration load.
func (s Secret) IsResolved() bool { return s.resolved }
// Format renders only the public reference name for every formatting verb.
func (s Secret) Format(state fmt.State, _ rune) {
_, _ = io.WriteString(state, "configkit.SecretEnv("+strconv.Quote(s.name)+")")
}
// MarshalJSON emits only the public environment-variable name.
func (s Secret) MarshalJSON() ([]byte, error) { return json.Marshal(s.name) }
func secretBinding() engine.SecretBinding {
return engine.SecretBinding{Type: reflect.TypeFor[Secret](), Read: func(value reflect.Value) engine.SecretState {
secret := value.Interface().(Secret)
return engine.SecretState{Name: secret.name, Value: secret.value, Specified: secret.specified, Resolved: secret.resolved}
}, Make: func(state engine.SecretState) reflect.Value {
return reflect.ValueOf(Secret{name: state.Name, value: state.Value, specified: state.Specified, resolved: state.Resolved})
}}
}

View File

@@ -1,102 +0,0 @@
package configkit
import (
"errors"
"io"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// SecretFileStatus describes the outcome for one file considered by
// LoadSecretsDir.
type SecretFileStatus string
const (
SecretFileLoaded SecretFileStatus = "loaded"
SecretFileSkippedExisting SecretFileStatus = "skipped_existing"
SecretFileNotApplied SecretFileStatus = "not_applied"
SecretFileFailed SecretFileStatus = "failed"
)
// SecretFileResult is the safe, value-free bootstrap result for one directory
// entry. ExistingEmpty is meaningful when Status is SecretFileSkippedExisting.
type SecretFileResult struct {
Name string
Path string
Status SecretFileStatus
ExistingEmpty bool
}
// SecretsReport is a detached snapshot of an explicit secrets-directory
// bootstrap. It does not retain file contents or environment values.
type SecretsReport struct{ value *engine.SecretsReport }
// Entries returns a copy of the report's filename-ordered entries.
func (r *SecretsReport) Entries() []SecretFileResult {
if r == nil || r.value == nil {
return nil
}
values := r.value.Entries()
if values == nil {
return nil
}
result := make([]SecretFileResult, len(values))
for index := range values {
result[index] = fromEngineSecretFileResult(values[index])
}
return result
}
// WriteTo renders one safe, deterministic line per entry. Names and paths are
// quoted so control characters cannot affect terminal output.
func (r *SecretsReport) WriteTo(output io.Writer) (int64, error) {
if r == nil || r.value == nil {
return (*engine.SecretsReport)(nil).WriteTo(output)
}
return r.value.WriteTo(output)
}
// SecretsError reports safe structured diagnostics for a failed explicit
// secrets-directory bootstrap. It intentionally does not unwrap filesystem or
// environment errors.
type SecretsError struct{ value *engine.SecretsError }
// Error implements error without rendering filenames, paths, or file contents.
func (e *SecretsError) Error() string {
if e == nil || e.value == nil {
return "configkit: secrets bootstrap failed"
}
return e.value.Error()
}
// Diagnostics returns a deep copy of the bootstrap diagnostics.
func (e *SecretsError) Diagnostics() []Diagnostic {
if e == nil || e.value == nil {
return nil
}
values := e.value.Diagnostics()
if values == nil {
return nil
}
result := make([]Diagnostic, len(values))
for index := range values {
result[index] = fromEngineDiagnostic(values[index])
}
return result
}
// LoadSecretsDir explicitly loads immediate regular files from directory into
// previously unset process environment variables. Applications should call it
// once during startup, before concurrent work; Load never calls it.
func LoadSecretsDir(directory string) (*SecretsReport, error) {
report, err := engine.LoadSecretsDir(directory)
result := &SecretsReport{value: report}
if err == nil {
return result, nil
}
var secretsError *engine.SecretsError
if errors.As(err, &secretsError) {
return result, &SecretsError{value: secretsError}
}
return result, &SecretsError{}
}

View File

@@ -1,25 +0,0 @@
package configkit
import (
"io"
"gitea.maximumdirect.net/eric/ConfigKit/internal/engine"
)
// Source is an opaque configuration input. Construct sources with File, Bytes,
// Reader, or NoSource; the zero value is invalid.
type Source struct{ value engine.Source }
// File returns a source that reopens path for every load attempt.
func File(path string) Source { return Source{value: engine.File(path)} }
// Bytes snapshots data immediately.
func Bytes(label string, data []byte) Source { return Source{value: engine.Bytes(label, data)} }
// Reader returns a single-use source. Copies share the same single-use claim.
func Reader(label string, input io.Reader) Source { return Source{value: engine.Reader(label, input)} }
// NoSource explicitly selects defaults-only input.
func NoSource() Source { return Source{value: engine.NoSource()} }
func (s Source) toEngine() engine.Source { return s.value }