Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

forge.gno

// Package forge is an on-chain software forge: repos, an append-only reference
// log, issues, change requests and reviews, browsable through gnoweb and
// writable only through signed transactions.
//
// It is the realm half of gno.land/p/nym-moultest123/forge/v1, which holds the whole
// domain model; this file is wiring. Every exported mutation is a crossing
// function that resolves the caller, forwards to the library, aborts on error
// (the only way to revert state in gno) and emits an event for indexers.
//
// What the chain stores is NOT the code. Git objects stay in git (a mirror, an
// IPFS CID, a peer) and the realm records what a forge is actually trusted for:
// which object a ref points at, in what order, on whose authority, under
// what review policy, and what got merged. See the package README for the
// design, the threat model and what this deliberately does not do.
//
// A caller may be a user or another realm: a repo whose owner is a DAO realm is
// a repo whose merge button is a governance vote.
package forge

import (
	"chain"
	"chain/runtime"
	"errors"
	"strings"

	fg "gno.land/p/nym-moultest123/forge/v1"
	"gno.land/r/sys/users"
)

// errForeignNamespace is the one rule this realm adds on top of the library:
// a namespace is yours or it is not.
var errForeignNamespace = errors.New("forge: namespace is not yours")

var f = fg.New()

// caller is the address that crossed into this realm. It is deliberately not
// restricted to end users: a realm holding a role is the point (see the doc
// comment above).
func caller(cur realm) address {
	if !cur.IsCurrent() {
		panic("forge: spoofed realm")
	}
	return cur.Previous().Address()
}

func height() int64 { return runtime.ChainHeight() }

// repo resolves a repo id or aborts. Read paths use f.Repo directly and return
// a rendered "not found" instead.
func repo(id string) *fg.Repo {
	r := f.Repo(id)
	if r == nil {
		panic(fg.ErrRepoNotFound)
	}
	return r
}

// requireNamespace enforces the ownership rule. Two namespaces exist and they
// cannot collide, since an address is 40 characters and a name caps at 39:
//
//   - an address namespace ("g1.../forge") belongs to that account, always, with
//     nothing to register and nothing to lose;
//   - a name namespace ("moul/forge") belongs to whoever holds that name in
//     r/sys/users, including through a rename, since the lookup resolves aliases
//     to the same record.
//
// A realm caller passes the same way a user does, which is what makes a
// DAO-owned repo possible: the DAO's address is its namespace.
func requireNamespace(a address, id string) {
	ns, _, ok := fg.SplitRepoID(id)
	if !ok {
		panic(fg.ErrInvalidRepoID)
	}
	if fg.AddressNamespace(ns) {
		if ns != a.String() {
			panic(errForeignNamespace)
		}
		return
	}
	data, _ := users.ResolveName(ns)
	if data.IsDeleted() || data.Addr() != a {
		panic(errForeignNamespace)
	}
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}

// splitList parses the comma-separated lists the transaction API has to use:
// gnokey can only pass strings, so a []string parameter would not be callable.
func splitList(s string) []string {
	s = strings.TrimSpace(s)
	if s == "" {
		return nil
	}
	parts := strings.Split(s, ",")
	out := make([]string, 0, len(parts))
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p != "" {
			out = append(out, p)
		}
	}
	return out
}

// ---------------------------------------------------------------------------
// Repos
// ---------------------------------------------------------------------------

// CreateRepo registers "<namespace>/<name>" with the caller as owner.
// defaultRef may be empty for refs/heads/main.
//
// The namespace must be one the caller owns: an r/sys/users name registered to
// their address, or their own bech32 address. Nobody squats anybody.
func CreateRepo(cur realm, id, description, defaultRef string) {
	a := caller(cur)
	requireNamespace(a, id)
	_, err := f.CreateRepo(a, height(), id, description, defaultRef)
	must(err)
	chain.Emit("RepoCreated", "repo", id, "owner", a.String())
}

// Fork registers newID as a fork of srcID, snapshotting the parent's current
// refs into the fork's log so the lineage records exactly what was forked.
func Fork(cur realm, srcID, newID string) {
	a := caller(cur)
	requireNamespace(a, newID)
	_, err := f.Fork(a, height(), srcID, newID)
	must(err)
	chain.Emit("RepoForked", "repo", newID, "parent", srcID, "owner", a.String())
}

// SetDescription updates the repo description (admin).
func SetDescription(cur realm, repoID, description string) {
	must(repo(repoID).SetDescription(caller(cur), description))
	chain.Emit("RepoUpdated", "repo", repoID, "field", "description")
}

// SetMirrors replaces the fetch locators, comma-separated, first one canonical
// (maintainer). The chain records them; it never fetches.
func SetMirrors(cur realm, repoID, mirrors string) {
	must(repo(repoID).SetMirrors(caller(cur), splitList(mirrors)))
	chain.Emit("RepoUpdated", "repo", repoID, "field", "mirrors")
}

// SetDefaultRef points the repo at another default branch (maintainer).
func SetDefaultRef(cur realm, repoID, name string) {
	must(repo(repoID).SetDefaultRef(caller(cur), name))
	chain.Emit("RepoUpdated", "repo", repoID, "field", "default_ref")
}

// SetPolicy sets how many writer approvals a change needs, and whether the
// author's own approval counts (admin).
func SetPolicy(cur realm, repoID string, requiredApprovals int, allowSelfApproval bool) {
	must(repo(repoID).SetPolicy(caller(cur), requiredApprovals, allowSelfApproval))
	chain.Emit("RepoUpdated", "repo", repoID, "field", "policy")
}

// SetMember grants a role: none, reader, writer, maintainer, admin, owner.
func SetMember(cur realm, repoID string, member address, role string) {
	parsed, err := fg.ParseRole(role)
	must(err)
	must(repo(repoID).SetMember(caller(cur), member, parsed))
	chain.Emit("MemberSet", "repo", repoID, "member", member.String(), "role", role)
}

// SetArchived freezes or unfreezes a repo (admin). The log stays readable.
func SetArchived(cur realm, repoID string, archived bool) {
	must(repo(repoID).SetArchived(caller(cur), archived))
	chain.Emit("RepoUpdated", "repo", repoID, "field", "archived")
}

// ---------------------------------------------------------------------------
// Refs: the reference log
// ---------------------------------------------------------------------------

// SetRef moves a ref by compare-and-swap (writer). expectedOID is the tip the
// caller last saw, empty to create. A stale expectation aborts instead of
// overwriting: git's --force-with-lease, with consensus holding the lease.
func SetRef(cur realm, repoID, name, expectedOID, newOID, note string) {
	a := caller(cur)
	e, err := repo(repoID).SetRef(a, height(), name, expectedOID, newOID, note)
	must(err)
	emitRef(repoID, e)
}

// ForceSetRef moves a ref with no expectation (maintainer). It is not
// forbidden, it is recorded as a force, in a log nobody can rewrite.
func ForceSetRef(cur realm, repoID, name, newOID, note string) {
	a := caller(cur)
	e, err := repo(repoID).ForceSetRef(a, height(), name, newOID, note)
	must(err)
	emitRef(repoID, e)
}

// DeleteRef removes a ref by compare-and-swap (maintainer). The default branch
// is not deletable.
func DeleteRef(cur realm, repoID, name, expectedOID, note string) {
	a := caller(cur)
	e, err := repo(repoID).DeleteRef(a, height(), name, expectedOID, note)
	must(err)
	emitRef(repoID, e)
}

