From 6f4d6f5609284aee086095cd49e15d8fcde61892 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Fri, 23 Oct 2026 14:29:30 +0200 Subject: [PATCH] feat: bubbletea dashboard, skill picker and update review Bare skm opens a dashboard with live upstream status per source; add uses a filterable picker and update a side-by-side diff review when run in a terminal. Non-interactive paths are unchanged. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 2 +- cmd/skm/main.go | 39 +++- cmd/skm/update.go | 72 +++++-- flake.nix | 4 +- go.mod | 27 ++- go.sum | 44 ++++ internal/core/core.go | 102 +++++++--- internal/tui/dashboard.go | 408 ++++++++++++++++++++++++++++++++++++++ internal/tui/picker.go | 149 ++++++++++++++ internal/tui/review.go | 174 ++++++++++++++++ internal/tui/tui.go | 114 +++++++++++ internal/tui/tui_test.go | 182 +++++++++++++++++ 12 files changed, 1262 insertions(+), 55 deletions(-) create mode 100644 go.sum create mode 100644 internal/tui/dashboard.go create mode 100644 internal/tui/picker.go create mode 100644 internal/tui/review.go create mode 100644 internal/tui/tui.go create mode 100644 internal/tui/tui_test.go diff --git a/PLAN.md b/PLAN.md index 4499b1e..2639e5d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -128,7 +128,7 @@ Diffs are computed in Go between `oldStorePath/subpath` and `newStorePath/subpat - Unit: manifest/lock round-trips, collision and alias rules, `*` expansion, subtree change detection, diff output (fake fetcher). - End-to-end: a temp `git+file://` repo with two skills; `add`, commit upstream, `outdated`, `update --yes`; assert the lock. Needs nix, no network. Nix can't run inside the build sandbox, so these tests skip during `nix flake check` and run via `go test` in the devShell. -- TUI: `teatest` golden files for the dashboard, picker and diff review. +- TUI: the picker, review and dashboard models are driven with key messages directly, asserting on state and ANSI-stripped views (no `teatest` golden files: less brittle, no extra dependency). ## Build order diff --git a/cmd/skm/main.go b/cmd/skm/main.go index 74ab0a0..71840e3 100644 --- a/cmd/skm/main.go +++ b/cmd/skm/main.go @@ -14,9 +14,12 @@ import ( "skill-manager/internal/fetch" "skill-manager/internal/jsonfile" "skill-manager/internal/manifest" + "skill-manager/internal/tui" ) -const usage = `usage: skm [--dir DIR] [args] +const usage = `usage: skm [--dir DIR] [command] [args] + +Without a command, skm opens the dashboard. commands: add [--ref R] [--name N] (--skill a,b=alias,dir/c | --all) @@ -53,9 +56,9 @@ func run(ctx context.Context, args []string) error { return err } args = global.Args() - if len(args) == 0 { + if len(args) == 0 && !tui.Interactive() { global.Usage() - return errors.New("no command") + return errors.New("no command (the dashboard needs a terminal)") } cfg, err := loadConfig(*dir) @@ -64,6 +67,20 @@ func run(ctx context.Context, args []string) error { } store := core.Store{Dir: cfg.ManifestDir, Fetcher: fetch.Nix{}} + if len(args) == 0 { + summary, err := tui.Dashboard(ctx, store) + if err != nil { + return err + } + for _, line := range summary { + fmt.Println(line) + } + if len(summary) > 0 { + return rebuild(cfg, false) + } + return nil + } + switch cmd, rest := args[0], args[1:]; cmd { case "add": return add(ctx, store, rest) @@ -150,6 +167,22 @@ func add(ctx context.Context, store core.Store, args []string) error { req.Skills = append(req.Skills, k) } + if !req.All && len(req.Skills) == 0 && tui.Interactive() { + found, installed, err := store.Available(ctx, req) + if err != nil { + return err + } + chosen, err := tui.Pick(ctx, "add from "+req.URL, found, installed) + if errors.Is(err, tui.ErrCanceled) { + fmt.Println("nothing added") + return nil + } + if err != nil { + return err + } + req.Skills = core.Select(found, chosen) + } + key, err := store.Add(ctx, req) if sel, ok := errors.AsType[*core.NoSelectionError](err); ok { fmt.Fprintf(os.Stderr, "skills in %s:\n", sel.Source) diff --git a/cmd/skm/update.go b/cmd/skm/update.go index 6a87cac..1cad705 100644 --- a/cmd/skm/update.go +++ b/cmd/skm/update.go @@ -12,6 +12,7 @@ import ( "strings" "skill-manager/internal/core" + "skill-manager/internal/tui" ) func outdated(ctx context.Context, store core.Store, args []string) error { @@ -53,36 +54,39 @@ func update(ctx context.Context, store core.Store, cfg config, args []string) er if err != nil { return err } - in := bufio.NewReader(os.Stdin) - var accepted []core.SourceStatus + var outdated []core.SourceStatus failed := 0 for _, st := range statuses { if st.Err != nil { fmt.Fprintf(os.Stderr, "%s: %v\n", st.Source, st.Err) failed++ - continue + } else if st.Outdated() { + outdated = append(outdated, st) } - if !st.Outdated() { - continue + } + + var accepted []core.SourceStatus + switch { + case len(outdated) == 0: + case *yes: + accepted = outdated + case tui.Interactive(): + accepted, err = tui.Review(ctx, outdated) + if errors.Is(err, tui.ErrCanceled) { + fmt.Println("aborted, nothing changed") + return nil } + if err != nil { + return err + } + default: + accepted, err = reviewText(ctx, outdated) + if err != nil { + return err + } + } + for _, st := range accepted { printStatus(os.Stdout, st) - if !*yes { - for _, ch := range st.Changes { - d, err := core.Diff(ctx, ch) - if err != nil { - return err - } - fmt.Print(d) - } - ok, err := confirm(in, fmt.Sprintf("apply %s? [y/N] ", st.Source)) - if err != nil { - return err - } - if !ok { - continue - } - } - accepted = append(accepted, st) } if len(accepted) > 0 { @@ -102,6 +106,30 @@ func update(ctx context.Context, store core.Store, cfg config, args []string) er return nil } +// reviewText prints each outdated source's diff and asks on stdin; used without a terminal. +func reviewText(ctx context.Context, outdated []core.SourceStatus) ([]core.SourceStatus, error) { + in := bufio.NewReader(os.Stdin) + var accepted []core.SourceStatus + for _, st := range outdated { + printStatus(os.Stdout, st) + for _, ch := range st.Changes { + d, err := core.Diff(ctx, ch) + if err != nil { + return nil, err + } + fmt.Print(d) + } + ok, err := confirm(in, fmt.Sprintf("apply %s? [y/N] ", st.Source)) + if err != nil { + return nil, err + } + if ok { + accepted = append(accepted, st) + } + } + return accepted, nil +} + func printStatus(w io.Writer, st core.SourceStatus) { switch { case st.OldRev == "": diff --git a/flake.nix b/flake.nix index 6c682f9..438f34a 100644 --- a/flake.nix +++ b/flake.nix @@ -26,11 +26,13 @@ root = ./.; fileset = pkgs.lib.fileset.unions [ ./go.mod + ./go.sum ./cmd ./internal ]; }; - vendorHash = null; + # Update after changing go.mod: set to lib.fakeHash, build, copy the "got" hash. + vendorHash = "sha256-rTR/1l7HFUL8Eh2LA1JdkrfBxnJdwwyKp094QL2KMzg="; # Tests that need nix skip themselves: it isn't on PATH in the sandbox. nativeCheckInputs = [ pkgs.git ]; nativeBuildInputs = [ pkgs.makeWrapper ]; diff --git a/go.mod b/go.mod index 9cf08f3..34c39f5 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,28 @@ module skill-manager -go 1.26 +go 1.26.0 + +require ( + charm.land/bubbles/v2 v2.2.1 + charm.land/bubbletea/v2 v2.1.0 + charm.land/lipgloss/v2 v2.0.6 + github.com/charmbracelet/x/ansi v0.11.9 + github.com/charmbracelet/x/term v0.2.2 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect + github.com/charmbracelet/x/termios v0.1.1 // indirect + github.com/charmbracelet/x/windows v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/lucasb-eyer/go-colorful v1.4.1 // indirect + github.com/mattn/go-runewidth v0.0.30 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v1.0.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e85827e --- /dev/null +++ b/go.sum @@ -0,0 +1,44 @@ +charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= +charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= +charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw= +charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= +charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= +charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= +github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw= +github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= +github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= +github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= +github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk= +github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= +github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/internal/core/core.go b/internal/core/core.go index a718446..ca85a2e 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -116,34 +116,10 @@ func (s Store) Add(ctx context.Context, req AddRequest) (string, error) { if err != nil { return "", err } - key := req.Name - if key == "" { - key = SourceKey(req.URL) + key, src, ref, err := target(m, l, req) + if err != nil { + return "", err } - - src := m.Sources[key] - var ref string - if src != nil { - if src.URL != req.URL { - return "", fmt.Errorf("source %q already exists with url %s; pick another name with --name", key, src.URL) - } - if req.Ref != "" && req.Ref != src.Ref { - return "", fmt.Errorf("source %q tracks ref %q; add a second source with --name to track %q", key, src.Ref, req.Ref) - } - locked := l.Sources[key] - if locked == nil { - return "", fmt.Errorf("source %q is in %s but not locked; run skm update %s first", key, ManifestFile, key) - } - ref = fetch.AtRev(flakeRef(src), locked.Rev()) - src = &manifest.Source{URL: src.URL, Ref: src.Ref, Skills: manifest.Selection{ - All: src.Skills.All, - Items: slices.Clone(src.Skills.Items), - }} - } else { - src = &manifest.Source{URL: req.URL, Ref: req.Ref} - ref = flakeRef(src) - } - res, found, err := s.fetchSkills(ctx, ref) if err != nil { return "", fmt.Errorf("%s: %w", key, err) @@ -181,6 +157,78 @@ func (s Store) Add(ctx context.Context, req AddRequest) (string, error) { return key, s.save(m, l) } +// target resolves the source an add goes to and the flake ref to fetch: the pinned +// rev for a tracked source, the head of its ref for a new one. src is a copy that +// is safe to modify. +func target(m *manifest.Manifest, l *lock.Lock, req AddRequest) (key string, src *manifest.Source, ref string, err error) { + key = req.Name + if key == "" { + key = SourceKey(req.URL) + } + existing := m.Sources[key] + if existing == nil { + src = &manifest.Source{URL: req.URL, Ref: req.Ref} + return key, src, flakeRef(src), nil + } + if existing.URL != req.URL { + return "", nil, "", fmt.Errorf("source %q already exists with url %s; pick another name with --name", key, existing.URL) + } + if req.Ref != "" && req.Ref != existing.Ref { + return "", nil, "", fmt.Errorf("source %q tracks ref %q; add a second source with --name to track %q", key, existing.Ref, req.Ref) + } + locked := l.Sources[key] + if locked == nil { + return "", nil, "", fmt.Errorf("source %q is in %s but not locked; run skm update %s first", key, ManifestFile, key) + } + src = &manifest.Source{URL: existing.URL, Ref: existing.Ref, Skills: manifest.Selection{ + All: existing.Skills.All, + Items: slices.Clone(existing.Skills.Items), + }} + return key, src, fetch.AtRev(flakeRef(src), locked.Rev()), nil +} + +// Select turns skills chosen from found into manifest entries. Names that appear +// more than once in found get their path, so the entry stays unambiguous. +func Select(found, chosen []skills.Skill) []manifest.Skill { + count := map[string]int{} + for _, f := range found { + count[f.Name]++ + } + var out []manifest.Skill + for _, c := range chosen { + k := manifest.Skill{Name: c.Name} + if count[c.Name] > 1 { + k.Path = c.Path + } + out = append(out, k) + } + return out +} + +// Available lists the skills Add would choose from, and which of their paths are +// already installed from that source. +func (s Store) Available(ctx context.Context, req AddRequest) ([]skills.Skill, map[string]bool, error) { + m, l, err := s.load() + if err != nil { + return nil, nil, err + } + key, _, ref, err := target(m, l, req) + if err != nil { + return nil, nil, err + } + _, found, err := s.fetchSkills(ctx, ref) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", key, err) + } + installed := map[string]bool{} + if locked := l.Sources[key]; locked != nil { + for _, path := range locked.Skills { + installed[path] = true + } + } + return found, installed, nil +} + func (s Store) fetchSkills(ctx context.Context, ref string) (fetch.Result, []skills.Skill, error) { res, err := s.Fetcher.Prefetch(ctx, ref) if err != nil { diff --git a/internal/tui/dashboard.go b/internal/tui/dashboard.go new file mode 100644 index 0000000..70c19c7 --- /dev/null +++ b/internal/tui/dashboard.go @@ -0,0 +1,408 @@ +package tui + +import ( + "context" + "fmt" + "maps" + "slices" + "strings" + + "charm.land/bubbles/v2/spinner" + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + + "skill-manager/internal/core" + "skill-manager/internal/skills" +) + +type mode int + +const ( + modeList mode = iota + modeConfirm + modeURL + modeBusy + modeSub +) + +// row is a source header (skill == "") or one of its installed skills. +type row struct{ source, skill, path string } + +type statusMsg struct { + source string + st core.SourceStatus +} + +type availableMsg struct { + url string + found []skills.Skill + installed map[string]bool + err error +} + +// doneMsg reports an add, remove or update that changed the manifest or lock. +type doneMsg struct { + summary string + recheck []string + err error +} + +type dashboard struct { + ctx context.Context + store core.Store + rows []row + revs map[string]string // source -> locked rev + status map[string]core.SourceStatus + checking map[string]bool + cursor int + spin spinner.Model + input textinput.Model + + mode mode + sub component + onSubDone func(component) tea.Cmd + question string + onYes func() tea.Cmd + + note string + summary []string + width int + height int +} + +// Dashboard runs the full-screen dashboard and returns one line per change made. +func Dashboard(ctx context.Context, store core.Store) ([]string, error) { + d := newDashboard(ctx, store) + if err := d.reload(); err != nil { + return nil, err + } + _, err := tea.NewProgram(d, tea.WithContext(ctx)).Run() + return d.summary, err +} + +func newDashboard(ctx context.Context, store core.Store) *dashboard { + in := textinput.New() + in.Placeholder = "github:owner/repo" + return &dashboard{ + ctx: ctx, + store: store, + status: map[string]core.SourceStatus{}, + checking: map[string]bool{}, + spin: spinner.New(spinner.WithSpinner(spinner.MiniDot)), + input: in, + width: 80, + height: 24, + } +} + +func (d *dashboard) reload() error { + installed, err := d.store.List() + if err != nil { + return err + } + bySource := map[string][]core.Installed{} + d.revs = map[string]string{} + for _, i := range installed { + bySource[i.Source] = append(bySource[i.Source], i) + d.revs[i.Source] = i.Rev + } + d.rows = nil + for _, src := range slices.Sorted(maps.Keys(bySource)) { + d.rows = append(d.rows, row{source: src}) + for _, i := range bySource[src] { + d.rows = append(d.rows, row{source: src, skill: i.Name, path: i.Path}) + } + } + for src := range d.status { + if _, ok := d.revs[src]; !ok { + delete(d.status, src) + } + } + d.cursor = max(0, min(d.cursor, len(d.rows)-1)) + return nil +} + +func (d *dashboard) sources() []string { return slices.Sorted(maps.Keys(d.revs)) } + +func (d *dashboard) Init() tea.Cmd { + return tea.Batch(d.spin.Tick, d.recheck(d.sources()...)) +} + +// recheck checks each source against upstream, one command per source so a slow +// one doesn't hold up the rest. +func (d *dashboard) recheck(sources ...string) tea.Cmd { + var cmds []tea.Cmd + for _, src := range sources { + if _, ok := d.revs[src]; !ok { + continue + } + d.checking[src] = true + ctx, store := d.ctx, d.store + cmds = append(cmds, func() tea.Msg { + sts, err := store.Check(ctx, src) + if err != nil { + return statusMsg{src, core.SourceStatus{Source: src, Err: err}} + } + return statusMsg{src, sts[0]} + }) + } + return tea.Batch(cmds...) +} + +func (d *dashboard) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + d.width, d.height = msg.Width, msg.Height + if d.sub != nil { + d.sub.resize(d.width, d.height) + } + case spinner.TickMsg: + var cmd tea.Cmd + d.spin, cmd = d.spin.Update(msg) + return d, cmd + case statusMsg: + delete(d.checking, msg.source) + d.status[msg.source] = msg.st + case availableMsg: + d.mode = modeList + if msg.err != nil { + d.note = red.Render(msg.err.Error()) + return d, nil + } + d.note = "" + d.open(newPicker("add from "+msg.url, msg.found, msg.installed), func(c component) tea.Cmd { + p := c.(*picker) + if p.canceled { + return nil + } + return d.add(msg.url, p.items, p.selection()) + }) + case doneMsg: + d.mode = modeList + if msg.err != nil { + d.note = red.Render(msg.err.Error()) + return d, nil + } + d.summary = append(d.summary, msg.summary) + d.note = green.Render(msg.summary) + dim.Render(" · rebuild to install") + if err := d.reload(); err != nil { + d.note = red.Render(err.Error()) + } + return d, d.recheck(msg.recheck...) + case tea.KeyPressMsg: + return d, d.key(msg) + } + return d, nil +} + +func (d *dashboard) open(c component, onDone func(component) tea.Cmd) { + c.resize(d.width, d.height) + d.sub, d.onSubDone, d.mode = c, onDone, modeSub +} + +func (d *dashboard) ask(question string, onYes func() tea.Cmd) { + d.question, d.onYes, d.mode = question, onYes, modeConfirm +} + +func (d *dashboard) key(msg tea.KeyPressMsg) tea.Cmd { + switch d.mode { + case modeSub: + cmd := d.sub.update(msg) + if !d.sub.finished() { + return cmd + } + c, onDone := d.sub, d.onSubDone + d.sub, d.onSubDone, d.mode = nil, nil, modeList + return tea.Batch(cmd, onDone(c)) + case modeConfirm: + d.mode = modeList + if msg.String() == "y" { + d.note = "" + return d.onYes() + } + d.note = "canceled" + return nil + case modeURL: + switch msg.String() { + case "esc": + d.mode = modeList + return nil + case "enter": + url := strings.TrimSpace(d.input.Value()) + if url == "" { + return nil + } + d.mode, d.note = modeBusy, "fetching "+url + ctx, store := d.ctx, d.store + return func() tea.Msg { + found, installed, err := store.Available(ctx, core.AddRequest{URL: url}) + return availableMsg{url, found, installed, err} + } + } + var cmd tea.Cmd + d.input, cmd = d.input.Update(msg) + return cmd + case modeBusy: + if msg.String() == "ctrl+c" { + return tea.Quit + } + return nil + } + + switch msg.String() { + case "q", "esc", "ctrl+c": + return tea.Quit + case "up", "k": + d.cursor = max(0, d.cursor-1) + case "down", "j": + d.cursor = min(len(d.rows)-1, d.cursor+1) + case "r": + d.note = "" + return d.recheck(d.sources()...) + case "a": + d.mode = modeURL + d.input.SetValue("") + return d.input.Focus() + case "U": + var outdated []core.SourceStatus + for _, src := range d.sources() { + if st := d.status[src]; st.Outdated() { + outdated = append(outdated, st) + } + } + d.review(outdated) + } + if d.cursor >= len(d.rows) { + return nil + } + r := d.rows[d.cursor] + switch msg.String() { + case "u", "enter": + d.review([]core.SourceStatus{d.status[r.source]}) + case "d": + if r.skill != "" { + d.ask(fmt.Sprintf("remove %s from %s?", r.skill, r.source), func() tea.Cmd { return d.remove(r.skill) }) + } else { + d.ask(fmt.Sprintf("remove source %s and all its skills?", r.source), func() tea.Cmd { return d.removeSource(r.source) }) + } + } + return nil +} + +func (d *dashboard) review(statuses []core.SourceStatus) { + r := newReview(d.ctx, statuses) + if r.done { + d.note = "nothing to update" + return + } + d.open(r, func(c component) tea.Cmd { + r := c.(*review) + if r.canceled || len(r.accepted) == 0 { + return nil + } + store, accepted := d.store, r.accepted + return func() tea.Msg { + var sources []string + for _, st := range accepted { + sources = append(sources, st.Source) + } + head, _, _ := strings.Cut(core.CommitMessage(accepted), "\n") + return doneMsg{strings.TrimPrefix(head, "skills: "), sources, store.Apply(accepted)} + } + }) +} + +func (d *dashboard) add(url string, found, chosen []skills.Skill) tea.Cmd { + req := core.AddRequest{URL: url, Skills: core.Select(found, chosen)} + var names []string + for _, c := range chosen { + names = append(names, c.Name) + } + ctx, store := d.ctx, d.store + return func() tea.Msg { + key, err := store.Add(ctx, req) + return doneMsg{fmt.Sprintf("added %s from %s", strings.Join(names, ", "), key), []string{key}, err} + } +} + +func (d *dashboard) remove(skill string) tea.Cmd { + store := d.store + return func() tea.Msg { + key, err := store.Remove(skill) + return doneMsg{fmt.Sprintf("removed %s from %s", skill, key), []string{key}, err} + } +} + +func (d *dashboard) removeSource(source string) tea.Cmd { + store := d.store + return func() tea.Msg { + return doneMsg{"removed source " + source, nil, store.RemoveSource(source)} + } +} + +func (d *dashboard) View() tea.View { + v := tea.NewView(d.render()) + v.AltScreen = true + return v +} + +func (d *dashboard) render() string { + if d.mode == modeSub { + return d.sub.view() + } + var b strings.Builder + b.WriteString(bold.Render("skm") + " " + dim.Render(d.store.Dir) + "\n\n") + + start, end := window(len(d.rows), d.cursor, d.height-5) + for i := start; i < end; i++ { + r := d.rows[i] + cursor := " " + if i == d.cursor { + cursor = selected.Render("› ") + } + st, checked := d.status[r.source] + if r.skill == "" { + fmt.Fprintf(&b, "%s%s %s %s\n", cursor, bold.Render(r.source), dim.Render(fmt.Sprintf("%.7s", d.revs[r.source])), d.sourceState(r.source, st, checked)) + continue + } + mark := " " + for _, ch := range st.Changes { + if ch.Name == r.skill { + mark = symbol(ch.Kind) + } + } + fmt.Fprintf(&b, "%s %s %s %s\n", cursor, mark, r.skill, dim.Render(r.path)) + } + if len(d.rows) == 0 { + b.WriteString(dim.Render(" no skills yet; press a to add a source") + "\n") + } + + var footer string + switch d.mode { + case modeURL: + footer = "add source: " + d.input.View() + case modeConfirm: + footer = yellow.Render(d.question + " [y/N]") + case modeBusy: + footer = d.spin.View() + " " + d.note + default: + footer = d.note + "\n" + dim.Render("↑/↓ move · u/enter review update · U review all · a add · d remove · r refresh · q quit") + } + return fit(b.String(), d.width, d.height-2) + "\n" + fit(footer, d.width, 2) +} + +func (d *dashboard) sourceState(src string, st core.SourceStatus, checked bool) string { + switch { + case d.checking[src]: + return d.spin.View() + dim.Render(" checking") + case !checked: + return "" + case st.Err != nil: + msg, _, _ := strings.Cut(st.Err.Error(), "\n") + return red.Render("✗ " + msg) + case st.Outdated(): + return yellow.Render(fmt.Sprintf("↑ %d changed upstream", len(st.Changes))) + default: + return green.Render("✓ up to date") + } +} diff --git a/internal/tui/picker.go b/internal/tui/picker.go new file mode 100644 index 0000000..4dff842 --- /dev/null +++ b/internal/tui/picker.go @@ -0,0 +1,149 @@ +package tui + +import ( + "context" + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + + "skill-manager/internal/skills" +) + +// picker is a filterable multi-select over a source's skills. Typing filters; +// already-installed skills are shown but can't be picked. +type picker struct { + title string + items []skills.Skill + installed map[string]bool // by path + filter string + cursor int // index into visible() + picked map[int]bool + width int + height int + done bool + canceled bool +} + +func newPicker(title string, items []skills.Skill, installed map[string]bool) *picker { + return &picker{title: title, items: items, installed: installed, picked: map[int]bool{}} +} + +// Pick lets the user choose skills from items. It returns ErrCanceled on escape. +func Pick(ctx context.Context, title string, items []skills.Skill, installed map[string]bool) ([]skills.Skill, error) { + p := newPicker(title, items, installed) + if err := run(ctx, p); err != nil { + return nil, err + } + if p.canceled { + return nil, ErrCanceled + } + return p.selection(), nil +} + +func (p *picker) visible() []int { + var out []int + f := strings.ToLower(p.filter) + for i, s := range p.items { + if strings.Contains(strings.ToLower(s.Name+" "+s.Path), f) { + out = append(out, i) + } + } + return out +} + +func (p *picker) selection() []skills.Skill { + var out []skills.Skill + for i, s := range p.items { + if p.picked[i] { + out = append(out, s) + } + } + return out +} + +func (p *picker) toggle(i int) { + if !p.installed[p.items[i].Path] { + p.picked[i] = !p.picked[i] + } +} + +func (p *picker) update(msg tea.Msg) tea.Cmd { + key, ok := msg.(tea.KeyPressMsg) + if !ok { + return nil + } + vis := p.visible() + switch key.String() { + case "ctrl+c", "esc": + p.canceled, p.done = true, true + case "enter": + // Enter with nothing picked takes the highlighted skill. + if len(p.selection()) == 0 && p.cursor < len(vis) { + p.toggle(vis[p.cursor]) + } + p.done = len(p.selection()) > 0 + case "up", "ctrl+p": + p.cursor = max(0, p.cursor-1) + case "down", "ctrl+n": + p.cursor = min(len(vis)-1, p.cursor+1) + case "space": + if p.cursor < len(vis) { + p.toggle(vis[p.cursor]) + } + case "ctrl+a": + for _, i := range vis { + p.toggle(i) + } + case "backspace": + if p.filter != "" { + p.filter = p.filter[:len(p.filter)-1] + p.cursor = 0 + } + default: + if key.Text != "" { + p.filter += key.Text + p.cursor = 0 + } + } + return nil +} + +func (p *picker) resize(width, height int) { p.width, p.height = width, height } + +func (p *picker) finished() bool { return p.done } + +func (p *picker) view() string { + var b strings.Builder + fmt.Fprintf(&b, "%s %s\n", bold.Render(p.title), dim.Render(fmt.Sprintf("%d selected", len(p.selection())))) + fmt.Fprintf(&b, "filter: %s%s\n\n", p.filter, dim.Render("▏")) + + vis := p.visible() + nameWidth := 0 + for _, i := range vis { + nameWidth = max(nameWidth, len(p.items[i].Name)) + } + start, end := window(len(vis), p.cursor, p.height-5) + for row := start; row < end; row++ { + s := p.items[vis[row]] + box := "[ ]" + switch { + case p.installed[s.Path]: + box = dim.Render("[•]") + case p.picked[vis[row]]: + box = green.Render("[x]") + } + line := fmt.Sprintf("%s %s %s", box, pad(s.Name, nameWidth), dim.Render(s.Path)) + if row == p.cursor { + line = selected.Render("›") + " " + line + } else { + line = " " + line + } + b.WriteString(line + "\n") + } + if len(vis) == 0 { + b.WriteString(dim.Render(" no skills match") + "\n") + } + body := fit(b.String(), p.width, p.height-1) + return body + "\n" + dim.Render("type to filter · ↑/↓ move · space toggle · ctrl+a toggle all · enter add · esc cancel") +} diff --git a/internal/tui/review.go b/internal/tui/review.go new file mode 100644 index 0000000..0381068 --- /dev/null +++ b/internal/tui/review.go @@ -0,0 +1,174 @@ +package tui + +import ( + "context" + "fmt" + "strings" + + "charm.land/bubbles/v2/viewport" + tea "charm.land/bubbletea/v2" + + "skill-manager/internal/core" +) + +// review walks outdated sources one at a time: changed skills on the left, the +// selected skill's diff on the right; y accepts the source, n skips it. +type review struct { + ctx context.Context + statuses []core.SourceStatus + i, sel int + vp viewport.Model + diffs map[[2]int]string + accepted []core.SourceStatus + width int + height int + done bool + canceled bool +} + +func newReview(ctx context.Context, statuses []core.SourceStatus) *review { + r := &review{ctx: ctx, vp: viewport.New(), diffs: map[[2]int]string{}} + for _, st := range statuses { + if st.Outdated() { + r.statuses = append(r.statuses, st) + } + } + r.done = len(r.statuses) == 0 + return r +} + +// Review shows the diffs of outdated statuses and returns the accepted ones. +// It returns ErrCanceled if the user aborts. +func Review(ctx context.Context, statuses []core.SourceStatus) ([]core.SourceStatus, error) { + r := newReview(ctx, statuses) + if r.done { + return nil, nil + } + if err := run(ctx, r); err != nil { + return nil, err + } + if r.canceled { + return nil, ErrCanceled + } + return r.accepted, nil +} + +func (r *review) leftWidth() int { return min(32, r.width/3) } + +func (r *review) load() { + if r.done { + return + } + k := [2]int{r.i, r.sel} + d, ok := r.diffs[k] + if !ok { + var err error + d, err = core.Diff(r.ctx, r.statuses[r.i].Changes[r.sel]) + if err != nil { + d = red.Render(err.Error()) + } else if d == "" { + d = dim.Render("(no file contents to show)") + } else { + d = colorDiff(d) + } + r.diffs[k] = d + } + r.vp.SetContent(d) + r.vp.GotoTop() +} + +func (r *review) next() { + r.i++ + r.sel = 0 + r.done = r.i >= len(r.statuses) + r.load() +} + +func (r *review) update(msg tea.Msg) tea.Cmd { + key, ok := msg.(tea.KeyPressMsg) + if !ok || r.done { + return nil + } + changes := r.statuses[r.i].Changes + switch key.String() { + case "ctrl+c", "esc", "q": + r.canceled, r.done = true, true + case "y": + r.accepted = append(r.accepted, r.statuses[r.i]) + r.next() + case "n": + r.next() + case "up", "shift+tab": + r.sel = max(0, r.sel-1) + r.load() + case "down", "tab": + r.sel = min(len(changes)-1, r.sel+1) + r.load() + default: + var cmd tea.Cmd + r.vp, cmd = r.vp.Update(msg) + return cmd + } + return nil +} + +func (r *review) resize(width, height int) { + r.width, r.height = width, height + r.vp.SetWidth(max(1, width-r.leftWidth()-3)) + r.vp.SetHeight(max(1, height-3)) + r.load() +} + +func (r *review) finished() bool { return r.done } + +func (r *review) view() string { + if r.done { + return "" + } + st := r.statuses[r.i] + header := fmt.Sprintf("%s %s %s", + bold.Render(fmt.Sprintf("review %d/%d", r.i+1, len(r.statuses))), + bold.Render(st.Source), dim.Render(revs(st))) + + var left strings.Builder + for j, ch := range st.Changes { + line := symbol(ch.Kind) + " " + ch.Name + if j == r.sel { + line = selected.Render("› ") + line + } else { + line = " " + line + } + left.WriteString(line + "\n") + } + bodyHeight := max(1, r.height-3) + leftCol := strings.Split(fit(left.String(), r.leftWidth(), bodyHeight), "\n") + rightCol := strings.Split(fit(r.vp.View(), r.width-r.leftWidth()-3, bodyHeight), "\n") + var body strings.Builder + for j := range bodyHeight { + fmt.Fprintf(&body, "%s %s %s\n", pad(leftCol[j], r.leftWidth()), dim.Render("│"), rightCol[j]) + } + return header + "\n\n" + strings.TrimRight(body.String(), "\n") + "\n" + + dim.Render("y accept · n skip · ↑/↓ skill · j/k pgup/pgdn scroll · q abort") +} + +func revs(st core.SourceStatus) string { + switch { + case st.OldRev == "": + return fmt.Sprintf("new → %.7s", st.NewRev) + case st.NewRev == "": + return fmt.Sprintf("%.7s → removed", st.OldRev) + default: + return fmt.Sprintf("%.7s → %.7s", st.OldRev, st.NewRev) + } +} + +func symbol(k core.ChangeKind) string { + switch k { + case core.Added: + return green.Render(k.Symbol()) + case core.Removed: + return red.Render(k.Symbol()) + default: + return yellow.Render(k.Symbol()) + } +} diff --git a/internal/tui/tui.go b/internal/tui/tui.go new file mode 100644 index 0000000..6556c72 --- /dev/null +++ b/internal/tui/tui.go @@ -0,0 +1,114 @@ +// Package tui holds skm's bubbletea views: the skill picker, the update review, +// and the dashboard that hosts both. All state changes go through internal/core. +package tui + +import ( + "context" + "errors" + "os" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/term" +) + +// ErrCanceled is returned when the user backs out of a picker or review. +var ErrCanceled = errors.New("canceled") + +// Interactive reports whether stdin and stdout are a terminal. +func Interactive() bool { + return term.IsTerminal(os.Stdin.Fd()) && term.IsTerminal(os.Stdout.Fd()) +} + +// component is a view that can run standalone or inside the dashboard. +type component interface { + update(tea.Msg) tea.Cmd + view() string + resize(width, height int) + finished() bool +} + +// runner runs one component as a full-screen program until it finishes. +type runner struct{ c component } + +func (r runner) Init() tea.Cmd { return nil } + +func (r runner) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if size, ok := msg.(tea.WindowSizeMsg); ok { + r.c.resize(size.Width, size.Height) + return r, nil + } + cmd := r.c.update(msg) + if r.c.finished() { + return r, tea.Quit + } + return r, cmd +} + +func (r runner) View() tea.View { + v := tea.NewView(r.c.view()) + v.AltScreen = true + return v +} + +func run(ctx context.Context, c component) error { + c.resize(80, 24) + _, err := tea.NewProgram(runner{c}, tea.WithContext(ctx)).Run() + return err +} + +var ( + bold = lipgloss.NewStyle().Bold(true) + dim = lipgloss.NewStyle().Faint(true) + green = lipgloss.NewStyle().Foreground(lipgloss.Color("2")) + red = lipgloss.NewStyle().Foreground(lipgloss.Color("1")) + yellow = lipgloss.NewStyle().Foreground(lipgloss.Color("3")) + cyan = lipgloss.NewStyle().Foreground(lipgloss.Color("6")) + selected = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("5")) +) + +// colorDiff styles a unified diff line by line. +func colorDiff(d string) string { + lines := strings.Split(strings.TrimRight(d, "\n"), "\n") + for i, l := range lines { + switch { + case strings.HasPrefix(l, "diff "), strings.HasPrefix(l, "--- "), strings.HasPrefix(l, "+++ "): + lines[i] = bold.Render(l) + case strings.HasPrefix(l, "@@"): + lines[i] = cyan.Render(l) + case strings.HasPrefix(l, "+"): + lines[i] = green.Render(l) + case strings.HasPrefix(l, "-"): + lines[i] = red.Render(l) + } + } + return strings.Join(lines, "\n") +} + +// window returns the [start, end) slice of n rows that keeps cursor visible in height rows. +func window(n, cursor, height int) (int, int) { + start := max(0, cursor-max(height, 1)+1) + return start, min(n, start+max(height, 1)) +} + +// pad right-pads s with spaces to width cells, ignoring escape codes. +func pad(s string, width int) string { + return s + strings.Repeat(" ", max(0, width-ansi.StringWidth(s))) +} + +// fit truncates each line to width and pads or cuts the block to height lines. +func fit(s string, width, height int) string { + lines := strings.Split(s, "\n") + if len(lines) > height { + lines = lines[:height] + } + for i, l := range lines { + lines[i] = ansi.Truncate(l, width, "…") + } + for len(lines) < height { + lines = append(lines, "") + } + return strings.Join(lines, "\n") +} diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go new file mode 100644 index 0000000..6d38475 --- /dev/null +++ b/internal/tui/tui_test.go @@ -0,0 +1,182 @@ +package tui + +import ( + "context" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "skill-manager/internal/core" + "skill-manager/internal/fetch" + "skill-manager/internal/skills" +) + +func press(keys ...string) []tea.Msg { + named := map[string]rune{ + "enter": tea.KeyEnter, "esc": tea.KeyEscape, "up": tea.KeyUp, "down": tea.KeyDown, + "space": tea.KeySpace, "backspace": tea.KeyBackspace, + } + var out []tea.Msg + for _, k := range keys { + if code, ok := named[k]; ok { + out = append(out, tea.KeyPressMsg{Code: code}) + continue + } + for _, r := range k { + out = append(out, tea.KeyPressMsg{Code: r, Text: string(r)}) + } + } + return out +} + +func feed(c component, msgs []tea.Msg) { + for _, m := range msgs { + c.update(m) + } +} + +func screen(c component) string { return ansi.Strip(c.view()) } + +func TestPicker(t *testing.T) { + items := []skills.Skill{{Name: "tdd", Path: "a/tdd"}, {Name: "grilling", Path: "b/grilling"}, {Name: "tdd", Path: "c/tdd"}} + p := newPicker("add from x", items, map[string]bool{"b/grilling": true}) + p.resize(80, 20) + + // Installed skills can't be picked, and enter needs a selection. + feed(p, press("grill", "space", "enter")) + if p.done || len(p.selection()) != 0 { + t.Fatalf("picked an installed skill: done=%v %v", p.done, p.selection()) + } + if !strings.Contains(screen(p), "[•] grilling") { + t.Errorf("installed marker missing:\n%s", screen(p)) + } + + feed(p, press("backspace", "backspace", "backspace", "backspace", "backspace", "td", "space", "down", "space", "enter")) + if !p.done || p.canceled { + t.Fatalf("done=%v canceled=%v", p.done, p.canceled) + } + if got := p.selection(); !reflect.DeepEqual(got, []skills.Skill{items[0], items[2]}) { + t.Errorf("selection %v", got) + } + + p = newPicker("x", items, nil) + feed(p, press("esc")) + if !p.canceled { + t.Error("esc should cancel") + } +} + +func TestReview(t *testing.T) { + dir := t.TempDir() + write := func(rel, content string) string { + path := filepath.Join(dir, rel) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return filepath.Dir(path) + } + oldA, newA := write("old/a/SKILL.md", "a v1\n"), write("new/a/SKILL.md", "a v2\n") + newB := write("new/b/SKILL.md", "b new\n") + + one := core.SourceStatus{Source: "one", OldRev: "r1", NewRev: "r2", Changes: []core.Change{ + {Name: "a", Kind: core.Modified, Old: oldA, New: newA}, + {Name: "b", Kind: core.Added, New: newB}, + }} + upToDate := core.SourceStatus{Source: "fine", OldRev: "r1", NewRev: "r1"} + two := core.SourceStatus{Source: "two", OldRev: "r1", NewRev: "r3", Changes: []core.Change{{Name: "a", Kind: core.Removed, Old: oldA}}} + + r := newReview(context.Background(), []core.SourceStatus{one, upToDate, two}) + r.resize(100, 20) + s := screen(r) + if !strings.Contains(s, "review 1/2") || !strings.Contains(s, "+a v2") { + t.Fatalf("first screen:\n%s", s) + } + feed(r, press("down")) + if s := screen(r); !strings.Contains(s, "+b new") { + t.Errorf("second change:\n%s", s) + } + feed(r, press("y")) + if s := screen(r); !strings.Contains(s, "review 2/2") || !strings.Contains(s, "-a v1") { + t.Errorf("second source:\n%s", s) + } + feed(r, press("n")) + if !r.done || r.canceled || len(r.accepted) != 1 || r.accepted[0].Source != "one" { + t.Errorf("done=%v canceled=%v accepted=%v", r.done, r.canceled, r.accepted) + } + + r = newReview(context.Background(), []core.SourceStatus{one}) + feed(r, press("q")) + if !r.canceled { + t.Error("q should abort") + } +} + +// oneRev serves fixed directories as rev r1, whatever the ref asks for. +type oneRev map[string]string + +func (f oneRev) Prefetch(_ context.Context, ref string) (fetch.Result, error) { + base, _, _ := strings.Cut(ref, "?") + return fetch.Result{StorePath: f[base], Locked: map[string]any{"rev": "r1", "narHash": "sha256-x"}}, nil +} + +func TestDashboard(t *testing.T) { + ctx := context.Background() + repo := t.TempDir() + for _, name := range []string{"tdd", "grilling"} { + if err := os.MkdirAll(filepath.Join(repo, "skills", name), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, "skills", name, "SKILL.md"), []byte(name), 0o644); err != nil { + t.Fatal(err) + } + } + store := core.Store{Dir: t.TempDir(), Fetcher: oneRev{"github:mp/skills": repo}} + if _, err := store.Add(ctx, core.AddRequest{URL: "github:mp/skills", All: false, Skills: core.Select(nil, []skills.Skill{{Name: "tdd"}, {Name: "grilling"}})}); err != nil { + t.Fatal(err) + } + + d := newDashboard(ctx, store) + if err := d.reload(); err != nil { + t.Fatal(err) + } + d.Update(tea.WindowSizeMsg{Width: 100, Height: 20}) + sts, err := store.Check(ctx, "mp/skills") + if err != nil { + t.Fatal(err) + } + d.Update(statusMsg{"mp/skills", sts[0]}) + if s := ansi.Strip(d.render()); !strings.Contains(s, "mp/skills r1 ✓ up to date") || !strings.Contains(s, "tdd") { + t.Fatalf("dashboard:\n%s", s) + } + + // Rows: source, grilling, tdd. Remove tdd after confirming. + for _, m := range press("down", "down", "d") { + d.Update(m) + } + if s := ansi.Strip(d.render()); !strings.Contains(s, "remove tdd from mp/skills? [y/N]") { + t.Fatalf("no confirmation:\n%s", s) + } + cmd := d.key(tea.KeyPressMsg{Code: 'y', Text: "y"}) + d.Update(cmd()) + if s := ansi.Strip(d.render()); strings.Contains(s, "tdd skills/tdd") || !strings.Contains(s, "removed tdd from mp/skills") { + t.Errorf("after remove:\n%s", s) + } + list, err := store.List() + if err != nil { + t.Fatal(err) + } + if len(list) != 1 || list[0].Name != "grilling" { + t.Errorf("store has %v", list) + } + if !reflect.DeepEqual(d.summary, []string{"removed tdd from mp/skills"}) { + t.Errorf("summary %v", d.summary) + } +}