-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdoc.go
65 lines (54 loc) · 1.52 KB
/
doc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package doc
import (
"fmt"
"io"
"github.com/fbiville/markdown-table-formatter/pkg/markdown"
)
// A package for automatic documentation generation.
type Interface interface {
Describe() ([]string, [][]string, error)
}
type Document struct {
writer io.Writer
header string
description string
keys []string
rows [][]string
}
// Creates a new empty document with a title.
func NewDocument(w io.Writer, header string) *Document {
return &Document{
writer: w,
header: header,
}
}
// SetDescription sets a document description.
func (d *Document) SetDescription(description string) {
d.description = description
}
// SetKeys sets keys in the table header.
func (d *Document) SetKeys(keys ...string) {
d.keys = keys
}
// SetRows manually sets rows.
func (d *Document) SetRows(rows [][]string) {
d.rows = rows
}
// Fill takes an object with .Describe() method returning []string keys and [][]string rows to fill the document table.
func (d *Document) Fill(obj Interface) error {
var err error
d.keys, d.rows, err = obj.Describe()
return err
}
// Generate generates a new document from the values it contains.
func (d *Document) Generate() error {
// Generate a table
table, err := markdown.NewTableFormatterBuilder().WithAlphabeticalSortIn(markdown.ASCENDING_ORDER).
WithPrettyPrint().Build(d.keys...).Format(d.rows)
if err != nil {
return err
}
// Assemble everything into one document
_, err = io.WriteString(d.writer, fmt.Sprintf("%s\n\n%s\n\n%s\n", d.header, d.description, table))
return err
}