Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

2.5 KB
Raw Blame
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
		})
	}
	lines = markEnv(lines, string(raw))
	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
	}
	// a note magpie put above a key goes with it
	out = markEnv(out, string(raw))
	if strings.TrimSpace(strings.Join(withoutNotes(out), "")) == "" {
		return Remove(path)
	}
	return WriteAtomic(path, []byte(joinLines(out)))
}