func emitRef(repoID string, e *fg.LogEntry) {
	chain.Emit("RefLog",
		"repo", repoID,
		"ref", e.Ref,
		"kind", e.Kind,
		"old", e.OldOID,
		"new", e.NewOID,
		"seq", itoa(e.Seq),
		"digest", e.Digest,
	)
}

// ---------------------------------------------------------------------------
// Issues
// ---------------------------------------------------------------------------

// OpenIssue files an issue. Permissionless: the author pays for their bytes.
// labels is comma-separated. Returns the issue id.
func OpenIssue(cur realm, repoID, title, body, labels string) int64 {
	a := caller(cur)
	i, err := repo(repoID).OpenIssue(a, height(), title, body, splitList(labels))
	must(err)
	chain.Emit("IssueOpened", "repo", repoID, "issue", itoa(i.ID), "author", a.String())
	return i.ID
}

// CommentIssue appends a reply.
func CommentIssue(cur realm, repoID string, issueID int64, body string) {
	a := caller(cur)
	_, err := repo(repoID).CommentIssue(a, height(), issueID, body)
	must(err)
	chain.Emit("IssueComment", "repo", repoID, "issue", itoa(issueID), "author", a.String())
}

// CloseIssue closes an issue (author or maintainer).
func CloseIssue(cur realm, repoID string, issueID int64) {
	must(repo(repoID).SetIssueOpen(caller(cur), height(), issueID, false))
	chain.Emit("IssueClosed", "repo", repoID, "issue", itoa(issueID))
}

// ReopenIssue reopens an issue (author or maintainer).
func ReopenIssue(cur realm, repoID string, issueID int64) {
	must(repo(repoID).SetIssueOpen(caller(cur), height(), issueID, true))
	chain.Emit("IssueReopened", "repo", repoID, "issue", itoa(issueID))
}

// SetIssueLabels replaces an issue's labels, comma-separated (maintainer).
func SetIssueLabels(cur realm, repoID string, issueID int64, labels string) {
	must(repo(repoID).SetIssueLabels(caller(cur), height(), issueID, splitList(labels)))
	chain.Emit("IssueLabeled", "repo", repoID, "issue", itoa(issueID), "labels", labels)
}

// ---------------------------------------------------------------------------
// Change requests
// ---------------------------------------------------------------------------

// OpenChange proposes moving targetRef to include headOID. sourceRepo may be
// another forge repo id, a mirror locator, or empty for this repo. Returns the
// change id.
func OpenChange(cur realm, repoID, title, body, sourceRepo, sourceRef, headOID, targetRef string) int64 {
	a := caller(cur)
	c, err := repo(repoID).OpenChange(a, height(), title, body, sourceRepo, sourceRef, headOID, targetRef)
	must(err)
	chain.Emit("ChangeOpened", "repo", repoID, "change", itoa(c.ID), "author", a.String(), "head", headOID, "target", targetRef)
	return c.ID
}

// UpdateChangeHead repoints an open change at a new object (author or writer).
// Every approval of the previous head stops counting, by construction.
func UpdateChangeHead(cur realm, repoID string, changeID int64, headOID string) {
	must(repo(repoID).UpdateChangeHead(caller(cur), height(), changeID, headOID))
	chain.Emit("ChangeUpdated", "repo", repoID, "change", itoa(changeID), "head", headOID)
}

// ReviewChange records a verdict: approve, request-changes, comment: against
// the change's current head. Anyone may review; a writer's approval counts.
func ReviewChange(cur realm, repoID string, changeID int64, verdict, body string) {
	a := caller(cur)
	must(repo(repoID).ReviewChange(a, height(), changeID, verdict, body))
	chain.Emit("ChangeReviewed", "repo", repoID, "change", itoa(changeID), "reviewer", a.String(), "verdict", verdict)
}

// CommentChange appends a reply to a change request.
func CommentChange(cur realm, repoID string, changeID int64, body string) {
	a := caller(cur)
	_, err := repo(repoID).CommentChange(a, height(), changeID, body)
	must(err)
	chain.Emit("ChangeComment", "repo", repoID, "change", itoa(changeID), "author", a.String())
}

// CloseChange withdraws or rejects a change (author or maintainer).
func CloseChange(cur realm, repoID string, changeID int64) {
	must(repo(repoID).CloseChange(caller(cur), height(), changeID))
	chain.Emit("ChangeClosed", "repo", repoID, "change", itoa(changeID))
}

// MergeChange moves the target ref to mergedOID and records the move as a merge
// entry naming the change (maintainer). expectedTargetOID is a compare-and-swap
// on the target: a change approved against a base that has moved is refused,
// not silently rebased.
func MergeChange(cur realm, repoID string, changeID int64, expectedTargetOID, mergedOID, note string) {
	a := caller(cur)
	e, err := repo(repoID).MergeChange(a, height(), changeID, expectedTargetOID, mergedOID, note)
	must(err)
	chain.Emit("ChangeMerged", "repo", repoID, "change", itoa(changeID), "merger", a.String(), "new", mergedOID, "digest", e.Digest)
	emitRef(repoID, e)
}

// ---------------------------------------------------------------------------
// Packages and releases
// ---------------------------------------------------------------------------

// PublishPackage records that a repo publishes a deployed package path.
//
// The claim is not verified and cannot be: a realm cannot ask the chain who
// deployed a path. What is guaranteed is that someone with write access to the
// repo said it, under a namespace r/sys/users governs. A reader weighs it the
// way they weigh a go.mod.
//
// ref, oid and tag may each be empty when unstated.
func PublishPackage(cur realm, repoID, path, ref, oid, tag string) {
	a := caller(cur)
	p, err := f.PublishPackage(a, height(), repoID, path, ref, oid, tag)
	must(err)
	chain.Emit("PackagePublished",
		"repo", repoID,
		"path", p.Path,
		"ref", p.Ref,
		"oid", p.OID,
		"tag", p.Tag,
	)
}

// UnpublishPackage withdraws the claim. The package stays on chain; only the
// repo's assertion about it goes away.
func UnpublishPackage(cur realm, repoID, path string) {
	a := caller(cur)
	must(f.UnpublishPackage(a, repoID, path))
	chain.Emit("PackageUnpublished", "repo", repoID, "path", path)
}

// CutRelease names a point in a repo's history. A tag cannot be re-cut: see
// YankRelease for withdrawing one.
func CutRelease(cur realm, repoID, tag, name, notes, oid, ref string, prerelease bool) {
	a := caller(cur)
	rel, err := repo(repoID).CutRelease(a, height(), tag, name, notes, oid, ref, prerelease)
	must(err)
	chain.Emit("ReleaseCut",
		"repo", repoID,
		"tag", rel.Tag,
		"oid", rel.OID,
		"prerelease", btoa(rel.Prerelease),
	)
}

// YankRelease marks a release withdrawn. It stays visible: a version that
// vanished reads as "never published" rather than "do not use this".
func YankRelease(cur realm, repoID, tag, reason string) {
	a := caller(cur)
	must(repo(repoID).YankRelease(a, tag, reason))
	chain.Emit("ReleaseYanked", "repo", repoID, "tag", tag, "reason", reason)
}

// ---------------------------------------------------------------------------
// Read-only helpers, for other realms and for vm/qeval
// ---------------------------------------------------------------------------

