cfgfile

package module
v0.0.0-...-136335f Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 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.

README

cfgfile

Versioned configuration files for Go, written in JWCC (JSON with comments and trailing commas), that programs can rewrite without losing the user's comments. Standard library only, besides timeshim for the watcher's injectable clock.

  • cfgfile: Open[T] reads a file into a struct (strict decoding, versions and migrations, environment and flag overrides, validation) and saves changes back atomically, touching only what changed; Watch reloads it on change. Load[T] is the read-only shortcut.
  • jwcc: parser and printer that keep every byte, error positions as line, column and JSON path, edits by path (Set, Delete, Rename, Move) and a canonical formatter. Usable on its own.
  • cmd/cfgfile-schema: JSON Schema from struct tags, for editors.
  • cmd/cfgfile-fmt: formatting with -w, -l, -d, -check, and -strict for plain JSON; cfgfile.Format and cfgfile.ToJSON offer the same to programs (for example for a config fmt subcommand).

A complete program

First run, read, modify, save and watch:

// Command app shows the whole cycle: find or create the file, read it with
// flags and environment on top, change a value, save it, and watch it.
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"io/fs"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/djylb/cfgfile"
)

type Config struct {
	Listen  string           `json:"listen" doc:"address to listen on"`
	DataDir cfgfile.FilePath `json:"data_dir" doc:"data directory, relative to this file"`
	Token   string           `json:"token" secret:"true" doc:"API token (or APP_TOKEN_FILE)"`
	Log     struct {
		Level string `json:"level" doc:"debug, info, warn or error"`
	} `json:"log"`
}

func (c *Config) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.DataDir = "data"
	c.Log.Level = "info"
}

func (c *Config) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	opts := &cfgfile.Options{Version: 1, EnvPrefix: "APP_", Flags: flag.CommandLine}
	path := flag.String("config", "", "configuration file")
	if err := cfgfile.DefineFlags[Config](flag.CommandLine, opts); err != nil {
		log.Fatal(err)
	}
	flag.Parse()

	// First run: find the file, or write a commented template.
	if *path == "" {
		p, err := cfgfile.Locate("app.jsonc", cfgfile.DefaultDirs("app")...)
		if errors.Is(err, fs.ErrNotExist) {
			p = "app.jsonc"
			if err := cfgfile.CreateFile[Config](p, opts); err != nil {
				log.Fatal(err)
			}
		} else if err != nil {
			log.Fatal(err)
		}
		*path = p
	}

	// Read: defaults, file, environment, flags, Validate.
	f, err := cfgfile.Open[Config](*path, opts)
	if err != nil {
		log.Fatal(err) // e.g. app.jsonc:4:5: log.levle: unknown member
	}
	for _, w := range f.Result().Warnings {
		log.Print(w)
	}
	cfg := f.Value()
	log.Printf("config: %+v", cfgfile.Redacted(&cfg))

	// Modify and save: only the changed member is rewritten.
	cfg.Listen = "127.0.0.1:9090"
	if err := f.Save(&cfg); err != nil {
		log.Fatal(err) // ErrConflict, ErrOverridden, validation errors
	}

	// Watch for edits; SIGHUP forces a reload.
	w, err := f.Watch(context.Background(), cfgfile.WatchOptions[Config]{
		OnChange: func(c cfgfile.Change[Config]) { log.Printf("changed: %v", c.Changed) },
		OnError:  func(err error) { log.Print(err) },
	})
	if err != nil {
		log.Fatal(err)
	}
	defer w.Close()
	hup := make(chan os.Signal, 1)
	signal.Notify(hup, syscall.SIGHUP, os.Interrupt)
	for s := range hup {
		if s == os.Interrupt {
			return
		}
		w.Reload()
	}
}

Traps

  • Values from flags and the environment are never written to the file. Changing one in memory and calling Save fails with ErrOverridden naming the paths; use SaveOverridden to write them on purpose.
  • Someone else edited the file: Save and Update fail with ErrConflict instead of overwriting; call Reload and retry. Two Files on the same path conflict the same way; share one File.
  • A versioned file needs its version member. With Options.Version set a file without "version" is rejected with a message saying what to add. Leave Version at 0 for files that are never migrated.
  • Defaults are not written by Save, only changes; use Template or CreateFile for a file with every member and its documentation.
  • Relative paths are relative to the working directory unless the field is a cfgfile.FilePath, which is resolved against the file's directory.
  • No includes, no multi-file merging. A rewrite needs one file that is the single source of every value; merged files would make it ambiguous which file a change belongs in.
  • Save writes new members in the file's style: the indentation unit of the surrounding members (else the file's first indentation, else two spaces) and the trailing-comma style of the enclosing object; objects go one member per line, arrays of plain values stay on one line.

