config

package
v0.11.21 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Interpolate

func Interpolate(raw map[string]any) (map[string]any, error)

Interpolate walks the parsed yaml tree (map[string]any / []any / string) and replaces ${VAR} occurrences in string leaves with env var values. Returns an error if any ${VAR} (without default) references an unset env var (strict mode).

To make a field tolerate a missing env var, use ${VAR:-default}: when VAR is unset, the literal default (which may be empty) is substituted instead and no error is raised. This is the recommended way to mark optional plugin credentials — strict-by-default for the common case, opt-in lenient for fields whose consumers validate presence themselves.

Type preservation: ${VAR} only makes sense in string fields. If used in int/bool fields, the resulting yaml unmarshal will fail with a type error. For numeric/bool config, use literal values directly.

Env values are inserted as strings. yaml.Marshal will quote them if needed (e.g. when they contain ":" or "#"), so structural breakage is not possible even if an env value contains yaml-significant characters.

func TopSection added in v0.3.3

func TopSection(urlOrPath string) string

TopSection returns the first path segment of a URL or content-relative path, e.g. "/books/foo/" → "books", "products/x.md" → "products", "http://h/books/" → "books". Returns "" when there is no segment.

Types

type AIConfig

type AIConfig struct {
	LlmsTxt        bool `yaml:"llmsTxt"`
	ContentAPI     bool `yaml:"contentAPI"`
	MarkdownMirror bool `yaml:"markdownMirror"`
}

AIConfig controls AI-friendly output features.

type AuthorConfig

type AuthorConfig struct {
	Name string `yaml:"name"`
}

type BuildConfig

type BuildConfig struct {
	List             string `yaml:"list"`   // never, always
	Render           string `yaml:"render"` // never, always
	PublishResources bool   `yaml:"publishResources"`
}

BuildConfig mirrors Hugo's build frontmatter directive.

type CascadeConfig

type CascadeConfig struct {
	Build   BuildConfig       `yaml:"build"`
	Sitemap SitemapPageConfig `yaml:"sitemap"`
}

CascadeConfig mirrors Hugo's cascade frontmatter directive.

type Config

type Config struct {
	BaseURL      string `yaml:"baseURL"`
	Title        string `yaml:"title"`
	LanguageCode string `yaml:"languageCode"`
	PublishDir   string `yaml:"publishDir"`
	// CleanPublishDir wipes the output dir before building. Default true.
	// Set false to keep stale files (legacy behavior).
	CleanPublishDir *bool `yaml:"cleanPublishDir"`
	Paginate        int   `yaml:"paginate"`
	Minify          bool  `yaml:"minify"`
	HasCJKLang      bool  `yaml:"hasCJKLanguage"`
	SummaryLen      int   `yaml:"summaryLength"`
	EnableEmoji     bool  `yaml:"enableEmoji"`

	// i18n: when Languages is non-empty, BuildMultiSite runs per-language.
	// See internal/config/languages.go and docs/adr/0007-i18n-build-system.md.
	DefaultContentLanguage string                    `yaml:"defaultContentLanguage"`
	Languages              map[string]LanguageConfig `yaml:"languages"`

	Author  AuthorConfig            `yaml:"author"`
	Params  ParamsConfig            `yaml:"params"`
	Menu    map[string][]MenuItem   `yaml:"menu"`
	Social  []SocialItem            `yaml:"social"`
	Markup  MarkupConfig            `yaml:"markup"`
	Sitemap SitemapConfig           `yaml:"sitemap"`
	RSS     RSSConfig               `yaml:"rss"`
	Outputs OutputsConfig           `yaml:"outputs"`
	AI      AIConfig                `yaml:"ai"`
	Plugins map[string]PluginConfig `yaml:"plugins"`
	Theme   string                  `yaml:"theme"`

	// Computed (not from YAML)
	BaseURLTemplate template.URL
	Services        ServicesConfig
}

