initial commit [141.14.140.180,mike]
This commit is contained in:
commit
156bb18c91
50 files changed
+13466
No files matched your search
@@ -0,0 +1,172 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Ghostty itself has no option categories; these groupings exist only to
|
||||
// make the editor easier to navigate.
|
||||
const (
|
||||
CatFonts = "Fonts"
|
||||
CatFontMetrics = "Font Metrics"
|
||||
CatColors = "Colors & Theme"
|
||||
CatBackground = "Background"
|
||||
CatCursor = "Cursor"
|
||||
CatWindow = "Window"
|
||||
CatTabsSplits = "Tabs & Splits"
|
||||
CatMouse = "Mouse & Selection"
|
||||
CatClipboard = "Clipboard"
|
||||
CatKeyboard = "Keyboard"
|
||||
CatShell = "Shell & Commands"
|
||||
CatScrolling = "Scrolling"
|
||||
CatNotifications = "Notifications & Bell"
|
||||
CatQuickTerminal = "Quick Terminal"
|
||||
CatShaders = "Shaders"
|
||||
CatMacOS = "macOS"
|
||||
CatLinux = "Linux & GTK"
|
||||
CatConfigFiles = "Config Files"
|
||||
CatAdvanced = "Advanced"
|
||||
)
|
||||
|
||||
var categoryOrder = []string{
|
||||
CatFonts, CatFontMetrics, CatColors, CatBackground, CatCursor, CatWindow,
|
||||
CatTabsSplits, CatMouse, CatClipboard, CatKeyboard, CatShell, CatScrolling,
|
||||
CatNotifications, CatQuickTerminal, CatShaders, CatMacOS, CatLinux,
|
||||
CatConfigFiles, CatAdvanced,
|
||||
}
|
||||
|
||||
// exact key assignments, checked before the prefix rules below.
|
||||
var categoryByKey = map[string]string{
|
||||
"keybind": CatKeyboard,
|
||||
"key-remap": CatKeyboard,
|
||||
"macos-option-as-alt": CatKeyboard,
|
||||
"vt-kam-allowed": CatKeyboard,
|
||||
"config-file": CatConfigFiles,
|
||||
"config-default-files": CatConfigFiles,
|
||||
"cursor-click-to-move": CatMouse,
|
||||
"theme": CatColors,
|
||||
"background": CatColors,
|
||||
"foreground": CatColors,
|
||||
"bold-color": CatColors,
|
||||
"minimum-contrast": CatColors,
|
||||
"faint-opacity": CatColors,
|
||||
"alpha-blending": CatColors,
|
||||
"osc-color-report-format": CatColors,
|
||||
"window-colorspace": CatColors,
|
||||
"selection-foreground": CatColors,
|
||||
"selection-background": CatColors,
|
||||
"window-title-font-family": CatWindow,
|
||||
"freetype-load-flags": CatFonts,
|
||||
"grapheme-width-method": CatFonts,
|
||||
"window-new-tab-position": CatTabsSplits,
|
||||
"window-show-tab-bar": CatTabsSplits,
|
||||
"window-inherit-working-directory": CatShell,
|
||||
"tab-inherit-working-directory": CatShell,
|
||||
"split-inherit-working-directory": CatShell,
|
||||
"scrollback-limit": CatScrolling,
|
||||
"scrollbar": CatScrolling,
|
||||
"scroll-to-bottom": CatScrolling,
|
||||
"mouse-scroll-multiplier": CatScrolling,
|
||||
"focus-follows-mouse": CatMouse,
|
||||
"click-repeat-interval": CatMouse,
|
||||
"right-click-action": CatMouse,
|
||||
"copy-on-select": CatClipboard,
|
||||
"command": CatShell,
|
||||
"initial-command": CatShell,
|
||||
"env": CatShell,
|
||||
"input": CatShell,
|
||||
"working-directory": CatShell,
|
||||
"wait-after-command": CatShell,
|
||||
"abnormal-command-exit-runtime": CatShell,
|
||||
"term": CatShell,
|
||||
"enquiry-response": CatShell,
|
||||
"command-palette-entry": CatShell,
|
||||
"app-notifications": CatNotifications,
|
||||
"desktop-notifications": CatNotifications,
|
||||
"progress-style": CatNotifications,
|
||||
"auto-update": CatMacOS,
|
||||
"auto-update-channel": CatMacOS,
|
||||
"class": CatLinux,
|
||||
"async-backend": CatLinux,
|
||||
"language": CatLinux,
|
||||
"maximize": CatWindow,
|
||||
"fullscreen": CatWindow,
|
||||
"title": CatWindow,
|
||||
"initial-window": CatWindow,
|
||||
"confirm-close-surface": CatWindow,
|
||||
"undo-timeout": CatWindow,
|
||||
}
|
||||
|
||||
var categoryPrefixes = []struct {
|
||||
prefix, cat string
|
||||
}{
|
||||
{"quick-terminal-", CatQuickTerminal},
|
||||
{"gtk-quick-terminal-", CatQuickTerminal},
|
||||
{"custom-shader", CatShaders},
|
||||
{"adjust-cursor-", CatCursor},
|
||||
{"adjust-", CatFontMetrics},
|
||||
{"font-", CatFonts},
|
||||
{"cursor-", CatCursor},
|
||||
{"background-", CatBackground},
|
||||
{"palette", CatColors},
|
||||
{"search-", CatColors},
|
||||
{"split-", CatTabsSplits},
|
||||
{"unfocused-split-", CatTabsSplits},
|
||||
{"mouse-", CatMouse},
|
||||
{"selection-", CatMouse},
|
||||
{"link", CatMouse},
|
||||
{"clipboard-", CatClipboard},
|
||||
{"shell-integration", CatShell},
|
||||
{"bell-", CatNotifications},
|
||||
{"notify-on-", CatNotifications},
|
||||
{"macos-", CatMacOS},
|
||||
{"gtk-", CatLinux},
|
||||
{"linux-", CatLinux},
|
||||
{"x11-", CatLinux},
|
||||
{"window-", CatWindow},
|
||||
{"resize-overlay", CatWindow},
|
||||
{"quit-after-", CatWindow},
|
||||
}
|
||||
|
||||
func categorize(key string) string {
|
||||
if c, ok := categoryByKey[key]; ok {
|
||||
return c
|
||||
}
|
||||
for _, p := range categoryPrefixes {
|
||||
if strings.HasPrefix(key, p.prefix) {
|
||||
return p.cat
|
||||
}
|
||||
}
|
||||
return CatAdvanced
|
||||
}
|
||||
|
||||
// platform reports which OS an option is limited to, based on its key
|
||||
// prefix and on sentences like "This is only supported on macOS." in its
|
||||
// documentation. Notes about individual values (e.g. "(macOS only)" in a
|
||||
// list item) or about several platforms are ignored.
|
||||
func platform(o *Option) string {
|
||||
switch {
|
||||
case strings.HasPrefix(o.Key, "macos-"):
|
||||
return "macOS"
|
||||
case strings.HasPrefix(o.Key, "gtk-"), strings.HasPrefix(o.Key, "linux-"),
|
||||
strings.HasPrefix(o.Key, "x11-"):
|
||||
return "Linux"
|
||||
}
|
||||
text := strings.Join(strings.Fields(o.Doc), " ")
|
||||
for _, sentence := range strings.SplitAfter(text, ". ") {
|
||||
m := rePlatformNote.FindStringSubmatch(strings.ToLower(strings.TrimSpace(sentence)))
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
if m[1] == "macos" || m[2] == "macos" {
|
||||
return "macOS"
|
||||
}
|
||||
return "Linux"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var rePlatformNote = regexp.MustCompile(
|
||||
`^(?:note: )?(?:(?:this|it)(?: \w+)? (?:is )?)?(?:currently )?only (?:supported|implemented|available) on (macos|linux|gtk)\b(?: \(gtk\))?[.,;]?$` +
|
||||
`|^(macos|gtk|linux) only\.?$`)
|
||||
@@ -0,0 +1,334 @@
|
||||
// Package schema describes every Ghostty configuration option: its value
|
||||
// kind, allowed values, documentation and default values.
|
||||
//
|
||||
// The type information is generated from Ghostty's Config.zig (see
|
||||
// tools/genschema) and embedded into the binary. Documentation and defaults
|
||||
// are refreshed at runtime from the installed Ghostty binary when available,
|
||||
// so they always match the version the user actually runs.
|
||||
package schema
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Kind describes how the value of an option is edited and validated.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindBool Kind = "bool"
|
||||
KindEnum Kind = "enum" // one of Values
|
||||
KindChoice Kind = "choice" // one of Values or a custom value
|
||||
KindFlags Kind = "flags" // comma separated set of Flags, "no-" prefix disables
|
||||
KindInt Kind = "int" // integer within Min/Max
|
||||
KindFloat Kind = "float" // floating point number
|
||||
KindColor Kind = "color" // hex or X11 color name, plus optional Values
|
||||
KindColorList Kind = "colorlist" // comma separated colors
|
||||
KindMetric Kind = "metric" // integer or percentage, e.g. "2" or "-10%"
|
||||
KindDuration Kind = "duration" // e.g. "750ms", "1h30m"
|
||||
KindPadding Kind = "padding" // "2" or "2,4"
|
||||
KindText Kind = "text"
|
||||
KindPath Kind = "path"
|
||||
KindTheme Kind = "theme"
|
||||
KindFont Kind = "font"
|
||||
KindKeybind Kind = "keybind"
|
||||
KindPalette Kind = "palette"
|
||||
)
|
||||
|
||||
// Option is a single configuration key.
|
||||
type Option struct {
|
||||
Key string `json:"key"`
|
||||
ZigType string `json:"zigType,omitempty"`
|
||||
Kind Kind `json:"kind"`
|
||||
Repeatable bool `json:"repeatable,omitempty"`
|
||||
Values []string `json:"values,omitempty"`
|
||||
Flags []string `json:"flags,omitempty"`
|
||||
Min *float64 `json:"min,omitempty"`
|
||||
Max *float64 `json:"max,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
Doc string `json:"doc,omitempty"`
|
||||
Defaults []string `json:"defaults,omitempty"`
|
||||
// NotListed marks options that Ghostty accepts but does not print
|
||||
// with `+show-config`. They are kept even when refreshing from a live
|
||||
// Ghostty binary.
|
||||
NotListed bool `json:"notListed,omitempty"`
|
||||
|
||||
Category string `json:"-"`
|
||||
Platform string `json:"-"` // "", "macOS" or "Linux"
|
||||
}
|
||||
|
||||
// Default returns the default value for scalar options ("" when unset).
|
||||
func (o *Option) Default() string {
|
||||
if len(o.Defaults) == 0 {
|
||||
return ""
|
||||
}
|
||||
return o.Defaults[len(o.Defaults)-1]
|
||||
}
|
||||
|
||||
// DefaultList returns the default entries of a repeatable option, ignoring
|
||||
// the empty placeholder entry Ghostty prints for empty lists.
|
||||
func (o *Option) DefaultList() []string {
|
||||
var out []string
|
||||
for _, d := range o.Defaults {
|
||||
if d != "" {
|
||||
out = append(out, d)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TypeLabel is a short human readable description of the value type.
|
||||
func (o *Option) TypeLabel() string {
|
||||
var s string
|
||||
switch o.Kind {
|
||||
case KindBool:
|
||||
s = "boolean"
|
||||
case KindEnum:
|
||||
s = "one of " + strings.Join(o.Values, ", ")
|
||||
case KindChoice:
|
||||
s = strings.Join(o.Values, ", ") + " or custom value"
|
||||
case KindFlags:
|
||||
s = "flags: " + strings.Join(o.Flags, ", ")
|
||||
case KindInt:
|
||||
s = "integer"
|
||||
if o.Min != nil && o.Max != nil {
|
||||
s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max))
|
||||
} else if o.Min != nil {
|
||||
s += fmt.Sprintf(" (%s or more)", num(*o.Min))
|
||||
}
|
||||
case KindFloat:
|
||||
s = "number"
|
||||
if o.Min != nil && o.Max != nil {
|
||||
s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max))
|
||||
} else if o.Min != nil {
|
||||
s += fmt.Sprintf(" (%s or more)", num(*o.Min))
|
||||
}
|
||||
case KindColor:
|
||||
s = "color (#rrggbb or X11 name)"
|
||||
if len(o.Values) > 0 {
|
||||
s += " or " + strings.Join(o.Values, ", ")
|
||||
}
|
||||
case KindColorList:
|
||||
s = "comma separated colors"
|
||||
case KindMetric:
|
||||
s = "integer or percentage (e.g. 2, -10%)"
|
||||
case KindDuration:
|
||||
s = "duration (e.g. 500ms, 5s, 1h30m)"
|
||||
case KindPadding:
|
||||
s = "pixels, optionally two values (e.g. 2 or 2,4)"
|
||||
case KindPath:
|
||||
s = "file path"
|
||||
case KindTheme:
|
||||
s = "theme name (or light:NAME,dark:NAME)"
|
||||
case KindFont:
|
||||
s = "font family"
|
||||
case KindKeybind:
|
||||
s = "key binding (trigger=action)"
|
||||
case KindPalette:
|
||||
s = "palette entries (N=color)"
|
||||
default:
|
||||
s = "text"
|
||||
}
|
||||
if o.Repeatable && o.Kind != KindKeybind && o.Kind != KindPalette {
|
||||
s = "list of " + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Schema is the full set of known options.
|
||||
type Schema struct {
|
||||
GhosttyVersion string `json:"ghosttyVersion"`
|
||||
Options []*Option `json:"options"`
|
||||
// Source describes where docs and defaults came from.
|
||||
Source string `json:"-"`
|
||||
|
||||
byKey map[string]*Option
|
||||
}
|
||||
|
||||
//go:embed schema.json
|
||||
var embedded []byte
|
||||
|
||||
// Embedded returns the schema compiled into the binary.
|
||||
func Embedded() (*Schema, error) {
|
||||
var s Schema
|
||||
if err := json.Unmarshal(embedded, &s); err != nil {
|
||||
return nil, fmt.Errorf("decode embedded schema: %w", err)
|
||||
}
|
||||
s.Source = "built-in (Ghostty " + s.GhosttyVersion + ")"
|
||||
s.finish()
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// Lookup returns the option for key, or nil.
|
||||
func (s *Schema) Lookup(key string) *Option {
|
||||
return s.byKey[key]
|
||||
}
|
||||
|
||||
func (s *Schema) finish() {
|
||||
s.byKey = make(map[string]*Option, len(s.Options))
|
||||
for _, o := range s.Options {
|
||||
o.Category = categorize(o.Key)
|
||||
o.Platform = platform(o)
|
||||
s.byKey[o.Key] = o
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh replaces docs and defaults with the output of
|
||||
// `ghostty +show-config --default --docs` from the installed Ghostty.
|
||||
// Options unknown to the installed version are dropped; options unknown to
|
||||
// the embedded schema are added with an inferred kind.
|
||||
func (s *Schema) Refresh(docsOutput, version string) {
|
||||
parsed := ParseDocs(docsOutput)
|
||||
if len(parsed) == 0 {
|
||||
return
|
||||
}
|
||||
var opts []*Option
|
||||
seen := make(map[string]bool)
|
||||
for _, p := range parsed {
|
||||
seen[p.Key] = true
|
||||
o := s.byKey[p.Key]
|
||||
if o == nil {
|
||||
o = inferOption(p)
|
||||
}
|
||||
o.Doc = p.Doc
|
||||
o.Defaults = p.Defaults
|
||||
opts = append(opts, o)
|
||||
}
|
||||
for _, o := range s.Options {
|
||||
if !seen[o.Key] && o.NotListed {
|
||||
opts = append(opts, o)
|
||||
}
|
||||
}
|
||||
s.Options = opts
|
||||
if version != "" {
|
||||
s.GhosttyVersion = version
|
||||
}
|
||||
s.Source = "Ghostty " + s.GhosttyVersion
|
||||
s.finish()
|
||||
}
|
||||
|
||||
// inferOption guesses the kind of an option the embedded schema does not
|
||||
// know about (e.g. one added in a newer Ghostty release).
|
||||
func inferOption(p DocEntry) *Option {
|
||||
o := &Option{Key: p.Key, Kind: KindText, Repeatable: len(p.Defaults) > 1}
|
||||
d := ""
|
||||
if len(p.Defaults) > 0 {
|
||||
d = p.Defaults[0]
|
||||
}
|
||||
switch {
|
||||
case d == "true" || d == "false":
|
||||
o.Kind = KindBool
|
||||
case isNumber(d):
|
||||
o.Kind = KindFloat
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
|
||||
|
||||
func isNumber(s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
var f float64
|
||||
_, err := fmt.Sscanf(s, "%g", &f)
|
||||
return err == nil && strings.TrimLeft(s, "-+0123456789.") == ""
|
||||
}
|
||||
|
||||
// DocEntry is one key parsed from `+show-config --default --docs`.
|
||||
type DocEntry struct {
|
||||
Key string
|
||||
Doc string
|
||||
Defaults []string
|
||||
}
|
||||
|
||||
// ParseDocs parses the output of `ghostty +show-config --default --docs`.
|
||||
// Keys that directly follow another key without their own comment block
|
||||
// share the previous documentation (e.g. font-family-bold).
|
||||
func ParseDocs(out string) []DocEntry {
|
||||
var (
|
||||
entries []DocEntry
|
||||
index = map[string]int{}
|
||||
pending []string
|
||||
lastDoc string
|
||||
)
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSuffix(line, "\r")
|
||||
switch {
|
||||
case strings.HasPrefix(line, "#"):
|
||||
text := strings.TrimPrefix(line, "#")
|
||||
text = strings.TrimPrefix(text, " ")
|
||||
pending = append(pending, text)
|
||||
case strings.TrimSpace(line) == "":
|
||||
continue
|
||||
default:
|
||||
key, value, ok := splitShowConfigLine(line)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if len(pending) > 0 {
|
||||
lastDoc = strings.TrimRight(strings.Join(pending, "\n"), "\n ")
|
||||
pending = nil
|
||||
}
|
||||
if i, ok := index[key]; ok {
|
||||
entries[i].Defaults = append(entries[i].Defaults, value)
|
||||
continue
|
||||
}
|
||||
index[key] = len(entries)
|
||||
entries = append(entries, DocEntry{Key: key, Doc: lastDoc, Defaults: []string{value}})
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// splitShowConfigLine splits "key = value". The value is kept verbatim
|
||||
// because leading whitespace can be significant (selection-word-chars).
|
||||
func splitShowConfigLine(line string) (key, value string, ok bool) {
|
||||
i := strings.Index(line, " =")
|
||||
if i <= 0 {
|
||||
return "", "", false
|
||||
}
|
||||
key = line[:i]
|
||||
if strings.ContainsAny(key, " \t") {
|
||||
return "", "", false
|
||||
}
|
||||
value = strings.TrimPrefix(line[i+2:], " ")
|
||||
return key, value, true
|
||||
}
|
||||
|
||||
// Categories returns category names in display order, restricted to those
|
||||
// that contain at least one option.
|
||||
func (s *Schema) Categories() []string {
|
||||
present := map[string]bool{}
|
||||
for _, o := range s.Options {
|
||||
present[o.Category] = true
|
||||
}
|
||||
var out []string
|
||||
for _, c := range categoryOrder {
|
||||
if present[c] {
|
||||
out = append(out, c)
|
||||
delete(present, c)
|
||||
}
|
||||
}
|
||||
var rest []string
|
||||
for c := range present {
|
||||
rest = append(rest, c)
|
||||
}
|
||||
sort.Strings(rest)
|
||||
return append(out, rest...)
|
||||
}
|
||||
|
||||
// InCategory returns the options of a category in schema order.
|
||||
func (s *Schema) InCategory(cat string) []*Option {
|
||||
var out []*Option
|
||||
for _, o := range s.Options {
|
||||
if o.Category == cat {
|
||||
out = append(out, o)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEmbeddedSchema(t *testing.T) {
|
||||
s, err := Embedded()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Options) < 150 {
|
||||
t.Fatalf("only %d options in embedded schema", len(s.Options))
|
||||
}
|
||||
for _, o := range s.Options {
|
||||
if o.Kind == "" {
|
||||
t.Errorf("%s has no kind", o.Key)
|
||||
}
|
||||
if o.Category == "" {
|
||||
t.Errorf("%s has no category", o.Key)
|
||||
}
|
||||
if (o.Kind == KindEnum || o.Kind == KindChoice) && len(o.Values) == 0 {
|
||||
t.Errorf("%s has no values", o.Key)
|
||||
}
|
||||
if o.Kind == KindEnum && o.Default() != "" && !contains(o.Values, o.Default()) {
|
||||
t.Errorf("%s: default %q is not a valid value", o.Key, o.Default())
|
||||
}
|
||||
if !o.Repeatable && o.Default() != "" {
|
||||
if err := o.Validate(o.Default()); err != nil {
|
||||
t.Errorf("%s: default %q does not validate: %v", o.Key, o.Default(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"font-family", "keybind", "palette", "theme", "cursor-style", "shell-integration-features"} {
|
||||
if s.Lookup(key) == nil {
|
||||
t.Errorf("missing %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDocs(t *testing.T) {
|
||||
out := `# Font families.
|
||||
#
|
||||
# Can be repeated.
|
||||
font-family =
|
||||
|
||||
font-family-bold =
|
||||
# The palette.
|
||||
palette = 0=#000000
|
||||
palette = 1=#ff0000
|
||||
selection-word-chars = '"
|
||||
`
|
||||
got := ParseDocs(out)
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("got %d entries", len(got))
|
||||
}
|
||||
if got[0].Doc != "Font families.\n\nCan be repeated." {
|
||||
t.Errorf("doc = %q", got[0].Doc)
|
||||
}
|
||||
if got[1].Doc != got[0].Doc {
|
||||
t.Errorf("font-family-bold should share the font-family docs")
|
||||
}
|
||||
if len(got[2].Defaults) != 2 {
|
||||
t.Errorf("palette defaults = %v", got[2].Defaults)
|
||||
}
|
||||
if got[3].Defaults[0] != " \t'\"" {
|
||||
t.Errorf("leading whitespace must be kept, got %q", got[3].Defaults[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
opt := func(k Kind) *Option {
|
||||
return &Option{Kind: k, Values: []string{"cell-foreground"}, Flags: []string{"cursor", "sudo"}}
|
||||
}
|
||||
cases := []struct {
|
||||
kind Kind
|
||||
value string
|
||||
ok bool
|
||||
}{
|
||||
{KindBool, "true", true},
|
||||
{KindBool, "yes", false},
|
||||
{KindColor, "#1e1e2e", true},
|
||||
{KindColor, "fff", true},
|
||||
{KindColor, "dark slate gray", true},
|
||||
{KindColor, "cell-foreground", true},
|
||||
{KindColor, "#12345", false},
|
||||
{KindMetric, "-10%", true},
|
||||
{KindMetric, "2", true},
|
||||
{KindMetric, "1.5", false},
|
||||
{KindDuration, "750ms", true},
|
||||
{KindDuration, "1h 30m", true},
|
||||
{KindDuration, "0", true},
|
||||
{KindDuration, "5", false},
|
||||
{KindPadding, "2,4", true},
|
||||
{KindPadding, "a", false},
|
||||
{KindFlags, "no-cursor,sudo", true},
|
||||
{KindFlags, "false", true},
|
||||
{KindFlags, "bogus", false},
|
||||
{KindKeybind, "ctrl+==reset_font_size", true},
|
||||
{KindKeybind, "clear", true},
|
||||
{KindKeybind, "ctrl+a", false},
|
||||
{KindPalette, "4=#89b4fa", true},
|
||||
{KindPalette, "256=#000000", false},
|
||||
{KindFloat, "0.5", true},
|
||||
{KindFloat, "x", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := opt(c.kind).Validate(c.value)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("%s %q: err = %v, want ok=%v", c.kind, c.value, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlags(t *testing.T) {
|
||||
o := &Option{Kind: KindFlags, Flags: []string{"cursor", "sudo", "title"}, Defaults: []string{"cursor,no-sudo,title"}}
|
||||
st := o.ParseFlags("no-cursor")
|
||||
if st["cursor"] || st["sudo"] || !st["title"] {
|
||||
t.Fatalf("state = %v", st)
|
||||
}
|
||||
if got := o.FormatFlags(st); got != "no-cursor,no-sudo,title" {
|
||||
t.Fatalf("format = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitKeybind(t *testing.T) {
|
||||
cases := map[string][2]string{
|
||||
"ctrl+a=new_tab": {"ctrl+a", "new_tab"},
|
||||
"==text:=": {"=", "text:="},
|
||||
"ctrl+==text:=hello": {"ctrl+=", "text:=hello"},
|
||||
"super+shift+,=reload": {"super+shift+,", "reload"},
|
||||
"ctrl+a>n=new_window": {"ctrl+a>n", "new_window"},
|
||||
"§=goto_split:next": {"§", "goto_split:next"},
|
||||
}
|
||||
for in, want := range cases {
|
||||
tr, ac := SplitKeybind(in)
|
||||
if tr != want[0] || ac != want[1] {
|
||||
t.Errorf("SplitKeybind(%q) = %q, %q", in, tr, ac)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCategoriesCoverEverything(t *testing.T) {
|
||||
s, _ := Embedded()
|
||||
cats := s.Categories()
|
||||
total := 0
|
||||
for _, c := range cats {
|
||||
total += len(s.InCategory(c))
|
||||
}
|
||||
if total != len(s.Options) {
|
||||
t.Fatalf("categories hold %d of %d options", total, len(s.Options))
|
||||
}
|
||||
if !strings.Contains(strings.Join(cats, ","), CatFonts) {
|
||||
t.Fatal("missing Fonts category")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformDetection(t *testing.T) {
|
||||
s, _ := Embedded()
|
||||
want := map[string]string{
|
||||
"keybind": "",
|
||||
"fullscreen": "",
|
||||
"window-theme": "",
|
||||
"window-step-resize": "macOS",
|
||||
"undo-timeout": "macOS",
|
||||
"window-subtitle": "Linux",
|
||||
"macos-icon": "macOS",
|
||||
"gtk-wide-tabs": "Linux",
|
||||
}
|
||||
for key, p := range want {
|
||||
if o := s.Lookup(key); o == nil || o.Platform != p {
|
||||
t.Errorf("%s: platform = %q, want %q", key, o.Platform, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ghosttyconf/internal/colors"
|
||||
"ghosttyconf/internal/keybind"
|
||||
)
|
||||
|
||||
var (
|
||||
reMetric = regexp.MustCompile(`^[+-]?\d+$|^[+-]?\d+(\.\d+)?%$`)
|
||||
reDuration = regexp.MustCompile(`^(\s*\d+\s*(y|w|d|h|m|s|ms|µs|us|ns)\s*)+$`)
|
||||
rePadding = regexp.MustCompile(`^\d+(\s*,\s*\d+)?$`)
|
||||
rePalette = regexp.MustCompile(`^\s*(\d{1,3})\s*=\s*(.+?)\s*$`)
|
||||
)
|
||||
|
||||
// Unquote strips one pair of surrounding double quotes, as Ghostty does
|
||||
// when reading a config file.
|
||||
func Unquote(s string) string {
|
||||
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Validate checks a single (raw, possibly quoted) value for the option. For
|
||||
// repeatable options it validates one list entry.
|
||||
func (o *Option) Validate(raw string) error {
|
||||
v := strings.TrimSpace(Unquote(raw))
|
||||
if v == "" {
|
||||
// An empty value resets the option to its default; always allowed.
|
||||
return nil
|
||||
}
|
||||
switch o.Kind {
|
||||
case KindBool:
|
||||
if v != "true" && v != "false" {
|
||||
return errors.New(`expected "true" or "false"`)
|
||||
}
|
||||
case KindEnum:
|
||||
if !contains(o.Values, v) {
|
||||
return fmt.Errorf("expected one of: %s", strings.Join(o.Values, ", "))
|
||||
}
|
||||
case KindFlags:
|
||||
return o.validateFlags(v)
|
||||
case KindInt:
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return errors.New("expected a whole number")
|
||||
}
|
||||
return o.checkRange(float64(n))
|
||||
case KindFloat:
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return errors.New("expected a number")
|
||||
}
|
||||
return o.checkRange(f)
|
||||
case KindColor:
|
||||
if contains(o.Values, v) || colors.Valid(v) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("expected a color like #1e1e2e, 1e1e2e, #fff or an X11 name like \"dark slate gray\"")
|
||||
case KindColorList:
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
if !colors.Valid(part) {
|
||||
return fmt.Errorf("%q is not a valid color", strings.TrimSpace(part))
|
||||
}
|
||||
}
|
||||
case KindMetric:
|
||||
if !reMetric.MatchString(v) {
|
||||
return errors.New("expected an integer (e.g. 2, -1) or a percentage (e.g. 10%, -5%)")
|
||||
}
|
||||
case KindDuration:
|
||||
if v != "0" && !reDuration.MatchString(v) {
|
||||
return errors.New("expected a duration such as 750ms, 5s, 2m or 1h30m")
|
||||
}
|
||||
case KindPadding:
|
||||
if !rePadding.MatchString(v) {
|
||||
return errors.New("expected one or two non-negative integers, e.g. 4 or 4,8")
|
||||
}
|
||||
case KindKeybind:
|
||||
if v == "clear" {
|
||||
return nil
|
||||
}
|
||||
trigger, action := SplitKeybind(v)
|
||||
if trigger == "" || action == "" {
|
||||
return errors.New("expected trigger=action, e.g. ctrl+shift+t=new_tab (or \"clear\")")
|
||||
}
|
||||
case KindPalette:
|
||||
m := rePalette.FindStringSubmatch(v)
|
||||
if m == nil {
|
||||
return errors.New("expected N=COLOR, e.g. 4=#89b4fa")
|
||||
}
|
||||
if n, _ := strconv.Atoi(m[1]); n > 255 {
|
||||
return errors.New("palette index must be between 0 and 255")
|
||||
}
|
||||
if !colors.Valid(m[2]) {
|
||||
return fmt.Errorf("%q is not a valid color", m[2])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Option) validateFlags(v string) error {
|
||||
if v == "true" || v == "false" {
|
||||
return nil
|
||||
}
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
name := strings.TrimPrefix(strings.TrimSpace(part), "no-")
|
||||
if !contains(o.Flags, name) {
|
||||
return fmt.Errorf("unknown flag %q (valid: %s)", name, strings.Join(o.Flags, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Option) checkRange(f float64) error {
|
||||
if o.Min != nil && f < *o.Min {
|
||||
return fmt.Errorf("must be at least %s", num(*o.Min))
|
||||
}
|
||||
if o.Max != nil && f > *o.Max {
|
||||
return fmt.Errorf("must be at most %s", num(*o.Max))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseFlags returns the state of every flag for a flags value, starting
|
||||
// from the option's default the same way Ghostty does.
|
||||
func (o *Option) ParseFlags(value string) map[string]bool {
|
||||
state := make(map[string]bool, len(o.Flags))
|
||||
apply := func(v string) {
|
||||
v = strings.TrimSpace(Unquote(v))
|
||||
if v == "true" || v == "false" {
|
||||
for _, f := range o.Flags {
|
||||
state[f] = v == "true"
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
on := !strings.HasPrefix(part, "no-")
|
||||
state[strings.TrimPrefix(part, "no-")] = on
|
||||
}
|
||||
}
|
||||
apply(o.Default())
|
||||
if value != "" {
|
||||
apply(value)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// FormatFlags renders flag states in Ghostty's explicit form,
|
||||
// e.g. "cursor,no-sudo,title".
|
||||
func (o *Option) FormatFlags(state map[string]bool) string {
|
||||
parts := make([]string, len(o.Flags))
|
||||
for i, f := range o.Flags {
|
||||
if state[f] {
|
||||
parts[i] = f
|
||||
} else {
|
||||
parts[i] = "no-" + f
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
|
||||
// SplitKeybind splits "trigger=action" exactly like Ghostty does.
|
||||
func SplitKeybind(v string) (trigger, action string) {
|
||||
return keybind.Split(v)
|
||||
}
|
||||
|
||||
// SplitPalette splits a palette entry into its index and color.
|
||||
func SplitPalette(v string) (index int, color string, ok bool) {
|
||||
m := rePalette.FindStringSubmatch(Unquote(v))
|
||||
if m == nil {
|
||||
return 0, "", false
|
||||
}
|
||||
n, err := strconv.Atoi(m[1])
|
||||
if err != nil || n > 255 {
|
||||
return 0, "", false
|
||||
}
|
||||
return n, m[2], true
|
||||
}
|
||||
|
||||
func contains(list []string, v string) bool {
|
||||
for _, s := range list {
|
||||
if s == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in new issue
Block a user