Reading

Open and Load apply, in order: Defaults(), the file, environment variables, flags, Validate(). A missing file is not an error. Decoding is strict: unknown members (or, with Unknown: UnknownWarn, a warning per member), null for non-pointer fields, case-only matches and extra elements of fixed-size arrays are rejected. Errors carry file, line, column and path: app.jsonc:4:5: log.levle: unknown member. Files larger than Limits.MaxSize (default 1 MiB; twice that for UTF-16) are not read.

Versions and migrations

With Options.Version set, the top-level integer version (name configurable) is required, a newer file is refused (ErrTooNew), and Migrations[N] turns version N into N+1 on the syntax tree, so it can handle members the struct no longer has; the version is then updated. With Persist, a migrated file is written back after copying the original to app.jsonc.v1.bak (never replaced). If that fails, for example on a read-only file system, the migrated value is still used and ErrNotPersisted is reported in Result.Warnings.

Flags and environment

Every leaf of the struct can come from a flag and an environment variable named after its path in the file:

file path flag environment (EnvPrefix: "APP_")
data_dir -data_dir APP_DATA_DIR or APP_DATA_DIR_FILE
log.level -log.level APP_LOG_LEVEL
admin.bootstrap.user -admin.bootstrap.user APP_ADMIN_BOOTSTRAP_USER

Path elements are json names; embedded structs are flattened; . and - become _ in variable names, which are upper case. NAME_FILE reads the value from a file (for secrets mounted as files). Leaves are non-struct fields and types that decode themselves; slices and maps are leaves and are written as JSON (APP_PORTS=[80,443]); strings are taken verbatim and encoding.TextUnmarshaler types use UnmarshalText. Precedence: flags, environment, file, Defaults.

DefineFlags[T](fs, opts) defines the flags with the defaults as default values and the doc tag (or the type) as usage. Set Options.Flags to the FlagSet; after Parse, the flags that were given override the rest. Tags: flag:"-" and env:"-" exclude a field; secret:"true" keeps its value out of errors, flag defaults, templates and Redacted (a rejected secret flag value is reported by Load without the value, not by the flag package).

Validation tags and sources

Beside Validate(), two tags are checked on load and emitted in the schema, so that editors and the program agree: required:"true" (the file, a flag or the environment must set the member; ErrRequired) and enum:"a,b,c" (ErrEnum, also checked before Save writes). Errors carry the position in the file or the flag or variable that set the value; a secret value is never shown.

File.Source(path) (and Result.Source) tells where a value came from: app.jsonc:4:5, environment variable APP_TOKEN_FILE, flag -log.level or default. It never includes the value.

Saving

