atomicfile.Write refuses a target the process cannot write (EACCES, as a
plain write in v0.2.7 did) instead of replacing it by rename. SetKey edits
a section written in the root table as dotted keys (ui.theme = ...) or as
a one-line inline table (ui = { theme = ... }), adding the key in the same
form when missing; multi-line inline tables are refused without touching
the file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358 lines
10 KiB
Go
358 lines
10 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*)(.*)$`)
|
|
|
|
if out, ok, err := editRootForms(lines, section, key, lit); err != nil || ok {
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return []byte(strings.Join(out, nl)), nil
|
|
}
|
|
|
|
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)
|
|
}
|
|
lines[i] = m[1] + styleLike(val, 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
|
|
}
|
|
|
|
// styleLike keeps the file's literal-string style ('...') when possible.
|
|
func styleLike(old, lit string) string {
|
|
if strings.HasPrefix(old, "'") && !strings.ContainsAny(lit, `'\`) && strings.HasPrefix(lit, `"`) {
|
|
if s, err := strconv.Unquote(lit); err == nil && !strings.ContainsAny(s, "'\n") {
|
|
return "'" + s + "'"
|
|
}
|
|
}
|
|
return lit
|
|
}
|
|
|
|
// namePattern matches a TOML key path (bare or quoted parts, spaces around
|
|
// dots allowed).
|
|
func namePattern(dotted string) string {
|
|
var parts []string
|
|
for _, p := range strings.Split(dotted, ".") {
|
|
q := regexp.QuoteMeta(p)
|
|
parts = append(parts, `(?:`+q+`|"`+q+`"|'`+q+`')`)
|
|
}
|
|
return strings.Join(parts, `\s*\.\s*`)
|
|
}
|
|
|
|
// editRootForms handles a section written without a [table] header, in the
|
|
// root table: dotted keys (`ui.theme = "x"`) or an inline table
|
|
// (`ui = { theme = "x" }`) — QA-14. ok reports whether it edited.
|
|
func editRootForms(lines []string, section, key, lit string) (out []string, ok bool, err error) {
|
|
if section == "" {
|
|
return nil, false, nil
|
|
}
|
|
sec, k := namePattern(section), namePattern(key)
|
|
reDotted := regexp.MustCompile(`^(\s*` + sec + `\s*\.\s*` + k + `\s*=\s*)(.*)$`)
|
|
reInline := regexp.MustCompile(`^(\s*` + sec + `\s*=\s*\{)(.*)\}(\s*(?:#.*)?)$`)
|
|
reInlineOpen := regexp.MustCompile(`^\s*` + sec + `\s*=\s*\{`)
|
|
rePrefix := regexp.MustCompile(`^\s*` + sec + `\s*\.`)
|
|
lastDotted := -1
|
|
for i, line := range lines {
|
|
if reHeader.MatchString(line) || reArray.MatchString(line) {
|
|
break // end of the root table
|
|
}
|
|
if m := reDotted.FindStringSubmatch(line); m != nil {
|
|
val, rest, err := splitValue(m[2])
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("%s.%s: %w", section, key, err)
|
|
}
|
|
lines[i] = m[1] + styleLike(val, lit) + rest
|
|
return lines, true, nil
|
|
}
|
|
if m := reInline.FindStringSubmatch(line); m != nil {
|
|
inner, err := setInline(m[2], key, lit)
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("%s: %w", section, err)
|
|
}
|
|
lines[i] = m[1] + inner + "}" + m[3]
|
|
return lines, true, nil
|
|
}
|
|
if reInlineOpen.MatchString(line) {
|
|
return nil, false, fmt.Errorf("%s: multi-line inline tables are not supported", section)
|
|
}
|
|
if rePrefix.MatchString(line) {
|
|
lastDotted = i
|
|
}
|
|
}
|
|
if lastDotted >= 0 { // the section exists only as dotted keys: add one more
|
|
nl := section + "." + key + " = " + lit
|
|
return append(lines[:lastDotted+1], append([]string{nl}, lines[lastDotted+1:]...)...), true, nil
|
|
}
|
|
return nil, false, nil
|
|
}
|
|
|
|
// setInline sets key in the body of a one-line inline table.
|
|
func setInline(inner, key, lit string) (string, error) {
|
|
re := regexp.MustCompile(`(^|,)(\s*` + namePattern(key) + `\s*=\s*)`)
|
|
loc := re.FindStringSubmatchIndex(inner)
|
|
if loc == nil {
|
|
t := strings.TrimRight(inner, " \t")
|
|
if strings.TrimSpace(t) == "" {
|
|
return " " + key + " = " + lit + " ", nil
|
|
}
|
|
return t + ", " + key + " = " + lit + " ", nil
|
|
}
|
|
start := loc[1]
|
|
rest := inner[start:]
|
|
var end int
|
|
switch {
|
|
case strings.HasPrefix(rest, `"`) || strings.HasPrefix(rest, `'`):
|
|
val, _, err := splitValue(rest)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
end = len(val)
|
|
case strings.HasPrefix(rest, "[") || strings.HasPrefix(rest, "{"):
|
|
return "", errors.New("nested values in inline tables are not supported")
|
|
default:
|
|
end = strings.IndexByte(rest, ',')
|
|
if end < 0 {
|
|
end = len(rest)
|
|
}
|
|
end = len(strings.TrimRight(rest[:end], " \t"))
|
|
}
|
|
return inner[:start] + styleLike(rest[:end], lit) + rest[end:], 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
|
|
}
|