diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go index 78c27d1..59432b8 100644 --- a/internal/atomicfile/atomicfile.go +++ b/internal/atomicfile/atomicfile.go @@ -14,6 +14,8 @@ import ( "os" "path/filepath" "syscall" + + "golang.org/x/sys/unix" ) // WriteFile atomically replaces path with data. See Write. @@ -29,6 +31,8 @@ func WriteFile(path string, data []byte, perm fs.FileMode) error { // // - If path is a symlink (dotfiles!), the file it points to is replaced and // the link is kept. +// - If path exists but is not writable by us (chmod a-w), Write fails with +// EACCES like a plain write would, instead of replacing it. // - If path exists, its permission bits are kept (perm is used only for a // new file) and, when running as root, its owner too — so sudo does not // leave a root-owned file in a user's home. @@ -42,6 +46,11 @@ func Write(path string, perm fs.FileMode, fill func(w io.Writer) error) (err err if !fi.Mode().IsRegular() { return fmt.Errorf("atomicfile: %s is not a regular file", target) } + // A file the user made read-only stays untouched: the rename would + // replace it although open(O_WRONLY) is refused (QA-13). + if err := unix.Access(target, unix.W_OK); err != nil { + return &fs.PathError{Op: "open", Path: target, Err: err} + } perm = fi.Mode().Perm() if st, ok := fi.Sys().(*syscall.Stat_t); ok && os.Geteuid() == 0 { uid, gid = int(st.Uid), int(st.Gid) diff --git a/internal/atomicfile/atomicfile_test.go b/internal/atomicfile/atomicfile_test.go index e3adf2c..fde3f7b 100644 --- a/internal/atomicfile/atomicfile_test.go +++ b/internal/atomicfile/atomicfile_test.go @@ -98,3 +98,23 @@ func TestAtomicWriteRefusesDirectory(t *testing.T) { t.Fatal("writing over a directory must fail") } } + +func TestAtomicWriteRefusesReadOnlyFile(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root may write anything") + } + p := filepath.Join(t.TempDir(), "ro") + if err := os.WriteFile(p, []byte("keep"), 0o444); err != nil { + t.Fatal(err) + } + err := WriteFile(p, []byte("new"), 0o644) + if !errors.Is(err, os.ErrPermission) { + t.Fatalf("err = %v, want EACCES", err) + } + if b, _ := os.ReadFile(p); string(b) != "keep" { + t.Fatalf("read-only file replaced: %q", b) + } + if n := names(t, filepath.Dir(p)); len(n) != 1 { + t.Fatalf("leftovers %v", n) + } +} diff --git a/internal/config/qa_rc2_test.go b/internal/config/qa_rc2_test.go index 3b4fd3f..2ed3171 100644 --- a/internal/config/qa_rc2_test.go +++ b/internal/config/qa_rc2_test.go @@ -69,7 +69,6 @@ func TestQASetKeyThroughSymlink(t *testing.T) { // A user who made the config read-only (chmod a-w) expects vcom not to // change it. v0.2.7 failed with EACCES; atomic rename now replaces it. func TestQASetKeyReadOnlyConfig(t *testing.T) { - t.Skip("BUG QA-13 (P2): SetKey replaces a read-only (0444) config via temp+rename; v0.2.7 refused (EACCES). atomicfile.Write ignores the missing write permission (atomicfile.go:40-52)") home := qaIsolate(t) p := filepath.Join(home, ".config", "vcom", "vcom.toml") qaWrite(t, p, "[ui]\ntheme = \"locked\"\n", 0o444) @@ -83,7 +82,6 @@ func TestQASetKeyReadOnlyConfig(t *testing.T) { // table. SetKey must either edit them or fail without touching the file; // failing means the theme silently stops being saved for these users. func TestQASetKeyDottedAndInlineForms(t *testing.T) { - t.Skip("BUG QA-14 (P2): SetKey cannot save the theme when the config uses `ui.theme = ...` at the root or `ui = { theme = ... }`: it appends a second [ui] table, verify() rejects the result, theme change reports 'save failed' (setkey.go:86-152)") for name, content := range map[string]string{ "dotted": "ui.theme = \"old\"\nui.icon_mode = \"ascii\"\n", "inline": "ui = { theme = \"old\" }\n", diff --git a/internal/config/setkey.go b/internal/config/setkey.go index 337f84b..6719377 100644 --- a/internal/config/setkey.go +++ b/internal/config/setkey.go @@ -94,6 +94,13 @@ func editTOML(data []byte, section, key, lit string) ([]byte, error) { 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 @@ -119,13 +126,7 @@ func editTOML(data []byte, section, key, lit string) ([]byte, error) { 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 + lines[i] = m[1] + styleLike(val, lit) + rest return []byte(strings.Join(lines, nl)), nil } if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") { @@ -152,6 +153,107 @@ func editTOML(data []byte, section, key, lit string) ([]byte, error) { 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) { diff --git a/internal/config/setkey_test.go b/internal/config/setkey_test.go index c1b079a..9c599ae 100644 --- a/internal/config/setkey_test.go +++ b/internal/config/setkey_test.go @@ -150,3 +150,29 @@ func TestSetKeyQuotingAndCRLF(t *testing.T) { t.Fatalf("got %q", got) } } + +func TestSetKeyRootForms(t *testing.T) { + cases := map[string]struct{ in, want string }{ + "dotted": {"ui.theme = 'old' # c\nui.icon_mode = \"ascii\"\n", "ui.theme = 'new' # c\nui.icon_mode = \"ascii\"\n"}, + "dotted missing": {"ui.icon_mode = \"ascii\"\n[browser]\nshow_hidden = true\n", "ui.icon_mode = \"ascii\"\nui.theme = \"new\"\n[browser]\nshow_hidden = true\n"}, + "inline": {"ui = { theme = \"old\", border = 'x' }\n", "ui = { theme = \"new\", border = 'x' }\n"}, + "inline missing": {"ui = { border = 'x' }\n", "ui = { border = 'x', theme = \"new\" }\n"}, + "inline empty": {"ui = {}\n", "ui = { theme = \"new\" }\n"}, + } + for name, c := range cases { + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, c.in) + if _, err := SetKey(p, "ui", "theme", "new"); err != nil { + t.Fatalf("%s: %v", name, err) + } + if got := readFile(t, p); got != c.want { + t.Errorf("%s:\n got %q\nwant %q", name, got, c.want) + } + } + // A multi-line inline table is refused, file untouched. + p := filepath.Join(t.TempDir(), "vcom.toml") + writeFile(t, p, "ui = {\n}\n") + if _, err := SetKey(p, "ui", "theme", "new"); err == nil { + t.Fatal("multi-line inline accepted") + } +}