File.Save(&v) compares v with what the file holds field by field (ignoring omitempty, so zero values are written) and edits only the members that differ; everything else, comments included, stays. File.Update(fn) edits the syntax tree directly. Both validate the result before writing, write atomically (temporary file in the same directory, fsync, rename, directory fsync; the mode is kept; a symbolic link's target is replaced and the link kept; a hard link is broken), and then read the file back. If only the directory sync fails the file is written and the error wraps ErrNotDurable. The conflict check and the rename are not one atomic step; to close that window between cooperating processes, set LockWrites: every write then holds an advisory lock on <file>.lock (flock on Linux, macOS and the BSDs, LockFileEx on Windows, nothing elsewhere or when the directory is read-only). Readers never take it, and the lock file is left in place.

Encodings and line endings

  • UTF-8 with or without a byte order mark; the mark is kept on rewrite and does not count in columns.
  • UTF-16 LE or BE with a byte order mark: transcoded to UTF-8 for reading (positions refer to the UTF-8 text; Result.Text is UTF-8) and written back as UTF-16 with the same mark.
  • Anything else, such as legacy 8-bit encodings, is rejected at the first invalid byte: app.jsonc:2:6: invalid UTF-8 byte 0xd6: the file is not UTF-8; save it as UTF-8. Bytes are never replaced silently.
  • The dialect is JWCC: comments and trailing commas, nothing else. Duplicate member names are rejected, a line comment may end at the end of the input, and a lone CR ends a line comment as it ends a line in editors.
  • LF, CRLF and a lone CR all end a line. Edits write new line breaks in the file's dominant style, so a file never ends up mixed. Files created by Update/Save use LF, or CRLF with Options.CRLF.

Characters that input methods put in place of JSON punctuation are rejected by name: 3:7: full-width colon ':'; use ':' (also full-width commas, braces, brackets, curly quotes, non-breaking and full-width spaces).

Formatting

jwcc.Format writes one member per line with consistent indentation (two spaces or Indent), "name": value, at most one blank line between members, and comments kept beside their members and re-indented. Member order, literal text, the byte order mark and the line-ending style are kept. Trailing commas follow Trailing: added to every multi-line container (default), kept as written, or removed. Arrays of plain values written on one line stay on one line. Formatting is idempotent and never changes the decoded value.

Hot reload

File.Watch(ctx, opts) polls every Interval (default 2s). A change of size, modification time or file identity (atomic rename), or a modification time recent enough that a coarse clock could hide a write, leads to a content hash, and only new content is loaded, after Debounce (default 200ms) of quiet. A reload runs the whole read pipeline; invalid files and removal (ErrRemoved) go to OnError and keep the previous value; a different valid value becomes File.Value and goes to OnChange with the old and new values and the top-level members that changed. Clock (a timeshim.Clock, default timeshim.Real) schedules the polls, so tests can drive them with a timeshim.Fake; the recent-modification check always compares file times with real time. Which members can be applied without a restart is the caller's decision. The File's own Save and Update do not cause callbacks. Watcher.Reload forces a reload, for example on SIGHUP.

Each watch runs exactly one goroutine, which ends when the context is done or Close is called; callbacks run on it one at a time. Close is idempotent and does not block; after it returns no new callback starts, and Done is closed once the goroutine (and a callback already running) has finished.

Finding the file

DefaultDirs("app") lists, in order of precedence, the working directory, the user's configuration directory (os.UserConfigDir) and the system directory (/etc/app; also /Library/Application Support/app on macOS; %ProgramData%\app on Windows). Locate(name, dirs...) returns the first that exists. A path given explicitly (-config) should win over all.

Schema

//go:generate go run github.com/djylb/cfgfile/cmd/cfgfile-schema -type Config -o app.schema.json

Point the file's "$schema" member at the published schema. The schema serves editors only; Load does not read it.

Concurrency

No global state; the only goroutine is the one per watch. All functions and File methods are safe for concurrent use; writes through one File are serialised.

License

Apache-2.0

Documentation

Overview

Package cfgfile reads, writes and watches versioned configuration files written in JWCC (JSON with comments and trailing commas; see package jwcc), and rewrites them without losing the user's comments.

Open loads a file into a struct and returns a File: Value is the configuration in effect, Save and Update write changes back, touching only what changed and refusing to overwrite edits made by someone else, and Watch reloads the file when it changes. Load is the read-only shortcut.

Reading applies Defaults, the file (strictly decoded, migrated step by step on the syntax tree when versioned), environment variables and flags named after the file's paths, then Validate:

file path   log.level
flag        -log.level
environment APP_LOG_LEVEL (or APP_LOG_LEVEL_FILE)   with EnvPrefix "APP_"

Values from flags and the environment only change the value in memory; Save refuses to write them (ErrOverridden) unless asked to.

Files may be UTF-8 (with or without a byte order mark) or UTF-16 with a byte order mark, with LF, CRLF or CR line endings; rewrites keep the encoding, the byte order mark and the line endings. Other encodings are rejected with the position of the first byte that is not UTF-8.

Includes and merging several files are not supported: a rewrite needs a single file that holds every value.

The package has no global state. The only goroutine it starts is the one per File.Watch, which ends when its context is done or Close is called. All functions and File methods are safe for concurrent use.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrTooNew       = errors.New("cfgfile: file version is newer than this program supports")
	ErrNoVersion    = errors.New("cfgfile: file has no valid version")
	ErrNoMigration  = errors.New("cfgfile: no migration for file version")
	ErrConflict     = errors.New("cfgfile: file changed since it was read")
	ErrOverridden   = errors.New("cfgfile: value set by a flag or environment variable was changed")
	ErrNotPersisted = errors.New("cfgfile: migrated configuration not written back")
	ErrNotDurable   = errors.New("cfgfile: file replaced, but the directory sync failed")
	ErrUnknown      = errors.New("unknown member")
	ErrEncoding     = errors.New("cfgfile: unsupported file encoding")
	ErrRemoved      = errors.New("cfgfile: configuration file removed")
	ErrRequired     = errors.New("required member missing")
	ErrEnum         = errors.New("value not allowed")
)

Errors of this package; test with errors.Is.

Functions

func BackupPath

func BackupPath(path string, v int) string

BackupPath is the name of the backup taken before migrating path from version v.

func CreateFile

