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 <noreply@anthropic.com>
This commit is contained in:
1 parent
65a96ada8e
commit
6f4d6f5609
12 files changed
+1262
-55
No files matched your search
+75
-27
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user