state.Save writes session.toml atomically (0600, state dir 0700), drops cursor-memory entries under cache/temp mounts and caps each pane at 200 entries; Load migrates the old ~/.config/vcom/session.toml once. The old UI's session functions are aliases over state, and theme selection uses config.SetKey, so the user's comments and keys survive. config.Save is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
256 lines
6.8 KiB
Go
256 lines
6.8 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
toml "github.com/pelletier/go-toml/v2"
|
|
|
|
"vcom/internal/atomicfile"
|
|
)
|
|
|
|
// SetKey sets section.key = value in the config file at path by editing that
|
|
// one line: comments, order, formatting and unknown keys are kept (design
|
|
// §9.2). A missing key is appended to its section, a missing section to the
|
|
// end of the file, a missing file is created (path "" means the default XDG
|
|
// location). The file must parse before the edit — a broken config is never
|
|
// touched — and the result is parsed again before it is written atomically.
|
|
//
|
|
// value is a string, bool, integer or float. section may be dotted
|
|
// ("browser.sort").
|
|
func SetKey(path, section, key string, value any) (string, error) {
|
|
if path == "" {
|
|
var err error
|
|
if path, err = DefaultUserPath(); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
lit, err := tomlValue(value)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
out := []byte("[" + section + "]\n" + key + " = " + lit + "\n")
|
|
if err := verify(out, section, key, value); err != nil {
|
|
return "", err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return "", err
|
|
}
|
|
return path, atomicfile.WriteFile(path, out, 0o644)
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var probe map[string]any
|
|
if err := toml.Unmarshal(data, &probe); err != nil {
|
|
return "", fmt.Errorf("%s does not parse, not editing it: %w", path, describe(err))
|
|
}
|
|
out, err := editTOML(data, section, key, lit)
|
|
if err != nil {
|
|
return "", fmt.Errorf("edit %s: %w", path, err)
|
|
}
|
|
if err := verify(out, section, key, value); err != nil {
|
|
return "", fmt.Errorf("edit %s: %w", path, err)
|
|
}
|
|
return path, atomicfile.WriteFile(path, out, 0o644)
|
|
}
|
|
|
|
var (
|
|
reHeader = regexp.MustCompile(`^\s*\[\s*([^\[\]]+?)\s*\]\s*(#.*)?$`)
|
|
reArray = regexp.MustCompile(`^\s*\[\[`)
|
|
)
|
|
|
|
// normSection canonicalises a table name: `a . "b"` → `a.b`.
|
|
func normSection(s string) string {
|
|
parts := strings.Split(s, ".")
|
|
for i, p := range parts {
|
|
p = strings.TrimSpace(p)
|
|
if len(p) >= 2 && (p[0] == '"' && p[len(p)-1] == '"' || p[0] == '\'' && p[len(p)-1] == '\'') {
|
|
p = p[1 : len(p)-1]
|
|
}
|
|
parts[i] = p
|
|
}
|
|
return strings.Join(parts, ".")
|
|
}
|
|
|
|
// editTOML returns data with section.key set to the TOML literal lit.
|
|
func editTOML(data []byte, section, key, lit string) ([]byte, error) {
|
|
text := string(data)
|
|
nl := "\n"
|
|
if strings.Contains(text, "\r\n") {
|
|
nl = "\r\n"
|
|
}
|
|
lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
|
|
section = normSection(section)
|
|
reKey := regexp.MustCompile(`^(\s*(?:` + regexp.QuoteMeta(key) + `|"` + regexp.QuoteMeta(key) + `"|'` +
|
|
regexp.QuoteMeta(key) + `')\s*=\s*)(.*)$`)
|
|
|
|
cur := "" // the root table
|
|
inTarget := section == ""
|
|
lastContent := -1 // last key/value line of the target section
|
|
headerAt := -1
|
|
for i, line := range lines {
|
|
if reArray.MatchString(line) {
|
|
cur, inTarget = "\x00array", false
|
|
continue
|
|
}
|
|
if m := reHeader.FindStringSubmatch(line); m != nil {
|
|
cur = normSection(m[1])
|
|
inTarget = cur == section
|
|
if inTarget {
|
|
headerAt = i
|
|
}
|
|
continue
|
|
}
|
|
if !inTarget {
|
|
continue
|
|
}
|
|
if m := reKey.FindStringSubmatch(line); m != nil {
|
|
val, rest, err := splitValue(m[2])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s.%s: %w", section, key, err)
|
|
}
|
|
if strings.HasPrefix(val, "'") && !strings.ContainsAny(lit, `'\`) && strings.HasPrefix(lit, `"`) {
|
|
// Keep the file's literal-string style when possible.
|
|
if s, err := strconv.Unquote(lit); err == nil && !strings.ContainsAny(s, "'\n") {
|
|
lit = "'" + s + "'"
|
|
}
|
|
}
|
|
lines[i] = m[1] + lit + rest
|
|
return []byte(strings.Join(lines, nl)), nil
|
|
}
|
|
if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") {
|
|
lastContent = i
|
|
}
|
|
}
|
|
newLine := key + " = " + lit
|
|
switch {
|
|
case headerAt >= 0 || section == "":
|
|
at := lastContent
|
|
if at < 0 {
|
|
at = headerAt // empty section (or root): right after the header
|
|
}
|
|
lines = append(lines[:at+1], append([]string{newLine}, lines[at+1:]...)...)
|
|
default:
|
|
for len(lines) > 0 && lines[len(lines)-1] == "" {
|
|
lines = lines[:len(lines)-1]
|
|
}
|
|
if len(lines) > 0 {
|
|
lines = append(lines, "")
|
|
}
|
|
lines = append(lines, "["+section+"]", newLine, "")
|
|
}
|
|
return []byte(strings.Join(lines, nl)), nil
|
|
}
|
|
|
|
// splitValue splits "value # comment" into the value token and the rest
|
|
// (whitespace and comment), respecting quoted strings.
|
|
func splitValue(s string) (val, rest string, err error) {
|
|
if strings.HasPrefix(s, `"""`) || strings.HasPrefix(s, `'''`) {
|
|
return "", "", errors.New("multi-line string values are not supported")
|
|
}
|
|
end := len(s)
|
|
switch {
|
|
case strings.HasPrefix(s, `"`):
|
|
end = -1
|
|
for i := 1; i < len(s); i++ {
|
|
if s[i] == '\\' {
|
|
i++
|
|
continue
|
|
}
|
|
if s[i] == '"' {
|
|
end = i + 1
|
|
break
|
|
}
|
|
}
|
|
case strings.HasPrefix(s, `'`):
|
|
end = -1
|
|
if j := strings.IndexByte(s[1:], '\''); j >= 0 {
|
|
end = j + 2
|
|
}
|
|
case strings.HasPrefix(s, "[") || strings.HasPrefix(s, "{"):
|
|
return "", "", errors.New("array and inline-table values are not supported")
|
|
default:
|
|
if j := strings.IndexByte(s, '#'); j >= 0 {
|
|
end = j
|
|
}
|
|
end = len(strings.TrimRight(s[:end], " \t"))
|
|
}
|
|
if end < 0 {
|
|
return "", "", errors.New("unterminated string")
|
|
}
|
|
return s[:end], s[end:], nil
|
|
}
|
|
|
|
// tomlValue renders value as a TOML literal.
|
|
func tomlValue(v any) (string, error) {
|
|
switch x := v.(type) {
|
|
case string:
|
|
var b strings.Builder
|
|
b.WriteByte('"')
|
|
for _, r := range x {
|
|
switch {
|
|
case r == '"':
|
|
b.WriteString(`\"`)
|
|
case r == '\\':
|
|
b.WriteString(`\\`)
|
|
case r == '\n':
|
|
b.WriteString(`\n`)
|
|
case r == '\t':
|
|
b.WriteString(`\t`)
|
|
case r < 0x20 || r == 0x7f:
|
|
fmt.Fprintf(&b, `\u%04X`, r)
|
|
default:
|
|
b.WriteRune(r)
|
|
}
|
|
}
|
|
b.WriteByte('"')
|
|
return b.String(), nil
|
|
case bool:
|
|
return strconv.FormatBool(x), nil
|
|
case int:
|
|
return strconv.Itoa(x), nil
|
|
case int64:
|
|
return strconv.FormatInt(x, 10), nil
|
|
case float64:
|
|
return strconv.FormatFloat(x, 'g', -1, 64), nil
|
|
}
|
|
return "", fmt.Errorf("config: unsupported value type %T", v)
|
|
}
|
|
|
|
// verify parses out and checks that section.key now holds value.
|
|
func verify(out []byte, section, key string, value any) error {
|
|
var m map[string]any
|
|
if err := toml.Unmarshal(out, &m); err != nil {
|
|
return fmt.Errorf("result does not parse: %w", err)
|
|
}
|
|
var cur any = m
|
|
path := append(strings.Split(normSection(section), "."), key)
|
|
if section == "" {
|
|
path = []string{key}
|
|
}
|
|
for _, p := range path {
|
|
mm, ok := cur.(map[string]any)
|
|
if !ok {
|
|
return fmt.Errorf("result: %s.%s not found", section, key)
|
|
}
|
|
cur = mm[p]
|
|
}
|
|
want := value
|
|
if n, ok := value.(int); ok {
|
|
want = int64(n)
|
|
}
|
|
if !reflect.DeepEqual(cur, want) {
|
|
return fmt.Errorf("result: %s.%s = %v, want %v", section, key, cur, value)
|
|
}
|
|
return nil
|
|
}
|