Skip to content
nao1215Public

About

simple markdown & mermaid builder in golang

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

146 stars

Watchers

2 watching

Forks

Latest commit

 

History

338 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

All Contributors

CI Coverage Gitleaks Trivy govulncheck Gosec reviewdog Go Reference License OpenSSF Scorecard Mentioned in Awesome Go

markdown

markdown is a Go package that builds GitHub Markdown with method chaining instead of a template engine like html/template. It writes headings, lists, checkbox lists, tables, code blocks, blockquotes, horizontal rules, text formatting, links, images, details, footnotes, math expressions and alerts, plus 24 kinds of mermaid diagram, status badges, and an index for a directory of markdown files.

The library stays small on purpose, so features that add a lot of complexity, such as nested lists, will not be added. Every exported function has a runnable example on pkg.go.dev.

Install

Linux, macOS and Windows, Go 1.26 or later.

go get github.com/nao1215/markdown

Basic usage

package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

func main() {
	md.NewMarkdown(os.Stdout, md.WithBlockSpacing()).
		H1("This is H1").
		PlainText("This is plain text").
		H2f("This is %s with text format", "H2").
		PlainTextf("Text formatting, such as %s and %s, %s styles.",
			md.Bold("bold"), md.Italic("italic"), md.Code("code")).
		H2("Code Block").
		CodeBlocks(md.SyntaxHighlightGo,
			`package main
import "fmt"

func main() {
	fmt.Println("Hello, World!")
}`).
		H2("List").
		BulletList("Bullet Item 1", "Bullet Item 2", "Bullet Item 3").
		OrderedList("Ordered Item 1", "Ordered Item 2", "Ordered Item 3").
		H2("CheckBox").
		CheckBox([]md.CheckBoxSet{
			{Checked: false, Text: md.Code("sample code")},
			{Checked: true, Text: md.Link("Go", "https://golang.org")},
			{Checked: false, Text: md.Strikethrough("strikethrough")},
		}).
		H2("Blockquote").
		Blockquote("If you can dream it, you can do it.").
		H3("Horizontal Rule").
		HorizontalRule().
		H2("Table").
		Table(md.TableSet{
			Header: []string{"Name", "Age", "Country"},
			Rows: [][]string{
				{"David", "23", "USA"},
				{"John", "30", "UK"},
				{"Bob", "25", "Canada"},
			},
		}).
		H2("Image").
		PlainTextf(md.Image("sample_image", "./sample.png")).
		Build()
}

Output: Output:

# This is H1

This is plain text

## This is H2 with text format

Text formatting, such as **bold** and *italic*, `code` styles.

## Code Block

```go
package main
import "fmt"

func main() {
	fmt.Println("Hello, World!")
}
```

## List

- Bullet Item 1
- Bullet Item 2
- Bullet Item 3

1. Ordered Item 1
2. Ordered Item 2
3. Ordered Item 3

## CheckBox