// PackageRepo is the lookup an explorer makes: given a deployed package path,
// which repo claims to publish it. Empty when nobody does.
func PackageRepo(pkgPath string) string { return f.PackageRepo(pkgPath) }

// PackageCount is how many package paths the whole forge claims.
func PackageCount() int { return f.PackageCount() }

// LatestReleaseTag is the most recently cut release of a repo that is neither a
// prerelease nor yanked, or "". Most recently CUT, never highest version: tags
// here are not required to be semver, so there is no order to sort by that
// would not be wrong for somebody.
func LatestReleaseTag(repoID string) string {
	r := f.Repo(repoID)
	if r == nil {
		return ""
	}
	rel := r.LatestRelease()
	if rel == nil {
		return ""
	}
	return rel.Tag
}

// ReleaseCount is how many releases a repo has cut, yanked ones included.
func ReleaseCount(repoID string) int {
	r := f.Repo(repoID)
	if r == nil {
		return 0
	}
	return r.ReleaseCount()
}

// RefOID returns the object a ref points at, or "" if there is no such ref.
func RefOID(repoID, name string) string {
	r := f.Repo(repoID)
	if r == nil {
		return ""
	}
	ref := r.Ref(name)
	if ref == nil {
		return ""
	}
	return ref.OID
}

// LogHead returns the repo's chain digest: pin it off chain and the whole
// history of every ref becomes falsifiable.
func LogHead(repoID string) string {
	r := f.Repo(repoID)
	if r == nil {
		return ""
	}
	return r.LogHead()
}

// HasRepo reports whether a repo id is registered.
func HasRepo(repoID string) bool { return f.HasRepo(repoID) }

// RepoCount is the number of repos on this forge.
func RepoCount() int { return f.Size() }

forge_test.gno

package forge

import (
	"testing"

	fg "gno.land/p/nym-moultest123/forge/v1"
	"gno.land/p/nt/uassert/v0"
)

// TestLifecycle drives the realm exactly as a user would: one signed call at a
// time, each from a different address.
func TestLifecycle(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "a demo repo", "")
	uassert.True(t, HasRepo(demoID))
	uassert.Equal(t, 1, RepoCount())
	uassert.Equal(t, "", LogHead(demoID), "a fresh repo has an empty log")

	// The creator is the owner, so roles are theirs to hand out.
	SetMember(cross(cur), demoID, carol, "writer")
	SetMember(cross(cur), demoID, bob, "maintainer")
	SetMirrors(cross(cur), demoID, "https://github.com/moul/demo.git, ipfs://bafyfakefakefakefakefakefakefakefakefake")
	uassert.Equal(t, 2, len(f.Repo(demoID).Mirrors), "comma-separated lists are how a tx passes a slice")

	// A writer creates the branch, then moves it by compare-and-swap.
	testing.SetRealm(testing.NewUserRealm(carol))
	SetRef(cross(cur), demoID, "refs/heads/main", "", oid("a"), "initial import")
	uassert.Equal(t, oid("a"), RefOID(demoID, "refs/heads/main"))
	head := LogHead(demoID)
	uassert.NotEqual(t, "", head)

	testing.SetRealm(testing.NewUserRealm(carol))
	SetRef(cross(cur), demoID, "refs/heads/main", oid("a"), oid("b"), "second commit")
	uassert.NotEqual(t, head, LogHead(demoID), "each entry advances the chain digest")

	// A stale expectation aborts: this is the lost-push case, caught.
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsContains(t, cur, "stale ref", func() {
		SetRef(cross(cur), demoID, "refs/heads/main", oid("a"), oid("c"), "")
	})

	// A stranger cannot move a ref at all.
	testing.SetRealm(testing.NewUserRealm(eve))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		SetRef(cross(cur), demoID, "refs/heads/main", oid("b"), oid("c"), "")
	})

	// ...but anyone may file an issue and propose a change.
	testing.SetRealm(testing.NewUserRealm(eve))
	issueID := OpenIssue(cross(cur), demoID, "the log needs a UI", "hard to read over RPC", "ux,help wanted")
	uassert.Equal(t, int64(0), issueID)

	testing.SetRealm(testing.NewUserRealm(eve))
	changeID := OpenChange(cross(cur), demoID, "add a log view", "", "eve/demo", "refs/heads/logview", oid("c"), "refs/heads/main")
	uassert.Equal(t, int64(0), changeID)

	// A maintainer's approval satisfies the default policy; the merge moves the
	// ref and lands in the same log as every other move.
	testing.SetRealm(testing.NewUserRealm(bob))
	ReviewChange(cross(cur), demoID, changeID, "approve", "lgtm")
	testing.SetRealm(testing.NewUserRealm(bob))
	MergeChange(cross(cur), demoID, changeID, oid("b"), oid("d"), "merge change 0")

	uassert.Equal(t, oid("d"), RefOID(demoID, "refs/heads/main"))
	r := f.Repo(demoID)
	uassert.Equal(t, 3, r.LogSize())
	uassert.Equal(t, fg.KindMerge, r.LogEntryAt(2).Kind)
	uassert.Equal(t, bob.String(), r.LogEntryAt(2).Actor.String(), "the log records who merged, not who proposed")
	ok, _ := r.VerifyLog()
	uassert.True(t, ok, "the digest chain verifies end to end")

	// Issue triage: the maintainer closes what the reporter opened.
	testing.SetRealm(testing.NewUserRealm(bob))
	CloseIssue(cross(cur), demoID, issueID)
	uassert.Equal(t, 0, r.OpenIssueCount())
}

// TestHeightsComeFromTheChain checks the realm stamps entries with the block it
// ran in. SkipHeights is relative and there is no absolute height getter, so the
// assertion is on the delta.
func TestHeightsComeFromTheChain(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), heightsID, "", "")
	testing.SetRealm(testing.NewUserRealm(alice))
	SetRef(cross(cur), heightsID, "refs/heads/main", "", oid("a"), "")

	testing.SkipHeights(7)

	testing.SetRealm(testing.NewUserRealm(alice))
	SetRef(cross(cur), heightsID, "refs/heads/main", oid("a"), oid("b"), "")

	r := f.Repo(heightsID)
	first := r.LogEntryAt(0).Height
	second := r.LogEntryAt(1).Height
	uassert.Equal(t, int64(7), second-first, "seven blocks passed between the two writes")
}

// TestUnknownRepoAborts: every write resolves the repo first, so a typo fails
// loudly instead of creating something.
func TestUnknownRepoAborts(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "repo not found", func() {
		SetRef(cross(cur), ghostID, "refs/heads/main", "", oid("a"), "")
	})
	uassert.Equal(t, "", RefOID(ghostID, "refs/heads/main"))
	uassert.Equal(t, "", LogHead(ghostID))
	uassert.False(t, HasRepo(ghostID))
}

// TestRoleParsing: the role argument is a string on the wire, so a typo must
// abort rather than silently grant nothing.
func TestRoleParsing(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), rolesID, "", "")
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "invalid role", func() {
		SetMember(cross(cur), rolesID, bob, "commiter")
	})
	testing.SetRealm(testing.NewUserRealm(alice))
	SetMember(cross(cur), rolesID, bob, "maintainer")
	uassert.Equal(t, "maintainer", f.Repo(rolesID).RoleOf(bob).String())
}

func TestSplitList(t *testing.T) {
	cases := []struct {
		in   string
		want int
	}{
		{"", 0},
		{"   ", 0},
		{"a", 1},
		{"a,b", 2},
		{" a , b ,, c ", 3},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, len(splitList(tc.in)), tc.in)
	}
}

