Playground
catalog.gno
package toolbox
import "gno.land/p/nt/bptree/v0"
// Catalog is the directory itself: tools keyed by slug, ordered by it.
//
// The zero value is an empty, usable catalog. A Catalog is a HANDLE: copying
// one shares the directory, and a write through either copy is seen through
// both, the way copying a map does. A copy of a zero value that was never
// written is a separate empty catalog.
//
// # Why a tree and not a sorted slice
//
// A sorted slice is cheaper to READ at the size a directory actually reaches:
// at n = 100 one cold operation costs 92,571 gas against a fanout-128 tree's
// 230,754 (`gnobench`, gno master 1fc4c140e, 2026-09-29). It is still the
// wrong structure, for two reasons that outlive the gas.
//
// A slice is ONE persisted object, so every write rewrites all of it: O(n) per
// transaction and O(n^2) over n of them. That costs nothing for a hub whose
// catalog is compiled in and never written after deploy, and it is the whole
// bill for one that accepts registration, which is the other half of what this
// package is for. Removing is worse than writing: shortening a slice in place
// keeps the peak allocation charged and refunds no deposit at all.
//
// And the ordering comes free. A slug-keyed tree iterates in slug order, which
// is the order every listing here wants, rather than a hand-rolled binary
// search that has to be kept correct.
type Catalog struct {
s *state
}
// state is everything a Catalog holds, behind one pointer so that a copy of
// the handle cannot split the tree from the counter that describes it.
//
// Embedding [bptree.BPTree] by value was the first shape here and it is wrong
// for exactly that reason: the tree's root is a pointer and its size is an int,
// so `b := a; b.Set(x)` would thread the new node onto the tree both of them
// see while incrementing only b's size. a.Len() would say 1 while a.Get(x)
// found the entry. One pointer, or two readers of the same directory disagree
// about how big it is.
type state struct {
tools *bptree.BPTree
}
// Fanout is the B+ tree fanout this package uses.
//
// 32 rather than 128 because a tool can be unregistered, and wide nodes lose
// most on removal: a removal shifts every later value in its leaf and rewrites
// each one. Same choice, and the same reason, as
// [gno.land/p/moul/kit/index](/p/moul/kit/index/v0).
const Fanout = 32
// New returns an empty catalog. It is the zero value, spelled out for a caller
// who prefers a constructor.
func New() *Catalog { return &Catalog{} }
// init materialises the state. Called by every mutating method, so the zero
// value works without a constructor. The tree is created with the state, so a
// non-nil state always has one.
func (c *Catalog) init() {
if c.s == nil {
c.s = &state{tools: bptree.NewBPTreeN(Fanout)}
}
}
// Set inserts t, replacing any tool already under its slug.
//
// Replacing rather than refusing is what makes a hub's init idempotent: a
// compiled-in catalog is rebuilt from source on every redeploy, and a second
// Set of the same slug is a corrected description rather than a collision.
func (c *Catalog) Set(t Tool) error {
if err := t.Validate(); err != nil {
return err
}
c.init()
c.s.tools.Set(t.Slug, copyTool(t))
return nil
}
// Remove deletes the tool under slug. It returns [ErrUnknownSlug] when there
// is none, so a realm removing an entry it believes in learns that it is gone.
func (c *Catalog) Remove(slug string) error {
if c.s == nil {
return ErrUnknownSlug
}
if _, removed := c.s.tools.Remove(slug); !removed {
return ErrUnknownSlug
}
return nil
}
// Get returns the tool under slug.
func (c *Catalog) Get(slug string) (Tool, bool) {
if c.s == nil {
return Tool{}, false
}
v := c.s.tools.Get(slug)
if v == nil {
return Tool{}, false
}
return copyTool(v.(Tool)), true
}
// Has reports whether slug is in the catalog.
func (c *Catalog) Has(slug string) bool {
return c.s != nil && c.s.tools.Has(slug)
}
// Len is how many tools the catalog holds.
func (c *Catalog) Len() int {
if c.s == nil {
return 0
}
return c.s.tools.Size()
}
// List returns every tool, in slug order.
func (c *Catalog) List() []Tool {
if c.s == nil {
return nil
}
out := make([]Tool, 0, c.s.tools.Size())
c.s.tools.Iterate("", "", func(_ string, v any) bool {
out = append(out, copyTool(v.(Tool)))
return false
})
return out
}
// ByTag returns every tool carrying tag, in slug order. An empty tag matches
// nothing rather than everything: it is almost always an unset field.
func (c *Catalog) ByTag(tag string) []Tool {
if tag == "" || c.s == nil {
return nil
}
var out []Tool
c.s.tools.Iterate("", "", func(_ string, v any) bool {
if t := v.(Tool); t.HasTag(tag) {
out = append(out, copyTool(t))
}
return false
})
return out
}
// Tags returns every tag used by any tool, each once, in first-seen order
// within slug order. Deterministic, which iterating a map would not be.
func (c *Catalog) Tags() []string {
if c.s == nil {
return nil
}
var out []string
c.s.tools.Iterate("", "", func(_ string, v any) bool {
for _, tag := range v.(Tool).Tags {
if !contains(out, tag) {
out = append(out, tag)
}
}
return false
})
return out
}
// copyTool deep-copies the one field that is not a scalar.
//
// A Tool is a value, so handing one out already copies Slug, Path, Title and
// Desc. Tags is a slice: the struct copy duplicates the header and shares the
// backing array, so `c.List()[0].Tags[0] = "x"` would reach into the catalog
// and change what every later read returns. Copied on the way in as well as on
// the way out, or the caller of Set keeps a handle on stored state.
func copyTool(t Tool) Tool {
if t.Tags == nil {
return t
}
tags := make([]string, len(t.Tags))
copy(tags, t.Tags)
t.Tags = tags
return t
}
func contains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
catalog_test.gno
package toolbox
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func tool(slug string, tags ...string) Tool {
return Tool{
Slug: slug,
Path: "gno.land/r/moul/toolbox/" + slug + "/v0",
Title: slug,
Desc: "the " + slug + " tool",
Tags: tags,
}
}
func slugs(tools []Tool) []string {
out := make([]string, len(tools))
for i, t := range tools {
out[i] = t.Slug
}
return out
}
// TestCatalogCopyIsAHandle is the shape bug the state pointer exists to stop.
// With the tree embedded by value, the root is a pointer and the size an int,
// so a write through a copy threaded the node onto the tree both of them saw
// while incrementing only the copy's counter: a.Len() said 1 while a.Get found
// the second entry.
func TestCatalogCopyIsAHandle(t *testing.T) {
a := New()
uassert.NoError(t, a.Set(tool("amm")))
b := *a
uassert.NoError(t, b.Set(tool("usernames")))
uassert.Equal(t, 2, a.Len())
uassert.Equal(t, 2, b.Len())
uassert.Equal(t, a.Len(), len(a.List()))
uassert.True(t, a.Has("usernames"))
uassert.NoError(t, b.Remove("amm"))
uassert.Equal(t, 1, a.Len())
uassert.False(t, a.Has("amm"))
}
// TestCatalogCopyOfAZeroValueIsSeparate: nothing has been allocated yet, so
// there is no directory to share. Stated because it is the one case where
// copying does NOT alias, and a reader would otherwise have to guess.
func TestCatalogCopyOfAZeroValueIsSeparate(t *testing.T) {
var a Catalog
b := a
uassert.NoError(t, b.Set(tool("usernames")))
uassert.Equal(t, 0, a.Len())
uassert.Equal(t, 1, b.Len())
}
func TestCatalogZeroValue(t *testing.T) {
var c Catalog
uassert.Equal(t, 0, c.Len())
uassert.Equal(t, 0, len(c.List()))
uassert.False(t, c.Has("usernames"))
uassert.ErrorIs(t, c.Remove("usernames"), ErrUnknownSlug)
}
// TestCatalogSortsBySlug checks the only ordering guarantee the type makes,
// against an insertion order that is reverse, interleaved and duplicated.
func TestCatalogSortsBySlug(t *testing.T) {
var c Catalog
for _, s := range []string{"zones", "amm", "usernames", "base64", "amm"} {
uassert.NoError(t, c.Set(tool(s)))
}
uassert.Equal(t, 4, c.Len())
want := []string{"amm", "base64", "usernames", "zones"}
got := slugs(c.List())
uassert.Equal(t, len(want), len(got))
for i := range want {
uassert.Equal(t, want[i], got[i])
}
}
func TestCatalogSetReplaces(t *testing.T) {
var c Catalog
uassert.NoError(t, c.Set(tool("usernames")))
updated := tool("usernames")
updated.Desc = "resolve a username or an address"
uassert.NoError(t, c.Set(updated))
uassert.Equal(t, 1, c.Len())
got, ok := c.Get("usernames")
uassert.True(t, ok)
uassert.Equal(t, "resolve a username or an address", got.Desc)
}
func TestCatalogSetRejectsInvalid(t *testing.T) {
var c Catalog
uassert.ErrorIs(t, c.Set(Tool{Path: "p", Title: "t"}), ErrEmptySlug)
uassert.ErrorIs(t, c.Set(Tool{Slug: "A", Path: "p", Title: "t"}), ErrBadSlug)
uassert.ErrorIs(t, c.Set(Tool{Slug: "a", Title: "t"}), ErrEmptyPath)
uassert.ErrorIs(t, c.Set(Tool{Slug: "a", Path: "p"}), ErrEmptyTitle)
uassert.Equal(t, 0, c.Len())
}
func TestCatalogGetAndRemove(t *testing.T) {
var c Catalog
for _, s := range []string{"amm", "base64", "usernames"} {
uassert.NoError(t, c.Set(tool(s)))
}
got, ok := c.Get("base64")
uassert.True(t, ok)
uassert.Equal(t, "gno.land/r/moul/toolbox/base64/v0", got.Path)
_, ok = c.Get("nope")
uassert.False(t, ok)
uassert.NoError(t, c.Remove("base64"))
uassert.False(t, c.Has("base64"))
uassert.Equal(t, 2, c.Len())
uassert.ErrorIs(t, c.Remove("base64"), ErrUnknownSlug)
// The two survivors are still in order around the hole.
got2 := slugs(c.List())
uassert.Equal(t, "amm", got2[0])
uassert.Equal(t, "usernames", got2[1])
}
// TestCatalogListIsACopy: a caller rewriting what List handed back must not
// reach the directory through it. The struct copy covers the string fields on
// its own; Tags is a slice, so without copyTool the header is duplicated and
// the backing array is shared, and the write below would land in the catalog.
func TestCatalogListIsACopy(t *testing.T) {
var c Catalog
uassert.NoError(t, c.Set(tool("usernames", "identity")))
got := c.List()
got[0].Title = "hijacked"
got[0].Tags[0] = "hijacked"
kept, ok := c.Get("usernames")
uassert.True(t, ok)
uassert.Equal(t, "usernames", kept.Title)
uassert.Equal(t, "identity", kept.Tags[0])
}
// TestCatalogDoesNotAliasTheCallersTags is the same hole from the other side:
// Set must not keep a handle on the slice the caller still holds.
func TestCatalogDoesNotAliasTheCallersTags(t *testing.T) {
var c Catalog
tags := []string{"identity"}
uassert.NoError(t, c.Set(Tool{
Slug: "usernames",
Path: "gno.land/r/moul/toolbox/usernames",
Title: "Usernames",
Tags: tags,
}))
tags[0] = "hijacked"
kept, ok := c.Get("usernames")
uassert.True(t, ok)
uassert.Equal(t, "identity", kept.Tags[0])
uassert.Equal(t, 1, len(c.ByTag("identity")))
uassert.Equal(t, 0, len(c.ByTag("hijacked")))
}
// TestCatalogGetIsACopyToo: ByTag and Get hand out the same values List does.
func TestCatalogGetIsACopyToo(t *testing.T) {
var c Catalog
uassert.NoError(t, c.Set(tool("usernames", "identity")))
got, ok := c.Get("usernames")
uassert.True(t, ok)
got.Tags[0] = "hijacked"
byTag := c.ByTag("identity")
uassert.Equal(t, 1, len(byTag))
byTag[0].Tags[0] = "hijacked-again"
kept, _ := c.Get("usernames")
uassert.Equal(t, "identity", kept.Tags[0])
}
func TestCatalogByTagAndTags(t *testing.T) {
var c Catalog
uassert.NoError(t, c.Set(tool("usernames", "identity", "read")))
uassert.NoError(t, c.Set(tool("amm", "defi")))
uassert.NoError(t, c.Set(tool("whois", "identity")))
identity := slugs(c.ByTag("identity"))
uassert.Equal(t, 2, len(identity))
uassert.Equal(t, "usernames", identity[0])
uassert.Equal(t, "whois", identity[1])
uassert.Equal(t, 0, len(c.ByTag("nope")))
uassert.Equal(t, 0, len(c.ByTag("")))
tags := c.Tags()
uassert.Equal(t, 3, len(tags))
uassert.Equal(t, "defi", tags[0])
uassert.Equal(t, "identity", tags[1])
uassert.Equal(t, "read", tags[2])
}
form.gno
package toolbox
import "strings"
// Query builds the gnoweb form a read-only tool needs: a text box whose
// submission navigates to one of the realm's own Render paths, with the typed
// values as query parameters.
//
// This is the "template of a query" a toolbox page is for. Rendered by gnoweb,
//
// NewQuery("lookup").Field("q", "username or g1 address").String()
//
// posts to the realm and redirects to `/r/moul/toolbox/usernames:lookup?q=moul`
// (`gno.land/pkg/gnoweb/handler_http.go`, `Post`: the `path` attribute travels
// as the hidden `__gno_path` field and becomes the render args, every other
// field becomes a query parameter). Nothing is signed and no transaction is
// built: the result is a `Render` call, which is exactly what
// `gnokey query vm/qrender` would have done from a terminal.
//
// A form whose fields should CALL a function instead is a different element,
// `<gno-form exec="Fn">`, and it is not what this type builds. A query form is
// free and a call is not, so the two are deliberately not one constructor with
// a flag.
type Query struct {
path string
fields []queryField
}
type queryField struct {
name string
placeholder string
}
// NewQuery starts a form submitting to the Render path args.
//
// Pass "" to submit to the realm's root page. Do not include a leading colon
// or the realm path itself: gnoweb supplies both, and a value that looks like
// a URL is percent-encoded into one path element rather than followed.
func NewQuery(path string) *Query {
return &Query{path: path}
}
// Field adds a text input. name is the query parameter the realm will read;
// placeholder is the grey text in the empty box.
//
// A field with an empty name is ignored: gnoweb rejects the whole form for it,
// and losing one input beats losing the page.
func (q *Query) Field(name, placeholder string) *Query {
if name == "" {
return q
}
q.fields = append(q.fields, queryField{name: name, placeholder: placeholder})
return q
}
// Len is how many fields the form carries.
func (q *Query) Len() int { return len(q.fields) }
// String renders the form as the markdown-embedded HTML gnoweb parses.
//
// A form with no field renders as the empty string rather than as a submit
// button with nothing to submit.
func (q *Query) String() string {
if len(q.fields) == 0 {
return ""
}
var b strings.Builder
b.WriteString(`<gno-form`)
if q.path != "" {
b.WriteString(` path="` + attr(q.path) + `"`)
}
b.WriteString(">\n")
for _, f := range q.fields {
b.WriteString(`<gno-input name="` + attr(f.name) + `" type="text"`)
if f.placeholder != "" {
b.WriteString(` placeholder="` + attr(f.placeholder) + `"`)
}
b.WriteString(" />\n")
}
b.WriteString("</gno-form>\n")
return b.String()
}
// attr escapes a value for an HTML attribute in double quotes.
//
// gnoweb parses these with a real HTML tokenizer, so an unescaped quote does
// not merely look wrong: it ends the attribute and whatever follows becomes
// further attributes of the same tag. Ampersand first, or the escapes of the
// later replacements would themselves be escaped.
func attr(s string) string {
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, `"`, """)
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
return s
}
form_test.gno
package toolbox
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestQueryString(t *testing.T) {
got := NewQuery("lookup").Field("q", "username or g1 address").String()
want := "<gno-form path=\"lookup\">\n" +
"<gno-input name=\"q\" type=\"text\" placeholder=\"username or g1 address\" />\n" +
"</gno-form>\n"
uassert.Equal(t, want, got)
}
func TestQueryNoPathNoPlaceholder(t *testing.T) {
got := NewQuery("").Field("q", "").String()
want := "<gno-form>\n<gno-input name=\"q\" type=\"text\" />\n</gno-form>\n"
uassert.Equal(t, want, got)
}
func TestQueryTwoFields(t *testing.T) {
q := NewQuery("compare").Field("a", "first").Field("b", "second")
uassert.Equal(t, 2, q.Len())
got := q.String()
uassert.True(t, strings.Contains(got, `name="a"`))
uassert.True(t, strings.Contains(got, `name="b"`))
uassert.Equal(t, 1, strings.Count(got, "<gno-form"))
}
// TestQueryEmptyRendersNothing: a form with no input is a submit button with
// nothing to submit, so it is not rendered at all.
func TestQueryEmptyRendersNothing(t *testing.T) {
uassert.Equal(t, "", NewQuery("lookup").String())
uassert.Equal(t, "", NewQuery("lookup").Field("", "ignored").String())
}
// TestQueryEscapesAttributes: gnoweb parses these with a real HTML tokenizer,
// so an unescaped quote ends the attribute and everything after it becomes
// further attributes of the same tag.
func TestQueryEscapesAttributes(t *testing.T) {
got := NewQuery(`a"b`).Field("q", `<script>&"`).String()
uassert.True(t, strings.Contains(got, `path="a"b"`))
uassert.True(t, strings.Contains(got, `placeholder="<script>&""`))
uassert.False(t, strings.Contains(got, "<script>"))
}
func TestAttr(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"plain", "username", "username"},
{"quote", `a"b`, "a"b"},
{"ampersand", "a&b", "a&b"},
{"angle", "<b>", "<b>"},
{"ampersand before quote", `&"`, "&""},
{"already escaped stays literal", "&", "&amp;"},
{"empty", "", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.want, attr(tc.in))
})
}
}
gnomod.toml
module = "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/v0" gno = "0.9" [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 755778 max_deposit = "17000000ugnot"
render.gno
package toolbox
import (
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
)
// Index renders a catalog as a markdown table: tool, what it does, tags.
//
// Every cell that came from a [Tool] is escaped exactly once, with the helper
// for the slot it lands in. A tool description is written by whoever wrote the
// entry, which in a hub that accepts runtime registration is not necessarily
// whoever owns the hub, and a pipe or a backtick in one would otherwise
// rewrite the table around it.
//
// The title link is built by hand rather than with [md.Link], which is the one
// place the obvious call is wrong: md.Link runs its text through
// sanitize.InlineText itself, so md.Link(ui.Cell(title), url) escapes twice and
// a title with an asterisk in it renders as a backslash. The slot here is link
// text INSIDE a table cell, and the helper for that is [ui.Cell] (InlineText
// plus the pipe escape InlineText deliberately leaves alone), with the URL
// escaped once by [md.EscapeURL].
func Index(tools []Tool) string {
t := ui.NewTable("Tool", "What it does", "Tags")
for _, tool := range tools {
t.Row(
"["+ui.Cell(tool.Title)+"]("+md.EscapeURL(tool.URL())+")",
ui.Cell(tool.Desc),
ui.Cell(strings.Join(tool.Tags, ", ")),
)
}
return t.OrEmpty("No tools yet.")
}
// Card renders one tool on its own: the title as a link, the description, the
// package path, and the two ways to reach it.
func Card(tool Tool) string {
var b strings.Builder
b.WriteString(md.H2(ui.Inline(tool.Title)))
if tool.Desc != "" {
b.WriteString("\n" + ui.Inline(tool.Desc) + "\n")
}
b.WriteString("\n" + md.BulletList([]string{
"Open: " + md.Link(tool.URL(), tool.URL()),
"Path: " + md.InlineCode(tool.Path),
}))
if len(tool.Tags) > 0 {
b.WriteString("\nTags: " + ui.Inline(strings.Join(tool.Tags, ", ")) + "\n")
}
return b.String()
}
// Nav renders the one line every tool page carries above its content: a link
// back to the hub, then the tool's own title.
//
// hubURL is a gnoweb path ("/r/moul/toolbox"), not a package path. A tool
// cannot import the hub to ask, so it states it, and this is the one place the
// two have to agree.
func Nav(hubURL, title string) string {
return md.Link("toolbox", hubURL) + " / " + md.Bold(ui.Inline(title)) + "\n"
}
render_test.gno
package toolbox
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestIndex(t *testing.T) {
var c Catalog
uassert.NoError(t, c.Set(Tool{
Slug: "usernames",
Path: "gno.land/r/moul/toolbox/usernames",
Title: "Usernames",
Desc: "resolve a username or an address",
Tags: []string{"identity", "read"},
}))
got := Index(c.List())
uassert.True(t, strings.Contains(got, "[Usernames](/r/moul/toolbox/usernames)"))
uassert.True(t, strings.Contains(got, "resolve a username or an address"))
uassert.True(t, strings.Contains(got, "identity, read"))
}
func TestIndexEmpty(t *testing.T) {
uassert.True(t, strings.Contains(Index(nil), "No tools yet."))
}
// TestIndexEscapesCells pins the escaping contract: a description is written
// by whoever wrote the entry, and a pipe in one would otherwise add a column to
// every row below it. The title is link text inside a cell, so it needs the
// pipe escaped there too.
func TestIndexEscapesCells(t *testing.T) {
got := Index([]Tool{{
Slug: "evil",
Path: "gno.land/r/moul/toolbox/evil",
Title: "Ev|il",
Desc: "a | b",
Tags: []string{"x|y"},
}})
uassert.False(t, strings.Contains(got, "a | b"))
uassert.True(t, strings.Contains(got, `[Ev\|il](/r/moul/toolbox/evil)`))
uassert.True(t, strings.Contains(got, `x\|y`))
}
// TestIndexEscapesTitleExactlyOnce is the double-wrap regression, and the
// values are copied from what the escapers actually produce rather than
// guessed: md.Link runs its text through sanitize.InlineText itself, so
// md.Link(ui.Cell(title), url) yields `[a\\\*b]` where one pass yields
// `[a\*b]`, and the reader sees a stray backslash.
func TestIndexEscapesTitleExactlyOnce(t *testing.T) {
got := Index([]Tool{{
Slug: "star",
Path: "gno.land/r/moul/toolbox/star",
Title: "a*b",
Desc: "c*d",
}})
uassert.True(t, strings.Contains(got, `[a\*b](/r/moul/toolbox/star)`))
uassert.False(t, strings.Contains(got, `a\\`))
uassert.True(t, strings.Contains(got, `c\*d`))
}
func TestCard(t *testing.T) {
got := Card(Tool{
Slug: "usernames",
Path: "gno.land/r/moul/toolbox/usernames",
Title: "Usernames",
Desc: "resolve a username or an address",
Tags: []string{"identity"},
})
uassert.True(t, strings.Contains(got, "## Usernames"))
uassert.True(t, strings.Contains(got, "resolve a username or an address"))
uassert.True(t, strings.Contains(got, "`gno.land/r/moul/toolbox/usernames`"))
uassert.True(t, strings.Contains(got, "/r/moul/toolbox/usernames"))
uassert.True(t, strings.Contains(got, "Tags: identity"))
}
func TestCardMinimal(t *testing.T) {
got := Card(Tool{Slug: "x", Path: "gno.land/r/moul/toolbox/x/v0", Title: "X"})
uassert.True(t, strings.Contains(got, "## X"))
uassert.False(t, strings.Contains(got, "Tags:"))
}
func TestNav(t *testing.T) {
uassert.Equal(t, "[toolbox](/r/moul/toolbox) / **Usernames**\n",
Nav("/r/moul/toolbox", "Usernames"))
}
toolbox.gno
// Package toolbox is the directory model behind
// [r/moul/toolbox](/r/moul/toolbox): a list of small gno.land utilities,
// each one a realm of its own, rendered as a single index.
//
// A tool is a [Tool]: a slug, the realm path that serves it, a title and one
// line of description. A [Catalog] holds them sorted by slug and answers the
// three questions a directory gets asked: what is here, what is this one, and
// what is tagged X.
//
// # Why a package and not just a realm
//
// The hub realm is `private = true`, which buys redeploy-in-place at a stable
// path and costs the ability to be imported at all: the type checker refuses
// any realm importing a private one (`ImportPrivateError`). So the hub cannot
// share a single line of code with its tools by importing them, and they
// cannot import it either. Everything both sides must agree about (what a tool
// entry looks like, how the index is rendered, how a query form is spelled)
// has to live in a `p/`, which is this one.
//
// # Nesting is checked on the base path, not on the full one
//
// [p/moul/nestedpkg](/p/moul/nestedpkg/v0) decides "is the caller below me" by
// prefixing one package path with the other. That is exactly right when
// neither path carries a version, which is the case for a private hub: it is
// redeployable, so its version could never increment and it does not carry
// one. It breaks the moment either side does, because
// `gno.land/r/moul/toolbox/usernames/v0` does not begin with
// `gno.land/r/moul/toolbox/v0`.
//
// [BasePath] removes a trailing `/vN` so the comparison is about the family
// rather than the version, and [IsUnder] and [SlugOf] are built on it. A hub
// and a tool may each be versioned or not, independently, and all four
// combinations answer the same.
//
// Live: [r/moul/toolbox](/r/moul/toolbox).
package toolbox
import (
"errors"
"strings"
)
// Errors a [Tool] or a [Catalog] returns. A /p/ package returns errors and
// lets the realm decide whether they are fatal; all of these are a mistake in
// the realm's own source rather than a value a user chose, so panicking on
// them is the normal handling.
var (
// ErrEmptySlug is returned for a tool with no slug. The slug is the key
// and the URL segment, so there is nothing to list it under.
ErrEmptySlug = errors.New("toolbox: the slug is empty")
// ErrBadSlug is returned for a slug carrying anything but lowercase
// letters, digits and dashes. A slug travels in a URL path and in a
// markdown link, and those are the characters that need no escaping in
// either.
ErrBadSlug = errors.New("toolbox: the slug has a character outside [a-z0-9-]")
// ErrEmptyPath is returned for a tool with no package path. A directory
// entry nobody can open is worse than no entry.
ErrEmptyPath = errors.New("toolbox: the path is empty")
// ErrEmptyTitle is returned for a tool with no title.
ErrEmptyTitle = errors.New("toolbox: the title is empty")
// ErrUnknownSlug is returned by [Catalog.Remove] for a slug it does not
// hold.
ErrUnknownSlug = errors.New("toolbox: no tool with that slug")
)
// Tool is one entry of the directory.
//
// Every field is a string or a slice of strings on purpose. A tool realm that
// registers itself into a public hub hands these values across a realm
// boundary, and a struct allocated by the caller would be the caller's object:
// persisting it panics with `cannot persist object from the private realm`
// when the caller is private. Scalars are copied, so the hub owns everything
// it stores whichever side built the entry.
type Tool struct {
// Slug is the key, the URL segment and the sort order: "usernames".
Slug string
// Path is the package path serving the tool, with its version if it has
// one: "gno.land/r/moul/toolbox/usernames".
Path string
// Title is the human name: "Usernames".
Title string
// Desc is one line about what the tool does. It is rendered inside a
// table cell, so [Index] escapes it rather than trusting it.
Desc string
// Tags group tools in the index. Order is preserved as written.
Tags []string
}
// Validate reports the first thing wrong with t, or nil.
func (t Tool) Validate() error {
switch {
case t.Slug == "":
return ErrEmptySlug
case !ValidSlug(t.Slug):
return ErrBadSlug
case t.Path == "":
return ErrEmptyPath
case t.Title == "":
return ErrEmptyTitle
}
return nil
}
// HasTag reports whether t carries tag, compared exactly.
func (t Tool) HasTag(tag string) bool {
for _, got := range t.Tags {
if got == tag {
return true
}
}
return false
}
// URL is the gnoweb path of the tool, the package path with the chain domain
// removed: "/r/moul/toolbox/usernames".
//
// It is derived rather than stored so an entry cannot carry a link that
// disagrees with its own path.
func (t Tool) URL() string {
if i := strings.Index(t.Path, "/"); i >= 0 && !strings.HasPrefix(t.Path, "/") {
return t.Path[i:]
}
return t.Path
}
// ValidSlug reports whether s is a usable slug: non-empty, and lowercase
// letters, digits and dashes only.
//
// It is deliberately narrower than what a package path allows. A slug ends up
// in a URL and in markdown link syntax, and this is the set that survives both
// untouched, so nothing downstream has to escape it.
func ValidSlug(s string) bool {
if s == "" {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= 'a' && c <= 'z':
case c >= '0' && c <= '9':
case c == '-':
default:
return false
}
}
return true
}
// BasePath returns pkgPath with a trailing version element removed:
// "gno.land/p/moul/toolbox/v0" becomes "gno.land/p/moul/toolbox".
//
// A path with no version element is returned unchanged, so calling it twice is
// the same as calling it once.
func BasePath(pkgPath string) string {
i := strings.LastIndex(pkgPath, "/")
if i < 0 {
return pkgPath
}
if !isVersion(pkgPath[i+1:]) {
return pkgPath
}
return pkgPath[:i]
}
// isVersion reports whether elem is a "vN" path element: a 'v' followed by at
// least one digit and nothing else.
func isVersion(elem string) bool {
if len(elem) < 2 || elem[0] != 'v' {
return false
}
for i := 1; i < len(elem); i++ {
if elem[i] < '0' || elem[i] > '9' {
return false
}
}
return true
}
// IsUnder reports whether pkgPath is a tool of the hub at hubPath, ignoring
// both paths' versions.
//
// The hub itself is not under itself, and neither is a sibling whose name
// merely starts with the hub's: "toolboxtwo" is not under "toolbox", because
// the comparison is against the base plus a slash.
func IsUnder(hubPath, pkgPath string) bool {
base := BasePath(hubPath)
if base == "" {
return false
}
return strings.HasPrefix(BasePath(pkgPath), base+"/")
}
// SlugOf returns the slug a tool at pkgPath would have under the hub at
// hubPath, or "" when pkgPath is not under it.
//
// A tool nested deeper than one element has no slug: the directory is one
// level by design, so "toolbox/a/b" is reported as not a tool rather than
// silently listed as "a".
func SlugOf(hubPath, pkgPath string) string {
if !IsUnder(hubPath, pkgPath) {
return ""
}
rest := strings.TrimPrefix(BasePath(pkgPath), BasePath(hubPath)+"/")
if strings.Contains(rest, "/") {
return ""
}
return rest
}
toolbox_test.gno
package toolbox
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestValidSlug(t *testing.T) {
cases := []struct {
name string
slug string
want bool
}{
{"plain", "usernames", true},
{"dashed", "gov-dao", true},
{"digits", "base64", true},
{"all dashes", "--", true},
{"empty", "", false},
{"uppercase", "Usernames", false},
{"underscore", "gov_dao", false},
{"slash", "a/b", false},
{"space", "gov dao", false},
{"dot", "v0.1", false},
{"percent", "a%2Fb", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.want, ValidSlug(tc.slug))
})
}
}
func TestBasePath(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"versioned realm", "gno.land/r/moul/toolbox/v0", "gno.land/r/moul/toolbox"},
{"two digit version", "gno.land/r/moul/toolbox/v12", "gno.land/r/moul/toolbox"},
{"nested tool", "gno.land/r/moul/toolbox/usernames/v0", "gno.land/r/moul/toolbox/usernames"},
{"unversioned", "gno.land/r/moul/home", "gno.land/r/moul/home"},
{"idempotent", "gno.land/r/moul/toolbox", "gno.land/r/moul/toolbox"},
{"v with no digit", "gno.land/r/moul/v", "gno.land/r/moul/v"},
{"v with a letter", "gno.land/r/moul/v0a", "gno.land/r/moul/v0a"},
{"no slash", "toolbox", "toolbox"},
{"empty", "", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.want, BasePath(tc.in))
})
}
}
func TestIsUnderAndSlugOf(t *testing.T) {
const hub = "gno.land/r/moul/toolbox/v0"
cases := []struct {
name string
path string
wantUnder bool
wantSlug string
}{
{"direct tool", "gno.land/r/moul/toolbox/usernames/v0", true, "usernames"},
{"unversioned tool", "gno.land/r/moul/toolbox/usernames", true, "usernames"},
{"tool at another version", "gno.land/r/moul/toolbox/usernames/v3", true, "usernames"},
{"nested deeper", "gno.land/r/moul/toolbox/a/b/v0", true, ""},
{"the hub itself", hub, false, ""},
{"hub unversioned", "gno.land/r/moul/toolbox", false, ""},
{"prefix sibling", "gno.land/r/moul/toolboxtwo/v0", false, ""},
{"unrelated realm", "gno.land/r/moul/home", false, ""},
{"empty", "", false, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.wantUnder, IsUnder(hub, tc.path))
uassert.Equal(t, tc.wantSlug, SlugOf(hub, tc.path))
})
}
}
// TestIsUnderIgnoresEitherSideVersion is the claim the package doc makes: a
// hub and a tool may each carry a version or not, independently, and all four
// combinations answer the same. The live shape is the unversioned one, since a
// private realm is redeployable and its version could never increment.
func TestIsUnderIgnoresEitherSideVersion(t *testing.T) {
hubs := []string{"gno.land/r/moul/toolbox", "gno.land/r/moul/toolbox/v0"}
tools := []string{"gno.land/r/moul/toolbox/usernames", "gno.land/r/moul/toolbox/usernames/v2"}
for _, hub := range hubs {
for _, tool := range tools {
t.Run(hub+" <- "+tool, func(t *testing.T) {
uassert.True(t, IsUnder(hub, tool))
uassert.Equal(t, "usernames", SlugOf(hub, tool))
uassert.False(t, IsUnder(hub, hub))
})
}
}
}
// TestIsUnderEmptyHub pins the one input that would otherwise make every path
// a tool: an empty hub path has no family to be below.
func TestIsUnderEmptyHub(t *testing.T) {
uassert.False(t, IsUnder("", "gno.land/r/moul/toolbox/usernames/v0"))
uassert.Equal(t, "", SlugOf("", "gno.land/r/moul/toolbox/usernames/v0"))
}
func TestToolValidate(t *testing.T) {
ok := Tool{Slug: "usernames", Path: "gno.land/r/moul/toolbox/usernames/v0", Title: "Usernames"}
cases := []struct {
name string
tool Tool
want error
}{
{"complete", ok, nil},
{"no slug", Tool{Path: ok.Path, Title: ok.Title}, ErrEmptySlug},
{"bad slug", Tool{Slug: "User Names", Path: ok.Path, Title: ok.Title}, ErrBadSlug},
{"no path", Tool{Slug: ok.Slug, Title: ok.Title}, ErrEmptyPath},
{"no title", Tool{Slug: ok.Slug, Path: ok.Path}, ErrEmptyTitle},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := tc.tool.Validate()
if tc.want == nil {
uassert.NoError(t, got)
return
}
uassert.ErrorIs(t, got, tc.want)
})
}
}
func TestToolURL(t *testing.T) {
cases := []struct {
name string
path string
want string
}{
{"chain path", "gno.land/r/moul/toolbox/usernames/v0", "/r/moul/toolbox/usernames/v0"},
{"other domain", "example.com/r/x/v0", "/r/x/v0"},
{"already a url", "/r/moul/toolbox/v0", "/r/moul/toolbox/v0"},
{"no slash", "toolbox", "toolbox"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.want, Tool{Path: tc.path}.URL())
})
}
}
func TestToolHasTag(t *testing.T) {
tool := Tool{Tags: []string{"identity", "read"}}
uassert.True(t, tool.HasTag("identity"))
uassert.True(t, tool.HasTag("read"))
uassert.False(t, tool.HasTag("Identity"))
uassert.False(t, tool.HasTag(""))
uassert.False(t, Tool{}.HasTag("identity"))
}