config

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 23 Imported by: 0 modules, 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.

Documentation

Overview

Package config loads and edits the TOML file that lists managed servers.

Index

Constants

View Source
const (
	RestartNo        = "no"
	RestartOnFailure = "on-failure"
	RestartAlways    = "always"

	// WrapAuto (the default) detects a server's tool environment and
	// WrapNone turns detection off.
	WrapAuto = "auto"
	WrapNone = "none"
)

Restart policies.

View Source
const (
	DefaultStopTimeout = 10 * time.Second
	DefaultShell       = "bash"
)

Defaults of the top-level stop_timeout and shell.

View Source
const AutoPortBase = 3001

AutoPortBase is the first port handed out to servers without an explicit port. It is 3001 rather than 3000 because 3000 is the most contested default.

View Source
const ComposeStop = "30s"

ComposeStop is the stop timeout given to compose stacks found by discovery or imported, so containers can shut down cleanly.

View Source
const DefaultUnreadyAfter = time.Minute

DefaultUnreadyAfter is how long a running server must go without answering before OnUnready runs, unless unready_after says otherwise.

Variables

View Source
var ErrConflict = errors.New("the config file changed since it was loaded; reload and try again")

ErrConflict means the file changed since the caller read it.

View Source
var ErrNotFound = errors.New("config file not found")

ErrNotFound is returned when the configuration file does not exist.

View Source
var Reserved = map[int]bool{
	3659: true, 4045: true, 5000: true, 5060: true, 5061: true, 6000: true,
	6566: true, 6665: true, 6666: true, 6667: true, 6668: true, 6669: true,
	6697: true, 7000: true, 10080: true,
}

Reserved ports are skipped by automatic assignment: 5000/7000 belong to the macOS AirPlay Receiver, the rest are on browsers' unsafe-port lists.

View Source
var WatchSkipped = []string{".git", "node_modules", ".venv", "venv", "__pycache__", "target", "dist", "build", ".next"}

WatchSkipped are the directories "**" does not descend into: version control, dependencies, virtual environments, caches and build output.

Functions

func AddServer

func AddServer(path string, s Spec) error

AddServer appends a new server table.

func CacheGood

func CacheGood(stateDir, path string, data []byte) error

CacheGood saves validated text with its original path for relative dirs.

func DefaultRestart added in v0.11.0

func DefaultRestart(oneshot bool) string

DefaultRestart is the restart policy of a server that sets none: a server comes back after a crash, while a task's failed run, such as a migration that may not be safe to repeat, is reported at once.

func IsComposeCommand

func IsComposeCommand(cmd string) bool

IsComposeCommand reports whether a server's command runs a compose stack.

func IsDashboardLabel

func IsDashboardLabel(label string) bool

IsDashboardLabel reports whether label has the form of a dashboard host label.

func NewDashboardLabel

func NewDashboardLabel() string

NewDashboardLabel returns a random label that IsDashboardLabel accepts.

func Quote

func Quote(s string) string

Quote renders s as a TOML basic string.

func ReadPort

func ReadPort(path string) (int, bool, error)

ReadPort reads just the dashboard port even when server validation fails, and whether it is automatic (the file sets none), as Parse decides.

func RemoveServer

func RemoveServer(path, name string) error

RemoveServer deletes a server table and the comments directly above it.

func Render

func Render(s Spec) string

Render returns the TOML table for a server, ending with a newline.

func ReplaceIfUnchanged

func ReplaceIfUnchanged(path string, text []byte, rev string) error

ReplaceIfUnchanged writes text only if the file still has revision rev.

func Revision

func Revision(data []byte) string

Revision identifies a version of the file's text for optimistic saves.

func SetEnabled

func SetEnabled(path, name string, enabled bool) error

SetEnabled toggles a server without touching anything else in its table.

func SetKey

func SetKey(path, name, k, literal string) error

SetKey sets one key inside a server table to a TOML literal, keeping every other line (and comment) of the table untouched.

func SetTopLevel

func SetTopLevel(path, k, literal string) error

SetTopLevel sets a top-level key (outside any table) to a TOML literal.

func SpecDir

func SpecDir(root, abs string) string

SpecDir is how the absolute directory abs is written as a server's dir: relative to root when inside it ("" for root itself), otherwise with the home directory shortened to ~.

func StarterRoot

func StarterRoot() string

StarterRoot picks the directory most likely to hold the user's projects: the candidate with the most projects one or two levels down, the more conventional name winning a tie, else the home directory.

func UpdateServer