// TestNamespaceOwnership: a namespace is an r/sys/users name you hold or your
// own address, and nothing else. No name is registered in a unit test, so the
// name path is exercised through its rejection.
func TestNamespaceOwnership(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "under alice's own address", "")
	uassert.True(t, HasRepo(demoID))

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "namespace is not yours", func() {
		CreateRepo(cross(cur), bob.String()+"/squat", "", "")
	}, "an address namespace belongs to that address")

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "namespace is not yours", func() {
		CreateRepo(cross(cur), "moul/forge", "", "")
	}, "an unregistered name belongs to nobody")

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsContains(t, cur, "namespace is not yours", func() {
		Fork(cross(cur), demoID, alice.String()+"/fork")
	}, "a fork lands in the forker's namespace, not the parent's")

	testing.SetRealm(testing.NewUserRealm(bob))
	Fork(cross(cur), demoID, bob.String()+"/fork")
	uassert.True(t, HasRepo(bob.String()+"/fork"))

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "invalid repo id", func() {
		CreateRepo(cross(cur), "nonamespace", "", "")
	})
}

gnomod.toml

module = "gno.land/r/nym-moultest123/forge/v0"
gno = "0.9"
private = true

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186410
  max_deposit = "25000000ugnot"

helpers_test.gno

package forge

import (
	"strings"

	fg "gno.land/p/nym-moultest123/forge/v1"
	"gno.land/p/nt/testutils/v0"
)

// Deterministic, checksum-valid test addresses.
var (
	alice = testutils.TestAddress("alice") // owner
	bob   = testutils.TestAddress("bob")   // maintainer
	carol = testutils.TestAddress("carol") // writer
	eve   = testutils.TestAddress("eve")   // stranger
)

// Repo ids used by the crossing tests. The realm only lets an address create
// under a namespace it owns, and no user name is registered in a unit test, so
// these are all address namespaces.
var (
	demoID    = alice.String() + "/demo"
	heightsID = alice.String() + "/heights"
	rolesID   = alice.String() + "/roles"
	ghostID   = alice.String() + "/ghost"
)

func oid(c string) string { return strings.Repeat(c, 40) }

// reset restores realm state to empty. Realm globals persist for the whole test
// binary and examples run after every Test, so anything that pins Render output
// must reset and re-seed first.
func reset() { f = fg.New() }

// seedFixture builds one deterministic repo straight through the library: no
// chain context needed, which is what lets an Example use it. It can use a name
// namespace because namespace ownership is a realm rule (it needs a chain to
// resolve a name); the library validates the shape and nothing more.
func seedFixture() {
	reset()
	r, err := f.CreateRepo(alice, 100, "moul/forge", "an on chain software forge", "")
	if err != nil {
		panic(err)
	}
	if err := r.SetMember(alice, bob, fg.RoleMaintainer); err != nil {
		panic(err)
	}
	if err := r.SetMember(alice, carol, fg.RoleWriter); err != nil {
		panic(err)
	}
	if err := r.SetMirrors(alice, []string{"https://github.com/moul/gno-contracts.git"}); err != nil {
		panic(err)
	}
	if _, err := r.SetRef(carol, 101, "refs/heads/main", "", oid("a"), "initial import"); err != nil {
		panic(err)
	}
	if _, err := r.SetRef(carol, 102, "refs/heads/main", oid("a"), oid("b"), "add the log"); err != nil {
		panic(err)
	}
	if _, err := r.OpenIssue(eve, 103, "force pushes are invisible", "A maintainer can rewrite a branch and nothing records it.", []string{"bug"}); err != nil {
		panic(err)
	}
	if _, err := r.CommentIssue(bob, 104, 0, "that is what the log is for"); err != nil {
		panic(err)
	}
	c, err := r.OpenChange(carol, 105, "record every ref move", "closes 0", "", "refs/heads/feat", oid("c"), "refs/heads/main")
	if err != nil {
		panic(err)
	}
	if err := r.ReviewChange(bob, 106, c.ID, fg.VerdictApprove, "lgtm"); err != nil {
		panic(err)
	}
}

pkgrelease_test.gno

package forge

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// The path an explorer walks: it arrives holding a deployed package path, knows
// no repo, and needs the issues and releases that belong to it.
func TestPackageLookupFromAPathAlone(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "a demo repo", "")

	uassert.Equal(t, "", PackageRepo("gno.land/r/nym-moultest123/home"), "nobody claims it yet")
	uassert.Equal(t, 0, PackageCount())

	testing.SetRealm(testing.NewUserRealm(alice))
	PublishPackage(cross(cur), demoID, "gno.land/r/nym-moultest123/home", "refs/heads/main", oid("a"), "")

	uassert.Equal(t, demoID, PackageRepo("gno.land/r/nym-moultest123/home"))
	uassert.Equal(t, 1, PackageCount())

	// One repo publishes many paths, which is the normal case: gno-contracts
	// publishes 193.
	testing.SetRealm(testing.NewUserRealm(alice))
	PublishPackage(cross(cur), demoID, "gno.land/p/nym-moultest123/forge/v1", "", "", "")
	uassert.Equal(t, 2, PackageCount())
	uassert.Equal(t, demoID, PackageRepo("gno.land/p/nym-moultest123/forge/v1"))

	testing.SetRealm(testing.NewUserRealm(alice))
	UnpublishPackage(cross(cur), demoID, "gno.land/r/nym-moultest123/home")
	uassert.Equal(t, "", PackageRepo("gno.land/r/nym-moultest123/home"))
	uassert.Equal(t, 1, PackageCount())
}

// Capturing another project's package path in every explorer that reads this
// index has to be impossible, not merely discouraged.
func TestPublishCannotCaptureAnotherReposPath(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "", "")
	PublishPackage(cross(cur), demoID, "gno.land/r/nym-moultest123/home", "", "", "")

	squatID := eve.String() + "/squat"
	testing.SetRealm(testing.NewUserRealm(eve))
	CreateRepo(cross(cur), squatID, "", "")
	testing.SetRealm(testing.NewUserRealm(eve))
	uassert.AbortsContains(t, cur, "claimed by another repo", func() {
		PublishPackage(cross(cur), squatID, "gno.land/r/nym-moultest123/home", "", "", "")
	})
	uassert.Equal(t, demoID, PackageRepo("gno.land/r/nym-moultest123/home"))
}

func TestPublishNeedsWriteAccess(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "", "")

	testing.SetRealm(testing.NewUserRealm(eve))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		PublishPackage(cross(cur), demoID, "gno.land/r/nym-moultest123/home", "", "", "")
	})
}

