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 ¶
- Variables
- func BackupPath(path string, v int) string
- func CreateFile[T any](path string, o *Options) (err error)
- func DefaultDirs(app string) []string
- func DefineFlags[T any](fs *flag.FlagSet, o *Options) error
- func Format(raw []byte, o *jwcc.FormatOptions) ([]byte, error)
- func Locate(name string, dirs ...string) (string, error)
- func Redacted[T any](v *T) any
- func Template[T any](o *Options) ([]byte, error)
- func ToJSON(raw []byte, indent string) ([]byte, error)
- func WriteFile(path string, data []byte, perm fs.FileMode) (err error)
- type Change
- type Defaulter
- type Duration
- type Error
- type Field
- type File
- func (f *File[T]) Dir() string
- func (f *File[T]) Path() string
- func (f *File[T]) Reload() error
- func (f *File[T]) Result() *Result[T]
- func (f *File[T]) Save(v *T) error
- func (f *File[T]) SaveOverridden(v *T) error
- func (f *File[T]) Source(p jwcc.Path) Source
- func (f *File[T]) Update(fn func(doc *jwcc.Value) error) error
- func (f *File[T]) Value() T
- func (f *File[T]) Watch(ctx context.Context, wo WatchOptions[T]) (*Watcher, error)
- type FilePath
- type Migration
- type Options
- type Result
- type Size
- type Source
- type SourceKind
- type Unknown
- type Validator
- type WatchOptions
- type Watcher
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
BackupPath is the name of the backup taken before migrating path from version v.
func CreateFile ¶
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 ¶
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 ¶
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 ¶
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 ¶
Redacted returns v in the generic form encoding/json produces, with the values of secret fields replaced by "[redacted]", for logging.
func Template ¶
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 ¶
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 ¶
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 ¶
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 ¶
MarshalText encodes d as time.Duration.String does.
func (*Duration) UnmarshalText ¶
UnmarshalText decodes what time.ParseDuration accepts.
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 ¶
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 ¶
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]) Reload ¶
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]) Save ¶
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 ¶
SaveOverridden is Save, but writes values set by flags or the environment too when v changed them.
func (*File[T]) 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 ¶
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 ¶
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 ¶
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 ¶
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:
- Defaults, if *T is a Defaulter.
- 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.
- Environment variables, then flags (see Field).
- Validate, if *T is a Validator.
- With Options.Persist, write a migrated file back.
Load is safe for concurrent use and starts no goroutines.
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 ¶
MarshalText encodes s with the largest binary unit that divides it.
func (*Size) UnmarshalText ¶
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.
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.
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.
Source Files
¶
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. |