func UpdateServer(path, name string, s Spec) error

UpdateServer patches changed fields of name with s (which may carry a new name). Comment lines directly above the table are kept unless s.Comment is set.

func UpdateServerIfUnchanged added in v0.10.2

func UpdateServerIfUnchanged(path, name string, s Spec, rev string) error

UpdateServerIfUnchanged is UpdateServer for an edit made from a form that showed revision rev of the file: it returns ErrConflict when the file has changed since ("" skips the check).

func UpdateSettingsIfUnchanged added in v0.11.1

func UpdateSettingsIfUnchanged(path string, s Settings, rev string) error

UpdateSettingsIfUnchanged writes the settings that differ from the file's, as UpdateServerIfUnchanged does for a server: a value equal to its default removes the key, and ErrConflict means the file is no longer at revision rev ("" skips the check). Comments and the other keys stay as they are.

func ValidName

func ValidName(name string) error

ValidName reports whether name can be used as a server name. Names double as DNS labels for the <name>.localhost proxy, hence the strict alphabet.

func WriteAtomic

func WriteAtomic(path string, data []byte) error

WriteAtomic replaces the file at path (or its symlink target) under the lock.

func WriteStarter

func WriteStarter(path string) error

WriteStarter creates a commented configuration file with no servers.

Types

type Config

type Config struct {
	Path string
	Root string
	Port int
	// PortAuto is true when the file sets no dashboard port, so the daemon
	// may choose another one when the default is taken (kept in the state
	// directory, see daemon.SavedPort).
	PortAuto    bool
	Shell       string
	PathPrepend []string
	Env         map[string]string
	Restore     bool
	Notify      bool
	Editor      string
	Terminal    string
	StopTimeout time.Duration
	// DockerStart is the command that starts the container engine; empty
	// means the engine behind the active Docker context is detected.
	DockerStart string
	// Share lets the owner's other devices on Tailscale connect to this daemon.
	Share bool
	// OwnEnv gives servers the daemon's own environment instead of the
	// account's login-shell environment (login_env = false).
	OwnEnv  bool
	Servers []Server
	// Warnings are non-fatal problems such as duplicate ports.
	Warnings []string
}

Config is the parsed configuration file.

func Load

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

Load reads and validates the configuration at path.

func LoadAssignedPorts

func LoadAssignedPorts(path string, avoid func(port int) bool) (*Config, error)

LoadAssignedPorts loads the daemon's config and persists automatic ports under the edit lock, so later removals or reordering cannot change them. Automatic ports skip the ports avoid reports (nil avoids none), such as those of temporary servers, which the config does not list.

func LoadRecoverable

func LoadRecoverable(path, stateDir string) (*Config, error)

LoadRecoverable always returns usable settings. Its error describes the requested file, which remains editable while the last good settings run.

func Parse

func Parse(path string, data []byte) (*Config, error)

Parse validates configuration text. path is used for messages and relative paths.

func (*Config) FreePort

func (c *Config) FreePort(inUse func(int) bool) int

FreePort returns the lowest unused, unreserved port at or above AutoPortBase.

func (*Config) Groups

func (c *Config) Groups() []string

Groups returns group names in first-appearance order.

func (*Config) Resolve

func (c *Config) Resolve(targets []string) ([]string, error)

Resolve expands names and group names into server names, keeping config order.

func (*Config) Server

func (c *Config) Server(name string) (Server, bool)

Server returns the server with the given name.

func (*Config) WithDeps

func (c *Config) WithDeps(names []string) []string

WithDeps returns names plus all their transitive dependencies, ordered so that every dependency comes before its dependents.

type Duration

type Duration struct {
	time.Duration
	Text string
}

Duration is a time.Duration written as a string such as "10s" in TOML; Text keeps that string as written.

func (*Duration) UnmarshalText

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

type Schedule added in v0.10.0

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

Schedule is a parsed crontab expression: the five standard fields (minute, hour, day of month, month, day of week) or a macro, matched in the local time of the instant Next is given.

func ParseSchedule added in v0.10.0

func ParseSchedule(expr string) (*Schedule, error)

ParseSchedule parses a crontab expression. Its errors do not repeat the expression; callers name the field and the value.

func (*Schedule) MarshalText added in v0.10.0

func (s *Schedule) MarshalText() ([]byte, error)

MarshalText writes the expression, so a Server survives JSON (as in a handoff to an upgraded daemon).

func (*Schedule) Next added in v0.10.0

func (s *Schedule) Next(after time.Time) time.Time

