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

+325
View File
@@ -0,0 +1,325 @@
// Package web serves an optional htmx based UI and a small JSON API.
package web
import (
"context"
"crypto/rand"
"crypto/subtle"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"net"
"net/http"
"strings"
"time"
"github.com/illustris/i-am-gcroot/internal/filter"
"github.com/illustris/i-am-gcroot/internal/roots"
)
//go:embed templates/*.html static/*
var assets embed.FS
type Options struct {
Addr string
NoAuth bool
Force bool
}
type Server struct {
set *roots.Set
opts Options
token string
tmpl *template.Template
ctx context.Context
}
func New(ctx context.Context, set *roots.Set, opts Options) (*Server, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return nil, err
}
funcs := template.FuncMap{
"size": filter.HumanSize,
"age": func(t time.Time) string { return filter.HumanAge(t, time.Now()) },
"kinds": func() []roots.Kind { return roots.AllKinds },
"sorts": func() []string { return filter.SortNames },
}
tmpl, err := template.New("").Funcs(funcs).ParseFS(assets, "templates/*.html")
if err != nil {
return nil, err
}
return &Server{set: set, opts: opts, token: hex.EncodeToString(b), tmpl: tmpl, ctx: ctx}, nil
}
// Listen binds the address and returns the URL to open (including the token).
func (s *Server) Listen() (net.Listener, string, error) {
ln, err := net.Listen("tcp", s.opts.Addr)
if err != nil {
return nil, "", err
}
url := "http://" + ln.Addr().String() + "/"
if !s.opts.NoAuth {
url += "?token=" + s.token
}
return ln, url, nil
}
func (s *Server) Serve(ln net.Listener) error {
srv := &http.Server{Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second}
go func() {
<-s.ctx.Done()
srv.Close()
}()
err := srv.Serve(ln)
if err == http.ErrServerClosed {
return nil
}
return err
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
static, _ := fs.Sub(assets, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
mux.HandleFunc("GET /{$}", s.index)
mux.HandleFunc("GET /rows", s.rows)
mux.HandleFunc("POST /delete", s.deleteHTML)
mux.HandleFunc("POST /gc", s.gcHTML)
mux.HandleFunc("POST /refresh", s.refreshHTML)
mux.HandleFunc("GET /api/roots", s.apiRoots)
mux.HandleFunc("POST /api/delete", s.apiDelete)
mux.HandleFunc("POST /api/gc", s.apiGC)
return s.auth(mux)
}
const cookieName = "i-am-gcroot-token"
// auth accepts the token as ?token=, a cookie, or a bearer header. A valid
// ?token= sets the cookie so the UI keeps working without it in the URL.
// Mutating requests from the browser must also carry X-Token (htmx sends it)
// so a cross-site form post cannot ride the cookie.
func (s *Server) auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.opts.NoAuth || strings.HasPrefix(r.URL.Path, "/static/") {
next.ServeHTTP(w, r)
return
}
ok := func(t string) bool { return subtle.ConstantTimeCompare([]byte(t), []byte(s.token)) == 1 }
header := r.Header.Get("X-Token")
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
header = strings.TrimPrefix(h, "Bearer ")
}
if r.Method != http.MethodGet {
if !ok(header) {
http.Error(w, "missing or bad token", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
return
}
if q := r.URL.Query().Get("token"); ok(q) {
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: s.token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode})
next.ServeHTTP(w, r)
return
}
if c, err := r.Cookie(cookieName); (err == nil && ok(c.Value)) || ok(header) {
next.ServeHTTP(w, r)
return
}
http.Error(w, "missing or bad token; use the URL printed at startup", http.StatusUnauthorized)
})
}
type viewParams struct {
Query string
Kinds map[roots.Kind]bool
Sort string
Desc bool
Hidden bool
Err string
Rows []roots.Root
Total int
Status roots.Status
Token string
Message string
Results []roots.Result
Checked map[string]bool
}
type deleteOutcome struct {
Results []roots.Result `json:"results"`
Collected *roots.CollectResult `json:"collected,omitempty"`
GCError string `json:"gcError,omitempty"`
}
func (s *Server) params(r *http.Request) viewParams {
_ = r.ParseForm()
p := viewParams{Query: r.Form.Get("q"), Sort: r.Form.Get("sort"), Desc: r.Form.Get("desc") != "", Hidden: r.Form.Get("hidden") != "", Checked: map[string]bool{}}
for _, l := range r.Form["link"] {
p.Checked[l] = true
}
if s.opts.NoAuth {
p.Token = ""
} else {
p.Token = s.token
}
p.Kinds = map[roots.Kind]bool{}
if ks, ok := r.Form["kind"]; ok || r.Form.Get("kinds") != "" {
for _, k := range ks {
p.Kinds[roots.Kind(k)] = true
}
} else {
for _, k := range roots.AllKinds {
p.Kinds[k] = k != roots.KindRuntime
}
}
if p.Sort == "" {
p.Sort = "age"
}
if p.Kinds[roots.KindRuntime] && !s.set.Status().Runtime {
s.set.SetRuntime(true)
_ = s.set.Refresh(s.ctx)
}
q, err := filter.Parse(p.Query)
if err != nil {
p.Err = err.Error()
q, _ = filter.Parse("")
}
all := s.set.Snapshot()
p.Total = len(all)
p.Rows = filter.Apply(all, q, p.Kinds, p.Hidden, filter.ParseSort(p.Sort), p.Desc)
p.Status = s.set.Status()
return p
}
func (s *Server) render(w http.ResponseWriter, name string, data any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (s *Server) index(w http.ResponseWriter, r *http.Request) {
s.render(w, "index.html", s.params(r))
}
func (s *Server) rows(w http.ResponseWriter, r *http.Request) {
s.render(w, "rows", s.params(r))
}
func (s *Server) doDelete(r *http.Request, links []string, dry, collect bool) deleteOutcome {
rs := s.set.Lookup(links)
out := deleteOutcome{Results: roots.Delete(r.Context(), s.set.Cfg, rs, roots.DeleteOpts{DryRun: dry, Force: s.opts.Force})}
if dry {
return out
}
gone := map[string]bool{}
for _, x := range out.Results {
if x.OK() {
gone[x.Link] = true
}
}
s.set.Remove(gone)
defer s.set.Refresh(s.ctx)
if collect {
c, err := roots.Collect(r.Context(), s.set.Cfg, roots.CollectedTargets(out.Results))
out.Collected = &c
if err != nil {
out.GCError = err.Error()
}
}
return out
}
func (s *Server) deleteHTML(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
dry := r.Form.Get("dry") != ""
out := s.doDelete(r, r.Form["link"], dry, r.Form.Get("collect") != "")
res := out.Results
p := s.params(r)
p.Results = res
ok := 0
for _, x := range res {
if x.OK() {
ok++
}
}
if dry {
p.Message = fmt.Sprintf("Dry run: %d action(s)", len(res))
} else {
p.Message = fmt.Sprintf("Deleted %d of %d root(s)", ok, len(res))
if out.Collected != nil {
p.Message += "; " + out.Collected.String()
}
p.Err = out.GCError
}
s.render(w, "rows", p)
}
func (s *Server) gcHTML(w http.ResponseWriter, r *http.Request) {
summary, err := roots.GC(r.Context(), s.set.Cfg)
_ = s.set.Refresh(s.ctx)
p := s.params(r)
if err != nil {
p.Err = err.Error()
} else {
p.Message = "GC: " + summary
}
s.render(w, "rows", p)
}
func (s *Server) refreshHTML(w http.ResponseWriter, r *http.Request) {
p := viewParams{}
if err := s.set.Refresh(s.ctx); err != nil {
p.Err = err.Error()
}
p2 := s.params(r)
p2.Err = p.Err
p2.Message = "Rescanned"
s.render(w, "rows", p2)
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
func (s *Server) apiRoots(w http.ResponseWriter, r *http.Request) {
p := s.params(r)
if p.Err != "" {
http.Error(w, p.Err, http.StatusBadRequest)
return
}
writeJSON(w, p.Rows)
}
type deleteReq struct {
Links []string `json:"links"`
DryRun bool `json:"dryRun"`
Collect bool `json:"collect"`
}
func (s *Server) apiDelete(w http.ResponseWriter, r *http.Request) {
var req deleteReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
writeJSON(w, s.doDelete(r, req.Links, req.DryRun, req.Collect))
}
func (s *Server) apiGC(w http.ResponseWriter, r *http.Request) {
summary, err := roots.GC(r.Context(), s.set.Cfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_ = s.set.Refresh(s.ctx)
writeJSON(w, map[string]string{"summary": summary})
}
+83
View File
@@ -0,0 +1,83 @@
package web
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/illustris/i-am-gcroot/internal/roots"
)
func testServer(t *testing.T) (*Server, string) {
dir := t.TempDir()
cfg := roots.Config{
StoreDir: filepath.Join(dir, "store"), StateDir: filepath.Join(dir, "state"),
NixStoreBin: "false", NixBin: "false", NixEnvBin: "true",
}
sp := filepath.Join(cfg.StoreDir, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-hello")
os.MkdirAll(sp, 0o755)
link := filepath.Join(dir, "result")
os.Symlink(sp, link)
os.MkdirAll(filepath.Join(cfg.StateDir, "gcroots", "auto"), 0o755)
os.Symlink(link, filepath.Join(cfg.StateDir, "gcroots", "auto", "h1"))
set := roots.NewSet(cfg)
if err := set.Refresh(context.Background()); err != nil {
t.Fatal(err)
}
srv, err := New(context.Background(), set, Options{})
if err != nil {
t.Fatal(err)
}
return srv, link
}
func TestAuthAndRender(t *testing.T) {
srv, link := testServer(t)
h := srv.Handler()
do := func(method, url string, hdr map[string]string, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, url, strings.NewReader(body))
for k, v := range hdr {
req.Header.Set(k, v)
}
if method == http.MethodPost && body != "" && !strings.HasPrefix(body, "{") {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
return w
}
if w := do("GET", "/", nil, ""); w.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", w.Code)
}
w := do("GET", "/?token="+srv.token, nil, "")
if w.Code != 200 || !strings.Contains(w.Body.String(), link) {
t.Fatalf("index: %d %s", w.Code, w.Body.String())
}
if len(w.Result().Cookies()) == 0 {
t.Error("token should set a cookie")
}
if w := do("GET", "/static/htmx.min.js", nil, ""); w.Code != 200 {
t.Errorf("static: %d", w.Code)
}
if w := do("GET", "/api/roots?q=hello", map[string]string{"Authorization": "Bearer " + srv.token}, ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"kind": "indirect"`) {
t.Errorf("api: %d %s", w.Code, w.Body.String())
}
// POST with only the cookie (no X-Token) must be rejected
if w := do("POST", "/delete", map[string]string{"Cookie": cookieName + "=" + srv.token}, "link="+link); w.Code != http.StatusUnauthorized {
t.Errorf("cookie-only post: %d", w.Code)
}
w = do("POST", "/delete", map[string]string{"X-Token": srv.token}, "link="+link)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Deleted 1 of 1") {
t.Errorf("delete: %d %s", w.Code, w.Body.String())
}
if _, err := os.Lstat(link); err == nil {
t.Error("link still exists")
}
}
+1
View File
@@ -0,0 +1 @@
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toStrinLine truncated
+124
View File
@@ -0,0 +1,124 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>i-am-gcroot</title>
<script src="/static/htmx.min.js"></script>
<style>
:root {
--bg: #fbfbfa; --fg: #1d1d1b; --dim: #6b6b66; --line: #e3e2de; --row: #f2f1ee;
--accent: #2f6fb3; --danger: #b3382f; --ok: #2f7d3a; --mark: #fff4cc;
--indirect: #1f7a8c; --profile: #8a3fa0; --direct: #2f6fb3; --dangling: #b3382f; --runtime: #6b6b66;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #17181a; --fg: #e6e4df; --dim: #9a978f; --line: #2c2d30; --row: #1f2023;
--accent: #6aa5e6; --danger: #e5776d; --ok: #74c47f; --mark: #3a3420;
--indirect: #5cc0d1; --profile: #c48ad6; --direct: #6aa5e6; --dangling: #e5776d; --runtime: #9a978f;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.4 system-ui, sans-serif; }
header { padding: 12px 16px; border-bottom: 1px solid var(--line); display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; position: sticky; top: 0; background: var(--bg); z-index: 1; }
h1 { font-size: 16px; margin: 0; font-family: ui-monospace, monospace; }
#controls { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; flex: 1; }
input[name=q] { flex: 1; min-width: 240px; padding: 6px 8px; font: 13px ui-monospace, monospace; background: var(--row); color: var(--fg); border: 1px solid var(--line); border-radius: 4px; }
label { white-space: nowrap; color: var(--dim); }
select, button { font: inherit; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--line); background: var(--row); color: var(--fg); cursor: pointer; }
button.danger { background: var(--danger); color: #fff; border-color: var(--danger); }
.actions { display: flex; gap: 8px; align-items: center; padding: 8px 16px; flex-wrap: wrap; }
.msg { padding: 8px 16px; }
.msg.err { color: var(--danger); }
.msg.ok { color: var(--ok); }
.dim { color: var(--dim); }
.wrap { overflow-x: auto; }
table { border-collapse: collapse; width: 100%; font: 12.5px ui-monospace, monospace; }
th, td { text-align: left; padding: 3px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { position: sticky; top: 0; background: var(--bg); color: var(--dim); font-weight: 600; }
td.num { text-align: right; }
td.path { max-width: 50vw; overflow: hidden; text-overflow: ellipsis; direction: rtl; text-align: left; }
tr:hover td { background: var(--row); }
tr:has(input:checked) td { background: var(--mark); }
.kind { font-weight: 600; }
.k-indirect { color: var(--indirect); } .k-profile { color: var(--profile); } .k-direct { color: var(--direct); }
.k-dangling { color: var(--dangling); } .k-runtime { color: var(--runtime); }
ul.results { margin: 4px 0; font: 12px ui-monospace, monospace; }
details summary { cursor: pointer; color: var(--dim); }
.htmx-request .spin { visibility: visible; } .spin { visibility: hidden; }
</style>
</head>
<body hx-headers='{"X-Token": "{{.Token}}"}'>
<header>
<h1>i-am-gcroot</h1>
<form id="controls" hx-get="/rows" hx-target="#rows" hx-include="#rows input[name=link]:checked"
hx-trigger="input changed delay:300ms from:input[name=q], change, submit" onsubmit="return false">
<input type="hidden" name="kinds" value="1">
<input name="q" value="{{.Query}}" placeholder="text /re/ kind: owner:me under:/tmp older:30d size>1G -negate" autofocus>
{{range kinds}}<label><input type="checkbox" name="kind" value="{{.}}" {{if index $.Kinds .}}checked{{end}}> <span class="k-{{.}}">{{.}}</span></label>{{end}}
<label>sort <select name="sort">
{{range $s := sorts}}<option {{if eq $s $.Sort}}selected{{end}}>{{$s}}</option>{{end}}
</select></label>
<label><input type="checkbox" name="desc" value="1" {{if .Desc}}checked{{end}}> desc</label>
<label title="nix cache roots such as ~/.cache/nix/flake-registry.json"><input type="checkbox" name="hidden" value="1" {{if .Hidden}}checked{{end}}> hidden</label>
</form>
</header>
<div id="rows">{{template "rows" .}}</div>
<script>
function selectAll(on) {
document.querySelectorAll('#rows input[name=link]:not([data-protected])').forEach(c => c.checked = on);
updateSel();
}
function updateSel() {
let n = 0, size = 0;
document.querySelectorAll('#rows input[name=link]:checked').forEach(c => { n++; size += +c.dataset.size || 0; });
const el = document.getElementById('sel');
if (el) el.textContent = n + ' selected, up to ' + human(size);
}
function human(n) {
const u = ['B', 'K', 'M', 'G', 'T']; let i = 0;
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
return (i ? n.toFixed(1) : n) + u[i];
}
document.addEventListener('change', e => { if (e.target.name === 'link') updateSel(); });
document.body.addEventListener('htmx:afterSwap', updateSel);
</script>
</body>
</html>
{{define "rows"}}
{{if .Err}}<div class="msg err">{{.Err}}</div>{{end}}
{{if .Message}}<div class="msg ok">{{.Message}}
{{if .Results}}<details {{if lt (len .Results) 15}}open{{end}}><summary>{{len .Results}} result(s)</summary><ul class="results">
{{range .Results}}<li>{{if .Err}}<span class="msg err">fail</span> {{.Link}}: {{.Err}}{{else}}ok {{.Action}}{{end}}</li>{{end}}
</ul></details>{{end}}
</div>{{end}}
<div class="actions">
<span class="dim">{{.Total}} roots, {{len .Rows}} shown{{if .Status.Sizing}}, sizing {{.Status.SizesDone}}/{{.Status.SizesTodo}}{{end}}</span>
<span id="sel" class="dim"></span>
<button type="button" onclick="selectAll(true)">select all shown</button>
<button type="button" onclick="selectAll(false)">clear</button>
<button hx-post="/delete" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked" hx-vals='{"dry": "1"}'>dry run</button>
<button class="danger" hx-post="/delete" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked"
hx-confirm="Delete the selected GC roots?">delete selected</button>
<button class="danger" hx-post="/delete" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked" hx-vals='{"collect": "1"}'
hx-confirm="Delete the selected GC roots and garbage collect the store paths only they kept alive?">delete + collect <span class="spin">...</span></button>
<button hx-post="/gc" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked"
hx-confirm="Run nix-store --gc now?">run gc <span class="spin">...</span></button>
<button hx-post="/refresh" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked">rescan</button>
</div>
{{if .Status.Sizing}}<div hx-get="/rows" hx-trigger="every 2s" hx-target="#rows" hx-include="#controls, #rows input[name=link]:checked"></div>{{end}}
<div class="wrap"><table>
<thead><tr><th></th><th>kind</th><th>owner</th><th>age</th><th>closure</th><th>link</th><th>target</th></tr></thead>
<tbody>
{{range .Rows}}<tr title="{{.Reason}}">
<td>{{if .Deletable}}<input type="checkbox" name="link" value="{{.Link}}" data-size="{{if gt .ClosureSize 0}}{{.ClosureSize}}{{end}}" {{if .Protected}}data-protected{{end}} {{if index $.Checked .Link}}checked{{end}}>{{end}}{{if .Protected}} <span title="{{.Reason}}">!</span>{{end}}</td>
<td class="kind k-{{.Kind}}">{{.Kind}}{{if .Current}} (current){{end}}</td>
<td>{{.Owner}}</td>
<td class="num">{{age .ModTime}}</td>
<td class="num">{{if eq .Kind "dangling"}}-{{else}}{{size .ClosureSize}}{{end}}</td>
<td class="path" title="{{.Link}}{{if .Via}} (via {{.Via}}){{end}}"><bdi>{{.Link}}{{if .Command}} <span class="dim">{{.Command}}</span>{{end}}</bdi></td>
<td title="{{.Target}}">{{if .Target}}{{.TargetName}}{{else if gt .Count 1}}<span class="dim">({{.Count}} paths)</span>{{else if eq .Kind "dangling"}}<span class="dim">(missing)</span>{{else}}<span class="dim">{{.Reason}}</span>{{end}}</td>
</tr>{{end}}
</tbody></table></div>
{{end}}