func TestReleaseLifecycle(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "", "")

	uassert.Equal(t, 0, ReleaseCount(demoID))
	uassert.Equal(t, "", LatestReleaseTag(demoID))

	testing.SetRealm(testing.NewUserRealm(alice))
	CutRelease(cross(cur), demoID, "v1.0.0", "First", "it works", oid("a"), "", false)
	uassert.Equal(t, 1, ReleaseCount(demoID))
	uassert.Equal(t, "v1.0.0", LatestReleaseTag(demoID))

	// A prerelease is cut later and is still not the latest.
	testing.SetRealm(testing.NewUserRealm(alice))
	CutRelease(cross(cur), demoID, "v2.0.0-rc.1", "", "", "", "", true)
	uassert.Equal(t, "v1.0.0", LatestReleaseTag(demoID))

	// A tag never moves.
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsContains(t, cur, "release already exists", func() {
		CutRelease(cross(cur), demoID, "v1.0.0", "Again", "", oid("b"), "", false)
	})

	// Yanking withdraws it without deleting it: a version that vanished reads
	// as never published rather than as do-not-use.
	testing.SetRealm(testing.NewUserRealm(alice))
	CutRelease(cross(cur), demoID, "v2.0.0", "", "", "", "", false)
	uassert.Equal(t, "v2.0.0", LatestReleaseTag(demoID))
	testing.SetRealm(testing.NewUserRealm(alice))
	YankRelease(cross(cur), demoID, "v2.0.0", "broken migration")
	uassert.Equal(t, "v1.0.0", LatestReleaseTag(demoID))
	uassert.Equal(t, 3, ReleaseCount(demoID), "a yank keeps the release")
}

func TestReleaseNeedsWriteAccess(cur realm, t *testing.T) {
	reset()

	testing.SetRealm(testing.NewUserRealm(alice))
	CreateRepo(cross(cur), demoID, "", "")

	testing.SetRealm(testing.NewUserRealm(eve))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		CutRelease(cross(cur), demoID, "v1.0.0", "", "", "", "", false)
	})
}

// A read against a repo that does not exist answers emptily rather than
// aborting: vm/qeval is how an explorer asks, and a panic there is a 500 the
// caller cannot tell from a broken node.
func TestReadsOnAnUnknownRepoAreEmpty(t *testing.T) {
	reset()

	uassert.Equal(t, "", PackageRepo("gno.land/r/nobody/nothing"))
	uassert.Equal(t, 0, ReleaseCount("nobody/nothing"))
	uassert.Equal(t, "", LatestReleaseTag("nobody/nothing"))
}

render.gno

package forge

import (
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"

	fg "gno.land/p/nym-moultest123/forge/v1"
	"gno.land/p/nym-moultest123/md/v0"
	"gno.land/p/nym-moultest123/realmpath/v0"
	"gno.land/p/nym-moultest123/txlink/v0"
)

// pageSize bounds every listing: a Render that walks unbounded state is a
// Render that eventually stops rendering.
const pageSize = 20

// Render routes gnoweb paths:
//
//	/                          the forge: every repo
//	/<ns>/<name>               repo overview
//	/<ns>/<name>/log           the full reference log (?page=N)
//	/<ns>/<name>/issues        issues (?page=N)
//	/<ns>/<name>/issues/<id>   one issue and its replies
//	/<ns>/<name>/changes       change requests (?page=N)
//	/<ns>/<name>/changes/<id>  one change, its reviews and its replies
//	/help                      what this realm is and how to call it
func Render(path string) string {
	req := realmpath.Parse(path)
	parts := req.PathParts()
	page := pageOf(req)

	switch {
	case len(parts) == 0 || parts[0] == "":
		return renderHome()
	case len(parts) == 1 && parts[0] == "help":
		return renderHelp()
	case len(parts) < 2:
		return notFound("no such page")
	}

	id := parts[0] + "/" + parts[1]
	r := f.Repo(id)
	if r == nil {
		return notFound("no repo " + md.InlineCode(id))
	}
	switch {
	case len(parts) == 2:
		return renderRepo(r)
	case len(parts) == 3 && parts[2] == "log":
		return renderLog(r, page)
	case len(parts) == 3 && parts[2] == "issues":
		return renderIssues(r, page)
	case len(parts) == 3 && parts[2] == "changes":
		return renderChanges(r, page)
	case len(parts) == 4 && parts[2] == "issues":
		return renderIssue(r, parts[3])
	case len(parts) == 4 && parts[2] == "changes":
		return renderChange(r, parts[3])
	}
	return notFound("no such page")
}

func renderHome() string {
	var b strings.Builder
	b.WriteString(md.H1("Forge"))
	b.WriteString("\nAn on-chain software forge. The objects stay in git; the chain keeps the part a forge is trusted for: which object a ref points at, in what order, on whose authority, and what was reviewed before it moved.\n")
	b.WriteString("\n**Repos:** " + strconv.Itoa(f.Size()) + "\n")

	if f.Size() == 0 {
		b.WriteString("\nNothing here yet. " + link("Create the first repo", txlink.Call("CreateRepo")) + "\n")
	} else {
		b.WriteString("\n| repo | refs | issues | changes | log |\n")
		b.WriteString("| --- | ---: | ---: | ---: | ---: |\n")
		f.IterateRepos(0, pageSize, func(r *fg.Repo) bool {
			b.WriteString("| " + link(r.ID, repoURL(r.ID)) + " | " +
				strconv.Itoa(r.RefCount()) + " | " +
				strconv.Itoa(r.OpenIssueCount()) + "/" + strconv.Itoa(r.IssueCount()) + " | " +
				strconv.Itoa(r.OpenChangeCount()) + "/" + strconv.Itoa(r.ChangeCount()) + " | " +
				strconv.Itoa(r.LogSize()) + " |\n")
			return false
		})
	}
	b.WriteString("\n" + link("Create a repo", txlink.Call("CreateRepo")) + " · " +
		link("How it works", base()+":help") + "\n")
	return b.String()
}

func renderRepo(r *fg.Repo) string {
	var b strings.Builder
	b.WriteString(md.H1(r.ID))
	if r.Description != "" {
		b.WriteString("\n" + md.EscapeText(r.Description) + "\n")
	}
	if r.Archived {
		b.WriteString("\n**Archived.** No further writes are accepted.\n")
	}

	facts := []string{
		"**Default ref:** " + md.InlineCode(r.DefaultRef) + " → " + oidCode(refOID(r, r.DefaultRef)),
		"**Merge policy:** " + strconv.Itoa(r.RequiredApprovals) + " writer approval(s), self-approval " + onOff(r.AllowSelfApproval),
		"**Members:** " + strconv.Itoa(r.MemberCount()),
		"**Log head:** " + md.InlineCode(shortDigest(r.LogHead())),
	}
	if r.ParentID != "" {
		facts = append(facts, "**Forked from:** "+link(r.ParentID, repoURL(r.ParentID)))
	}
	if len(r.Mirrors) > 0 {
		facts = append(facts, "**Fetch from:** "+md.InlineCode(r.Mirrors[0])+mirrorRest(r.Mirrors))
	} else {
		facts = append(facts, "**Fetch from:** no mirror declared: the objects are wherever the maintainers keep them")
	}
	b.WriteString("\n" + md.BulletList(facts))

	b.WriteString("\n" + md.H2("Refs"))
	if r.RefCount() == 0 {
		b.WriteString("\nNo ref has ever been recorded.\n")
	} else {
		var refs []string
		r.IterateRefs(func(ref *fg.Ref) bool {
			refs = append(refs, md.InlineCode(ref.Name)+" → "+oidCode(ref.OID)+" · block "+strconv.FormatInt(ref.UpdatedAt, 10)+" · "+userLink(ref.UpdatedBy))
			return false
		})
		b.WriteString("\n" + md.BulletList(refs))
	}

	b.WriteString("\n" + md.H2("Recent log"))
	b.WriteString("\n" + logList(r, 0, 5))
	b.WriteString("\n" + link("Full log, "+strconv.Itoa(r.LogSize())+" entries", repoURL(r.ID)+"/log") + "\n")

	b.WriteString("\n" + md.H2("Open change requests"))
	b.WriteString("\n" + changeList(r, 0, 5, true))
	b.WriteString("\n" + link("All changes, "+strconv.Itoa(r.ChangeCount())+" total", repoURL(r.ID)+"/changes") + " · " +
		link("Propose a change", txlink.Call("OpenChange", "repoID", r.ID)) + "\n")

	b.WriteString("\n" + md.H2("Open issues"))
	b.WriteString("\n" + issueList(r, 0, 5, true))
	b.WriteString("\n" + link("All issues, "+strconv.Itoa(r.IssueCount())+" total", repoURL(r.ID)+"/issues") + " · " +
		link("Open an issue", txlink.Call("OpenIssue", "repoID", r.ID)) + "\n")
	return b.String()
}

