agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they didn't parse, and the next save wrote that emptiness over them. What magpie had applied to each agent, the WSL distros and the WSL session listing were lost with no copy. stash.json already kept a bad file aside as .bad-<time>. Each of these now does the same through one helper, lastgood.KeepUnparsed, instead of a copy per file: - It does nothing when the file is missing or empty. - When the file doesn't unmarshal into the reader's own type (lastgood.Into[T]), it copies the file aside (KeepBad). - It stops the write when the copy can't be kept. This also fixes the issue's claim about stash.json. Stash judged a file with json.Valid, so `[]`, which a map reader takes as empty, was written over unkept. Its failed copy was only logged, and the write went ahead anyway. Both are fixed (TestUnreadStashArrayKeptAside), and gateway-hidden.json uses the same helper. Siblings found by going through every single-file JSON reader that takes a bad file as empty and then writes it whole: - stepfun-auth - login-returns - quota-history - balance-history - credits-daily - Claude Desktop tiers - plugin updates - usage's computer id - davsync's sync state Each now keeps a bad copy. Caches that are rebuilt from the vendor are left alone; docs/subsystems/providers-accounts.md lists them. Run: - gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui, GOOS=windows): clean. - go test -tags nogui -p 4 -timeout 40m ./... with the other three commits of this push: see the last one's body. Broken by hand: on the code before this, these fail: - the issue's applied_keep_test.go and wsl_keep_test.go - TestUnreadStashArrayKeptAside - TestUnreadStateKeptAside (10 subtests) - the gateway, usage, davsync and plugin _keep tests TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the helper. I dropped a test, "not written when it can't be kept", for stash. It passed on the old code too, because a read-only folder also stops the atomic write. Not tried: a real WSL distro. Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
@@ -174,6 +174,7 @@ readings on both sides of detected boundaries.
|
||||
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
|
||||
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
|
||||
- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. So does every write of an agent's own sign-in (#2239): `codexToken`'s rotated tokens into Codex's `auth.json` (`~/.codex`, or `$CODEX_HOME` when set) and `writeClaudeCredential`'s `.credentials.json` go through `writePrivate`, never a truncating `os.WriteFile`, so a machine going down mid-write leaves the old sign-in whole, and on Windows a file another program holds for a moment is waited out (`steady.Rename`) instead of the rotation being dropped while the refresh token on the disk is spent. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
|
||||
- A state file whose reader takes one that doesn't unmarshal into its type as empty is copied aside before it is written over (`lastgood.KeepUnparsed` with `lastgood.Into[T]`, #2263): valid JSON of another shape, `[]` for a map, counts as not parsing. A copy that can't be made stops the write. These are `stash.json`, `applied.json` and `wsl.json` ([agent](../../internal/agent/)), `sessions-wsl.json` and `gateway-sessions-hidden.json` ([sessions](../../internal/sessions/)), `stepfun-auth.json`, `login-returns.json`, `quota-history.json`, `balance-history.json` and `credits-daily.json` ([provider](../../internal/provider/)), `claude-desktop.tiers.json`, `plugin-updates.json`, `usage-computer.json` and `sync-state.json`. Caches magpie fills again by itself (last quota readings, check-in and warm-up marks, plugin icons, npm and GitHub lookups, client shapes, seats, alert marks, `served.json`, `bun/state.json`) are still written over: losing one costs a refetch or a repeated notice.
|
||||
- The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write.
|
||||
- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.
|
||||
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
@@ -44,7 +46,15 @@ func appliedLoad() map[string]applied {
|
||||
return out
|
||||
}
|
||||
|
||||
// appliedSave writes m as applied.json. It holds what magpie set on every
|
||||
// agent, and appliedLoad reads a file that doesn't parse as empty: such a
|
||||
// file is copied aside first, and one that can't be copied isn't written
|
||||
// over (#2263).
|
||||
func appliedSave(m map[string]applied) {
|
||||
if err := lastgood.KeepUnparsed(appliedPath(), lastgood.Into[map[string]applied]); err != nil {
|
||||
log.Printf("applied.json wasn't written over: %v", err)
|
||||
return
|
||||
}
|
||||
b, _ := json.MarshalIndent(m, "", " ")
|
||||
os.MkdirAll(filepath.Dir(appliedPath()), 0o755)
|
||||
os.WriteFile(appliedPath(), b, 0o600)
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// applied.json holds what magpie last set on every agent. A file that
|
||||
// doesn't parse is read as no record, and the next record writes that
|
||||
// over it: every other agent's record is copied aside first.
|
||||
func TestUnreadAppliedKeptAside(t *testing.T) {
|
||||
stashHome(t)
|
||||
p := appliedPath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half := `{"claude":{"at":"2026-10-01T00:00:00Z","fields":{"model":"magpie/opus"}},"codex":{"at":"2026-10-01T00:00:00Z","fields":{"model":"magpie/gpt"}}`
|
||||
if err := os.WriteFile(p, []byte(half), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record("pi", "model", "magpie/pi-model")
|
||||
kept := keptAside(t, p)
|
||||
if string(kept) != half {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
live, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(live), `"magpie/pi-model"`) {
|
||||
t.Fatalf("applied.json after the record: %s", live)
|
||||
}
|
||||
|
||||
// a file that parses is written over as before, nothing more kept
|
||||
good := `{"claude":{"at":"2026-10-01T00:00:00Z","fields":{"model":"magpie/opus"}}}`
|
||||
if err := os.WriteFile(p, []byte(good), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record("pi", "model", "magpie/pi-model")
|
||||
if more, _ := filepath.Glob(p + ".bad-*"); len(more) != 1 {
|
||||
t.Fatalf("kept aside after a good write: %v", more)
|
||||
}
|
||||
live, err = os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(live), `"magpie/opus"`) || !strings.Contains(string(live), `"magpie/pi-model"`) {
|
||||
t.Fatalf("applied.json after a good record: %s", live)
|
||||
}
|
||||
}
|
||||
|
||||
// JSON that isn't the record map (an array, as a hand edit or another
|
||||
// program might leave) is not a record of what magpie set either.
|
||||
func TestUnreadAppliedArrayKeptAside(t *testing.T) {
|
||||
stashHome(t)
|
||||
p := appliedPath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
arr := []byte(`[]`)
|
||||
if err := os.WriteFile(p, arr, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record("pi", "model", "magpie/pi-model")
|
||||
if kept := keptAside(t, p); string(kept) != string(arr) {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// A copy that can't be made stops the write: the unread file stays.
|
||||
func TestUnreadAppliedNotWrittenWhenItCantBeKept(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a directory without write permission still accepts a new name")
|
||||
}
|
||||
stashHome(t)
|
||||
p := appliedPath()
|
||||
dir := filepath.Dir(p)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half := `{"claude":{"at":"2026-10-01T00:00:00Z","fields":{"model":"magpie/opus"}}`
|
||||
if err := os.WriteFile(p, []byte(half), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(dir, 0o555); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })
|
||||
if f, err := os.Create(filepath.Join(dir, "probe")); err == nil {
|
||||
f.Close()
|
||||
t.Skip("the filesystem does not enforce the read-only folder")
|
||||
}
|
||||
record("pi", "model", "magpie/pi-model")
|
||||
live, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(live) != half {
|
||||
t.Fatalf("applied.json = %q, want it left as %q", live, half)
|
||||
}
|
||||
}
|
||||
|
||||
// wsl.json holds every distro's last probe. A file that doesn't parse is
|
||||
// read as no distro, and the next save writes that over it.
|
||||
func TestUnreadWSLConfigKeptAside(t *testing.T) {
|
||||
stashHome(t)
|
||||
p := wslStatePath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half := `{"Ubuntu":{"name":"Ubuntu","home":"/home/me","probe":2,"values":{"claude.model":"magpie/opus"}}`
|
||||
if err := os.WriteFile(p, []byte(half), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saveFreshWSL(t)
|
||||
kept := keptAside(t, p)
|
||||
if string(kept) != half {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
live, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(live), `"Fresh"`) {
|
||||
t.Fatalf("wsl.json after the save: %s", live)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnreadWSLConfigArrayKeptAside(t *testing.T) {
|
||||
stashHome(t)
|
||||
p := wslStatePath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
arr := []byte(`[]`)
|
||||
if err := os.WriteFile(p, arr, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saveFreshWSL(t)
|
||||
if kept := keptAside(t, p); string(kept) != string(arr) {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
}
|
||||
|
||||
func saveFreshWSL(t *testing.T) {
|
||||
t.Helper()
|
||||
wsl.Lock()
|
||||
oldSeen, oldDirty, oldAt, oldRun := wsl.seen, wsl.dirty, wsl.at, wsl.runAt
|
||||
wsl.seen = map[string]*distro{"Fresh": {Name: "Fresh", Home: "/home/fresh", Probe: wslProbeVersion}}
|
||||
wsl.dirty = true
|
||||
wsl.Unlock()
|
||||
t.Cleanup(func() {
|
||||
wsl.Lock()
|
||||
wsl.seen, wsl.dirty, wsl.at, wsl.runAt = oldSeen, oldDirty, oldAt, oldRun
|
||||
wsl.Unlock()
|
||||
})
|
||||
wslSave()
|
||||
}
|
||||
|
||||
func keptAside(t *testing.T, path string) []byte {
|
||||
t.Helper()
|
||||
matches, err := filepath.Glob(path + ".bad-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
t.Fatalf("kept aside %d copies, want 1: %v", len(matches), matches)
|
||||
}
|
||||
b, err := os.ReadFile(matches[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
+8
-17
@@ -8,9 +8,9 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -47,7 +47,13 @@ func stashWrite(m map[string]string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
keepUnreadStash(p)
|
||||
// stashLoad reads a file that doesn't unmarshal into the stash (a JSON
|
||||
// array too, not only one cut short) as empty: it is copied aside, and
|
||||
// one that can't be copied isn't written over
|
||||
if err := lastgood.KeepUnparsed(p, lastgood.Into[map[string]string]); err != nil {
|
||||
log.Printf("stash.json wasn't written over: %v", err)
|
||||
return err
|
||||
}
|
||||
// made 0600 first: WriteAtomic keeps a file's mode, and the stash holds
|
||||
// keys
|
||||
if f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err == nil {
|
||||
@@ -58,21 +64,6 @@ func stashWrite(m map[string]string) error {
|
||||
return edit.WriteAtomic(p, b)
|
||||
}
|
||||
|
||||
// keepUnreadStash copies a stash.json that doesn't parse aside before it is
|
||||
// written over.
|
||||
func keepUnreadStash(path string) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil || len(b) == 0 || json.Valid(b) {
|
||||
return
|
||||
}
|
||||
bad := path + ".bad-" + time.Now().Format("20060102-150405.000000000")
|
||||
if err := os.WriteFile(bad, b, 0o600); err != nil {
|
||||
log.Printf("stash.json doesn't parse and couldn't be kept: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("stash.json didn't parse; it is kept as %s", filepath.Base(bad))
|
||||
}
|
||||
|
||||
func stash(kv map[string]string) {
|
||||
stashMu.Lock()
|
||||
defer stashMu.Unlock()
|
||||
|
||||
@@ -69,3 +69,23 @@ func TestUnreadStashKeptAside(t *testing.T) {
|
||||
t.Fatalf("stash.json is %v; it holds keys", fi.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// stashLoad reads a stash.json that is valid JSON but not the stash's map
|
||||
// (an array) as empty too: it is kept aside like one cut short, not taken
|
||||
// as a stash because json.Valid passes it (#2263).
|
||||
func TestUnreadStashArrayKeptAside(t *testing.T) {
|
||||
stashHome(t)
|
||||
p := stashPath()
|
||||
os.MkdirAll(filepath.Dir(p), 0o755)
|
||||
if err := os.WriteFile(p, []byte(`[]`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stash(map[string]string{"pi.was": "x"})
|
||||
bad, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != `[]` {
|
||||
t.Fatalf("kept aside as %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
+15
-4
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
@@ -1067,11 +1069,20 @@ func wslSave() {
|
||||
wslSaveLocked()
|
||||
}
|
||||
|
||||
// wslSaveLocked writes wsl.seen when it changed. wsl.json holds every
|
||||
// distro's last probe, and wslDistros reads a file that doesn't parse as
|
||||
// no distro: such a file is copied aside first, and one that can't be
|
||||
// copied isn't written over (#2263).
|
||||
func wslSaveLocked() {
|
||||
if wsl.dirty {
|
||||
if b, err := json.MarshalIndent(wsl.seen, "", " "); err == nil && edit.WriteAtomic(wslStatePath(), b) == nil {
|
||||
wsl.dirty = false
|
||||
}
|
||||
if !wsl.dirty {
|
||||
return
|
||||
}
|
||||
if err := lastgood.KeepUnparsed(wslStatePath(), lastgood.Into[map[string]*distro]); err != nil {
|
||||
log.Printf("wsl.json wasn't written over: %v", err)
|
||||
return
|
||||
}
|
||||
if b, err := json.MarshalIndent(wsl.seen, "", " "); err == nil && edit.WriteAtomic(wslStatePath(), b) == nil {
|
||||
wsl.dirty = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/backup"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/profile"
|
||||
@@ -547,7 +548,14 @@ func loadState() state {
|
||||
return st
|
||||
}
|
||||
|
||||
// saveState writes st. loadState reads a file that doesn't parse as no
|
||||
// state, which starts sync afresh and loses a restore's Undo and the Blind
|
||||
// guard: such a file is kept aside first, and one that can't be isn't
|
||||
// written over.
|
||||
func saveState(st state) {
|
||||
if lastgood.KeepUnparsed(path("sync-state.json"), lastgood.Into[state]) != nil {
|
||||
return
|
||||
}
|
||||
b, _ := json.MarshalIndent(st, "", " ")
|
||||
edit.WriteAtomic(path("sync-state.json"), b)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sync-state.json is read as no state when it doesn't parse, and the next
|
||||
// save wrote that over it, a restore's Undo and the Blind guard with it
|
||||
// (#2263): what was there is copied aside first.
|
||||
func TestUnreadSyncStateKeptAside(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
p := path("sync-state.json")
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
was := `{"key":"k","undo":"/somewhere`
|
||||
if err := os.WriteFile(p, []byte(was), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saveState(state{Key: "k"})
|
||||
bad, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != was {
|
||||
t.Fatalf("kept aside as %q, want %q", b, was)
|
||||
}
|
||||
if loadState().Key != "k" {
|
||||
t.Fatal("the new state wasn't written")
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -251,6 +252,12 @@ func DesktopTiers() map[string]string {
|
||||
// SetDesktopTier picks the model (a catalog id) Claude Desktop runs a tier
|
||||
// on; "" takes the pick away.
|
||||
func SetDesktopTier(tier, id string) error {
|
||||
// DesktopTiers reads a file that doesn't parse as no pick: what it held,
|
||||
// every other tier's pick, is kept aside before it is written over or
|
||||
// taken away
|
||||
if err := lastgood.KeepUnparsed(desktopTiersPath(), lastgood.Into[map[string]string]); err != nil {
|
||||
return err
|
||||
}
|
||||
tiers := DesktopTiers()
|
||||
if id == "" {
|
||||
delete(tiers, tier)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// claude-desktop.tiers.json is read as no pick when it doesn't parse, and
|
||||
// picking one tier wrote that over every other tier's pick (#2263): what
|
||||
// was there is copied aside first.
|
||||
func TestUnreadDesktopTiersKeptAside(t *testing.T) {
|
||||
for _, was := range []string{`{"opus": "fake/m1", "sonn`, `[]`} {
|
||||
t.Run(was, func(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
p := desktopTiersPath()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(was), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetDesktopTier("haiku", "fake/m2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != was {
|
||||
t.Fatalf("kept aside as %q, want %q", b, was)
|
||||
}
|
||||
if DesktopTiers()["haiku"] != "fake/m2" {
|
||||
t.Fatalf("the pick wasn't kept: %v", DesktopTiers())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,35 @@ func Keep(path string, valid Valid, perm fs.FileMode) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Into is a file that unmarshals into a T: what a reader that takes any
|
||||
// other file as empty can read. `[]` is valid JSON but not a map, so a
|
||||
// reader of a map would see nothing in it.
|
||||
func Into[T any](b []byte) bool {
|
||||
var v T
|
||||
return json.Unmarshal(b, &v) == nil
|
||||
}
|
||||
|
||||
// KeepUnparsed is called before path is written over, by a writer whose
|
||||
// reader takes a file that doesn't parse (parses false) as empty: such a
|
||||
// file is copied aside (KeepBad) first, so the write of what was read as
|
||||
// empty doesn't lose what it held. A file not there, or empty, needs
|
||||
// nothing. An error stops the write: the file there couldn't be read, or
|
||||
// couldn't be kept.
|
||||
func KeepUnparsed(path string, parses Valid) error {
|
||||
b, err := steady.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(b)) == 0 || parses(b) {
|
||||
return nil
|
||||
}
|
||||
_, err = KeepBad(path, b)
|
||||
return err
|
||||
}
|
||||
|
||||
// now is time.Now; a test stands in for it.
|
||||
var now = time.Now
|
||||
|
||||
|
||||
@@ -192,3 +192,51 @@ func TestDescribe(t *testing.T) {
|
||||
t.Error("JSON misjudged")
|
||||
}
|
||||
}
|
||||
|
||||
// KeepUnparsed keeps aside a file its reader can't read as its type (cut
|
||||
// short, or valid JSON of another shape), leaves one that parses, an empty
|
||||
// one and one not there alone, and keeps the same bad bytes once.
|
||||
func TestKeepUnparsed(t *testing.T) {
|
||||
p := setup(t)
|
||||
parses := Into[map[string]string]
|
||||
bads := func() []string { m, _ := filepath.Glob(p + ".bad-*"); return m }
|
||||
if err := KeepUnparsed(p, parses); err != nil {
|
||||
t.Fatalf("a file not there: %v", err)
|
||||
}
|
||||
for _, ok := range []string{`{"a":"b"}`, "", " \n", "null"} {
|
||||
os.WriteFile(p, []byte(ok), 0o600)
|
||||
if err := KeepUnparsed(p, parses); err != nil || len(bads()) != 0 {
|
||||
t.Fatalf("%q: err %v, kept %v", ok, err, bads())
|
||||
}
|
||||
}
|
||||
for i, bad := range []string{`[]`, `{"a":"b"`, `{"a":1}`} {
|
||||
os.WriteFile(p, []byte(bad), 0o600)
|
||||
for range 2 {
|
||||
if err := KeepUnparsed(p, parses); err != nil {
|
||||
t.Fatalf("%q: %v", bad, err)
|
||||
}
|
||||
}
|
||||
if got := bads(); len(got) != i+1 {
|
||||
t.Fatalf("%q: kept %v, want %d copies", bad, got, i+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file that doesn't parse and can't be copied aside stops the write.
|
||||
func TestKeepUnparsedFailsWhenItCantBeKept(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a folder's mode doesn't stop a new file on Windows")
|
||||
}
|
||||
p := setup(t)
|
||||
os.WriteFile(p, []byte(`[]`), 0o600)
|
||||
dir := filepath.Dir(p)
|
||||
os.Chmod(dir, 0o500)
|
||||
defer os.Chmod(dir, 0o700)
|
||||
if f, err := os.Create(filepath.Join(dir, "probe")); err == nil {
|
||||
f.Close()
|
||||
t.Skip("the filesystem does not enforce the read-only folder")
|
||||
}
|
||||
if err := KeepUnparsed(p, Into[map[string]string]); err == nil {
|
||||
t.Fatal("a bad file not kept, and the write let go on")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/ghtoken"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
@@ -112,6 +113,17 @@ func readUpdates() Updates {
|
||||
return u
|
||||
}
|
||||
|
||||
// writeUpdates writes b as plugin-updates.json. readUpdates reads a file
|
||||
// that doesn't parse as no updates, and Updated, the plugins magpie updated
|
||||
// by itself, can't be found again: such a file is kept aside first, and
|
||||
// one that can't be isn't written over.
|
||||
func writeUpdates(b []byte) error {
|
||||
if err := lastgood.KeepUnparsed(updatesPath(), lastgood.Into[Updates]); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeWhole(updatesPath(), b)
|
||||
}
|
||||
|
||||
// PendingUpdates is what the last look found, less what has changed since:
|
||||
// a plugin updated, removed or switched off since waits no more.
|
||||
func PendingUpdates() Updates {
|
||||
@@ -214,7 +226,7 @@ func CheckUpdates(ctx context.Context) (Updates, error) {
|
||||
}
|
||||
if b, err := json.MarshalIndent(u, "", " "); err == nil {
|
||||
if err := os.MkdirAll(settings.Dir(), 0o700); err == nil {
|
||||
_ = writeWhole(updatesPath(), b)
|
||||
_ = writeUpdates(b)
|
||||
}
|
||||
}
|
||||
updatesMu.Unlock()
|
||||
@@ -440,7 +452,7 @@ func CheckNow(ctx context.Context) VersionChecks {
|
||||
u.Checked, u.Waiting = now, waiting
|
||||
if b, err := json.MarshalIndent(u, "", " "); err == nil {
|
||||
if err := os.MkdirAll(settings.Dir(), 0o700); err == nil {
|
||||
_ = writeWhole(updatesPath(), b)
|
||||
_ = writeUpdates(b)
|
||||
}
|
||||
}
|
||||
updatesMu.Unlock()
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// plugin-updates.json is read as no updates when it doesn't parse, and the
|
||||
// next check wrote that over it: Updated, the plugins magpie updated by
|
||||
// itself, can't be found again (#2263). What was there is copied aside
|
||||
// first.
|
||||
func TestUnreadUpdatesKeptAside(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("HOME", dir)
|
||||
t.Setenv("USERPROFILE", dir)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
|
||||
if err := os.MkdirAll(filepath.Dir(updatesPath()), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
was := `{"updated":[{"package":"opencode-gemini-auth","from":"0.1.2","to":"0.2`
|
||||
if err := os.WriteFile(updatesPath(), []byte(was), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := CheckUpdates(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad, _ := filepath.Glob(updatesPath() + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != was {
|
||||
t.Fatalf("kept aside as %q, want %q", b, was)
|
||||
}
|
||||
if PendingUpdates().Checked.IsZero() {
|
||||
t.Fatal("the check wasn't written")
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -89,6 +91,12 @@ func writeBalanceHist(h balanceHist) {
|
||||
return
|
||||
}
|
||||
path := balanceHistPath()
|
||||
// readBalanceHist reads a file that doesn't parse as no history: it is
|
||||
// kept aside before it is written over, and not written over when it
|
||||
// can't be
|
||||
if lastgood.KeepUnparsed(path, lastgood.Into[balanceHist]) != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(path), 0o700)
|
||||
_ = writeFileAtomic(path, b)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// loginSwitchEvery is how often the account each agent is on is looked at.
|
||||
@@ -297,6 +298,11 @@ func setLoginReturn(agent string, r loginReturn) {
|
||||
m[agent] = r
|
||||
}
|
||||
b, err := json.MarshalIndent(m, "", " ")
|
||||
if err == nil {
|
||||
// readLoginReturns reads a file that doesn't parse as none: it is
|
||||
// kept aside before it is written over
|
||||
err = lastgood.KeepUnparsed(loginReturnsPath(), lastgood.Into[map[string]loginReturn])
|
||||
}
|
||||
if err == nil {
|
||||
err = writePrivate(loginReturnsPath(), append(b, '\n'))
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// DailyCredits is what an account's credits went to day by day.
|
||||
@@ -172,6 +173,11 @@ func noteDailyCredits(qs []SubscriptionQuota, now time.Time) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// parseCredits reads a file that doesn't parse as no days: it is kept
|
||||
// aside before it is written over, and not written over when it can't be
|
||||
if lastgood.KeepUnparsed(path, lastgood.Into[map[string]*creditsAccount]) != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(path), 0o700)
|
||||
_ = writeFileAtomic(path, b)
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -108,6 +109,12 @@ func writeQuotaHist(h quotaHist) {
|
||||
return
|
||||
}
|
||||
path := quotaHistPath()
|
||||
// parseQuotaHist reads a file that doesn't parse as no history: it is
|
||||
// kept aside before it is written over, and not written over when it
|
||||
// can't be
|
||||
if lastgood.KeepUnparsed(path, lastgood.Into[quotaHist]) != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(path), 0o700)
|
||||
_ = writeFileAtomic(path, b)
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// stepfunSites are StepFun's two platforms, by the API host a provider uses.
|
||||
@@ -147,6 +149,11 @@ func saveStepFun(all map[string]stepfunSession) error {
|
||||
if err := os.MkdirAll(filepath.Dir(stepfunPath()), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
// loadStepFun reads a file that doesn't parse as no session: what it
|
||||
// held, every site's sign-in, is kept aside before it is written over
|
||||
if err := lastgood.KeepUnparsed(stepfunPath(), lastgood.Into[map[string]stepfunSession]); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFileAtomic(stepfunPath(), b)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Each of these files is read as empty when it doesn't parse, and the next
|
||||
// write put that over it: every other account's, site's or day's record
|
||||
// was gone, with no copy (#2263). What was there is copied aside first,
|
||||
// valid JSON of another shape (an array for a map) too.
|
||||
func TestUnreadStateKeptAside(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
path func() string
|
||||
write func()
|
||||
}{
|
||||
{"stepfun-auth.json", stepfunPath, func() { saveStepFun(map[string]stepfunSession{"cn": {}}) }},
|
||||
{"login-returns.json", loginReturnsPath, func() { setLoginReturn("codex", loginReturn{Back: "a", To: "b"}) }},
|
||||
{"quota-history.json", quotaHistPath, func() { writeQuotaHist(quotaHist{}) }},
|
||||
{"balance-history.json", balanceHistPath, func() { writeBalanceHist(balanceHist{}) }},
|
||||
{"credits-daily.json", creditsPath, func() {
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy", "me", 1, 10)}, time.Now())
|
||||
}},
|
||||
} {
|
||||
for _, was := range []string{`{"someone": {"a": `, `[]`} {
|
||||
t.Run(c.name+" "+was, func(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
p := c.path()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(was), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.write()
|
||||
bad, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != was {
|
||||
t.Fatalf("kept aside as %q, want %q", b, was)
|
||||
}
|
||||
if b, _ := os.ReadFile(p); string(b) == was {
|
||||
t.Fatal("the write didn't happen")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,13 @@ package sessions
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
@@ -79,21 +78,7 @@ func writeHidden(list []hiddenGateway) error {
|
||||
// magpie made before, and a read that came back empty is unknown, not
|
||||
// nothing. A copy that can't be made stops the write.
|
||||
func keepUnreadHidden() error {
|
||||
p := gatewayHiddenPath()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil || len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
var list []hiddenGateway
|
||||
if json.Unmarshal(b, &list) == nil {
|
||||
return nil
|
||||
}
|
||||
bad := p + ".bad-" + time.Now().Format("20060102-150405.000000000")
|
||||
if err := os.WriteFile(bad, b, 0o600); err != nil {
|
||||
return fmt.Errorf("gateway-sessions-hidden.json doesn't parse and couldn't be kept aside: %w", err)
|
||||
}
|
||||
log.Printf("gateway-sessions-hidden.json didn't parse; it is kept as %s", filepath.Base(bad))
|
||||
return nil
|
||||
return lastgood.KeepUnparsed(gatewayHiddenPath(), lastgood.Into[[]hiddenGateway])
|
||||
}
|
||||
|
||||
// GatewayHidden says whether a gateway session was deleted: true when it
|
||||
|
||||
@@ -3,12 +3,15 @@ package sessions
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// Sessions in WSL. On Windows an agent installed in a WSL distro keeps its
|
||||
@@ -243,7 +246,12 @@ func wslList(gen uint64, done chan struct{}) {
|
||||
}
|
||||
if b != nil && !bytes.Equal(b, wslSess.kept) {
|
||||
p := wslListPath()
|
||||
if os.MkdirAll(filepath.Dir(p), 0o755) == nil {
|
||||
// wslFiles reads a file that doesn't parse as no listing: it is
|
||||
// copied aside before this one goes over it, and one that can't be
|
||||
// copied isn't written over (#2263)
|
||||
if err := lastgood.KeepUnparsed(p, lastgood.Into[map[string]*wslListing]); err != nil {
|
||||
log.Printf("sessions-wsl.json wasn't written over: %v", err)
|
||||
} else if os.MkdirAll(filepath.Dir(p), 0o755) == nil {
|
||||
tmp := p + ".tmp"
|
||||
if os.WriteFile(tmp, b, 0o644) == nil && os.Rename(tmp, p) == nil {
|
||||
wslSess.kept = b
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sessions-wsl.json is the listing of session files in WSL distros, kept
|
||||
// so a stopped distro is not started to list it again. A file that doesn't
|
||||
// parse is read as no listing, and the next list writes that over it.
|
||||
func TestUnreadWSLSessionListKeptAside(t *testing.T) {
|
||||
p := wslListHome(t)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half := `{"Ubuntu":{"home":"/home/me","files":[{"agent":"claude","key":"s1","path":"/home/me/.claude/projects/a/s1.jsonl","size":1,"mod":"2026-10-01T00:00:00Z"}]`
|
||||
if err := os.WriteFile(p, []byte(half), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wslFiles("claude")
|
||||
wslSettle()
|
||||
kept := keptWSLAside(t, p)
|
||||
if string(kept) != half {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// JSON that isn't the listing map is not a listing either.
|
||||
func TestUnreadWSLSessionListArrayKeptAside(t *testing.T) {
|
||||
p := wslListHome(t)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
arr := []byte(`[]`)
|
||||
if err := os.WriteFile(p, arr, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wslFiles("claude")
|
||||
wslSettle()
|
||||
if kept := keptWSLAside(t, p); string(kept) != string(arr) {
|
||||
t.Fatalf("the file kept aside isn't the one that was there: %s", kept)
|
||||
}
|
||||
}
|
||||
|
||||
func wslListHome(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
t.Setenv("HOME", filepath.Join(dir, "home"))
|
||||
t.Setenv("USERPROFILE", filepath.Join(dir, "home"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
|
||||
prevHomes, prevOff, prevRun := WSLHomes, WSLOff, WSLRunning
|
||||
WSLHomes = func() []WSLHome { return nil }
|
||||
WSLOff = nil
|
||||
WSLRunning = nil
|
||||
t.Cleanup(func() {
|
||||
wslSettle()
|
||||
WSLHomes, WSLOff, WSLRunning = prevHomes, prevOff, prevRun
|
||||
Reset()
|
||||
})
|
||||
Reset()
|
||||
return wslListPath()
|
||||
}
|
||||
|
||||
func keptWSLAside(t *testing.T, path string) []byte {
|
||||
t.Helper()
|
||||
matches, err := filepath.Glob(path + ".bad-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
t.Fatalf("kept aside %d copies, want 1: %v", len(matches), matches)
|
||||
}
|
||||
b, err := os.ReadFile(matches[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// usage-computer.json holds the id this computer's synced days are under.
|
||||
// One that doesn't parse was written over with a new id and no copy
|
||||
// (#2263): it is copied aside first.
|
||||
func TestUnreadComputerKeptAside(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
p := filepath.Join(dir(), "usage-computer.json")
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
was := `{"id":"0123456789abcdef","name":"desk`
|
||||
if err := os.WriteFile(p, []byte(was), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id, _ := Computer(); id == "" {
|
||||
t.Fatal("no id")
|
||||
}
|
||||
bad, _ := filepath.Glob(p + ".bad-*")
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("kept aside: %v", bad)
|
||||
}
|
||||
if b, _ := os.ReadFile(bad[0]); string(b) != was {
|
||||
t.Fatalf("kept aside as %q, want %q", b, was)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
@@ -48,14 +49,17 @@ func dir() string { return filepath.Dir(provider.Path()) }
|
||||
// OthersDir is where the other computers' days are kept: one folder each.
|
||||
func OthersDir() string { return filepath.Join(dir(), "usage-others") }
|
||||
|
||||
// computerFile is usage-computer.json.
|
||||
type computerFile struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// Computer is this computer's id and name, the id made the first time and
|
||||
// kept in usage-computer.json, which no backup or sync carries.
|
||||
func Computer() (id, name string) {
|
||||
p := filepath.Join(dir(), "usage-computer.json")
|
||||
var c struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
var c computerFile
|
||||
if b, err := os.ReadFile(p); err == nil {
|
||||
json.Unmarshal(b, &c)
|
||||
}
|
||||
@@ -64,7 +68,10 @@ func Computer() (id, name string) {
|
||||
rand.Read(b)
|
||||
c.ID = hex.EncodeToString(b)
|
||||
os.MkdirAll(dir(), 0o755)
|
||||
if j, err := json.Marshal(c); err == nil {
|
||||
// a file that doesn't parse held this computer's id, the one its
|
||||
// synced days are under: it is kept aside before a new id goes
|
||||
// over it, and not written over when it can't be
|
||||
if j, err := json.Marshal(c); err == nil && lastgood.KeepUnparsed(p, lastgood.Into[computerFile]) == nil {
|
||||
edit.WriteAtomic(p, j)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user