func CreateFile[T any](path string, o *Options) (err error)

CreateFile writes Template to path if no file exists there; otherwise it fails with an error wrapping fs.ErrExist and leaves the file alone.

func DefaultDirs

func DefaultDirs(app string) []string

DefaultDirs returns the usual places for the configuration of app, in order of precedence: the working directory, the user's configuration directory (os.UserConfigDir, e.g. ~/.config/app), then the system directory (/etc/app on Unix, also /Library/Application Support/app on macOS, %ProgramData%\app on Windows). A path given explicitly, such as a -config flag, should take precedence over all of them.

func DefineFlags

func DefineFlags[T any](fs *flag.FlagSet, o *Options) error

DefineFlags defines one flag per leaf of T on fs (see Field), with the defaults from T's Defaults as default values (not for secret fields) and the doc tag, or else the type, as usage. Values are checked when fs is parsed. Set Options.Flags to fs so that Load applies the flags that were given; flags defined by other means but named like a field are applied too.

Example

Flags and environment variables named after the file's paths override it in memory only.

package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"github.com/djylb/cfgfile"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	fs := flag.NewFlagSet("app", flag.ContinueOnError)
	config := fs.String("config", "app.jsonc", "configuration file")
	o := &cfgfile.Options{EnvPrefix: "APP_", Flags: fs}
	if err := cfgfile.DefineFlags[ExampleConfig](fs, o); err != nil {
		fmt.Println(err)
		return
	}
	_ = fs.Parse([]string{"-log.level=warn"})
	r, err := cfgfile.Load[ExampleConfig](filepath.Join(os.TempDir(), "missing", *config), o)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Exists, r.Value.Log.Level, r.Overrides)
}
Output:
false warn [log.level]

func Format

func Format(raw []byte, o *jwcc.FormatOptions) ([]byte, error)

Format formats the content of a configuration file with jwcc.Format, keeping its encoding (UTF-8 with or without a byte order mark, or UTF-16 with one) and line endings.

func Locate

func Locate(name string, dirs ...string) (string, error)

Locate returns the first of dir/name for dirs that is an existing file. If there is none, the error wraps fs.ErrNotExist and lists the places tried; a program without a file can then Open the path it would create.

func Redacted

func Redacted[T any](v *T) any

Redacted returns v in the generic form encoding/json produces, with the values of secret fields replaced by "[redacted]", for logging.

func Template

func Template[T any](o *Options) ([]byte, error)

Template returns a configuration file for T holding every member with its default (from Defaults; fields under a secret member are left zero), the doc tag of each member as a comment above it and, when versioned, the version.

Example

Template writes every member with its default and documentation.

package main

import (
	"fmt"

	"github.com/djylb/cfgfile"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	b, _ := cfgfile.Template[ExampleConfig](&cfgfile.Options{Version: 1})
	fmt.Print(string(b))
}
Output:
{
  "version": 1,
  // address to listen on
  "listen": "127.0.0.1:8080",
  "log": {
    // debug, info, warn or error
    "level": "info",
  },
}

func ToJSON

func ToJSON(raw []byte, indent string) ([]byte, error)

ToJSON returns the content of a configuration file as indented standard JSON in UTF-8, without comments, trailing commas or byte order mark.

func WriteFile

func WriteFile(path string, data []byte, perm fs.FileMode) (err error)

WriteFile replaces path atomically: it writes a uniquely named temporary file in the same directory, syncs it, renames it over path and syncs the directory. Readers see the old or the new content, never a mix. The temporary file is removed on every failure.

If path is a symbolic link, the file it points to is replaced and the link is kept. A hard link is broken: the path gets a new file and other names keep the old content. An existing file keeps its mode; a new one gets perm. Ownership is not copied.

If only the final directory sync fails, the file has been replaced and the error wraps ErrNotDurable.

Types

type Change

type Change[T any] struct {
	Old, New T
	// Changed lists the top-level members whose value differs, as the
	// struct encodes them. Which of them can be applied without a restart
	// is the caller's decision.
	Changed []jwcc.Path
	// Result is the new load result (warnings, migration).
	Result *Result[T]
}

Change describes a reload that changed the value in effect.

type Defaulter

type Defaulter interface{ Defaults() }

Defaulter is implemented by configuration types that set defaults before the file is decoded; members absent from the file keep them.

type Duration

type Duration time.Duration

Duration is a time.Duration written as a string such as "30s" or "1h30m".

MarshalText has a value receiver so that values and fields both encode; UnmarshalText needs a pointer receiver. The same holds for Size.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText encodes d as time.Duration.String does.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(b []byte) error