func renderLog(r *fg.Repo, page int) string {
	var b strings.Builder
	b.WriteString(md.H1(r.ID + ": reference log"))
	b.WriteString("\nAppend-only and hash-chained: every entry commits to the one before it, so pinning the head digest anywhere off chain pins this whole history.\n")
	b.WriteString("\n**Head:** " + md.InlineCode(shortDigest(r.LogHead())) + " · **Entries:** " + strconv.Itoa(r.LogSize()) + "\n")
	b.WriteString("\n" + logList(r, page*pageSize, pageSize))
	b.WriteString("\n" + pager(r.LogSize(), page, repoURL(r.ID)+"/log"))
	return b.String()
}

func renderIssues(r *fg.Repo, page int) string {
	var b strings.Builder
	b.WriteString(md.H1(r.ID + ": issues"))
	b.WriteString("\n**Open:** " + strconv.Itoa(r.OpenIssueCount()) + " / " + strconv.Itoa(r.IssueCount()) + "\n")
	b.WriteString("\n" + issueList(r, page*pageSize, pageSize, false))
	b.WriteString("\n" + pager(r.IssueCount(), page, repoURL(r.ID)+"/issues"))
	b.WriteString("\n" + link("Open an issue", txlink.Call("OpenIssue", "repoID", r.ID)) + "\n")
	return b.String()
}

func renderIssue(r *fg.Repo, raw string) string {
	id, err := strconv.ParseInt(raw, 10, 64)
	if err != nil {
		return notFound("bad issue id")
	}
	i := r.Issue(id)
	if i == nil {
		return notFound("no issue " + raw)
	}

	var b strings.Builder
	b.WriteString(md.H1("#" + raw + " " + md.EscapeText(i.Title)))
	b.WriteString("\n" + state(i.Open, "open", "closed") + " · opened at block " + strconv.FormatInt(i.CreatedAt, 10) + " by " + userLink(i.Author) + "\n")
	if len(i.Labels) > 0 {
		b.WriteString("\n**Labels:** " + codeList(i.Labels) + "\n")
	}
	if i.Body != "" {
		b.WriteString("\n" + md.EscapeText(i.Body) + "\n")
	}
	b.WriteString("\n" + md.H2("Replies ("+strconv.Itoa(i.CommentCount())+")"))
	if i.CommentCount() == 0 {
		b.WriteString("\nNone yet.\n")
	} else {
		var items []string
		i.IterateComments(0, pageSize, func(c *fg.Comment) bool {
			items = append(items, userLink(c.Author)+" at block "+strconv.FormatInt(c.CreatedAt, 10)+": "+md.EscapeText(c.Body))
			return false
		})
		b.WriteString("\n" + md.BulletList(items))
	}
	b.WriteString("\n" + link("Reply", txlink.Call("CommentIssue", "repoID", r.ID, "issueID", raw)) + " · " +
		link("Close", txlink.Call("CloseIssue", "repoID", r.ID, "issueID", raw)) + " · " +
		link("Back to issues", repoURL(r.ID)+"/issues") + "\n")
	return b.String()
}

func renderChanges(r *fg.Repo, page int) string {
	var b strings.Builder
	b.WriteString(md.H1(r.ID + ": change requests"))
	b.WriteString("\n**Open:** " + strconv.Itoa(r.OpenChangeCount()) + " / " + strconv.Itoa(r.ChangeCount()) + "\n")
	b.WriteString("\n" + changeList(r, page*pageSize, pageSize, false))
	b.WriteString("\n" + pager(r.ChangeCount(), page, repoURL(r.ID)+"/changes"))
	b.WriteString("\n" + link("Propose a change", txlink.Call("OpenChange", "repoID", r.ID)) + "\n")
	return b.String()
}

func renderChange(r *fg.Repo, raw string) string {
	id, err := strconv.ParseInt(raw, 10, 64)
	if err != nil {
		return notFound("bad change id")
	}
	c := r.Change(id)
	if c == nil {
		return notFound("no change " + raw)
	}

	var b strings.Builder
	b.WriteString(md.H1("!" + raw + " " + md.EscapeText(c.Title)))
	b.WriteString("\n**" + c.State + "** · opened at block " + strconv.FormatInt(c.CreatedAt, 10) + " by " + userLink(c.Author) + "\n")

	src := "this repo"
	if c.SourceRepo != "" {
		src = md.InlineCode(c.SourceRepo)
	}
	facts := []string{
		"**Head:** " + oidCode(c.HeadOID) + " (from " + src + refSuffix(c.SourceRef) + ")",
		"**Target:** " + md.InlineCode(c.TargetRef) + " → " + oidCode(refOID(r, c.TargetRef)),
		"**Approvals:** " + strconv.Itoa(r.CountApprovals(c)) + " of " + strconv.Itoa(r.RequiredApprovals) + " required",
		"**Blocking:** " + strconv.Itoa(r.CountBlocking(c)),
	}
	if c.State == fg.StateMerged {
		facts = append(facts, "**Merged:** "+oidCode(c.MergedOID)+" at block "+strconv.FormatInt(c.MergedAt, 10)+" by "+userLink(c.MergedBy))
	}
	b.WriteString("\n" + md.BulletList(facts))
	if c.Body != "" {
		b.WriteString("\n" + md.EscapeText(c.Body) + "\n")
	}

	b.WriteString("\n" + md.H2("Reviews ("+strconv.Itoa(c.ReviewCount())+")"))
	if c.ReviewCount() == 0 {
		b.WriteString("\nNone yet.\n")
	} else {
		var items []string
		c.IterateReviews(func(rv *fg.Review) bool {
			line := userLink(rv.Reviewer) + ": **" + rv.Verdict + "** on " + oidCode(rv.OID)
			if c.Stale(rv) {
				line += " (stale: the head moved since)"
			}
			if rv.Body != "" {
				line += ": " + md.EscapeText(rv.Body)
			}
			items = append(items, line)
			return false
		})
		b.WriteString("\n" + md.BulletList(items))
	}

	b.WriteString("\n" + md.H2("Replies ("+strconv.Itoa(c.CommentCount())+")"))
	if c.CommentCount() == 0 {
		b.WriteString("\nNone yet.\n")
	} else {
		var items []string
		c.IterateComments(0, pageSize, func(cm *fg.Comment) bool {
			items = append(items, userLink(cm.Author)+" at block "+strconv.FormatInt(cm.CreatedAt, 10)+": "+md.EscapeText(cm.Body))
			return false
		})
		b.WriteString("\n" + md.BulletList(items))
	}

	b.WriteString("\n" + link("Review", txlink.Call("ReviewChange", "repoID", r.ID, "changeID", raw, "verdict", "approve")) + " · " +
		link("Reply", txlink.Call("CommentChange", "repoID", r.ID, "changeID", raw)) + " · " +
		link("Merge", txlink.Call("MergeChange", "repoID", r.ID, "changeID", raw, "expectedTargetOID", refOID(r, c.TargetRef))) + " · " +
		link("Back to changes", repoURL(r.ID)+"/changes") + "\n")
	return b.String()
}

