vcom/internal/state/session.go

185 lines
4.9 KiB
Go
Raw Normal View History

// Package state persists the UI session (design §9.1, §9.2):
// $XDG_STATE_HOME/vcom/session.toml, written atomically, migrated once from
// the pre-0.3 location next to the config.
package state
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
toml "github.com/pelletier/go-toml/v2"
"vcom/internal/atomicfile"
"vcom/internal/paths"
)
// MaxCursorMemory bounds the remembered "cursor per directory" entries per pane.
const MaxCursorMemory = 200
// Session is the UI state restored on the next launch.
type Session struct {
ActivePane string `toml:"active_pane"`
Left PaneSession `toml:"left"`
Right PaneSession `toml:"right"`
}
// PaneSession is one pane's state: its directory, the selected entry and the
// last selected entry per visited directory.
type PaneSession struct {
Path string `toml:"path"`
EntryName string `toml:"entry_name"`
CursorMemory map[string]string `toml:"cursor_memory"`
}
// File is the session path: StateDir/session.toml.
func File() (string, error) {
d, err := paths.StateDir()
if err != nil {
return "", err
}
return filepath.Join(d, "session.toml"), nil
}
// Load reads the session. A missing file is not an error (zero Session). If
// only the old file (~/.config/vcom/session.toml) exists, it is read, saved
// to the new location and removed — except under sudo, where the old file
// belongs to the invoking user and is left alone.
func Load() (Session, error) {
p, err := File()
if err != nil {
return Session{}, err
}
s, err := read(p)
if err == nil || !errors.Is(err, fs.ErrNotExist) {
return s, err
}
old, oerr := paths.OldSessionFile()
if oerr != nil {
return Session{}, nil
}
s, err = read(old)
if errors.Is(err, fs.ErrNotExist) {
return Session{}, nil
}
if err != nil {
return Session{}, err
}
if err := Save(s); err != nil {
return s, fmt.Errorf("migrate session from %s: %w", old, err)
}
if _, sudo := paths.SudoUser(); !sudo {
_ = os.Remove(old)
}
return s, nil
}
func read(p string) (Session, error) {
data, err := os.ReadFile(p)
if err != nil {
return Session{}, err
}
var s Session
if err := toml.Unmarshal(data, &s); err != nil {
return Session{}, fmt.Errorf("parse %s: %w", p, err)
}
return s, nil
}
// Save normalises s (see Normalize) and writes it atomically (0600) into a
// 0700 state directory.
func Save(s Session) error {
p, err := File()
if err != nil {
return err
}
if err := paths.EnsureDir(filepath.Dir(p)); err != nil {
return err
}
s.Normalize(transientPrefixes())
var buf bytes.Buffer
if err := toml.NewEncoder(&buf).Encode(s); err != nil {
return fmt.Errorf("encode session: %w", err)
}
return atomicfile.WriteFile(p, buf.Bytes(), 0o600)
}
// transientPrefixes are directories whose paths are not worth remembering:
// vcom's cache/run dirs and the old UI's temp mounts.
func transientPrefixes() []string {
var out []string
if c, err := paths.CacheDir(); err == nil {
out = append(out, c)
}
tmp := os.TempDir()
out = append(out, filepath.Join(tmp, "vcom-archive-"), filepath.Join(tmp, "vcom-remote-"))
return out
}
// Normalize drops cursor-memory entries under any of the transient prefixes
// and caps each pane at MaxCursorMemory entries.
func (s *Session) Normalize(transient []string) {
s.Left.CursorMemory = capMemory(s.Left.CursorMemory, s.Left.Path, transient)
s.Right.CursorMemory = capMemory(s.Right.CursorMemory, s.Right.Path, transient)
}
// capMemory keeps at most MaxCursorMemory entries. The map carries no
// recency, so it keeps first the entries on the pane's current path (its
// ancestors and descendants: where the user is most likely to go back), then
// the rest in path order. Deterministic, which keeps the file diff-friendly.
func capMemory(m map[string]string, current string, transient []string) map[string]string {
if len(m) == 0 {
return m
}
keys := make([]string, 0, len(m))
for k, v := range m {
if k == "" || v == "" || hasAnyPrefix(k, transient) {
continue
}
keys = append(keys, k)
}
related := func(k string) bool {
return current != "" && (isWithin(k, current) || isWithin(current, k))
}
sort.Slice(keys, func(i, j int) bool {
ri, rj := related(keys[i]), related(keys[j])
if ri != rj {
return ri
}
return keys[i] < keys[j]
})
if len(keys) > MaxCursorMemory {
keys = keys[:MaxCursorMemory]
}
out := make(map[string]string, len(keys))
for _, k := range keys {
out[k] = m[k]
}
return out
}
func hasAnyPrefix(p string, prefixes []string) bool {
for _, pre := range prefixes {
if pre != "" && (p == pre || strings.HasPrefix(p, pre)) {
return true
}
}
return false
}
func isWithin(child, parent string) bool {
child, parent = filepath.Clean(child), filepath.Clean(parent)
if child == parent {
return true
}
if !strings.HasSuffix(parent, string(filepath.Separator)) {
parent += string(filepath.Separator)
}
return strings.HasPrefix(child, parent)
}