- [ ] `sample code`
- [x] [Go](https://golang.org)
- [ ] ~~strikethrough~~

## Blockquote

> If you can dream it, you can do it.

### Horizontal Rule

---

## Table

| Name | Age | Country |
|---------|---------|---------|
| David | 23 | USA |
| John | 30 | UK |
| Bob | 25 | Canada |

## Image

![sample_image](./sample.png)

The rendered result is in doc/generated_example.md.

Generate Markdown with go generate

Put the builder in a main.go with a //go:generate line, then run go generate ./....

Code example:

package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

//go:generate go run main.go

func main() {
	f, err := os.Create("generated.md")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	md.NewMarkdown(f).
		H1("go generate example").
		PlainText("This markdown is generated by `go generate`").
		Build()
}
go generate ./...

Output:

# go generate example
This markdown is generated by `go generate`

Alerts and status badges

Code example:

	md.NewMarkdown(f).
		H1("Alert example").
		Note("This is note").LF().
		Tip("This is tip").LF().
		Important("This is important").LF().
		Warning("This is warning").LF().
		Caution("This is caution").LF().
		Build()

Output:

# Alert example
> [!NOTE]  
> This is note
  
> [!TIP]  
> This is tip
  
> [!IMPORTANT]  
> This is important
  
> [!WARNING]  
> This is warning
  
> [!CAUTION]  
> This is caution

Code example:

	md.NewMarkdown(os.Stdout).
		H1("badge example").
		RedBadge("red_badge").
		YellowBadge("yellow_badge").
		GreenBadge("green_badge").
		BlueBadge("blue_badge").
		Build()

Output:

# badge example
![Badge](https://img.shields.io/badge/red_badge-red)
![Badge](https://img.shields.io/badge/yellow_badge-yellow)
![Badge](https://img.shields.io/badge/green_badge-green)
![Badge](https://img.shields.io/badge/blue_badge-blue)

Mermaid diagrams

Each diagram type has its own builder package. The builder returns the diagram as a string, which you put in a mermaid code block:

package main

import (
	"io"
	"os"

	"github.com/nao1215/markdown"
	"github.com/nao1215/markdown/mermaid/sequence"
)

//go:generate go run main.go

func main() {
	diagram := sequence.NewDiagram(io.Discard).
		Participant("Sophia").
		Participant("David").
		Participant("Subaru").
		LF().
		SyncRequest("Sophia", "David", "Please wake up Subaru").
		SyncResponse("David", "Sophia", "OK").
		LF().
		LoopStart("until Subaru wake up").
		SyncRequest("David", "Subaru", "Wake up!").
		SyncResponse("Subaru", "David", "zzz").
		SyncRequest("David", "Subaru", "Hey!!!").
		BreakStart("if Subaru wake up").
		SyncResponse("Subaru", "David", "......").
		BreakEnd().
		LoopEnd().
		LF().
		SyncResponse("David", "Sophia", "wake up, wake up").
		String()

	markdown.NewMarkdown(os.Stdout, markdown.WithBlockSpacing()).
		H2("Sequence Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build()
}

Plain text output: markdown is here

## Sequence Diagram

```mermaid
sequenceDiagram
    participant Sophia
    participant David
    participant Subaru

    Sophia->>David: Please wake up Subaru
    David-->>Sophia: OK

    loop until Subaru wake up
    David->>Subaru: Wake up!
    Subaru-->>David: zzz
    David->>Subaru: Hey!!!
    break if Subaru wake up
    Subaru-->>David: ......
    end
    end

    David-->>Sophia: wake up, wake up
```

Mermaid output:

sequenceDiagram
    participant Sophia
    participant David
    participant Subaru

    Sophia->>David: Please wake up Subaru
    David-->>Sophia: OK

    loop until Subaru wake up
    David->>Subaru: Wake up!
    Subaru-->>David: zzz
    David->>Subaru: Hey!!!
    break if Subaru wake up
    Subaru-->>David: ......
    end
    end

    David-->>Sophia: wake up, wake up
Loading

The other diagram types work the same way. Each has a generator under doc/ and the document it writes:

Diagram Package Code Output
Sequence diagram mermaid/sequence main.go generated.md
User journey mermaid/userjourney main.go generated.md
Git graph mermaid/gitgraph main.go generated.md
Mindmap mermaid/mindmap main.go generated.md
Requirement diagram mermaid/requirement main.go generated.md
XY chart mermaid/xychart main.go generated.md
Packet mermaid/packet main.go generated.md
Block diagram mermaid/block main.go generated.md
Kanban mermaid/kanban main.go generated.md
Entity relationship diagram mermaid/er main.go generated.md
Flowchart mermaid/flowchart main.go generated.md
Pie chart mermaid/piechart main.go generated.md
Architecture (mermaid beta) mermaid/arch main.go generated.md
State diagram mermaid/state main.go generated.md
Class diagram mermaid/class main.go generated.md
Quadrant chart mermaid/quadrant main.go generated.md
Gantt chart mermaid/gantt main.go generated.md
Timeline mermaid/timeline main.go generated.md
Sankey mermaid/sankey main.go generated.md
Radar mermaid/radar main.go generated.md
Treemap mermaid/treemap main.go generated.md
C4 context mermaid/c4 main.go generated.md
Venn mermaid/venn main.go generated.md
Wardley map mermaid/wardley main.go generated.md

Write GitHub Actions job summaries

Inside a GitHub Actions step, the file named by GITHUB_STEP_SUMMARY is rendered on the run's summary page as GitHub Flavored Markdown, mermaid diagrams included, so a Go tool in CI can report with tables, alerts and charts:

package main

import (
	"io"
	"os"

	"github.com/nao1215/markdown"
	"github.com/nao1215/markdown/mermaid/piechart"
)

func main() {
	// Inside a step, append to the summary the runner renders; outside one,
	// write a local file.
	path := os.Getenv("GITHUB_STEP_SUMMARY")
	flags := os.O_APPEND | os.O_CREATE | os.O_WRONLY
	if path == "" {
		path = "generated.md"
		flags = os.O_TRUNC | os.O_CREATE | os.O_WRONLY
	}
	f, err := os.OpenFile(path, flags, 0o600)
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := f.Close(); err != nil {
			panic(err)
		}
	}()

	coverage := piechart.NewPieChart(
		io.Discard,
		piechart.WithTitle("Coverage"),
		piechart.WithShowData(true),
	).
		LabelAndIntValue("covered", 92).
		LabelAndIntValue("uncovered", 8).
		String()

	err = markdown.NewMarkdown(f, markdown.WithBlockSpacing()).
		H2("Test Results").
		Table(markdown.TableSet{
			Header: []string{"Package", "Passed", "Failed"},
			Rows: [][]string{
				{"api", "120", "0"},
				{"core", "89", "2"},
			},
		}).
		Warning("2 tests failed in core; see the failed step for logs.").
		CodeBlocks(markdown.SyntaxHighlightMermaid, coverage).
		Build()

	if err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Test Results

| Package | Passed | Failed |
|---------|---------|---------|
| api | 120 | 0 |
| core | 89 | 2 |

> [!WARNING]  
> 2 tests failed in core; see the failed step for logs.

```mermaid
%%{init: {"pie": {"textPosition": 0.75}, "themeVariables": {"pieOuterStrokeWidth": "5px"}} }%%
pie showData
    title Coverage
    "covered" : 92
    "uncovered" : 8
```

Create an index for a directory of markdown files

GenerateIndex writes an index of every Markdown file under a directory. It was written for the documents nao1215/spectest produces. Given this tree:

testdata
├── abc
│   ├── dummy.txt
│   ├── jkl
│   │   └── text.md
│   └── test.md
├── def
│   ├── test.md
│   └── test2.md
├── expected
│   └── index.md
├── ghi
└── test.md

this call:

		if err := GenerateIndex(
			"testdata", // target directory that contains markdown files
			WithTitle("Test Title"), // title of index markdown
			WithDescription([]string{"Test Description", "Next Description"}), // description of index markdown
		); err != nil {
			panic(err)
		}

writes testdata/index.md (change the destination with WithWriter()). Each link is named after the first H1 or H2 in the target file, or the file name when it has neither.

Output:

## Test Title
Test Description
  
Next Description
  
### testdata
- [test.md](test.md)
  
### abc
- [h2 is here](abc/test.md)
  
### jkl
- [text.md](abc/jkl/text.md)
  
### def
- [h2 is first, not h1](def/test.md)
- [h1 is here](def/test2.md)
  
### expected
- [Test Title](expected/index.md)

Verifying releases

Since v1.1.3, each GitHub Release has a source archive (markdown-<tag>.tar.gz), checksums.txt, a keyless cosign signature of it (checksums.txt.sigstore.json) and the build provenance of the archive (markdown-<tag>.intoto.jsonl). Download them from the release page (replace <tag> with the release tag), then verify:

gh attestation verify markdown-<tag>.tar.gz --repo nao1215/markdown \
  --bundle markdown-<tag>.intoto.jsonl

cosign verify-blob --bundle checksums.txt.sigstore.json \
  --certificate-identity-regexp '^https://github\.com/nao1215/markdown/\.github/workflows/release\.yml@refs/tags/v' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  checksums.txt

sha256sum --check checksums.txt

Testing

Technique Bug class caught here
Unit tests and godoc examples Wrong bytes from a builder method, on Linux, macOS and Windows
Golden files Unintended changes to a whole generated document
Parsing the output back Output that reads fine but renders as something else: a table that loses a column, a list that swallows a paragraph
Property-based tests Escaped tables, lists, headings and code blocks that do not keep their shape for some input
Metamorphic tests Blocks that merge or change kind depending on WithBlockSpacing
Fuzzing Escaping, anchors and fences that break on arbitrary text
Mutation testing Tests that run changed code without checking its result
Mermaid render check Diagrams that the real mermaid renderer rejects or draws differently

The commands and CI jobs for each are in doc/testing.md.

License

MIT License

Contribution

See CONTRIBUTING.md. Bug reports, feature requests and GitHub Stars all help.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

💻
Karthik Sundari
Karthik Sundari

💻 🤔
Avihuc
Avihuc

💻
Clarance Liberiste Ntwari
Clarance Liberiste Ntwari

💻
Amitai Frey
Amitai Frey

💻
William Poussier
William Poussier

🤔
Shubham Hibare
Shubham Hibare

🐛
Barry Morrison
Barry Morrison

🤔
chaunsin
chaunsin

🤔
EvilBit Labs LLC
EvilBit Labs LLC

💵
UncleSp1d3r
UncleSp1d3r

💵
Add your contributions

This project follows the all-contributors specification. Contributions of any kind are welcome, and that includes bug reports and feature requests: several of the features above exist because someone opened an issue asking for them.

About

simple markdown & mermaid builder in golang

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

146 stars

Watchers

2 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages