Files
magpie/internal/edit/env.go
T
yetone 5160809d2e agent: a catalog sync's round looks at each file once; a write reads the disk (#1665)
A catalog sync asked about each agent's files many times a round
(GetJSON, GetTOMLTop, settings.load from each agent's Sync): on Windows
an empty sandbox's start stat'ed settings.json 1065 times and
config.toml 569 in 25s, almost all from SyncCatalog. Each round now
holds what was read (filememo.Hold), as the GUI's read-only requests and
the gateway already do.

What a hold serves may be up to a second old, so nothing is written from
it any more:
- edit.Read, which every Set*/Del* helper and the agents' own
  read-modify-write code start from, looks at the disk even under a
  hold (filememo.ReadNow). The getters (GetJSON, GetJSONRaw,
  GetJSONItem, GetEnvFile, GetYAMLTop, the YAML getters, GetTOMLTop's
  line reader) read through the hold.
- settings: a write's load under fileMu (lockFile) reads the disk too.
Before this, a GUI request's hold could already hand a Set* stale
bytes; that is closed as well.

WriteAtomic forgot every held file even when it left the file as it
was, and a sync writes each agent's files each round, almost always
unchanged: it now forgets only after a real write.

Measured on xiaomi-gpu (Windows 11), as in the steady commit before
this one (second start, 27s, stats counted by an uncommitted build):
  before          2307 stats, sync 1318 of them, round 1308ms
  this alone      1787 stats, sync  864,          round 1273ms
  with steady's    988 stats, sync   96,          round   96ms
First start of an empty sandbox: 2448 stats before, 1041 after.

Run:
- TestHeldReadIsNotWhatAWriteIsMadeFrom (json, toml, yaml),
  TestUnchangedWriteKeepsWhatIsHeld, TestHeldSettingsAreNotWhatAWriteIsMadeFrom:
  with edit.Read and the settings write load put back on the held read
  and WriteAtomic's Forget removed by hand, json and yaml lost the other
  app's key, the settings case wrote "light" over "dark", and the
  forget case went red; green with the change, on mote.
- mote, at the pushed head: gofmt -l internal clean; GOOS=linux/windows/
  darwin go vet of steady, edit, filememo, settings and agent clean;
  go test -count=1 of steady, edit, filememo, settings, agent, provider,
  catalog and library ok; internal/gui red only on TestMainWindowCorners
  (#3949, macOS 27, red on main before this).
- xiaomi-gpu: go test of edit, filememo and settings ok.
2026-10-28 13:43:37 +08:00

92 lines
2.4 KiB
Go

package edit
import (
"regexp"
"strings"
)
// dotenv files (KEY=value per line) as Gemini CLI reads from ~/.gemini/.env.
var envLine = regexp.MustCompile(`^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$`)
// GetEnvFile reads one key from a dotenv file.
func GetEnvFile(path, key string) (string, bool) {
raw, err := readHeld(path)
if err != nil {
return "", false
}
// A key set twice takes its last value: dotenv readers, Gemini CLI's among
// them, let a later line override an earlier one.
lines := splitLines(string(raw))
for i := len(lines) - 1; i >= 0; i-- {
if m := envLine.FindStringSubmatch(lines[i]); m != nil && m[1] == key {
if v, ok := unquote(m[2]); ok {
return v, true
}
v := m[2]
if i := strings.IndexByte(v, '#'); i >= 0 {
v = strings.TrimSpace(v[:i])
}
return v, true
}
}
return "", false
}
// SetEnvFile sets keys in a dotenv file, replacing lines in place and
// appending new ones. Other lines are kept byte for byte.
func SetEnvFile(path string, kvs ...KV) error {
raw, err := Read(path)
if err != nil {
return err
}
lines := splitLines(string(raw))
for _, kv := range kvs {
v := toString(kv.Value)
if strings.ContainsAny(v, " #\"'$\r\n") {
// Gemini CLI's dotenv keeps backslashes literal inside single quotes.
if !strings.ContainsAny(v, "'\r\n") {
v = "'" + v + "'"
} else {
v = `"` + strings.ReplaceAll(strings.ReplaceAll(v, `\`, `\\`), `"`, `\"`) + `"`
}
}
lines = setLine(lines, kv.Path, kv.Path+"="+v, nil, func(l string) (string, bool) {
if m := envLine.FindStringSubmatch(l); m != nil {
return m[1], true
}
return "", false
})
}
return WriteAtomic(path, []byte(joinLinesLike(lines, string(raw))))
}
// DelEnvFile removes keys from a dotenv file, and the file when they were
// all it held (Gemini CLI's .env, made by magpie for its key).
func DelEnvFile(path string, keys ...string) error {
raw, err := Read(path)
if err != nil || len(raw) == 0 {
return err
}
drop := map[string]bool{}
for _, k := range keys {
drop[k] = true
}
var out []string
changed := false
for _, l := range splitLines(string(raw)) {
if m := envLine.FindStringSubmatch(l); m != nil && drop[m[1]] {
changed = true
continue
}
out = append(out, l)
}
if !changed {
return nil
}
if strings.TrimSpace(strings.Join(out, "")) == "" {
return Remove(path)
}
return WriteAtomic(path, []byte(joinLines(out)))
}