UnmarshalText decodes what time.ParseDuration accepts.

type Error

type Error struct {
	File         string
	Line, Column int
	Path         jwcc.Path
	Err          error
}

Error locates a problem in a configuration file.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Field

type Field struct {
	// Path is the path of the value in the file, such as log.level.
	Path jwcc.Path
	// Flag is the flag name: the path in text form, such as "log.level";
	// empty with flag:"-".
	Flag string
	// Env is the environment variable: the prefix followed by the path
	// with '.', '-' and brackets turned into '_' and letters upper-cased,
	// such as APP_LOG_LEVEL; empty with env:"-" or without a prefix.
	// Env+"_FILE" names a file holding the value instead.
	Env string
	// Doc is the field's doc tag.
	Doc    string
	Secret bool
	Type   reflect.Type
	// contains filtered or unexported fields
}

Field is a leaf of a configuration type: a value that the file, a flag and an environment variable can each set.

Struct tags control it beside json: doc:"text" documents it (flag usage, generated files, schema); flag:"-" and env:"-" keep it from flags or the environment; secret:"true" keeps its value out of errors, flag defaults, generated files and Redacted; required:"true" makes Load fail (ErrRequired) unless the file, a flag or the environment sets it; enum:"a,b,c" limits it to the listed values (ErrEnum). The schema tool emits required and enum too.

func Fields

func Fields[T any](o *Options) ([]Field, error)

Fields lists the leaves of T, which must be a struct. A leaf is a field whose type is not a struct, or decodes itself through encoding.TextUnmarshaler or json.Unmarshaler; slices and maps are leaves. The top-level version member of a versioned file is not a field. Two leaves mapping to the same environment variable are an error.

type File

type File[T any] struct {
	// contains filtered or unexported fields
}

File is an open configuration file: the value in effect and what is needed to write the file back safely. It is the main entry point:

f, err := cfgfile.Open[Config]("app.jsonc", opts)
cfg := f.Value()
cfg.Log.Level = "debug"
err = f.Save(&cfg)

File remembers the content it read, so Save and Update refuse to overwrite changes made by someone else since (ErrConflict), and it remembers which values came from flags or the environment, so they are not written to the file by accident (ErrOverridden). Methods are safe for concurrent use; writes are serialised.

func Open

func Open[T any](path string, o *Options) (*File[T], error)

Open loads the configuration at path, as Load, and returns a handle for reading, saving and watching it. A missing file is not an error: the value then holds the defaults and overrides, and the first Save or Update creates the file (see CreateFile to write a commented template instead).

Example

Open a file, change a value and save it: comments and layout stay.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/djylb/cfgfile"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			fmt.Println(err)
		}
	}()
	path := filepath.Join(dir, "app.jsonc")
	_ = os.WriteFile(path, []byte(`{
  "version": 1,
  // reachable from the LAN
  "listen": "0.0.0.0:8080",
}
`), 0o600)

	f, err := cfgfile.Open[ExampleConfig](path, &cfgfile.Options{Version: 1})
	if err != nil {
		fmt.Println(err)
		return
	}
	cfg := f.Value()
	fmt.Println(cfg.Listen, cfg.Log.Level)

	cfg.Log.Level = "debug"
	if err := f.Save(&cfg); err != nil {
		fmt.Println(err)
		return
	}
	b, _ := os.ReadFile(path)
	fmt.Print(string(b))
}
Output:
0.0.0.0:8080 info
{
  "version": 1,
  // reachable from the LAN
  "listen": "0.0.0.0:8080",
  "log": {
    "level": "debug",
  },
}

func (*File[T]) Dir

func (f *File[T]) Dir() string

Dir returns the directory relative Path fields are resolved against.

func (*File[T]) Path

func (f *File[T]) Path() string

Path returns the file's path.

func (*File[T]) Reload

func (f *File[T]) Reload() error

Reload reads the file again now, with the environment and flags, and makes the result the value in effect. On error the previous value stays.

func (*File[T]) Result

func (f *File[T]) Result() *Result[T]

Result returns the outcome of the last load. Treat it as read-only.

func (*File[T]) Save

func (f *File[T]) Save(v *T) error

Save writes v to the file, changing only the members whose value differs from what the file holds, so comments and untouched formatting stay. Fields are compared one by one (omitempty is ignored), so a zero value is written too. Values that came from a flag or the environment are not written; if v changes one of them, Save fails with ErrOverridden naming it (see SaveOverridden). After writing, the file is read back and becomes the value in effect.