func Defaults

func Defaults() *Config

Defaults returns a Config with sensible defaults.

func Load

func Load(sourceDir string) (*Config, error)

Load reads and parses huan.yaml from the given source directory. It starts from Defaults and overlays the parsed values.

Pipeline: read .env → inject env vars → read bytes → unmarshal to map → ${VAR} interpolate (strict) → re-marshal → unmarshal to Config struct. The two-stage unmarshal lets us run interpolation on the generic tree before type-checked decoding.

.env loading: if <sourceDir>/.env exists, its KEY=VALUE lines are loaded into os.Environ BEFORE huan.yaml interpolation. Existing env vars are NOT overridden (CI-injected vars take precedence over local .env). This lets projects keep CF API tokens / API keys in a gitignored .env file locally while CI injects them via the workflow's env: block.

func (*Config) DefaultLanguage added in v0.3.0

func (c *Config) DefaultLanguage() LanguageConfig

DefaultLanguage returns the LanguageConfig for the default language. Returns a zero-value LanguageConfig when single-language (caller should fall back to cfg-level Title / BaseURL / LanguageCode in that case).

func (*Config) DefaultLanguageCode added in v0.3.0

func (c *Config) DefaultLanguageCode() string

DefaultLanguageCode returns the language code of the default (lowest-weight, or defaultContentLanguage) language. Returns cfg.LanguageCode when no languages: block is configured (single-language backward compat).

func (*Config) IsDefaultLanguageCurrent added in v0.3.0

func (c *Config) IsDefaultLanguageCurrent() bool

IsDefaultLanguageCurrent returns true when cfg.LanguageCode matches the default language code (i.e. this build is rendering the default language). Used to decide whether per-language params overrides apply.

Returns true for single-language configs.

func (*Config) IsMultiLanguage added in v0.3.0

func (c *Config) IsMultiLanguage() bool

IsMultiLanguage reports whether cfg has a non-empty Languages map with at least one entry. Used by build pipeline to decide between the single- language fast path and the multi-language BuildMultiSite path.

func (*Config) IsSectionExcludedForLang added in v0.3.3

func (c *Config) IsSectionExcludedForLang(code, urlOrPath string) bool

IsSectionExcludedForLang reports whether the section that urlOrPath belongs to is excluded for the given language code. The language's BaseURL prefix (e.g. "/en") is stripped first so both raw config URLs ("/books/") and language-prefixed URLs ("/en/books/") resolve to the same top section.

func (*Config) LanguageBaseURL added in v0.3.0

func (c *Config) LanguageBaseURL(langCode string) string

LanguageBaseURL returns the BaseURL prefix for the given language code. Returns empty string for unknown languages or single-language configs.

func (*Config) LanguageName added in v0.3.0

func (c *Config) LanguageName(langCode string) string

LanguageName returns the display name for the given language code. Returns the code itself when not configured.

func (*Config) Now

func (c *Config) Now() time.Time

Now returns the current time, exposed to templates.

func (*Config) ShouldCleanPublishDir added in v0.8.0

func (c *Config) ShouldCleanPublishDir() bool

ShouldCleanPublishDir reports the effective cleanPublishDir setting, defaulting to true when unset.

func (*Config) SortedLanguages added in v0.3.0

func (c *Config) SortedLanguages() []LanguageEntry

SortedLanguages returns Languages sorted by Weight (ascending), then by language code (alphabetical) for stable iteration. Used by templates and sitemap to enumerate languages in deterministic order.

type DisqusConfig

type DisqusConfig struct {
	Shortname string
}

DisqusConfig placeholder for Hugo compatibility.

type ErrEnvVarNotSet

type ErrEnvVarNotSet struct {
	VarName string
}

ErrEnvVarNotSet is returned when a ${VAR} reference cannot be resolved because the env var is not set. Strict mode treats this as a fail-fast error to avoid silent empty-string substitution (a classic source of "apiToken: \"\" -> 401 -> debug for hours" bugs).

