summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 17:16:31 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-16 17:16:31 +0000
commitd6f5caf5a403c3ad1093eacf38d83bcc6ec4d9fe (patch)
treebbac8b4d0fd6fe162585a6d25294664f2a517f05
parentInitial commit. (diff)
downloadgo-md2man-v2-d6f5caf5a403c3ad1093eacf38d83bcc6ec4d9fe.tar.xz
go-md2man-v2-d6f5caf5a403c3ad1093eacf38d83bcc6ec4d9fe.zip
Adding upstream version 2.0.4.upstream/2.0.4upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
-rw-r--r--.github/dependabot.yml10
-rw-r--r--.github/workflows/test.yml38
-rw-r--r--.gitignore2
-rw-r--r--.golangci.yml6
-rw-r--r--Dockerfile14
-rw-r--r--LICENSE.md21
-rw-r--r--Makefile49
-rw-r--r--README.md15
-rw-r--r--go-md2man.1.md28
-rw-r--r--go.mod5
-rw-r--r--go.sum2
-rw-r--r--md2man.go53
-rw-r--r--md2man/md2man.go16
-rw-r--r--md2man/roff.go382
-rw-r--r--md2man/roff_test.go480
15 files changed, 1121 insertions, 0 deletions
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..77b7be5
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,10 @@
+version: 2
+updates:
+- package-ecosystem: gomod
+ directory: /
+ schedule:
+ interval: weekly
+- package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..5eddd07
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,38 @@
+name: CI
+
+on:
+ push:
+ branches: [master]
+ pull_request:
+ branches: [master]
+
+jobs:
+ test:
+ name: Build
+ strategy:
+ matrix:
+ go-version: [1.18.x, 1.19.x, 1.20.x, 1.21.x]
+ platform: [ubuntu-20.04]
+ runs-on: ${{ matrix.platform }}
+ steps:
+ - name: Install Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: ${{ matrix.go-version }}
+
+ - name: Check out code into the Go module directory
+ uses: actions/checkout@v4
+
+ - name: Build
+ run: make build
+
+ - name: Test
+ run: make test
+
+ lint:
+ runs-on: ubuntu-20.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: golangci/golangci-lint-action@v4.0.0
+ with:
+ version: v1.55
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..30f97c3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+go-md2man
+bin
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..71f073f
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,6 @@
+# For documentation, see https://golangci-lint.run/usage/configuration/
+
+linters:
+ enable:
+ - gofumpt
+
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..b9fc4df
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,14 @@
+ARG GO_VERSION=1.21
+
+FROM --platform=${BUILDPLATFORM} golang:${GO_VERSION} AS build
+COPY . /go/src/github.com/cpuguy83/go-md2man
+WORKDIR /go/src/github.com/cpuguy83/go-md2man
+ARG TARGETOS TARGETARCH TARGETVARIANT
+RUN \
+ --mount=type=cache,target=/go/pkg/mod \
+ --mount=type=cache,target=/root/.cache/go-build \
+ make build
+
+FROM scratch
+COPY --from=build /go/src/github.com/cpuguy83/go-md2man/bin/go-md2man /go-md2man
+ENTRYPOINT ["/go-md2man"]
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..1cade6c
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Brian Goff
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..5f4a423
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,49 @@
+GO111MODULE ?= on
+
+export GO111MODULE
+
+GOOS ?= $(if $(TARGETOS),$(TARGETOS),)
+GOARCH ?= $(if $(TARGETARCH),$(TARGETARCH),)
+
+ifeq ($(TARGETARCH),amd64)
+GOAMD64 ?= $(TARGETVARIANT)
+endif
+
+ifeq ($(TARGETARCH),arm)
+GOARM ?= $(TARGETVARIANT:v%=%)
+endif
+
+ifneq ($(GOOS),)
+export GOOS
+endif
+
+ifneq ($(GOARCH),)
+export GOARCH
+endif
+
+ifneq ($(GOAMD64),)
+export GOAMD64
+endif
+
+ifneq ($(GOARM),)
+export GOARM
+endif
+
+.PHONY:
+build: bin/go-md2man
+
+.PHONY: clean
+clean:
+ @rm -rf bin/*
+
+.PHONY: test
+test:
+ @go test $(TEST_FLAGS) ./...
+
+bin/go-md2man: go.mod go.sum md2man/* *.go
+ @mkdir -p bin
+ CGO_ENABLED=0 go build $(BUILD_FLAGS) -o $@
+
+.PHONY: mod
+mod:
+ @go mod tidy
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0e30d34
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+go-md2man
+=========
+
+Converts markdown into roff (man pages).
+
+Uses blackfriday to process markdown into man pages.
+
+### Usage
+
+./md2man -in /path/to/markdownfile.md -out /manfile/output/path
+
+### How to contribute
+
+We use go modules to manage dependencies.
+As such you must be using at lest go1.11.
diff --git a/go-md2man.1.md b/go-md2man.1.md
new file mode 100644
index 0000000..aa4587e
--- /dev/null
+++ b/go-md2man.1.md
@@ -0,0 +1,28 @@
+go-md2man 1 "January 2015" go-md2man "User Manual"
+==================================================
+
+# NAME
+go-md2man - Convert markdown files into manpages
+
+# SYNOPSIS
+**go-md2man** [**-in**=*/path/to/md/file*] [**-out**=*/path/to/output*]
+
+# DESCRIPTION
+**go-md2man** converts standard markdown formatted documents into manpages. It is
+written purely in Go so as to reduce dependencies on 3rd party libs.
+
+By default, the input is stdin and the output is stdout.
+
+# EXAMPLES
+Convert the markdown file *go-md2man.1.md* into a manpage:
+```
+go-md2man < go-md2man.1.md > go-md2man.1
+```
+
+Same, but using command line arguments instead of shell redirection:
+```
+go-md2man -in=go-md2man.1.md -out=go-md2man.1
+```
+
+# HISTORY
+January 2015, Originally compiled by Brian Goff (cpuguy83@gmail.com).
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..0bc888d
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,5 @@
+module github.com/cpuguy83/go-md2man/v2
+
+go 1.11
+
+require github.com/russross/blackfriday/v2 v2.1.0
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..502a072
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,2 @@
+github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
diff --git a/md2man.go b/md2man.go
new file mode 100644
index 0000000..4ff873b
--- /dev/null
+++ b/md2man.go
@@ -0,0 +1,53 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "io/ioutil"
+ "os"
+
+ "github.com/cpuguy83/go-md2man/v2/md2man"
+)
+
+var (
+ inFilePath = flag.String("in", "", "Path to file to be processed (default: stdin)")
+ outFilePath = flag.String("out", "", "Path to output processed file (default: stdout)")
+)
+
+func main() {
+ var err error
+ flag.Parse()
+
+ inFile := os.Stdin
+ if *inFilePath != "" {
+ inFile, err = os.Open(*inFilePath)
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ }
+ defer inFile.Close() // nolint: errcheck
+
+ doc, err := ioutil.ReadAll(inFile)
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+
+ out := md2man.Render(doc)
+
+ outFile := os.Stdout
+ if *outFilePath != "" {
+ outFile, err = os.Create(*outFilePath)
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ defer outFile.Close() // nolint: errcheck
+ }
+ _, err = outFile.Write(out)
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+}
diff --git a/md2man/md2man.go b/md2man/md2man.go
new file mode 100644
index 0000000..42bf32a
--- /dev/null
+++ b/md2man/md2man.go
@@ -0,0 +1,16 @@
+package md2man
+
+import (
+ "github.com/russross/blackfriday/v2"
+)
+
+// Render converts a markdown document into a roff formatted document.
+func Render(doc []byte) []byte {
+ renderer := NewRoffRenderer()
+
+ return blackfriday.Run(doc,
+ []blackfriday.Option{
+ blackfriday.WithRenderer(renderer),
+ blackfriday.WithExtensions(renderer.GetExtensions()),
+ }...)
+}
diff --git a/md2man/roff.go b/md2man/roff.go
new file mode 100644
index 0000000..8a290f1
--- /dev/null
+++ b/md2man/roff.go
@@ -0,0 +1,382 @@
+package md2man
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/russross/blackfriday/v2"
+)
+
+// roffRenderer implements the blackfriday.Renderer interface for creating
+// roff format (manpages) from markdown text
+type roffRenderer struct {
+ extensions blackfriday.Extensions
+ listCounters []int
+ firstHeader bool
+ firstDD bool
+ listDepth int
+}
+
+const (
+ titleHeader = ".TH "
+ topLevelHeader = "\n\n.SH "
+ secondLevelHdr = "\n.SH "
+ otherHeader = "\n.SS "
+ crTag = "\n"
+ emphTag = "\\fI"
+ emphCloseTag = "\\fP"
+ strongTag = "\\fB"
+ strongCloseTag = "\\fP"
+ breakTag = "\n.br\n"
+ paraTag = "\n.PP\n"
+ hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n"
+ linkTag = "\n\\[la]"
+ linkCloseTag = "\\[ra]"
+ codespanTag = "\\fB"
+ codespanCloseTag = "\\fR"
+ codeTag = "\n.EX\n"
+ codeCloseTag = ".EE\n" // Do not prepend a newline character since code blocks, by definition, include a newline already (or at least as how blackfriday gives us on).
+ quoteTag = "\n.PP\n.RS\n"
+ quoteCloseTag = "\n.RE\n"
+ listTag = "\n.RS\n"
+ listCloseTag = "\n.RE\n"
+ dtTag = "\n.TP\n"
+ dd2Tag = "\n"
+ tableStart = "\n.TS\nallbox;\n"
+ tableEnd = ".TE\n"
+ tableCellStart = "T{\n"
+ tableCellEnd = "\nT}\n"
+ tablePreprocessor = `'\" t`
+)
+
+// NewRoffRenderer creates a new blackfriday Renderer for generating roff documents
+// from markdown
+func NewRoffRenderer() *roffRenderer { // nolint: golint
+ var extensions blackfriday.Extensions
+
+ extensions |= blackfriday.NoIntraEmphasis
+ extensions |= blackfriday.Tables
+ extensions |= blackfriday.FencedCode
+ extensions |= blackfriday.SpaceHeadings
+ extensions |= blackfriday.Footnotes
+ extensions |= blackfriday.Titleblock
+ extensions |= blackfriday.DefinitionLists
+ return &roffRenderer{
+ extensions: extensions,
+ }
+}
+
+// GetExtensions returns the list of extensions used by this renderer implementation
+func (r *roffRenderer) GetExtensions() blackfriday.Extensions {
+ return r.extensions
+}
+
+// RenderHeader handles outputting the header at document start
+func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {
+ // We need to walk the tree to check if there are any tables.
+ // If there are, we need to enable the roff table preprocessor.
+ ast.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
+ if node.Type == blackfriday.Table {
+ out(w, tablePreprocessor+"\n")
+ return blackfriday.Terminate
+ }
+ return blackfriday.GoToNext
+ })
+
+ // disable hyphenation
+ out(w, ".nh\n")
+}
+
+// RenderFooter handles outputting the footer at the document end; the roff
+// renderer has no footer information
+func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {
+}
+
+// RenderNode is called for each node in a markdown document; based on the node
+// type the equivalent roff output is sent to the writer
+func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
+ walkAction := blackfriday.GoToNext
+
+ switch node.Type {
+ case blackfriday.Text:
+ escapeSpecialChars(w, node.Literal)
+ case blackfriday.Softbreak:
+ out(w, crTag)
+ case blackfriday.Hardbreak:
+ out(w, breakTag)
+ case blackfriday.Emph:
+ if entering {
+ out(w, emphTag)
+ } else {
+ out(w, emphCloseTag)
+ }
+ case blackfriday.Strong:
+ if entering {
+ out(w, strongTag)
+ } else {
+ out(w, strongCloseTag)
+ }
+ case blackfriday.Link:
+ // Don't render the link text for automatic links, because this
+ // will only duplicate the URL in the roff output.
+ // See https://daringfireball.net/projects/markdown/syntax#autolink
+ if !bytes.Equal(node.LinkData.Destination, node.FirstChild.Literal) {
+ out(w, string(node.FirstChild.Literal))
+ }
+ // Hyphens in a link must be escaped to avoid word-wrap in the rendered man page.
+ escapedLink := strings.ReplaceAll(string(node.LinkData.Destination), "-", "\\-")
+ out(w, linkTag+escapedLink+linkCloseTag)
+ walkAction = blackfriday.SkipChildren
+ case blackfriday.Image:
+ // ignore images
+ walkAction = blackfriday.SkipChildren
+ case blackfriday.Code:
+ out(w, codespanTag)
+ escapeSpecialChars(w, node.Literal)
+ out(w, codespanCloseTag)
+ case blackfriday.Document:
+ break
+ case blackfriday.Paragraph:
+ // roff .PP markers break lists
+ if r.listDepth > 0 {
+ return blackfriday.GoToNext
+ }
+ if entering {
+ out(w, paraTag)
+ } else {
+ out(w, crTag)
+ }
+ case blackfriday.BlockQuote:
+ if entering {
+ out(w, quoteTag)
+ } else {
+ out(w, quoteCloseTag)
+ }
+ case blackfriday.Heading:
+ r.handleHeading(w, node, entering)
+ case blackfriday.HorizontalRule:
+ out(w, hruleTag)
+ case blackfriday.List:
+ r.handleList(w, node, entering)
+ case blackfriday.Item:
+ r.handleItem(w, node, entering)
+ case blackfriday.CodeBlock:
+ out(w, codeTag)
+ escapeSpecialChars(w, node.Literal)
+ out(w, codeCloseTag)
+ case blackfriday.Table:
+ r.handleTable(w, node, entering)
+ case blackfriday.TableHead:
+ case blackfriday.TableBody:
+ case blackfriday.TableRow:
+ // no action as cell entries do all the nroff formatting
+ return blackfriday.GoToNext
+ case blackfriday.TableCell:
+ r.handleTableCell(w, node, entering)
+ case blackfriday.HTMLSpan:
+ // ignore other HTML tags
+ case blackfriday.HTMLBlock:
+ if bytes.HasPrefix(node.Literal, []byte("<!--")) {
+ break // ignore comments, no warning
+ }
+ fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
+ default:
+ fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
+ }
+ return walkAction
+}
+
+func (r *roffRenderer) handleHeading(w io.Writer, node *blackfriday.Node, entering bool) {
+ if entering {
+ switch node.Level {
+ case 1:
+ if !r.firstHeader {
+ out(w, titleHeader)
+ r.firstHeader = true
+ break
+ }
+ out(w, topLevelHeader)
+ case 2:
+ out(w, secondLevelHdr)
+ default:
+ out(w, otherHeader)
+ }
+ }
+}
+
+func (r *roffRenderer) handleList(w io.Writer, node *blackfriday.Node, entering bool) {
+ openTag := listTag
+ closeTag := listCloseTag
+ if node.ListFlags&blackfriday.ListTypeDefinition != 0 {
+ // tags for definition lists handled within Item node
+ openTag = ""
+ closeTag = ""
+ }
+ if entering {
+ r.listDepth++
+ if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
+ r.listCounters = append(r.listCounters, 1)
+ }
+ out(w, openTag)
+ } else {
+ if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
+ r.listCounters = r.listCounters[:len(r.listCounters)-1]
+ }
+ out(w, closeTag)
+ r.listDepth--
+ }
+}
+
+func (r *roffRenderer) handleItem(w io.Writer, node *blackfriday.Node, entering bool) {
+ if entering {
+ if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
+ out(w, fmt.Sprintf(".IP \"%3d.\" 5\n", r.listCounters[len(r.listCounters)-1]))
+ r.listCounters[len(r.listCounters)-1]++
+ } else if node.ListFlags&blackfriday.ListTypeTerm != 0 {
+ // DT (definition term): line just before DD (see below).
+ out(w, dtTag)
+ r.firstDD = true
+ } else if node.ListFlags&blackfriday.ListTypeDefinition != 0 {
+ // DD (definition description): line that starts with ": ".
+ //
+ // We have to distinguish between the first DD and the
+ // subsequent ones, as there should be no vertical
+ // whitespace between the DT and the first DD.
+ if r.firstDD {
+ r.firstDD = false
+ } else {
+ out(w, dd2Tag)
+ }
+ } else {
+ out(w, ".IP \\(bu 2\n")
+ }
+ } else {
+ out(w, "\n")
+ }
+}
+
+func (r *roffRenderer) handleTable(w io.Writer, node *blackfriday.Node, entering bool) {
+ if entering {
+ out(w, tableStart)
+ // call walker to count cells (and rows?) so format section can be produced
+ columns := countColumns(node)
+ out(w, strings.Repeat("l ", columns)+"\n")
+ out(w, strings.Repeat("l ", columns)+".\n")
+ } else {
+ out(w, tableEnd)
+ }
+}
+
+func (r *roffRenderer) handleTableCell(w io.Writer, node *blackfriday.Node, entering bool) {
+ if entering {
+ var start string
+ if node.Prev != nil && node.Prev.Type == blackfriday.TableCell {
+ start = "\t"
+ }
+ if node.IsHeader {
+ start += strongTag
+ } else if nodeLiteralSize(node) > 30 {
+ start += tableCellStart
+ }
+ out(w, start)
+ } else {
+ var end string
+ if node.IsHeader {
+ end = strongCloseTag
+ } else if nodeLiteralSize(node) > 30 {
+ end = tableCellEnd
+ }
+ if node.Next == nil && end != tableCellEnd {
+ // Last cell: need to carriage return if we are at the end of the
+ // header row and content isn't wrapped in a "tablecell"
+ end += crTag
+ }
+ out(w, end)
+ }
+}
+
+func nodeLiteralSize(node *blackfriday.Node) int {
+ total := 0
+ for n := node.FirstChild; n != nil; n = n.FirstChild {
+ total += len(n.Literal)
+ }
+ return total
+}
+
+// because roff format requires knowing the column count before outputting any table
+// data we need to walk a table tree and count the columns
+func countColumns(node *blackfriday.Node) int {
+ var columns int
+
+ node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
+ switch node.Type {
+ case blackfriday.TableRow:
+ if !entering {
+ return blackfriday.Terminate
+ }
+ case blackfriday.TableCell:
+ if entering {
+ columns++
+ }
+ default:
+ }
+ return blackfriday.GoToNext
+ })
+ return columns
+}
+
+func out(w io.Writer, output string) {
+ io.WriteString(w, output) // nolint: errcheck
+}
+
+func escapeSpecialChars(w io.Writer, text []byte) {
+ scanner := bufio.NewScanner(bytes.NewReader(text))
+
+ // count the number of lines in the text
+ // we need to know this to avoid adding a newline after the last line
+ n := bytes.Count(text, []byte{'\n'})
+ idx := 0
+
+ for scanner.Scan() {
+ dt := scanner.Bytes()
+ if idx < n {
+ idx++
+ dt = append(dt, '\n')
+ }
+ escapeSpecialCharsLine(w, dt)
+ }
+
+ if err := scanner.Err(); err != nil {
+ panic(err)
+ }
+}
+
+func escapeSpecialCharsLine(w io.Writer, text []byte) {
+ for i := 0; i < len(text); i++ {
+ // escape initial apostrophe or period
+ if len(text) >= 1 && (text[0] == '\'' || text[0] == '.') {
+ out(w, "\\&")
+ }
+
+ // directly copy normal characters
+ org := i
+
+ for i < len(text) && text[i] != '\\' {
+ i++
+ }
+ if i > org {
+ w.Write(text[org:i]) // nolint: errcheck
+ }
+
+ // escape a character
+ if i >= len(text) {
+ break
+ }
+
+ w.Write([]byte{'\\', text[i]}) // nolint: errcheck
+ }
+}
diff --git a/md2man/roff_test.go b/md2man/roff_test.go
new file mode 100644
index 0000000..5bda3ac
--- /dev/null
+++ b/md2man/roff_test.go
@@ -0,0 +1,480 @@
+package md2man
+
+import (
+ "testing"
+
+ "github.com/russross/blackfriday/v2"
+)
+
+type TestParams struct {
+ extensions blackfriday.Extensions
+}
+
+func TestCodeBlocks(t *testing.T) {
+ tests := []string{
+ "```\nsome code\n```\n",
+ ".nh\n\n.EX\nsome code\n.EE\n",
+
+ "```bash\necho foo\n```\n",
+ ".nh\n\n.EX\necho foo\n.EE\n",
+
+ // make sure literal new lines surrounding the markdown block are preserved as they are intentional
+ "```bash\n\nsome code\n\n```",
+ ".nh\n\n.EX\n\nsome code\n\n.EE\n",
+ }
+ doTestsParam(t, tests, TestParams{blackfriday.FencedCode})
+}
+
+func TestEmphasis(t *testing.T) {
+ tests := []string{
+ "nothing inline\n",
+ ".nh\n\n.PP\nnothing inline\n",
+
+ "simple *inline* test\n",
+ ".nh\n\n.PP\nsimple \\fIinline\\fP test\n",
+
+ "*at the* beginning\n",
+ ".nh\n\n.PP\n\\fIat the\\fP beginning\n",
+
+ "at the *end*\n",
+ ".nh\n\n.PP\nat the \\fIend\\fP\n",
+
+ "*try two* in *one line*\n",
+ ".nh\n\n.PP\n\\fItry two\\fP in \\fIone line\\fP\n",
+
+ "over *two\nlines* test\n",
+ ".nh\n\n.PP\nover \\fItwo\nlines\\fP test\n",
+
+ "odd *number of* markers* here\n",
+ ".nh\n\n.PP\nodd \\fInumber of\\fP markers* here\n",
+
+ "odd *number\nof* markers* here\n",
+ ".nh\n\n.PP\nodd \\fInumber\nof\\fP markers* here\n",
+
+ "simple _inline_ test\n",
+ ".nh\n\n.PP\nsimple \\fIinline\\fP test\n",
+
+ "_at the_ beginning\n",
+ ".nh\n\n.PP\n\\fIat the\\fP beginning\n",
+
+ "at the _end_\n",
+ ".nh\n\n.PP\nat the \\fIend\\fP\n",
+
+ "_try two_ in _one line_\n",
+ ".nh\n\n.PP\n\\fItry two\\fP in \\fIone line\\fP\n",
+
+ "over _two\nlines_ test\n",
+ ".nh\n\n.PP\nover \\fItwo\nlines\\fP test\n",
+
+ "odd _number of_ markers_ here\n",
+ ".nh\n\n.PP\nodd \\fInumber of\\fP markers_ here\n",
+
+ "odd _number\nof_ markers_ here\n",
+ ".nh\n\n.PP\nodd \\fInumber\nof\\fP markers_ here\n",
+
+ "mix of *markers_\n",
+ ".nh\n\n.PP\nmix of *markers_\n",
+
+ "*What is A\\* algorithm?*\n",
+ ".nh\n\n.PP\n\\fIWhat is A* algorithm?\\fP\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestStrong(t *testing.T) {
+ tests := []string{
+ "nothing inline\n",
+ ".nh\n\n.PP\nnothing inline\n",
+
+ "simple **inline** test\n",
+ ".nh\n\n.PP\nsimple \\fBinline\\fP test\n",
+
+ "**at the** beginning\n",
+ ".nh\n\n.PP\n\\fBat the\\fP beginning\n",
+
+ "at the **end**\n",
+ ".nh\n\n.PP\nat the \\fBend\\fP\n",
+
+ "**try two** in **one line**\n",
+ ".nh\n\n.PP\n\\fBtry two\\fP in \\fBone line\\fP\n",
+
+ "over **two\nlines** test\n",
+ ".nh\n\n.PP\nover \\fBtwo\nlines\\fP test\n",
+
+ "odd **number of** markers** here\n",
+ ".nh\n\n.PP\nodd \\fBnumber of\\fP markers** here\n",
+
+ "odd **number\nof** markers** here\n",
+ ".nh\n\n.PP\nodd \\fBnumber\nof\\fP markers** here\n",
+
+ "simple __inline__ test\n",
+ ".nh\n\n.PP\nsimple \\fBinline\\fP test\n",
+
+ "__at the__ beginning\n",
+ ".nh\n\n.PP\n\\fBat the\\fP beginning\n",
+
+ "at the __end__\n",
+ ".nh\n\n.PP\nat the \\fBend\\fP\n",
+
+ "__try two__ in __one line__\n",
+ ".nh\n\n.PP\n\\fBtry two\\fP in \\fBone line\\fP\n",
+
+ "over __two\nlines__ test\n",
+ ".nh\n\n.PP\nover \\fBtwo\nlines\\fP test\n",
+
+ "odd __number of__ markers__ here\n",
+ ".nh\n\n.PP\nodd \\fBnumber of\\fP markers__ here\n",
+
+ "odd __number\nof__ markers__ here\n",
+ ".nh\n\n.PP\nodd \\fBnumber\nof\\fP markers__ here\n",
+
+ "mix of **markers__\n",
+ ".nh\n\n.PP\nmix of **markers__\n",
+
+ "**`/usr`** : this folder is named `usr`\n",
+ ".nh\n\n.PP\n\\fB\\fB/usr\\fR\\fP : this folder is named \\fBusr\\fR\n",
+
+ "**`/usr`** :\n\n this folder is named `usr`\n",
+ ".nh\n\n.PP\n\\fB\\fB/usr\\fR\\fP :\n\n.PP\nthis folder is named \\fBusr\\fR\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestEmphasisMix(t *testing.T) {
+ tests := []string{
+ "***triple emphasis***\n",
+ ".nh\n\n.PP\n\\fB\\fItriple emphasis\\fP\\fP\n",
+
+ "***triple\nemphasis***\n",
+ ".nh\n\n.PP\n\\fB\\fItriple\nemphasis\\fP\\fP\n",
+
+ "___triple emphasis___\n",
+ ".nh\n\n.PP\n\\fB\\fItriple emphasis\\fP\\fP\n",
+
+ "***triple emphasis___\n",
+ ".nh\n\n.PP\n***triple emphasis___\n",
+
+ "*__triple emphasis__*\n",
+ ".nh\n\n.PP\n\\fI\\fBtriple emphasis\\fP\\fP\n",
+
+ "__*triple emphasis*__\n",
+ ".nh\n\n.PP\n\\fB\\fItriple emphasis\\fP\\fP\n",
+
+ "**improper *nesting** is* bad\n",
+ ".nh\n\n.PP\n\\fBimproper *nesting\\fP is* bad\n",
+
+ "*improper **nesting* is** bad\n",
+ ".nh\n\n.PP\n*improper \\fBnesting* is\\fP bad\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestCodeSpan(t *testing.T) {
+ tests := []string{
+ "`source code`\n",
+ ".nh\n\n.PP\n\\fBsource code\\fR\n",
+
+ "` source code with spaces `\n",
+ ".nh\n\n.PP\n\\fBsource code with spaces\\fR\n",
+
+ "` source code with spaces `not here\n",
+ ".nh\n\n.PP\n\\fBsource code with spaces\\fRnot here\n",
+
+ "a `single marker\n",
+ ".nh\n\n.PP\na `single marker\n",
+
+ "a single multi-tick marker with ``` no text\n",
+ ".nh\n\n.PP\na single multi-tick marker with ``` no text\n",
+
+ "markers with ` ` a space\n",
+ ".nh\n\n.PP\nmarkers with a space\n",
+
+ "`source code` and a `stray\n",
+ ".nh\n\n.PP\n\\fBsource code\\fR and a `stray\n",
+
+ "`source *with* _awkward characters_ in it`\n",
+ ".nh\n\n.PP\n\\fBsource *with* _awkward characters_ in it\\fR\n",
+
+ "`split over\ntwo lines`\n",
+ ".nh\n\n.PP\n\\fBsplit over\ntwo lines\\fR\n",
+
+ "```multiple ticks``` for the marker\n",
+ ".nh\n\n.PP\n\\fBmultiple ticks\\fR for the marker\n",
+
+ "```multiple ticks `with` ticks inside```\n",
+ ".nh\n\n.PP\n\\fBmultiple ticks `with` ticks inside\\fR\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestListLists(t *testing.T) {
+ tests := []string{
+ "\n\n**[grpc]**\n: Section for gRPC socket listener settings. Contains three properties:\n - **address** (Default: \"/run/containerd/containerd.sock\")\n - **uid** (Default: 0)\n - **gid** (Default: 0)",
+ ".nh\n\n.TP\n\\fB[grpc]\\fP\nSection for gRPC socket listener settings. Contains three properties:\n.RS\n.IP \\(bu 2\n\\fBaddress\\fP (Default: \"/run/containerd/containerd.sock\")\n.IP \\(bu 2\n\\fBuid\\fP (Default: 0)\n.IP \\(bu 2\n\\fBgid\\fP (Default: 0)\n\n.RE\n\n",
+ "Definition title\n: Definition description one\n: And two\n: And three\n",
+ ".nh\n\n.TP\nDefinition title\nDefinition description one\n\nAnd two\n\nAnd three\n",
+ }
+ doTestsParam(t, tests, TestParams{blackfriday.DefinitionLists})
+}
+
+func TestLineBreak(t *testing.T) {
+ tests := []string{
+ "this line \nhas a break\n",
+ ".nh\n\n.PP\nthis line\n.br\nhas a break\n",
+
+ "this line \ndoes not\n",
+ ".nh\n\n.PP\nthis line\ndoes not\n",
+
+ "this line\\\ndoes not\n",
+ ".nh\n\n.PP\nthis line\\\\\ndoes not\n",
+
+ "this line\\ \ndoes not\n",
+ ".nh\n\n.PP\nthis line\\\\\ndoes not\n",
+
+ "this has an \nextra space\n",
+ ".nh\n\n.PP\nthis has an\n.br\nextra space\n",
+ }
+ doTestsInline(t, tests)
+
+ tests = []string{
+ "this line \nhas a break\n",
+ ".nh\n\n.PP\nthis line\n.br\nhas a break\n",
+
+ "this line \ndoes not\n",
+ ".nh\n\n.PP\nthis line\ndoes not\n",
+
+ "this line\\\nhas a break\n",
+ ".nh\n\n.PP\nthis line\n.br\nhas a break\n",
+
+ "this line\\ \ndoes not\n",
+ ".nh\n\n.PP\nthis line\\\\\ndoes not\n",
+
+ "this has an \nextra space\n",
+ ".nh\n\n.PP\nthis has an\n.br\nextra space\n",
+ }
+ doTestsInlineParam(t, tests, TestParams{
+ extensions: blackfriday.BackslashLineBreak,
+ })
+}
+
+func TestTable(t *testing.T) {
+ tests := []string{
+ `
+| Animal | Color |
+| --------------| --- |
+| elephant | Gray. The elephant is very gray. |
+| wombat | No idea. |
+| zebra | Sometimes black and sometimes white, depending on the stripe. |
+| robin | red. |
+`,
+ `'\" t
+.nh
+
+.TS
+allbox;
+l l
+l l .
+\fBAnimal\fP \fBColor\fP
+elephant T{
+Gray. The elephant is very gray.
+T}
+wombat No idea.
+zebra T{
+Sometimes black and sometimes white, depending on the stripe.
+T}
+robin red.
+.TE
+`,
+ }
+ doTestsInlineParam(t, tests, TestParams{blackfriday.Tables})
+}
+
+func TestTableWithEmptyCell(t *testing.T) {
+ tests := []string{
+ `
+| Col1 | Col2 | Col3 |
+|:---------|:-----:|:----:|
+| row one | | |
+| row two | x | |
+`,
+ `'\" t
+.nh
+
+.TS
+allbox;
+l l l
+l l l .
+\fBCol1\fP \fBCol2\fP \fBCol3\fP
+row one
+row two x
+.TE
+`,
+ }
+ doTestsInlineParam(t, tests, TestParams{blackfriday.Tables})
+}
+
+func TestTableWrapping(t *testing.T) {
+ tests := []string{
+ `
+| Col1 | Col2 |
+| ----------- | ------------------------------------------------ |
+| row one | This is a short line. |
+| row\|two | Col1 should not wrap. |
+| row three | no\|wrap |
+| row four | Inline _cursive_ should not wrap. |
+| row five | Inline ` + "`code markup`" + ` should not wrap. |
+| row six | A line that's longer than 30 characters with inline ` + "`code markup`" + ` or _cursive_ should not wrap. |
+| row seven | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu ipsum eget tortor aliquam accumsan. Quisque ac turpis convallis, sagittis urna ac, tempor est. Mauris nibh arcu, hendrerit id eros sed, sodales lacinia ex. Suspendisse sed condimentum urna, vitae mattis lectus. Mauris imperdiet magna vel purus pretium, id interdum libero. |
+`,
+ `'\" t
+.nh
+
+.TS
+allbox;
+l l
+l l .
+\fBCol1\fP \fBCol2\fP
+row one This is a short line.
+row|two Col1 should not wrap.
+row three no|wrap
+row four Inline \fIcursive\fP should not wrap.
+row five Inline \fBcode markup\fR should not wrap.
+row six T{
+A line that's longer than 30 characters with inline \fBcode markup\fR or \fIcursive\fP should not wrap.
+T}
+row seven T{
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu ipsum eget tortor aliquam accumsan. Quisque ac turpis convallis, sagittis urna ac, tempor est. Mauris nibh arcu, hendrerit id eros sed, sodales lacinia ex. Suspendisse sed condimentum urna, vitae mattis lectus. Mauris imperdiet magna vel purus pretium, id interdum libero.
+T}
+.TE
+`,
+ }
+ doTestsInlineParam(t, tests, TestParams{blackfriday.Tables})
+}
+
+func TestLinks(t *testing.T) {
+ tests := []string{
+ "See [docs](https://docs.docker.com/) for\nmore",
+ ".nh\n\n.PP\nSee docs\n\\[la]https://docs.docker.com/\\[ra] for\nmore\n",
+ "See [docs](https://docs-foo.docker.com/) for\nmore",
+ ".nh\n\n.PP\nSee docs\n\\[la]https://docs\\-foo.docker.com/\\[ra] for\nmore\n",
+ "See <https://docs-foo.docker.com/> for\nmore",
+ ".nh\n\n.PP\nSee \n\\[la]https://docs\\-foo.docker.com/\\[ra] for\nmore\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestEscapeCharacters(t *testing.T) {
+ tests := []string{
+ "Test-one_two&three\\four~five",
+ ".nh\n\n.PP\nTest-one_two&three\\\\four~five\n",
+ "'foo'\n'bar'",
+ ".nh\n\n.PP\n\\&'foo'\n\\&'bar'\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestSpan(t *testing.T) {
+ tests := []string{
+ "Text containing a <span>html span</span> element\n",
+ ".nh\n\n.PP\nText containing a html span element\n",
+
+ `Text containing an inline <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"><image href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="200" width="200"/></svg>SVG image`,
+ ".nh\n\n.PP\nText containing an inline SVG image\n",
+
+ "Text containing a <span id=\"e-123\" class=\"foo\">html span</span> element\n",
+ ".nh\n\n.PP\nText containing a html span element\n",
+ }
+ doTestsInline(t, tests)
+}
+
+func TestEmails(t *testing.T) {
+ tests := []string{
+ `April 2014, Originally compiled by William Henry (whenry at redhat dot com)
+based on docker.com source material and internal work.
+June 2014, updated by Sven Dowideit <SvenDowideit@home.org.au>
+July 2014, updated by Sven Dowideit (SvenDowideit@home.org.au)
+`,
+ `.nh
+
+.PP
+April 2014, Originally compiled by William Henry (whenry at redhat dot com)
+based on docker.com source material and internal work.
+June 2014, updated by Sven Dowideit SvenDowideit@home.org.au
+\[la]mailto:SvenDowideit@home.org.au\[ra]
+July 2014, updated by Sven Dowideit (SvenDowideit@home.org.au)
+`,
+ }
+ doTestsInline(t, tests)
+}
+
+func TestComments(t *testing.T) {
+ blockTests := []string{
+ "First paragraph\n\n<!-- Comment, HTML should be separated by blank lines -->\n\nSecond paragraph\n",
+ ".nh\n\n.PP\nFirst paragraph\n\n.PP\nSecond paragraph\n",
+ }
+ doTestsParam(t, blockTests, TestParams{})
+
+ inlineTests := []string{
+ "Text with a com<!--...-->ment in the middle\n",
+ ".nh\n\n.PP\nText with a comment in the middle\n",
+ }
+ doTestsInlineParam(t, inlineTests, TestParams{})
+}
+
+func execRecoverableTestSuite(t *testing.T, tests []string, params TestParams, suite func(candidate *string)) {
+ // Catch and report panics. This is useful when running 'go test -v' on
+ // the integration server. When developing, though, crash dump is often
+ // preferable, so recovery can be easily turned off with doRecover = false.
+ var candidate string
+ const doRecover = true
+ if doRecover {
+ defer func() {
+ if err := recover(); err != nil {
+ t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err)
+ }
+ }()
+ }
+ suite(&candidate)
+}
+
+func runMarkdown(input string, params TestParams) string {
+ renderer := NewRoffRenderer()
+ return string(blackfriday.Run([]byte(input), blackfriday.WithRenderer(renderer),
+ blackfriday.WithExtensions(params.extensions)))
+}
+
+func doTestsParam(t *testing.T, tests []string, params TestParams) {
+ execRecoverableTestSuite(t, tests, params, func(candidate *string) {
+ for i := 0; i+1 < len(tests); i += 2 {
+ input := tests[i]
+ t.Run(input, func(t *testing.T) {
+ *candidate = input
+ expected := tests[i+1]
+ actual := runMarkdown(*candidate, params)
+ if actual != expected {
+ t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]",
+ *candidate, expected, actual)
+ }
+
+ // now test every substring to stress test bounds checking
+ if !testing.Short() {
+ for start := 0; start < len(input); start++ {
+ for end := start + 1; end <= len(input); end++ {
+ *candidate = input[start:end]
+ runMarkdown(*candidate, params)
+ }
+ }
+ }
+ })
+ }
+ })
+}
+
+func doTestsInline(t *testing.T, tests []string) {
+ doTestsInlineParam(t, tests, TestParams{})
+}
+
+func doTestsInlineParam(t *testing.T, tests []string, params TestParams) {
+ params.extensions |= blackfriday.Strikethrough
+ doTestsParam(t, tests, params)
+}