Save fails with ErrConflict if the file changed since it was last read; Reload and retry. If only the final directory sync fails, the file has been written and the error wraps ErrNotDurable.

func (*File[T]) SaveOverridden

func (f *File[T]) SaveOverridden(v *T) error

SaveOverridden is Save, but writes values set by flags or the environment too when v changed them.

func (*File[T]) Source

func (f *File[T]) Source(p jwcc.Path) Source

Source returns where the value in effect at p came from; see Result.Source.

Example

Source tells where each value came from, for diagnostics such as a "config show" command.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/djylb/cfgfile"
	"github.com/djylb/cfgfile/jwcc"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			fmt.Println(err)
		}
	}()
	path := filepath.Join(dir, "app.jsonc")
	_ = os.WriteFile(path, []byte("{\n  \"listen\": \":80\"\n}\n"), 0o600)

	env := map[string]string{"APP_LOG_LEVEL": "debug"}
	f, err := cfgfile.Open[ExampleConfig](path, &cfgfile.Options{
		EnvPrefix: "APP_",
		LookupEnv: func(k string) (string, bool) { v, ok := env[k]; return v, ok },
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(filepath.Base(f.Source(jwcc.Path{"listen"}).File), f.Source(jwcc.Path{"listen"}).Line)
	fmt.Println(f.Source(jwcc.Path{"log", "level"}))
}
Output:
app.jsonc 2
environment variable APP_LOG_LEVEL

func (*File[T]) Update

func (f *File[T]) Update(fn func(doc *jwcc.Value) error) error

Update edits the file's syntax tree through fn and writes it back atomically; comments and formatting fn does not touch are kept. The result must decode into a T and pass its Validate. A missing file starts as an empty object; an older file is migrated first and backed up. Errors are as for Save.

If the file was written but the result does not load with the flags and environment applied (for example an override no longer validates), the error says so, the previous value stays in effect, and the next Save or Update fails with ErrConflict until Reload succeeds; a running Watch reports the error through OnError.

func (*File[T]) Value

func (f *File[T]) Value() T

Value returns a copy of the configuration in effect. The copy is shallow: do not modify maps or slices shared with it in place.

func (*File[T]) Watch

func (f *File[T]) Watch(ctx context.Context, wo WatchOptions[T]) (*Watcher, error)

Watch reloads the file when it changes and reports to wo's callbacks. It polls every Interval: a change in size, modification time or file identity (an atomic rename replaces it), or a recent modification time (coarse clocks), leads to a content hash; only content that differs from the value in effect is loaded, after Debounce of quiet. A reload runs the whole Load pipeline (migrations are written back only with Options.Persist). Invalid results and removal go to OnError and keep the previous value; a valid value that differs from the previous one becomes the value in effect and goes to OnChange. The file's own Save and Update do not cause callbacks.

Watch starts exactly one goroutine, which ends when ctx is done or Watcher.Close is called. Callbacks run on it one at a time. A File has at most one Watcher at a time.

Example

Watch delivers valid changes; invalid edits keep the previous value.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/djylb/cfgfile"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			fmt.Println(err)
		}
	}()
	path := filepath.Join(dir, "app.jsonc")
	_ = os.WriteFile(path, []byte(`{"listen": ":80"}`), 0o600)

	f, err := cfgfile.Open[ExampleConfig](path, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	changes := make(chan cfgfile.Change[ExampleConfig], 1)
	w, err := f.Watch(context.Background(), cfgfile.WatchOptions[ExampleConfig]{
		Interval: 10 * time.Millisecond,
		OnChange: func(c cfgfile.Change[ExampleConfig]) { changes <- c },
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer w.Close()
	_ = os.WriteFile(path, []byte(`{"listen": ":81"}`), 0o600)
	c := <-changes
	fmt.Println(c.Old.Listen, "->", c.New.Listen, c.Changed)
}
Output:
:80 -> :81 [listen]

type FilePath

type FilePath string

FilePath is a file system path that Load resolves against the directory of the configuration file when it is relative, so "data" next to /etc/app/app.jsonc means /etc/app/data. Values from flags and the environment stay relative to the working directory, and Save writes a changed value as given.

type Migration

type Migration func(doc *jwcc.Value) error

Migration rewrites a document of version N into version N+1. It edits the syntax tree, so it can handle members the current type no longer has. Load sets the version member afterwards.

Example

A migration renames a member of version 1 on the syntax tree.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/djylb/cfgfile"
	"github.com/djylb/cfgfile/jwcc"
)

type ExampleConfig struct {
	Listen string `doc:"address to listen on" json:"listen"`
	Log    struct {
		Level string `doc:"debug, info, warn or error" json:"level"`
	} `json:"log"`
}

func (c *ExampleConfig) Defaults() {
	c.Listen = "127.0.0.1:8080"
	c.Log.Level = "info"
}

func (c *ExampleConfig) Validate() error {
	switch c.Log.Level {
	case "debug", "info", "warn", "error":
		return nil
	}
	return fmt.Errorf("log.level: unknown level %q", c.Log.Level)
}

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			fmt.Println(err)
		}
	}()
	path := filepath.Join(dir, "app.jsonc")
	_ = os.WriteFile(path, []byte(`{"version": 1, "addr": ":80"}`), 0o600)

	o := &cfgfile.Options{
		Version: 2,
		Migrations: map[int]cfgfile.Migration{
			1: func(doc *jwcc.Value) error { return doc.Rename(jwcc.Path{"addr"}, "listen") },
		},
		Persist: true,
	}
	r, err := cfgfile.Load[ExampleConfig](path, o)
	if err != nil {
		fmt.Println(err)
		return
	}
	b, _ := os.ReadFile(path)
	fmt.Println(r.Value.Listen, r.Persisted, string(b))
}
Output:
:80 true {"version": 2, "listen": ":80"}