func renderHelp() string {
	return md.H1("Forge: how it works") + `
A forge is trusted for three things git does not do by itself: saying which
object a branch points at, saying who may move it, and recording that a human
reviewed the move. Those three are what lives here. The objects do not: they
stay in git, behind whatever mirror the repo declares.

## The reference log

Every ref move is one entry in an append-only, hash-chained log. An entry names
the ref, the object it left, the object it reached, the actor, the block and the
kind: create, update, force, delete or merge: and commits to the digest of the
entry before it. Pin the head digest anywhere off chain and the entire history
becomes falsifiable.

Moves are compare-and-swap: the caller states the tip it expected, and a stale
expectation aborts instead of overwriting. That is git's --force-with-lease,
except the lease is held by consensus rather than by the server you push to. A
move that skips the discipline is not forbidden, it is recorded as a force.

The chain has no objects, so it cannot check that a new tip descends from the
old one. It does not pretend to. Ordering, attribution and policy are on chain;
ancestry is verified by a client that has the repo.

## Namespaces

A repo id is "namespace/name". A namespace is either a name you hold in
r/sys/users or your own address, so "g1.../forge" works with nothing registered
and "moul/forge" needs the name. Nobody can claim a namespace they do not own,
and a realm passes the same test a user does, by its address.

## Roles

reader < writer < maintainer < admin < owner. Writers move refs, maintainers
force and merge, admins manage members and policy. A role can be held by
another realm, so a repo owned by a DAO is a repo whose merge button is a vote.

## Reviews

Anyone may open an issue or a change request, and anyone may review one: the
spam gate is that you pay for your own bytes. Only a writer's approval counts
toward the merge policy, and an approval names the object it reviewed: push a
new head and it stops counting, with nothing to remember to dismiss.

## Calling it

` + md.CodeBlock(`gnokey maketx call -pkgpath gno.land/r/nym-moultest123/forge/v0 \
  -func SetRef -send "" -gas-fee 30000ugnot -gas-wanted 3000000 \
  -args "moul/forge" -args "refs/heads/main" \
  -args "<expected-oid>" -args "<new-oid>" -args "ship it" \
  -broadcast -chainid <chain> -remote <rpc> <key>`) + `
Read paths are free: ` + md.InlineCode("vm/qeval") + ` on ` + md.InlineCode("RefOID") + `, ` +
		md.InlineCode("LogHead") + ` or ` + md.InlineCode("HasRepo") + `, or just browse the routes above.
`
}

// ---------------------------------------------------------------------------
// Fragments
// ---------------------------------------------------------------------------

func logList(r *fg.Repo, offset, count int) string {
	if r.LogSize() == 0 {
		return "No entry yet.\n"
	}
	var items []string
	r.IterateLogReverse(offset, count, func(e *fg.LogEntry) bool {
		line := "`#" + strconv.FormatInt(e.Seq, 10) + "` **" + e.Kind + "** " + md.InlineCode(e.Ref) + " " +
			oidCode(e.OldOID) + " → " + oidCode(e.NewOID) +
			" · block " + strconv.FormatInt(e.Height, 10) + " · " + userLink(e.Actor)
		if e.Kind == fg.KindMerge {
			line += " · change " + link("!"+strconv.FormatInt(e.ChangeID, 10), changeURL(r.ID, e.ChangeID))
		}
		if e.Note != "" {
			line += " · " + md.EscapeText(e.Note)
		}
		items = append(items, line)
		return false
	})
	if len(items) == 0 {
		return "Nothing on this page.\n"
	}
	return md.BulletList(items)
}

func issueList(r *fg.Repo, offset, count int, openOnly bool) string {
	var items []string
	r.IterateIssues(offset, count, func(i *fg.Issue) bool {
		if openOnly && !i.Open {
			return false
		}
		items = append(items, link("#"+strconv.FormatInt(i.ID, 10)+" "+i.Title, issueURL(r.ID, i.ID))+
			" · "+state(i.Open, "open", "closed")+" · "+userLink(i.Author)+
			" · "+strconv.Itoa(i.CommentCount())+" replies")
		return false
	})
	if len(items) == 0 {
		return "None.\n"
	}
	return md.BulletList(items)
}

func changeList(r *fg.Repo, offset, count int, openOnly bool) string {
	var items []string
	r.IterateChanges(offset, count, func(c *fg.Change) bool {
		if openOnly && c.State != fg.StateOpen {
			return false
		}
		items = append(items, link("!"+strconv.FormatInt(c.ID, 10)+" "+c.Title, changeURL(r.ID, c.ID))+
			" · **"+c.State+"** · "+md.InlineCode(c.TargetRef)+
			" · "+strconv.Itoa(r.CountApprovals(c))+"/"+strconv.Itoa(r.RequiredApprovals)+" approvals")
		return false
	})
	if len(items) == 0 {
		return "None.\n"
	}
	return md.BulletList(items)
}

func pager(total, page int, path string) string {
	if total <= pageSize {
		return ""
	}
	out := "Page " + strconv.Itoa(page+1) + " of " + strconv.Itoa((total+pageSize-1)/pageSize) + " · "
	if page > 0 {
		out += link("previous", path+"?page="+strconv.Itoa(page)) + " "
	}
	if (page+1)*pageSize < total {
		out += link("next", path+"?page="+strconv.Itoa(page+2))
	}
	return out + "\n"
}

// ---------------------------------------------------------------------------
// Small helpers
// ---------------------------------------------------------------------------

func base() string {
	return strings.TrimPrefix(unsafe.CurrentRealm().PkgPath(), runtime.ChainDomain())
}

func repoURL(id string) string { return base() + ":" + id }

func issueURL(id string, n int64) string {
	return repoURL(id) + "/issues/" + strconv.FormatInt(n, 10)
}

func changeURL(id string, n int64) string {
	return repoURL(id) + "/changes/" + strconv.FormatInt(n, 10)
}

// link builds a markdown link. Internal targets are realm paths this file
// built, so only the text needs escaping.
func link(text, url string) string { return "[" + md.EscapeText(text) + "](" + url + ")" }

func userLink(a address) string {
	if l := md.UserLink(a.String()); l != "" {
		return l
	}
	return md.InlineCode(a.String())
}

func notFound(why string) string {
	return md.H1("Not found") + "\n" + why + ".\n\n" + link("Back to the forge", base()) + "\n"
}

func state(ok bool, yes, no string) string {
	if ok {
		return "**" + yes + "**"
	}
	return "**" + no + "**"
}

func onOff(b bool) string {
	if b {
		return "allowed"
	}
	return "off"
}

func refOID(r *fg.Repo, name string) string {
	if ref := r.Ref(name); ref != nil {
		return ref.OID
	}
	return ""
}

// oidCode shows the short object id, code-spanned. An empty id renders as
// "(none)": that is a ref being created or deleted, not a zero object.
func oidCode(oid string) string {
	if oid == "" {
		return "(none)"
	}
	if len(oid) > 12 {
		return md.InlineCode(oid[:12])
	}
	return md.InlineCode(oid)
}

