[Golang] Create reStructuredText Metadata via text/template Package


Create reStructuredText metadata via Go text/template and text/width package.

Install package width:

$ go get -u golang.org/x/text/width

Source code:

rstmeta.go | repository | view raw
 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 rstmeta

import (
	"golang.org/x/text/width"
	"io"
	"strings"
	"text/template"
)

var rstMetadataTmpl = `{{.Title}}
{{rstTitle .Title}}

:date: {{.Date}}
:tags: {{.Tags}}
:category: {{.Category}}
:summary: {{.Summary}}


`

type RstMetadata struct {
	Title    string
	Date     string
	Tags     string
	Category string
	Summary  string
}

func GetWidthUTF8String(s string) int {
	size := 0
	for _, runeValue := range s {
		p := width.LookupRune(runeValue)
		if p.Kind() == width.EastAsianWide {
			size += 2
			continue
		}
		if p.Kind() == width.EastAsianNarrow {
			size += 1
			continue
		}
		panic("cannot determine!")
	}
	return size
}

func rstTitle(title string) string {
	width := GetWidthUTF8String(title)
	return strings.Repeat("=", width)
}

func writeRstMetadata(wr io.Writer, title, date, tags, category, summary string) {
	meta := RstMetadata{
		Title:    title,
		Date:     date,
		Tags:     tags,
		Category: category,
		Summary:  summary,
	}

	var funcMap = template.FuncMap{
		"rstTitle": rstTitle,
	}
	tmpl := template.Must(template.New("rstmeta").Funcs(funcMap).Parse(rstMetadataTmpl))
	tmpl.Execute(wr, meta)
}
rstmeta_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package rstmeta

import (
	"os"
	"testing"
)

func TestRstMeta(t *testing.T) {
	writeRstMetadata(os.Stdout, "test title 測試標題", "2016-04-22T20:58+08:00", "tag1, tag2", "category1", "my summary")
}

Output:

=== RUN   TestRstMeta
test title 測試標題
===================

:date: 2016-04-22T20:58+08:00
:tags: tag1, tag2
:category: category1
:summary: my summary


--- PASS: TestRstMeta (0.00s)
PASS

Tested on: Ubuntu Linux 15.10, Go 1.6.1.


References:

[1]
[2]go repeat string - Google search
[3]use template · twnanda/twnanda@98cb592 · GitHub