This commit is contained in:
illustris committed 2026-10-28 08:00:16 +05:30
commit 625becd03e
24 files changed
+3822

No files matched your search

+517
View File
@@ -0,0 +1,517 @@
// Package tui implements the interactive terminal interface.
package tui
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/illustris/i-am-gcroot/internal/filter"
"github.com/illustris/i-am-gcroot/internal/roots"
)
type mode int
const (
modeNormal mode = iota
modeFilter
modeConfirmDelete
modeConfirmGC
modeDetails
modeResults
modeHelp
)
type Options struct {
Query string
Force bool
WebURL string // shown in the status bar when the web UI runs alongside
}
type Model struct {
ctx context.Context
set *roots.Set
opts Options
changed chan struct{}
all []roots.Root
view []roots.Root
cursor int
offset int
marks map[string]bool
kinds map[roots.Kind]bool
sortKey filter.SortKey
desc bool
hidden bool // show hidden (nix cache) roots
input textinput.Model
query *filter.Query
queryErr string
mode mode
pending []roots.Root // roots awaiting delete confirmation
collect bool // run a targeted GC after the pending delete
dryRun bool
results []roots.Result
collected string
status string
statusOK bool
busy string // long running operation, shown on the activity line
since time.Time
scanning bool
width int
height int
quitting bool
}
func New(ctx context.Context, set *roots.Set, opts Options) *Model {
ti := textinput.New()
ti.Prompt = "/ "
ti.Placeholder = "filter: text, /re/, kind:, owner:me, under:/tmp, older:30d, size>1G"
ti.SetValue(opts.Query)
m := &Model{
ctx: ctx,
set: set,
opts: opts,
changed: make(chan struct{}, 1),
marks: map[string]bool{},
kinds: defaultKinds(),
input: ti,
sortKey: filter.SortAge,
}
m.query, _ = filter.Parse(opts.Query)
set.OnChange(func() {
select {
case m.changed <- struct{}{}:
default:
}
})
return m
}
func defaultKinds() map[roots.Kind]bool {
k := map[roots.Kind]bool{}
for _, kind := range roots.AllKinds {
k[kind] = kind != roots.KindRuntime
}
return k
}
type changedMsg struct{}
type tickMsg struct{}
type refreshedMsg struct{ err error }
type deletedMsg struct {
results []roots.Result
dryRun bool
collected string // summary of the targeted GC, if one ran
}
type gcMsg struct {
summary string
err error
}
func (m *Model) waitChange() tea.Cmd {
return func() tea.Msg {
select {
case <-m.changed:
return changedMsg{}
case <-m.ctx.Done():
return nil
}
}
}
func (m *Model) refresh() tea.Cmd {
m.scanning = true
return func() tea.Msg { return refreshedMsg{m.set.Refresh(m.ctx)} }
}
// startBusy shows an operation on the activity line with a running timer.
func (m *Model) startBusy(what string) tea.Cmd {
m.busy, m.since = what, time.Now()
return tick()
}
func tick() tea.Cmd {
return tea.Tick(time.Second, func(time.Time) tea.Msg { return tickMsg{} })
}
func (m *Model) setStatus(s string, ok bool) {
m.status, m.statusOK = s, ok
}
func (m *Model) Init() tea.Cmd {
return tea.Batch(m.refresh(), m.waitChange())
}
func (m *Model) reload() {
m.all = m.set.Snapshot()
m.apply()
}
func (m *Model) apply() {
var curLink string
if m.cursor < len(m.view) {
curLink = m.view[m.cursor].Link
}
m.view = filter.Apply(m.all, m.query, m.kinds, m.hidden, m.sortKey, m.desc)
m.cursor = 0
for i := range m.view {
if m.view[i].Link == curLink {
m.cursor = i
break
}
}
// forget marks that are no longer present at all
present := map[string]bool{}
for _, r := range m.all {
present[r.Link] = true
}
for l := range m.marks {
if !present[l] {
delete(m.marks, l)
}
}
m.clamp()
}
// footerLines is the number of lines below the list: kinds/sort, key hints,
// the activity line when there is something to report, and the filter.
func (m *Model) footerLines() int {
n := 2
if m.activity() != "" {
n++
}
if m.mode == modeFilter || m.input.Value() != "" {
n++
}
return n
}
func (m *Model) listHeight() int {
h := m.height - 2 - m.footerLines()
if h < 1 {
h = 1
}
return h
}
func (m *Model) clamp() {
if m.cursor >= len(m.view) {
m.cursor = len(m.view) - 1
}
if m.cursor < 0 {
m.cursor = 0
}
h := m.listHeight()
if m.cursor < m.offset {
m.offset = m.cursor
}
if m.cursor >= m.offset+h {
m.offset = m.cursor - h + 1
}
if m.offset > max(0, len(m.view)-h) {
m.offset = max(0, len(m.view)-h)
}
}
// selection returns marked roots, or the root under the cursor if nothing is
// marked.
func (m *Model) selection() []roots.Root {
var out []roots.Root
for _, r := range m.all {
if m.marks[r.Link] {
out = append(out, r)
}
}
if len(out) == 0 && m.cursor < len(m.view) {
out = append(out, m.view[m.cursor])
}
return out
}
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.input.Width = max(10, msg.Width-4)
m.clamp()
return m, nil
case changedMsg:
m.reload()
return m, m.waitChange()
case tickMsg:
if m.busy != "" {
return m, tick()
}
return m, nil
case refreshedMsg:
m.scanning = false
if msg.err != nil {
m.setStatus("scan failed: "+msg.err.Error(), false)
}
m.reload()
return m, nil
case deletedMsg:
m.busy = ""
m.results = msg.results
m.dryRun = msg.dryRun
m.collected = msg.collected
m.setStatus(m.summarize(msg), true)
if !msg.dryRun {
gone := map[string]bool{}
for _, r := range msg.results {
if r.OK() {
gone[r.Link] = true
delete(m.marks, r.Link)
} else {
m.statusOK = false
}
}
m.set.Remove(gone)
}
return m, nil
case gcMsg:
m.busy = ""
if msg.err != nil {
m.setStatus("gc failed: "+msg.err.Error(), false)
} else {
m.setStatus("gc: "+msg.summary, true)
}
return m, m.refresh()
case tea.KeyMsg:
return m.handleKey(msg)
}
return m, nil
}
func (m *Model) handleKey(k tea.KeyMsg) (tea.Model, tea.Cmd) {
key := k.String()
if key == "ctrl+c" {
m.quitting = true
return m, tea.Quit
}
switch m.mode {
case modeFilter:
switch key {
case "enter", "esc":
m.mode = modeNormal
m.input.Blur()
return m, nil
}
var cmd tea.Cmd
m.input, cmd = m.input.Update(k)
q, err := filter.Parse(m.input.Value())
if err != nil {
m.queryErr = err.Error()
} else {
m.queryErr = ""
m.query = q
m.apply()
}
return m, cmd
case modeConfirmDelete:
switch key {
case "y", "Y":
m.mode = modeNormal
rs, opts, collect := m.pending, roots.DeleteOpts{Force: m.opts.Force}, m.collect
what := fmt.Sprintf("deleting %d root(s)", len(rs))
if collect {
what += " and collecting their garbage"
}
return m, tea.Batch(m.startBusy(what), func() tea.Msg {
res := roots.Delete(m.ctx, m.set.Cfg, rs, opts)
msg := deletedMsg{results: res}
if collect {
c, err := roots.Collect(m.ctx, m.set.Cfg, roots.CollectedTargets(res))
msg.collected = c.String()
if err != nil {
msg.collected += "; gc error: " + err.Error()
}
}
// rebuild the list from disk rather than trusting in-memory state
_ = m.set.Refresh(m.ctx)
return msg
})
case "n", "N", "esc", "q":
m.mode = modeNormal
}
return m, nil
case modeConfirmGC:
switch key {
case "y", "Y":
m.mode = modeNormal
return m, tea.Batch(m.startBusy("running nix-store --gc"), func() tea.Msg {
s, err := roots.GC(m.ctx, m.set.Cfg)
return gcMsg{s, err}
})
case "n", "N", "esc", "q":
m.mode = modeNormal
}
return m, nil
case modeDetails, modeResults, modeHelp:
switch key {
case "esc", "q", "enter", "?":
m.mode = modeNormal
}
return m, nil
}
switch key {
case "q":
m.quitting = true
return m, tea.Quit
case "esc":
if m.input.Value() != "" {
m.input.SetValue("")
m.query, _ = filter.Parse("")
m.apply()
}
case "/":
m.mode = modeFilter
return m, m.input.Focus()
case "up", "k":
m.cursor--
case "down", "j":
m.cursor++
case "pgup", "ctrl+b":
m.cursor -= m.listHeight()
case "pgdown", "ctrl+f":
m.cursor += m.listHeight()
case "home":
m.cursor = 0
case "end", "G":
m.cursor = len(m.view) - 1
case " ", "x":
if m.cursor < len(m.view) {
r := m.view[m.cursor]
if r.Deletable() {
if m.marks[r.Link] {
delete(m.marks, r.Link)
} else {
m.marks[r.Link] = true
}
}
}
case "a":
for _, r := range m.view {
if r.Deletable() && !r.Protected {
m.marks[r.Link] = true
}
}
case "A":
m.marks = map[string]bool{}
case "1", "2", "3", "4", "5":
kind := roots.AllKinds[int(key[0]-'1')]
m.kinds[kind] = !m.kinds[kind]
if kind == roots.KindRuntime && m.kinds[kind] && !m.set.Status().Runtime {
m.set.SetRuntime(true)
m.apply()
return m, m.refresh()
}
m.apply()
case "0":
m.kinds = defaultKinds()
m.apply()
case "s":
m.sortKey = (m.sortKey + 1) % filter.SortKey(len(filter.SortNames))
m.apply()
case "S":
m.desc = !m.desc
m.apply()
case "r":
return m, m.refresh()
case "enter":
if m.cursor < len(m.view) {
m.mode = modeDetails
}
case "d", "D", "X":
sel := m.selection()
if len(sel) == 0 {
return m, nil
}
if key == "D" {
return m, func() tea.Msg {
return deletedMsg{results: roots.Delete(m.ctx, m.set.Cfg, sel, roots.DeleteOpts{DryRun: true, Force: m.opts.Force}), dryRun: true}
}
}
if m.busy != "" {
m.setStatus("wait for "+m.busy+" to finish", false)
return m, nil
}
m.pending = sel
m.collect = key == "X"
m.mode = modeConfirmDelete
case "h":
m.hidden = !m.hidden
m.apply()
case "g":
if m.busy != "" {
m.setStatus("wait for "+m.busy+" to finish", false)
return m, nil
}
m.mode = modeConfirmGC
case "R":
if m.results != nil {
m.mode = modeResults
}
case "?":
m.mode = modeHelp
}
m.clamp()
return m, nil
}
func kindList(kinds map[roots.Kind]bool) string {
var parts []string
for i, k := range roots.AllKinds {
mark := " "
if kinds[k] {
mark = "x"
}
parts = append(parts, fmt.Sprintf("%d[%s]%s", i+1, mark, k))
}
return strings.Join(parts, " ")
}
// summarize turns a delete outcome into one status line; R shows the rest.
func (m *Model) summarize(msg deletedMsg) string {
var ok, failed []roots.Result
for _, r := range msg.results {
if r.OK() {
ok = append(ok, r)
} else {
failed = append(failed, r)
}
}
var s string
if msg.dryRun {
s = fmt.Sprintf("dry run: %d action(s)", len(ok))
if len(ok) > 0 {
s += ", e.g. " + ok[0].Action
}
if len(failed) > 0 {
s += fmt.Sprintf("; %d would fail", len(failed))
}
} else {
s = fmt.Sprintf("deleted %d/%d root(s)", len(ok), len(msg.results))
if msg.collected != "" {
s += "; " + msg.collected
} else if len(ok) > 0 {
s += "; g to collect garbage"
}
}
if len(failed) > 0 {
s += fmt.Sprintf("; failed %s: %s", filepath.Base(failed[0].Link), failed[0].Err)
if len(failed) > 1 {
s += fmt.Sprintf(" (+%d more)", len(failed)-1)
}
}
return s + " [R details]"
}
+343
View File
@@ -0,0 +1,343 @@
package tui
import (
"fmt"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/illustris/i-am-gcroot/internal/filter"
"github.com/illustris/i-am-gcroot/internal/roots"
)
var (
styleHeader = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("12"))
styleColHeader = lipgloss.NewStyle().Bold(true).Underline(true)
styleCursor = lipgloss.NewStyle().Reverse(true)
styleMarked = lipgloss.NewStyle().Foreground(lipgloss.Color("11")).Bold(true)
styleDim = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
styleErr = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
styleOK = lipgloss.NewStyle().Foreground(lipgloss.Color("10"))
styleBox = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1)
kindColor = map[roots.Kind]lipgloss.Color{
roots.KindIndirect: "14",
roots.KindProfile: "13",
roots.KindDirect: "12",
roots.KindDangling: "9",
roots.KindRuntime: "8",
}
)
func (m *Model) View() string {
if m.quitting {
return ""
}
if m.width == 0 {
return "loading..."
}
switch m.mode {
case modeHelp:
return m.overlay(helpText)
case modeDetails:
return m.overlay(m.details())
case modeResults:
return m.overlay(m.resultsView())
case modeConfirmDelete:
return m.overlay(m.confirmView())
case modeConfirmGC:
return m.overlay("Run nix-store --gc now?\n\nThis deletes every store path that is no longer reachable from a root.\n\n[y] yes [n] no")
}
return m.listView()
}
func (m *Model) overlay(body string) string {
box := styleBox.Width(min(m.width-4, 120)).Render(body)
return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, box)
}
const (
wMark = 2
wKind = 9
wOwner = 10
wAge = 6
wSize = 8
)
func (m *Model) columns() (link, target int) {
rest := m.width - wMark - wKind - wOwner - wAge - wSize - 6
if rest < 20 {
rest = 20
}
target = rest * 2 / 5
return rest - target, target
}
func (m *Model) listView() string {
var b strings.Builder
st := m.set.Status()
title := styleHeader.Render("i-am-gcroot")
info := fmt.Sprintf(" %d roots, %d shown, %d marked (up to %s)", st.Total, len(m.view), len(m.marks), filter.HumanSize(m.markedSize()))
if m.opts.WebURL != "" {
info += styleDim.Render(" web: " + m.opts.WebURL)
}
b.WriteString(trunc(title+info, m.width+20) + "\n")
wl, wt := m.columns()
hdr := fmt.Sprintf("%-*s %-*s %-*s %*s %*s %-*s %-*s", wMark, "", wKind, "KIND", wOwner, "OWNER", wAge, "AGE", wSize, "CLOSURE", wl, "LINK", wt, "TARGET")
b.WriteString(styleColHeader.Render(trunc(hdr, m.width)) + "\n")
h := m.listHeight()
now := time.Now()
for i := m.offset; i < m.offset+h; i++ {
if i >= len(m.view) {
b.WriteString("\n")
continue
}
b.WriteString(m.row(&m.view[i], i == m.cursor, wl, wt, now) + "\n")
}
// footer
sortDir := "asc"
if m.desc {
sortDir = "desc"
}
hidden := " "
if m.hidden {
hidden = "x"
}
line := fmt.Sprintf("%s h[%s]hidden sort:%s %s", kindList(m.kinds), hidden, m.sortKey, sortDir)
if st.Sizing {
line += fmt.Sprintf(" sizing %d/%d", st.SizesDone, st.SizesTodo)
}
if m.scanning {
line += " scanning..."
}
b.WriteString(styleDim.Render(trunc(line, m.width)) + "\n")
b.WriteString(styleDim.Render(trunc(hints, m.width)) + "\n")
if a := m.activity(); a != "" {
b.WriteString(a + "\n")
}
if m.mode == modeFilter || m.input.Value() != "" {
b.WriteString(m.input.View())
}
return b.String()
}
const hints = "space mark a mark all d delete X delete+collect D dry-run g gc / filter s sort h hidden enter details R results ? help q quit"
// activity is the line under the key hints: a running operation, a filter
// error, or the outcome of the last operation.
func (m *Model) activity() string {
switch {
case m.busy != "":
return styleMarked.Render(trunc(fmt.Sprintf("%s... %ds", m.busy, int(time.Since(m.since).Seconds())), m.width))
case m.queryErr != "":
return styleErr.Render(trunc(m.queryErr, m.width))
case m.status == "":
return ""
case m.statusOK:
return styleOK.Render(trunc(m.status, m.width))
}
return styleErr.Render(trunc(m.status, m.width))
}
func (m *Model) row(r *roots.Root, cursor bool, wl, wt int, now time.Time) string {
mark := " "
if m.marks[r.Link] {
mark = "*"
} else if r.Protected {
mark = "!"
}
link := r.Link
if r.Kind == roots.KindRuntime && r.Command != "" {
link += " " + r.Command
}
target := r.TargetName()
switch {
case r.Kind == roots.KindRuntime && r.Count > 1:
target = fmt.Sprintf("(%d paths)", r.Count)
case r.Kind == roots.KindDangling:
target = "(missing)"
case r.Reason != "" && r.Target == "":
target = "(" + r.Reason + ")"
}
size := filter.HumanSize(r.ClosureSize)
if r.Kind == roots.KindDangling {
size = "-"
}
kind := fmt.Sprintf("%-*s", wKind, r.Kind)
if !cursor {
kind = lipgloss.NewStyle().Foreground(kindColor[r.Kind]).Render(kind)
}
s := fmt.Sprintf("%-*s %s %-*s %*s %*s %-*s %-*s",
wMark, mark, kind, wOwner, trunc(r.Owner, wOwner), wAge, filter.HumanAge(r.ModTime, now),
wSize, size, wl, midTrunc(link, wl), wt, trunc(target, wt))
switch {
case cursor:
return styleCursor.Render(s)
case m.marks[r.Link]:
return styleMarked.Render(s)
}
return s
}
func (m *Model) markedSize() int64 {
var n int64
for _, r := range m.all {
if m.marks[r.Link] && r.ClosureSize > 0 {
n += r.ClosureSize
}
}
return n
}
func (m *Model) details() string {
r := m.view[m.cursor]
var b strings.Builder
field := func(k, v string) {
if v != "" {
fmt.Fprintf(&b, "%s %s\n", styleHeader.Render(fmt.Sprintf("%-12s", k)), v)
}
}
field("kind", string(r.Kind))
field("link", r.Link)
field("via", r.Via)
field("target", r.Target)
field("owner", fmt.Sprintf("%s (uid %d)", r.Owner, r.UID))
if !r.ModTime.IsZero() {
field("modified", r.ModTime.Format(time.RFC3339)+" ("+filter.HumanAge(r.ModTime, time.Now())+" ago)")
}
if r.Kind == roots.KindProfile {
field("profile", r.Profile)
cur := ""
if r.Current {
cur = " (current)"
}
field("generation", fmt.Sprintf("%d%s", r.Generation, cur))
}
if r.Count > 0 {
field("store paths", fmt.Sprint(r.Count))
}
field("command", r.Command)
if r.Target != "" {
field("closure", filter.HumanSize(r.ClosureSize))
field("nar size", filter.HumanSize(r.NarSize))
}
if r.Protected {
field("protected", r.Reason)
} else {
field("note", r.Reason)
}
b.WriteString("\n" + styleDim.Render("esc to close"))
return b.String()
}
func (m *Model) confirmView() string {
var b strings.Builder
var size int64
protected := 0
for _, r := range m.pending {
if r.ClosureSize > 0 {
size += r.ClosureSize
}
if r.Protected {
protected++
}
}
verb := "Delete"
if m.collect {
verb = "Delete and garbage collect"
}
fmt.Fprintf(&b, "%s %d root(s)? Closures total up to %s (shared paths may stay alive).\n", verb, len(m.pending), filter.HumanSize(size))
if m.collect {
b.WriteString(styleDim.Render("Store paths only reachable through these roots are deleted right away.") + "\n")
}
b.WriteString("\n")
show := min(len(m.pending), max(3, m.height-12))
for _, r := range m.pending[:show] {
fmt.Fprintf(&b, " %-9s %s\n", r.Kind, r.Link)
}
if len(m.pending) > show {
fmt.Fprintf(&b, " ... and %d more\n", len(m.pending)-show)
}
if protected > 0 && !m.opts.Force {
b.WriteString(styleErr.Render(fmt.Sprintf("\n%d protected root(s) will be skipped (use --force to override).\n", protected)))
}
b.WriteString("\n[y] delete [n] cancel")
return b.String()
}
func (m *Model) resultsView() string {
var b strings.Builder
if m.dryRun {
b.WriteString(styleHeader.Render("Dry run: these actions would be taken") + "\n\n")
} else {
b.WriteString(styleHeader.Render("Delete results") + "\n\n")
}
if m.collected != "" {
b.WriteString(m.collected + "\n\n")
}
show := min(len(m.results), max(3, m.height-10))
for _, r := range m.results[:show] {
if r.OK() {
b.WriteString(styleOK.Render("ok ") + r.Action + "\n")
} else {
b.WriteString(styleErr.Render("fail ") + r.Link + ": " + r.Err + "\n")
}
}
if len(m.results) > show {
fmt.Fprintf(&b, "... and %d more\n", len(m.results)-show)
}
b.WriteString("\n" + styleDim.Render("esc to close"))
return b.String()
}
const helpText = `Keys
j/k, up/down, pgup/pgdn, home/end move
space / x mark/unmark root under cursor
a / A mark all shown (non-protected) / clear marks
d delete marked roots (or the one under cursor)
X delete, then garbage collect just the paths they held
D dry run: show what delete would do
g run nix-store --gc
/ edit filter, enter/esc to leave, esc again clears it
1-5 toggle kinds: indirect profile direct dangling runtime
0 reset kind toggles
h show/hide nix cache roots (~/.cache/nix/...)
s / S cycle sort key / reverse
enter details
R full results of the last delete / dry run
r rescan
q quit
Filter syntax (terms are ANDed, prefix with - to negate)
foo /regex/ kind:indirect,dangling owner:me under:/tmp
older:30d newer:2h size>1G size<10M is:protected is:current is:hidden`
func trunc(s string, w int) string {
if w <= 0 {
return ""
}
r := []rune(s)
if len(r) <= w {
return s
}
if w == 1 {
return string(r[:1])
}
return string(r[:w-1]) + "~"
}
// midTrunc keeps both ends of a path, which carry the most information.
func midTrunc(s string, w int) string {
r := []rune(s)
if len(r) <= w || w < 5 {
return trunc(s, w)
}
head := (w - 3) / 3
tail := w - 3 - head
return string(r[:head]) + "..." + string(r[len(r)-tail:])
}