type Options

type Options struct {
	// Version is the file version this program reads and writes. Zero
	// means unversioned: no version member is required or written.
	Version int
	// VersionField is the top-level member holding the version; default
	// "version".
	VersionField string
	// Migrations[N] migrates version N to N+1.
	Migrations map[int]Migration
	// EnvPrefix enables environment overlay ("" disables it); see Field.
	EnvPrefix string
	// LookupEnv reads the environment; default os.LookupEnv.
	LookupEnv func(string) (string, bool)
	// Flags is read after it has been parsed: every flag that was set on
	// the command line and is named like a field (see Field and
	// DefineFlags) overrides the environment and the file.
	Flags *flag.FlagSet
	// Limits bounds parsing; nil uses the jwcc defaults. Files larger than
	// Limits.MaxSize (twice that for UTF-16) are not read.
	Limits *jwcc.Limits
	// Unknown selects how unknown members are handled.
	Unknown Unknown
	// NewFilePerm is the mode of a file this package creates; default 0600.
	// Existing files keep their mode.
	NewFilePerm fs.FileMode
	// Persist makes Load write a migrated file back: the original is first
	// copied to <path>.v<old>.bak (never overwritten), then the file is
	// replaced atomically. If that fails Load still succeeds and reports
	// the failure in Result.Warnings, wrapped with ErrNotPersisted.
	Persist bool
	// NewFileCRLF makes a file this package creates use CRLF line endings
	// instead of LF. Existing files keep their own line endings.
	NewFileCRLF bool
	// LockWrites makes every write (Save, Update, Persist) hold an
	// advisory lock on <path>.lock from the conflict check to the rename,
	// so that cooperating processes cannot interleave writes. Readers never
	// take it. It uses flock on Linux, macOS and the BSDs and LockFileEx on
	// Windows, and does nothing elsewhere or when the directory is not
	// writable. The lock file is left in place.
	LockWrites bool
}

Options configures Load and Open. A nil *Options is the zero value: an unversioned file, no environment, no flags.

type Result

type Result[T any] struct {
	Value T
	// FileVersion is the version found in the file (0 without a file or
	// when unversioned).
	FileVersion int
	// Exists reports that the file was found.
	Exists bool
	// Migrated reports that migrations ran; Persisted that the result was
	// written back.
	Migrated, Persisted bool
	// Text is the document after migration (nil without a file), for
	// example for a dry run. It is UTF-8 even for a UTF-16 file.
	Text []byte
	// Overrides lists the paths set by a flag or an environment variable.
	Overrides []jwcc.Path
	// Warnings are non-fatal problems, such as ErrNotPersisted and, with
	// UnknownWarn, ErrUnknown.
	Warnings []error
	// contains filtered or unexported fields
}

Result is the outcome of Load.

func Load

func Load[T any](path string, o *Options) (*Result[T], error)

Load reads the configuration at path into a T, which must be a struct. It is the stateless form of Open, for programs that only read:

  1. Defaults, if *T is a Defaulter.
  2. The file, if path is not empty and the file exists: parse, check the version (newer than Options.Version is ErrTooNew), run migrations, then decode strictly: unknown members (see Options.Unknown), null for non-pointer fields, and members that differ from a field name only in case are errors. The top-level "$schema" member and, when versioned, the version member are always allowed. Relative Path fields are resolved against the file's directory.
  3. Environment variables, then flags (see Field).
  4. Validate, if *T is a Validator.
  5. With Options.Persist, write a migrated file back.

