config

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package config provides configuration loading and management for markata-go.

Package config provides configuration loading and management for markata-go.

Configuration File Formats

The package supports three configuration formats:

  • TOML (primary, recommended) using github.com/BurntSushi/toml
  • YAML using gopkg.in/yaml.v3
  • JSON using the standard library

All formats use a top-level "markata-go" key to namespace configuration:

# TOML example
[markata-go]
output_dir = "public"
url = "https://example.com"

# YAML example
markata-go:
  output_dir: public
  url: https://example.com

# JSON example
{"markata-go": {"output_dir": "public", "url": "https://example.com"}}

Configuration Discovery

When no explicit config path is provided, the package searches for configuration files in the following order:

  1. ./markata-go.toml
  2. ./markata-go.yaml
  3. ./markata-go.yml
  4. ./markata-go.json
  5. ~/.config/markata-go/config.toml

If no configuration file is found, default values are used.

Environment Variable Overrides

Configuration values can be overridden using environment variables with the MARKATA_GO_ prefix. Environment variables take precedence over file configuration.

Simple fields:

MARKATA_GO_OUTPUT_DIR=public
MARKATA_GO_URL=https://example.com

Nested fields use underscores:

MARKATA_GO_GLOB_PATTERNS=posts/**/*.md,pages/*.md
MARKATA_GO_FEED_DEFAULTS_ITEMS_PER_PAGE=20

Boolean values accept: "true", "1", "yes" for true; "false", "0", "no" for false.

List values are comma-separated:

MARKATA_GO_HOOKS=markdown,template,sitemap

Usage

Basic usage:

// Load from default locations with env overrides
config, err := config.Load("")

// Load from specific file
config, err := config.Load("/path/to/config.toml")

// Load with defaults only
config, err := config.LoadWithDefaults()

// Load and validate
config, validationErrs, err := config.LoadAndValidate("/path/to/config.toml")

Merging Configurations

The MergeConfigs function performs a deep merge of two configurations:

base := config.DefaultConfig()
override := &models.Config{OutputDir: "custom"}
merged := config.MergeConfigs(base, override)

String fields are overridden if non-empty. Integer fields are overridden if non-zero. Slices are replaced if non-empty. Feed formats are replaced if any format is enabled.

Validation

Configurations can be validated to catch common errors and warnings:

errs := config.ValidateConfig(cfg)
if config.HasErrors(errs) {
    // Handle errors
}
if config.HasWarnings(errs) {
    // Handle warnings
}

Validation checks include:

  • URL format validation
  • Concurrency must be >= 0
  • Feed slugs are required
  • Warning on empty glob patterns
  • Warning on feeds with no output formats

Index

Constants

This section is empty.

Variables

View Source
var ErrConfigNotFound = errors.New("no configuration file found")

ErrConfigNotFound is returned when no config file is found.

Functions

func AppendDisabledHooks

func AppendDisabledHooks(config *models.Config, hooks ...string)

AppendDisabledHooks appends hooks to the configuration's DisabledHooks slice.

func AppendFeeds

func AppendFeeds(config *models.Config, feeds ...models.FeedConfig)

AppendFeeds appends feeds to the configuration's Feeds slice.

func AppendGlobPatterns

func AppendGlobPatterns(config *models.Config, patterns ...string)

AppendGlobPatterns appends patterns to the configuration's GlobConfig.Patterns slice.

func AppendHooks

func AppendHooks(config *models.Config, hooks ...string)

mergeExtra merges Extra map values (for plugin configs like image_zoom, wikilinks, etc.)// AppendHooks appends hooks to the configuration's Hooks slice.

func ApplyEnvOverrides

func ApplyEnvOverrides(config *models.Config) error

ApplyEnvOverrides applies environment variable overrides to a config. Environment variables are expected to follow the format MARKATA_GO_*. Nested keys use underscores: MARKATA_GO_FEEDS_DEFAULTS_ITEMS_PER_PAGE Boolean values: "true", "1", "yes" -> true; "false", "0", "no" -> false List values: comma-separated strings

func DefaultConfig

func DefaultConfig() *models.Config

DefaultConfig returns a Config with sensible default values.

func Discover

func Discover() (string, error)

Discover searches for a configuration file in the standard locations. It returns the path to the first config file found, or ErrConfigNotFound.

Discovery order:

  1. ./markata-go.toml
  2. ./markata-go.yaml (or .yml)
  3. ./markata-go.json
  4. ~/.config/markata-go/config.toml

func FormatConfigError added in v0.5.0

func FormatConfigError(err *ConfigError) string

FormatConfigError formats a ConfigError for CLI display with colors and context.

func FormatConfigErrors added in v0.5.0

func FormatConfigErrors(configErrors *ConfigErrors) string

FormatConfigErrors formats multiple ConfigErrors for CLI display.

func FromEnv

func FromEnv() *models.Config

FromEnv creates a Config entirely from environment variables. This is useful when no config file is available.

func GetEnvValue

func GetEnvValue(key string) (string, bool)

GetEnvValue returns the value of an environment variable with the MARKATA_GO_ prefix.

func GetFixSuggestion added in v0.5.0

func GetFixSuggestion(errorType, field, value string) string

GetFixSuggestion returns a fix suggestion for a known error type.

func GetValueFromFile added in v0.7.0

func GetValueFromFile(path, key string) (any, error)

GetValueFromFile reads a config file and returns the value for a key path.

func HasErrors

func HasErrors(errs []error) bool

HasErrors returns true if the error slice contains any actual errors (not warnings).

func HasWarnings

func HasWarnings(errs []error) bool

HasWarnings returns true if the error slice contains any warnings.

func Load

func Load(configPath string) (*models.Config, error)

Load loads configuration from the specified file path. If configPath is empty, it will attempt to discover a config file. Environment variable overrides are applied after loading the file. A .env file in the current directory is loaded first (if present) so that encryption keys and other settings can be stored there.

func LoadAndValidate

func LoadAndValidate(configPath string) (*models.Config, []error, error)

LoadAndValidate loads and validates configuration. Returns the config and any validation errors/warnings.

func LoadDotEnv added in v0.7.0

func LoadDotEnv() error

LoadDotEnv loads environment variables from a .env file in the current directory. Lines starting with '#' are treated as comments. Empty lines are skipped. Values can optionally be quoted with single or double quotes. Variables are set into the process environment so they are available to os.Environ() and os.Getenv() calls (including encryption key lookups).

This function is safe to call even if no .env file exists - it will silently return nil in that case.

func LoadDotEnvFile added in v0.7.0

func LoadDotEnvFile(path string) error

LoadDotEnvFile loads environment variables from the specified file path. Returns nil if the file does not exist.

func LoadFromString

func LoadFromString(data string, format Format) (*models.Config, error)

LoadFromString parses configuration from a string with the specified format.

func LoadSingleConfig added in v0.7.0

func LoadSingleConfig(configPath string) (*models.Config, error)

LoadSingleConfig loads a single config file without merging defaults or env overrides. This is useful for loading partial configs that will be merged with others.

func LoadWithDefaults

func LoadWithDefaults() (*models.Config, error)

LoadWithDefaults returns a configuration with default values and environment variable overrides applied.

func LoadWithMerge added in v0.7.0

func LoadWithMerge(basePath string, overridePaths ...string) (*models.Config, error)

LoadWithMerge loads a base configuration and merges it with one or more override configurations. Override configs are applied in order, with later configs taking precedence over earlier ones.

This is useful for environment-specific overrides, e.g.:

  • markata-go.toml (base config)
  • markata-go.local.toml (local overrides, gitignored)
  • fast-markata-go.toml (fast build overrides)

Example usage:

// Load base + local overrides
config, err := LoadWithMerge("markata-go.toml", "markata-go.local.toml")

// Load with multiple overrides
config, err := LoadWithMerge("markata-go.toml", "fast-markata-go.toml", "debug.toml")

func MergeConfigs

func MergeConfigs(base, override *models.Config) *models.Config

MergeConfigs merges override configuration into base configuration. The override values take precedence over base values. For nested objects, a deep merge is performed. Arrays replace by default (use *_append fields for appending).

func MergeSlice

func MergeSlice[T any](base, override []T, appendMode bool) []T

MergeSlice merges two slices with optional append behavior. If append is true, the override slice is appended to the base slice. Otherwise, the override slice replaces the base slice.

func MustLoad

func MustLoad(configPath string) *models.Config

MustLoad loads configuration and panics on error. This is useful for initialization code where config loading failure should be fatal.

func ParseJSON

func ParseJSON(data []byte) (*models.Config, error)

ParseJSON parses JSON configuration data into a Config struct. The JSON data is expected to have a top-level "markata-go" key.

func ParseTOML

func ParseTOML(data []byte) (*models.Config, error)

ParseTOML parses TOML configuration data into a Config struct. The TOML data is expected to have a top-level [markata-go] section.

func ParseYAML

func ParseYAML(data []byte) (*models.Config, error)

ParseYAML parses YAML configuration data into a Config struct. The YAML data is expected to have a top-level markata-go key.

func SetEnvValue

func SetEnvValue(key, value string) error

SetEnvValue sets an environment variable with the MARKATA_GO_ prefix. This is primarily useful for testing.

func SetValueInFile added in v0.7.0

func SetValueInFile(path, key string, value any) error

SetValueInFile updates a config file in place with the provided key path/value.

func SplitErrorsAndWarnings

func SplitErrorsAndWarnings(errs []error) (errsOut, warnsOut []error)

SplitErrorsAndWarnings separates errors and warnings into separate slices.

func StructToEnvKeys

func StructToEnvKeys(prefix string, v interface{}) map[string]string

StructToEnvKeys returns a map of environment variable keys for a struct. This is useful for documentation and debugging.

func UnsetEnvValue

func UnsetEnvValue(key string) error

UnsetEnvValue unsets an environment variable with the MARKATA_GO_ prefix. This is primarily useful for testing.

func ValidateAndWarn

func ValidateAndWarn(config *models.Config, warnFunc func(error)) []error

ValidateAndWarn validates config and logs warnings but only returns actual errors. This is useful when you want to proceed with warnings but stop on errors.

func ValidateConfig

func ValidateConfig(config *models.Config) []error

ValidateConfig validates a configuration and returns any errors or warnings. Errors are returned first, followed by warnings. The returned slice will be nil if no issues are found.

Types

type ConfigError added in v0.5.0

type ConfigError struct {
	File    string   // Path to the configuration file
	Line    int      // 1-based line number
	Column  int      // 1-based column number
	Field   string   // Configuration field name (e.g., "url", "feeds[0].items_per_page")
	Value   string   // The problematic value
	Message string   // Error message describing the problem
	Fix     string   // Suggested fix
	IsWarn  bool     // If true, this is a warning rather than an error
	Context []string // Surrounding lines for context
}

ConfigError represents a detailed configuration error with file position and fix suggestion. The name is intentionally verbose to clearly indicate this is a configuration-specific error type with position tracking.

func NewConfigError added in v0.5.0

func NewConfigError(tracker *PositionTracker, field, value, message string, isWarn bool) *ConfigError

NewConfigError creates a new ConfigError with position tracking.

func NewConfigErrorWithFix added in v0.5.0

func NewConfigErrorWithFix(tracker *PositionTracker, field, value, message, fix string, isWarn bool) *ConfigError

NewConfigErrorWithFix creates a ConfigError with a fix suggestion.

func (*ConfigError) Error added in v0.5.0

func (e *ConfigError) Error() string

Error implements the error interface with a detailed, user-friendly message.

func (*ConfigError) ShortError added in v0.5.0

func (e *ConfigError) ShortError() string

ShortError returns a concise single-line error message.

type ConfigErrors added in v0.5.0

type ConfigErrors struct {
	Errors []*ConfigError
}

ConfigErrors collects multiple configuration errors for batch reporting.

func LoadAndValidateWithPositions added in v0.5.0

func LoadAndValidateWithPositions(configPath string) (*models.Config, *ConfigErrors, error)

LoadAndValidateWithPositions loads configuration and validates it with position tracking for enhanced error messages. Returns the config, detailed errors with file positions, and any loading error.

func ValidateConfigWithPositions added in v0.5.0

func ValidateConfigWithPositions(config *models.Config, tracker *PositionTracker) *ConfigErrors

ValidateConfigWithPositions validates a configuration with file position tracking. It returns a ConfigErrors collection with detailed error information including file paths, line numbers, and fix suggestions.

func (*ConfigErrors) Add added in v0.5.0

func (e *ConfigErrors) Add(err *ConfigError)

Add adds an error to the collection.

func (*ConfigErrors) Error added in v0.5.0

func (e *ConfigErrors) Error() string

Error implements the error interface with a summary of all errors.

func (*ConfigErrors) HasErrors added in v0.5.0

func (e *ConfigErrors) HasErrors() bool

HasErrors returns true if there are any actual errors (not warnings).

func (*ConfigErrors) HasWarnings added in v0.5.0

func (e *ConfigErrors) HasWarnings() bool

HasWarnings returns true if there are any warnings.

func (*ConfigErrors) SplitErrorsAndWarnings added in v0.5.0

func (e *ConfigErrors) SplitErrorsAndWarnings() (errors, warnings []*ConfigError)

SplitErrorsAndWarnings separates errors and warnings.

type Edit added in v0.7.0

type Edit struct {
	Start   int
	End     int
	NewText string
}

type FieldPosition added in v0.5.0

type FieldPosition struct {
	Line   int
	Column int
}

FieldPosition tracks the location of a field in a configuration file.

type Format

type Format string

Format represents a configuration file format.

const (
	FormatTOML Format = "toml"
	FormatYAML Format = "yaml"
	FormatJSON Format = "json"
)

type KeySegment added in v0.7.0

type KeySegment struct {
	Key   string
	Index *int
}

KeySegment represents a dot path segment with an optional array index.

func ParseKeyPath added in v0.7.0

func ParseKeyPath(path string) ([]KeySegment, error)

ParseKeyPath parses dotted paths with optional indexes, e.g. "feeds[0].title".

type Path

type Path struct {
	Path   string // Full path to the config file
	Format Format // Format of the config file
	Source string // Where it was found: "cli", "cwd", "user"
}

Path holds the result of config file discovery with additional metadata.

func DiscoverAll

func DiscoverAll() []Path

DiscoverAll finds all config files in the standard locations. This is useful for debugging or showing available configs.

type PositionTracker added in v0.5.0

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

PositionTracker helps find field positions in configuration files.

func NewPositionTracker added in v0.5.0

func NewPositionTracker(content []byte, filePath string) *PositionTracker

NewPositionTracker creates a new position tracker for the given file content.

func (*PositionTracker) ExtractContext added in v0.5.0

func (p *PositionTracker) ExtractContext(targetLine, contextLines int) []string

ExtractContext extracts surrounding lines for context display. The target line is marked with "> " prefix, others with " ".

func (*PositionTracker) FilePath added in v0.5.0

func (p *PositionTracker) FilePath() string

FilePath returns the file path associated with this tracker.

func (*PositionTracker) FindFieldPosition added in v0.5.0

func (p *PositionTracker) FindFieldPosition(fieldName string) FieldPosition

FindFieldPosition finds the line and column of a field in the config file. It searches for patterns like `field = value` or `field: value`.

func (*PositionTracker) GetLine added in v0.5.0

func (p *PositionTracker) GetLine(lineNum int) string

GetLine returns the content of a specific line (1-based).

type ValidationError

type ValidationError struct {
	Field   string
	Message string
	IsWarn  bool // If true, this is a warning rather than an error
}

ValidationError represents a configuration validation error. This type is kept for backward compatibility.

func (ValidationError) Error

func (e ValidationError) Error() string

Jump to

Keyboard shortcuts

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