func (*ErrEnvVarNotSet) Error

func (e *ErrEnvVarNotSet) Error() string

type GoldmarkConfig

type GoldmarkConfig struct {
	Renderer   GoldmarkRendererConfig   `yaml:"renderer"`
	Extensions GoldmarkExtensionsConfig `yaml:"extensions"`
}

type GoldmarkExtensionsConfig

type GoldmarkExtensionsConfig struct {
	Typographer bool `yaml:"typographer"`
}

type GoldmarkRendererConfig

type GoldmarkRendererConfig struct {
	Unsafe bool `yaml:"unsafe"`
}

type LanguageConfig added in v0.3.0

type LanguageConfig struct {
	// Weight controls sort order in sitemap.xml and language switcher UI.
	// Lower weight sorts first. Default 0.
	Weight int `yaml:"weight"`

	// LanguageName is the display name (e.g. "中文", "English").
	LanguageName string `yaml:"languageName"`

	// BaseURL is the URL prefix for this language's content. Empty string
	// means root path (typically the default language). Non-empty (e.g. "/en")
	// prepends to all URLs for this language's pages.
	BaseURL string `yaml:"baseURL"`

	// ContentDir overrides the default content/ directory for this language.
	// Empty means use the project's top-level content/ dir (default behavior).
	// When set, huan loads pages from this dir INSTEAD of looking for
	// .<lang>.md sidecars in the main content/ dir.
	ContentDir string `yaml:"contentDir"`

	// Title overrides the top-level cfg.Title for this language.
	Title string `yaml:"title"`

	// LanguageCode is the BCP-47 language code (e.g. "zh-cn", "en").
	// Empty means use the map key from `languages:` block.
	LanguageCode string `yaml:"languageCode"`

	// ExcludeSections lists top-level content sections (e.g. "books",
	// "gallery") that should NOT appear in this language. Pages under these
	// sections are dropped from the build (no content/listing pages, no
	// sitemap entries), and templates use IsSectionExcludedForLang to hide
	// their entry points (menu items, social icons). Typically used to keep
	// untranslated or intentionally-monolingual sections off a translated
	// site. Empty means no exclusion (default).
	ExcludeSections []string `yaml:"excludeSections"`

	// CatalogSections lists top-level sections rendered in this language as
	// "catalog-only": the section index page renders (from its `_index.<lang>.md`
	// sidecar), but the section's content pages are dropped from the build (no
	// content pages, no sitemap entries). Used to advertise an untranslated
	// section's contents (e.g. a disabled book index) without publishing the
	// individual pages.
	CatalogSections []string `yaml:"catalogSections"`

	// NeutralSections lists top-level sections whose content is language-neutral
	// (e.g. an image gallery). In this (non-default) language's build, the
	// section's default-language content pages are included as-is, while the
	// section index uses this language's `_index.<lang>.md` sidecar.
	NeutralSections []string `yaml:"neutralSections"`

	// Params overrides the top-level `params:` block for this language's
	// build (e.g. translated subTitle / description / keywords). Only fields
	// that are relevant per-language are honored: subTitle, footerSlogan,
	// keywords, description. Empty fields fall back to the top-level params.
	Params LanguageParamsConfig `yaml:"params"`

	// StaticExclude lists slash-path prefixes under static/ skipped when
	// copying static assets for THIS language's build (e.g. ["en/"] on the
	// en language prevents static/en/ from landing at <out>/en/en/).
	StaticExclude []string `yaml:"staticExclude"`

	// StaticRoot maps a static/ subdirectory to this language's output root.
	// e.g. "en" makes static/en/* the language-local static dir, copied to
	// the output root of this language's build (replacing the plain static/
	// copy for those prefixed files).
	StaticRoot string `yaml:"staticRoot"`
}