Load is safe for concurrent use and starts no goroutines.

func (*Result[T]) Source

func (r *Result[T]) Source(p jwcc.Path) Source

Source returns where the value at p came from: a flag, an environment variable, a position in the file, or the default. A position refers to the document as loaded; after an in-memory migration that is Result.Text, not the file on disk.

type Size

type Size uint64

Size is a byte count written as a string: a non-negative integer with an optional unit B, KB, MB, GB, TB, PB (powers of 1000) or KiB, MiB, GiB, TiB, PiB (powers of 1024), such as "64MiB". It marshals with the largest binary unit that represents it exactly.

func (Size) MarshalText

func (s Size) MarshalText() ([]byte, error)

MarshalText encodes s with the largest binary unit that divides it.

func (*Size) UnmarshalText

func (s *Size) UnmarshalText(b []byte) error

UnmarshalText decodes a byte count with an optional unit suffix.

type Source

type Source struct {
	Kind         SourceKind
	File         string
	Line, Column int
	Name         string
}

Source tells where a value came from. It never holds the value, so it is safe to show for secrets.

func (Source) String

func (s Source) String() string

type SourceKind

type SourceKind int

SourceKind is where a value came from.

const (
	// FromDefault means neither the file, the environment nor a flag set it.
	FromDefault SourceKind = iota
	// FromFile means the file holds it, at Source.File:Line:Column.
	FromFile
	// FromEnv means it came from the environment variable Source.Name (possibly NAME_FILE).
	FromEnv
	// FromFlag means it came from the flag -Source.Name.
	FromFlag
)

type Unknown

type Unknown int

Unknown selects what happens to members of the file that the type does not have.

const (
	// UnknownReject makes an unknown member an error (the default).
	UnknownReject Unknown = iota
	// UnknownWarn ignores unknown members and reports each one in
	// Result.Warnings, wrapped with ErrUnknown.
	UnknownWarn
)

type Validator

type Validator interface{ Validate() error }

Validator is implemented by configuration types that check themselves after the file and the overlay are applied.

type WatchOptions

type WatchOptions[T any] struct {
	// Interval between checks of the file; default 2s.
	Interval time.Duration
	// Debounce is how long the file must stay unchanged after a change is
	// seen before it is read; default 200ms. A burst of writes is read once.
	Debounce time.Duration
	// OnChange receives every new valid configuration that differs from
	// the previous one.
	OnChange func(Change[T])
	// OnError receives failed reloads (with file positions where known)
	// and ErrRemoved. The previous value stays in effect.
	OnError func(error)
	// Clock schedules the polling; nil uses timeshim.Real. Tests can supply
	// a timeshim.Fake to run the watcher deterministically. The check for a
	// recently modified file compares file times with real time whatever
	// the clock, since file times come from the real file system.
	Clock timeshim.Clock
}

WatchOptions configures File.Watch.

type Watcher

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

Watcher is a running File.Watch.

func (*Watcher) Close

func (w *Watcher) Close()

Close stops the watcher. It is idempotent and does not block. The goroutine commits to each callback under the watcher's lock: after Close returns no callback is committed, so at most the one committed before Close can still be running (or about to run); Done is closed after it returns. A callback may call Close and the File's methods.

func (*Watcher) Done

func (w *Watcher) Done() <-chan struct{}

Done is closed when the watcher's goroutine has ended.

func (*Watcher) Reload

func (w *Watcher) Reload()

Reload asks for a reload now, for example on SIGHUP, even if the file looks unchanged; the environment is read again too. It does not block; requests made while one is pending are merged.

Directories

Path Synopsis
cmd
cfgfile-fmt command
Command cfgfile-fmt formats JWCC configuration files in canonical layout (see jwcc.Format), keeping comments, encoding and line endings.
Command cfgfile-fmt formats JWCC configuration files in canonical layout (see jwcc.Format), keeping comments, encoding and line endings.
cfgfile-schema command
Command cfgfile-schema writes a JSON Schema (draft 2020-12) for a configuration struct, for editor completion and checking.
Command cfgfile-schema writes a JSON Schema (draft 2020-12) for a configuration struct, for editor completion and checking.
internal
leakcheck
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
Package jwcc parses and edits JWCC documents: JSON with "//" and "/* */" comments and trailing commas, and nothing else.
Package jwcc parses and edits JWCC documents: JSON with "//" and "/* */" comments and trailing commas, and nothing else.

Jump to

Keyboard shortcuts

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