Next returns the first time after after that the schedule matches, in after's location. A local time that occurs twice (a clock turned back) matches once, at its first occurrence; one that does not occur (a clock turned forward) matches at the first instant after the jump. It returns the zero time when nothing matches within 400 years, the period after which the calendar and its weekdays repeat, which ParseSchedule rules out.

func (*Schedule) String added in v0.10.0

func (s *Schedule) String() string

String returns the expression as written.

func (*Schedule) UnmarshalText added in v0.10.0

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

type Server

type Server struct {
	Name      string
	Dir       string // absolute
	DirRaw    string // as written in the file
	Cmd       string
	Port      int  // 0 means the server does not listen on a port
	PortAuto  bool // port was assigned automatically
	Group     string
	DependsOn []string
	Projects  []string
	Env       map[string]string
	Restart   string
	Health    string // optional HTTP path probed for readiness, e.g. "/"
	Icon      string // optional absolute icon path
	Open      string // optional path appended to the URL when opening
	// Wrap selects how the command enters the project's tool environment:
	// "" or WrapAuto detects direnv, devbox, mise or a Node version file, WrapNone runs
	// it as is, anything else is a command prefix.
	Wrap    string
	Stop    time.Duration
	IconRaw string // icon as written
	Enabled bool
	// LAN says the server is meant to be reachable from other devices, so
	// listening on the network is not pointed out.
	LAN bool
	// OnCrash is the shell command run once the server has crashed for good:
	// the server's own on_crash, else the top-level one; "" runs nothing.
	OnCrash string
	// ReadyLog, when set, is a regular expression a line of the server's
	// output must match before it counts as running (checked at load).
	ReadyLog string
	// ReadyAfter is how long the process must have run before it counts as
	// running; 0 means the default (immediately with a port, 1.5 s without).
	ReadyAfter time.Duration
	// OnUnready runs once a running server has not answered for
	// UnreadyAfter (0 means DefaultUnreadyAfter), and OnRecover once a server that OnCrash or OnUnready
	// reported is ready again; like OnCrash, the server's own or the
	// top-level one, "" for none.
	OnUnready    string
	OnRecover    string
	UnreadyAfter time.Duration
	// RetryAfter, when positive, starts a server that its restart policy
	// gave up on (or that could not start) again after that long, with a
	// fresh round of restarts. Only with on-failure or always.
	RetryAfter time.Duration
	// Umask, when set, is the file mode creation mask the command runs
	// with, as octal digits such as "0007"; "" keeps the daemon's.
	Umask string
	// Oneshot makes the server a task: its command runs to completion,
	// code 0 is success, and servers that depend on it wait for that
	// instead of for readiness. A task has no port.
	Oneshot bool
	// Schedule, when set, starts the server at the times it matches in
	// local time; nil for none.
	Schedule *Schedule
	// MemoryLimit, when above zero, is how much memory the server's process
	// tree may use: a usage sample above it stops the server as a crash.
	// The server's own memory_limit, else the top-level one.
	MemoryLimit Size
	// Watch, when set, holds file patterns relative to Dir whose changes
	// restart the server; nil for none.
	Watch *Watch
	// contains filtered or unexported fields
}

Server is one managed dev server with defaults applied and paths resolved.

func (Server) RetriesAfterGivingUp added in v0.9.0

func (s Server) RetriesAfterGivingUp() bool

RetriesAfterGivingUp reports whether s is started again after its automatic restarts gave up or its start failed.

type Settings added in v0.11.1

type Settings struct {
	Root         string            `json:"root"`
	Port         int               `json:"port"`
	Path         []string          `json:"path"`
	Env          map[string]string `json:"env"`
	Restore      bool              `json:"restore"`
	Notify       bool              `json:"notify"`
	StopTimeout  string            `json:"stopTimeout"`
	Shell        string            `json:"shell"`
	DockerStart  string            `json:"dockerStart"`
	OnCrash      string            `json:"onCrash"`
	OnUnready    string            `json:"onUnready"`
	OnRecover    string            `json:"onRecover"`
	UnreadyAfter string            `json:"unreadyAfter"`
	RetryAfter   string            `json:"retryAfter"`
	MemoryLimit  string            `json:"memoryLimit"`
	LoginEnv     bool              `json:"loginEnv"`
	Umask        string            `json:"umask"`
}

Settings are the top-level keys the dashboard edits, as written in the file: durations and sizes keep their text, "" means unset and a Port of 0 leaves the port to the daemon. share, editor and terminal have their own controls.