func shortDigest(d string) string {
	if d == "" {
		return "(empty log)"
	}
	if len(d) > 16 {
		return d[:16]
	}
	return d
}

func mirrorRest(mirrors []string) string {
	if len(mirrors) < 2 {
		return ""
	}
	return " (+" + strconv.Itoa(len(mirrors)-1) + " more)"
}

func refSuffix(ref string) string {
	if ref == "" {
		return ""
	}
	return " " + md.InlineCode(ref)
}

func codeList(items []string) string {
	out := ""
	for i, it := range items {
		if i > 0 {
			out += " "
		}
		out += md.InlineCode(it)
	}
	return out
}

func pageOf(req *realmpath.Request) int {
	n, err := strconv.Atoi(req.Query.Get("page"))
	if err != nil || n < 1 {
		return 0
	}
	return n - 1
}

func itoa(n int64) string { return strconv.FormatInt(n, 10) }

// btoa renders a bool for an event value: chain.Emit takes strings only.
func btoa(b bool) string {
	if b {
		return "true"
	}
	return "false"
}

render_test.gno

package forge

// Every route is pinned by an example: a realm's Render is its whole public
// surface, and output that varies between identical calls is a consensus bug.
// Examples run after every Test, so each one re-seeds the state it renders.

// ExampleRender pins the forge home page.
func ExampleRender() {
	seedFixture()
	print(Render(""))
	// Output:
	// # Forge
	//
	// An on-chain software forge. The objects stay in git; the chain keeps the part a forge is trusted for: which object a ref points at, in what order, on whose authority, and what was reviewed before it moved.
	//
	// **Repos:** 1
	//
	// | repo | refs | issues | changes | log |
	// | --- | ---: | ---: | ---: | ---: |
	// | [moul/forge](/r/nym-moultest123/forge/v0:moul/forge) | 1 | 1/1 | 1/1 | 2 |
	//
	// [Create a repo](/r/nym-moultest123/forge/v0$help&func=CreateRepo) · [How it works](/r/nym-moultest123/forge/v0:help)
}

// ExampleRenderRepo pins a repo overview.
func ExampleRenderRepo() {
	seedFixture()
	print(Render("moul/forge"))
	// Output:
	// # moul/forge
	//
	// an on chain software forge
	//
	// - **Default ref:** `refs/heads/main` → `bbbbbbbbbbbb`
	// - **Merge policy:** 1 writer approval(s), self-approval off
	// - **Members:** 3
	// - **Log head:** `07ca3613cc68e1dc`
	// - **Fetch from:** `https://github.com/moul/gno-contracts.git`
	//
	// ## Refs
	//
	// - `refs/heads/main` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94)
	//
	// ## Recent log
	//
	// - `#1` **update** `refs/heads/main` `aaaaaaaaaaaa` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · add the log
	// - `#0` **create** `refs/heads/main` (none) → `aaaaaaaaaaaa` · block 101 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · initial import
	//
	// [Full log, 2 entries](/r/nym-moultest123/forge/v0:moul/forge/log)
	//
	// ## Open change requests
	//
	// - [\!0 record every ref move](/r/nym-moultest123/forge/v0:moul/forge/changes/0) · **open** · `refs/heads/main` · 1/1 approvals
	//
	// [All changes, 1 total](/r/nym-moultest123/forge/v0:moul/forge/changes) · [Propose a change](/r/nym-moultest123/forge/v0$help&func=OpenChange&repoID=moul%2Fforge)
	//
	// ## Open issues
	//
	// - [\#0 force pushes are invisible](/r/nym-moultest123/forge/v0:moul/forge/issues/0) · **open** · [g1v4mx2h6lta047h6lta047h6lta047h6lslgc76](/u/g1v4mx2h6lta047h6lta047h6lta047h6lslgc76) · 1 replies
	//
	// [All issues, 1 total](/r/nym-moultest123/forge/v0:moul/forge/issues) · [Open an issue](/r/nym-moultest123/forge/v0$help&func=OpenIssue&repoID=moul%2Fforge)
}

// ExampleRenderLog pins the reference log.
func ExampleRenderLog() {
	seedFixture()
	print(Render("moul/forge/log"))
	// Output:
	// # moul/forge: reference log
	//
	// Append-only and hash-chained: every entry commits to the one before it, so pinning the head digest anywhere off chain pins this whole history.
	//
	// **Head:** `07ca3613cc68e1dc` · **Entries:** 2
	//
	// - `#1` **update** `refs/heads/main` `aaaaaaaaaaaa` → `bbbbbbbbbbbb` · block 102 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · add the log
	// - `#0` **create** `refs/heads/main` (none) → `aaaaaaaaaaaa` · block 101 · [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94) · initial import
}

// ExampleRenderIssue pins one issue.
func ExampleRenderIssue() {
	seedFixture()
	print(Render("moul/forge/issues/0"))
	// Output:
	// # #0 force pushes are invisible
	//
	// **open** · opened at block 103 by [g1v4mx2h6lta047h6lta047h6lta047h6lslgc76](/u/g1v4mx2h6lta047h6lta047h6lta047h6lslgc76)
	//
	// **Labels:** `bug`
	//
	// A maintainer can rewrite a branch and nothing records it\.
	//
	// ## Replies (1)
	//
	// - [g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu](/u/g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu) at block 104: that is what the log is for
	//
	// [Reply](/r/nym-moultest123/forge/v0$help&func=CommentIssue&issueID=0&repoID=moul%2Fforge) · [Close](/r/nym-moultest123/forge/v0$help&func=CloseIssue&issueID=0&repoID=moul%2Fforge) · [Back to issues](/r/nym-moultest123/forge/v0:moul/forge/issues)
}

// ExampleRenderChange pins one change request.
func ExampleRenderChange() {
	seedFixture()
	print(Render("moul/forge/changes/0"))
	// Output:
	// # !0 record every ref move
	//
	// **open** · opened at block 105 by [g1vdshymmvta047h6lta047h6lta047h6l2asz94](/u/g1vdshymmvta047h6lta047h6lta047h6l2asz94)
	//
	// - **Head:** `cccccccccccc` (from this repo `refs/heads/feat`)
	// - **Target:** `refs/heads/main` → `bbbbbbbbbbbb`
	// - **Approvals:** 1 of 1 required
	// - **Blocking:** 0
	//
	// closes 0
	//
	// ## Reviews (1)
	//
	// - [g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu](/u/g1vfhkyh6lta047h6lta047h6lta047h6l03vdhu): **approve** on `cccccccccccc`: lgtm
	//
	// ## Replies (0)
	//
	// None yet.
	//
	// [Review](/r/nym-moultest123/forge/v0$help&func=ReviewChange&changeID=0&repoID=moul%2Fforge&verdict=approve) · [Reply](/r/nym-moultest123/forge/v0$help&func=CommentChange&changeID=0&repoID=moul%2Fforge) · [Merge](/r/nym-moultest123/forge/v0$help&func=MergeChange&changeID=0&expectedTargetOID=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb&repoID=moul%2Fforge) · [Back to changes](/r/nym-moultest123/forge/v0:moul/forge/changes)
}

// ExampleRenderNotFound pins an unknown repo.
func ExampleRenderNotFound() {
	seedFixture()
	print(Render("moul/nope"))
	// Output:
	// # Not found
	//
	// no repo `moul/nope`.
	//
	// [Back to the forge](/r/nym-moultest123/forge/v0)
}