Skip to content Search Apps Documentation Source Content 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.

mdtable.gno

1.60 Kb · 66 lines
 1// Package mdtable provides a simple way to create Markdown tables.
 2//
 3// Example usage:
 4//
 5//	import "gno.land/p/moul/mdtable/v0"
 6//
 7//	func Render(path string) string {
 8//	    table := mdtable.Table{
 9//	        Headers: []string{"ID", "Title", "Status", "Date"},
10//	    }
11//	    table.Append([]string{"#1", "Add a new validator", "succeed", "2024-01-01"})
12//	    table.Append([]string{"#2", "Change parameter", "timed out", "2024-01-02"})
13//	    return table.String()
14//	}
15//
16// Output:
17//
18//	| ID | Title | Status | Date |
19//	| --- | --- | --- | --- |
20//	| #1 | Add a new validator | succeed | 2024-01-01 |
21//	| #2 | Change parameter | timed out | 2024-01-02 |
22package mdtable
23
24import (
25	"strings"
26)
27
28type Table struct {
29	Headers []string
30	Rows    [][]string
31	// XXX: optional headers alignment.
32}
33
34func (t *Table) Append(row []string) {
35	t.Rows = append(t.Rows, row)
36}
37
38func (t Table) String() string {
39	// XXX: switch to using text/tabwriter when porting to Gno to support
40	// better-formatted raw Markdown output.
41
42	if len(t.Headers) == 0 && len(t.Rows) == 0 {
43		return ""
44	}
45
46	var sb strings.Builder
47
48	if len(t.Headers) == 0 {
49		t.Headers = make([]string, len(t.Rows[0]))
50	}
51
52	// Print header.
53	sb.WriteString("| " + strings.Join(t.Headers, " | ") + " |\n")
54	sb.WriteString("|" + strings.Repeat(" --- |", len(t.Headers)) + "\n")
55
56	// Print rows.
57	for _, row := range t.Rows {
58		escapedRow := make([]string, len(row))
59		for i, cell := range row {
60			escapedRow[i] = strings.ReplaceAll(cell, "|", "|") // Escape pipe characters.
61		}
62		sb.WriteString("| " + strings.Join(escapedRow, " | ") + " |\n")
63	}
64
65	return sb.String()
66}