func DefaultSettings added in v0.11.1

func DefaultSettings(path string) Settings

DefaultSettings are the values in effect for keys the config at path does not set; "" where the default is none, or the daemon's own.

func ReadSettings added in v0.11.1

func ReadSettings(path string) (Settings, string, error)

ReadSettings returns the settings written in the file at path and the file's revision.

type Size added in v0.10.0

type Size struct {
	Bytes  int64
	Binary bool
}

Size is an amount of memory in bytes. Binary says it was written in binary units (KiB, MiB, GiB, TiB), so it is shown in them too.

func ParseSize added in v0.10.0

func ParseSize(v string) (Size, error)

ParseSize reads a size such as "2GB", "1.5 GiB" or "512MB" (units in any case). "0" is the zero size; any other number needs a unit.

func (Size) Over added in v0.10.0

func (s Size) Over(used int64) string

Over describes used, a size above s, in s's units: "2.3 GB". A value that would read the same as s gets more decimals.

func (Size) String added in v0.10.0

func (s Size) String() string

String shows the size in GB, MB or KB (GiB, MiB or KiB when Binary) with up to one decimal below 10 of the unit.

type Spec

type Spec struct {
	Name       string            `json:"name"`
	Dir        string            `json:"dir"`
	Cmd        string            `json:"cmd"`
	Oneshot    bool              `json:"oneshot,omitempty"`
	Port       *int              `json:"port,omitempty"`
	Group      string            `json:"group,omitempty"`
	DependsOn  []string          `json:"dependsOn,omitempty"`
	Projects   []string          `json:"projects,omitempty"`
	Env        map[string]string `json:"env,omitempty"`
	Restart    string            `json:"restart,omitempty"`
	Health     string            `json:"health,omitempty"`
	ReadyLog   string            `json:"readyLog,omitempty"`
	ReadyAfter string            `json:"readyAfter,omitempty"`
	Icon       string            `json:"icon,omitempty"`
	Open       string            `json:"open,omitempty"`
	Stop       string            `json:"stopTimeout,omitempty"`
	Enabled    *bool             `json:"enabled,omitempty"`
	LAN        bool              `json:"lan,omitempty"`
	Schedule   string            `json:"schedule,omitempty"`
	Watch      []string          `json:"watch,omitempty"`
	Wrap       string            `json:"wrap,omitempty"`
	// The hook commands: nil inherits the top-level one, "" runs none.
	OnCrash      *string `json:"onCrash,omitempty"`
	OnUnready    *string `json:"onUnready,omitempty"`
	OnRecover    *string `json:"onRecover,omitempty"`
	UnreadyAfter string  `json:"unreadyAfter,omitempty"`
	RetryAfter   string  `json:"retryAfter,omitempty"`
	Umask        string  `json:"umask,omitempty"`
	MemoryLimit  string  `json:"memoryLimit,omitempty"`
	// Comment is written as # lines above the table header.
	Comment string `json:"comment,omitempty"`
}

Spec describes a server as written to the file. Empty fields are omitted; durations and sizes are the text written, such as "30s" or "2GB".

func SpecOf

func SpecOf(s Server) Spec

SpecOf returns a loaded server's entry as written in the file, with the restart policy in effect.

type Watch added in v0.10.0

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

Watch is a server's watch setting: file patterns relative to its directory whose changes restart it. A pattern is a slash-separated path whose segments follow path.Match, and a segment "**" stands for any number of directories, none included. "**" never enters the directories in WatchSkipped; a pattern that names one in a segment of its own reaches inside it.

func ParseWatch added in v0.10.0

func ParseWatch(patterns []string) (*Watch, error)

ParseWatch reads the patterns of a watch setting; nil for none. A pattern that is empty, malformed, absolute, starts at the home directory or contains ".." is an error, so watching never leaves the directory.

func (*Watch) Enter added in v0.10.0

func (w *Watch) Enter(rel string) bool

Enter reports whether a file inside the directory at rel, relative to the server's directory, can be watched, so a walk descends into it.

func (*Watch) Match added in v0.10.0

func (w *Watch) Match(rel string) bool

Match reports whether the file at rel, a slash-separated path relative to the server's directory, is watched.

func (*Watch) Patterns added in v0.10.0

func (w *Watch) Patterns() []string

Patterns returns the patterns as written.

func (*Watch) String added in v0.10.0

func (w *Watch) String() string

String identifies the patterns, for telling whether they changed.

Jump to

Keyboard shortcuts

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