LanguageConfig holds per-language settings declared under the `languages:` block in huan.yaml. Mirrors Hugo's languages map structure for familiarity.

Example yaml:

languages:
  zh-cn:
    weight: 1
    languageName: 中文
    baseURL: ""           # root path
    title: "祝融说。"
  en:
    weight: 2
    languageName: English
    baseURL: "/en"        # subpath prefix
    title: "Zhurong Says"

type LanguageEntry added in v0.3.0

type LanguageEntry struct {
	Code string
	Lang LanguageConfig
}

LanguageEntry pairs a language code with its LanguageConfig, returned by SortedLanguages for deterministic iteration.

type LanguageParamsConfig added in v0.8.0

type LanguageParamsConfig struct {
	SubTitle     string   `yaml:"subTitle"`
	FooterSlogan string   `yaml:"footerSlogan"`
	Keywords     []string `yaml:"keywords"`
	Description  string   `yaml:"description"`
}

LanguageParamsConfig is the per-language subset of ParamsConfig honored by `languages.<code>.params`. Fields left empty keep the top-level `params:` value for this language's build.

type MarkupConfig

type MarkupConfig struct {
	Goldmark GoldmarkConfig `yaml:"goldmark"`
}
type MenuItem struct {
	Name       string `yaml:"name"`
	Weight     int    `yaml:"weight"`
	Identifier string `yaml:"identifier"`
	URL        string `yaml:"url"`
}

type OutputsConfig

type OutputsConfig struct {
	Home     []string `yaml:"home"`
	Page     []string `yaml:"page"`
	Section  []string `yaml:"section"`
	Taxonomy []string `yaml:"taxonomy"`
	Term     []string `yaml:"term"`
}

type ParamsConfig

type ParamsConfig struct {
	SubTitle        string   `yaml:"subTitle"`
	FooterSlogan    string   `yaml:"footerSlogan"`
	Keywords        []string `yaml:"keywords"`
	Description     string   `yaml:"description"`
	Copyrights      string   `yaml:"copyrights"`
	EnableMathJax   bool     `yaml:"enableMathJax"`
	EnableSummary   bool     `yaml:"enableSummary"`
	MainSections    []string `yaml:"mainSections"`
	GoogleAnalytics string   `yaml:"googleAnalytics"`
	CDNURL          string   `yaml:"cdnURL"`

	Author AuthorConfig `yaml:"author"`
}

type PluginConfig added in v0.7.0

type PluginConfig struct {
	Category string         `yaml:"category"` // "static" | "dynamic" | "mixed", empty = dynamic
	Config   map[string]any `yaml:",inline"`
}

PluginConfig is the configuration for a single plugin entry in huan.yaml.

func (PluginConfig) RawConfig added in v0.7.0

func (p PluginConfig) RawConfig() map[string]any

RawConfig returns the plugin's raw config map (excluding the category field). Provides backward compatibility for code that previously received map[string]any.

type RSSConfig

type RSSConfig struct {
	Limit int `yaml:"limit"`
}

type ServicesConfig

type ServicesConfig struct {
	RSS    RSSConfig
	Disqus DisqusConfig
}

ServicesConfig mirrors Hugo's [services] section for template compatibility.

type SitemapConfig

type SitemapConfig struct {
	ChangeFreq string  `yaml:"changefreq"`
	Filename   string  `yaml:"filename"`
	Priority   float64 `yaml:"priority"`
}

type SitemapPageConfig

type SitemapPageConfig struct {
	Disable    bool    `yaml:"disable"`
	ChangeFreq string  `yaml:"changefreq"`
	Priority   float64 `yaml:"priority"`
}

SitemapPageConfig for per-page sitemap control.

type SocialItem

type SocialItem struct {
	Name   string `yaml:"name"`
	URL    string `yaml:"url"`
	Weight int    `yaml:"weight"`
}

Jump to

Keyboard shortcuts

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