-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmarkdown.go
184 lines (156 loc) · 4.22 KB
/
markdown.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright (C) 2019 rameshvk. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.
package test
import (
"bytes"
"fmt"
"go/format"
"io"
"io/ioutil"
"log"
"runtime"
"strings"
"text/template"
"github.com/russross/blackfriday/v2"
"golang.org/x/tools/imports"
)
// Markdown generates test code by compiling together snippets in the
// provided markdown file names. The output is written to the provided
// output file name.
//
// Fenced blocks can also specify the test/example name in the info string.
// The first word of the infostring must be go or golang
//
// A fenced block can "import" other modules by simply placing a comment
// of the form `// import path`.
//
// See https://github.com/tvastar/test/blob/master/testdata/markdown.md
// for a sample markdown and
// https://github.com/tvastar/test/blob/master/testdata/markdown_test.go
// for example generated tests.
func Markdown(src []string, dest, pkg string) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
pc := []uintptr{0}
runtime.Callers(2, pc)
frame, _ := runtime.CallersFrames(pc).Next()
var output bytes.Buffer
im := [][2]string{{"", "testing"}, {"", "fmt"}, {"", "log"}}
i := info{Package: pkg, Imports: im, Generator: sanitize(frame.File)}
input := readSources(src)
count := 0
opts := blackfriday.WithExtensions(blackfriday.CommonExtensions)
blackfriday.New(opts).Parse(input).Walk(
func(n *blackfriday.Node, entering bool) blackfriday.WalkStatus {
if entering && n.Type == blackfriday.CodeBlock {
count++
fence := string(n.Literal)
title := string(n.CodeBlockData.Info)
im := formatFence(&output, fence, title, pkg, count)
i.Imports = append(i.Imports, im...)
}
return blackfriday.GoToNext
})
var hdr bytes.Buffer
must(headerTpl.Execute(&hdr, i), "")
contents := append(hdr.Bytes(), output.Bytes()...)
p, err := format.Source(contents)
must(err, string(contents))
result, err := imports.Process(src[0], p, nil)
must(err, string(p))
return ioutil.WriteFile(dest, result, 0644)
}
func readSources(sources []string) []byte {
var result []byte
for _, src := range sources {
input, err := ioutil.ReadFile(src)
must(err, src)
result = append(result, input...)
}
return result
}
func sanitize(fileName string) string {
if x := strings.Index(fileName, "github.com"); x >= 0 {
return fileName[x:]
}
return fileName
}
func formatFence(w io.Writer, fence, title, pkg string, count int) [][2]string {
title = strings.TrimSpace(title)
if !strings.HasPrefix(title, "go") {
return nil
}
parts := strings.Fields(title)
name := ""
if title != "" && len(parts) > 1 {
name = parts[1]
}
if strings.Contains(name, ".") {
parts = strings.SplitN(name, ".", 2)
if strings.TrimSpace(parts[0]) != pkg {
return nil
}
name = parts[1]
}
if name == "" {
name = fmt.Sprintf("Example_%d", count)
}
if strings.HasPrefix(name, "Test") {
ioMust(io.WriteString(w, "func "))
ioMust(io.WriteString(w, name))
ioMust(io.WriteString(w, "(t *testing.T) {\n"))
ioMust(io.WriteString(w, fence))
ioMust(io.WriteString(w, "\n}\n\n"))
} else if name == "skip" {
} else if name == "global" {
ioMust(io.WriteString(w, fence))
} else {
ioMust(io.WriteString(w, "func "))
ioMust(io.WriteString(w, name))
ioMust(io.WriteString(w, "() {\n"))
ioMust(io.WriteString(w, fence))
ioMust(io.WriteString(w, "\n}\n\n"))
}
imports := [][2]string{}
for _, l := range strings.Split(fence, "\n") {
l = strings.TrimSpace(l)
if !strings.HasPrefix(l, "//") {
continue
}
l = strings.TrimSpace(l[2:])
if !strings.HasPrefix(l, "import") {
continue
}
l = strings.TrimSpace(l[len("import"):])
imports = append(imports, [2]string{"", l})
}
return imports
}
func ioMust(n int, err error) {
if err != nil {
panic(err)
}
}
func must(err error, s string) {
if err != nil {
log.Println(s)
panic(err)
}
}
var headerTpl = template.Must(template.New("code").Parse(`
// Code generated by {{.Generator}}. DO NOT EDIT.
package {{.Package}}
import (
{{range $import := .Imports}}{{index $import 0}} "{{index $import 1}}"
{{end -}}
)
`))
type info struct {
Generator string
Package string
Imports [][2]string
}