This repository has been archived by the owner on Nov 19, 2024. It is now read-only.
forked from rsdoiel/mkpage
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pandoc.go
357 lines (338 loc) · 10.7 KB
/
pandoc.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// Package mkpage is an experimental static site generator
//
// @author R. S. Doiel, <rsdoiel@caltech.edu>
//
// Copyright (c) 2021, Caltech
// All rights not granted herein are expressly reserved by Caltech
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package mkpage
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"strings"
)
var (
// Set a default -f (from) value used by Pandoc
PandocFrom string
// Set a default -t (to) value used by Pandoc
PandocTo string
)
// MetadataBlock holds the Pandoc style Metadata block delimited
// by start '%' at the being of the line in the start of a text file.
type MetadataBlock struct {
Title string `json:"title"`
Authors []string `json:"authors"`
Date string `json:"date"`
}
func (block *MetadataBlock) String() string {
return fmt.Sprintf("%% %s\n%% %s\n%% %s", block.Title, strings.Join(block.Authors, "; "), block.Date)
}
func (block *MetadataBlock) Unmarshal(src []byte) error {
lines := bytes.Split(src, []byte("\n"))
fieldCnt := 0
key := ""
block.Title = ""
block.Authors = []string{}
block.Date = ""
for i := 0; i < len(lines); i++ {
line := lines[i]
if bytes.HasPrefix(line, []byte("% ")) {
fieldCnt += 1
switch fieldCnt {
case 1:
key = "title"
case 2:
key = "authors"
case 3:
key = "date"
default:
key = ""
}
line = bytes.TrimPrefix(line, []byte("% "))
}
if (len(key) > 0) && (fieldCnt <= 3) {
switch key {
case "title":
if len(block.Title) > 0 {
block.Title = fmt.Sprintf("%s\n%s", block.Title, bytes.TrimSpace(line))
} else {
block.Title = fmt.Sprintf("%s", bytes.TrimSpace(line))
}
case "authors":
if bytes.Contains(line, []byte(";")) {
parts := bytes.Split(line, []byte(";"))
for _, part := range parts {
block.Authors = append(block.Authors, fmt.Sprintf("%s", bytes.TrimSpace(part)))
}
} else {
block.Authors = append(block.Authors, fmt.Sprintf("%s", bytes.TrimSpace(line)))
}
case "date":
block.Date = fmt.Sprintf("%s", bytes.TrimSpace(line))
key = ""
}
}
}
if fieldCnt != 3 {
return fmt.Errorf("Missing or ill formed metablock, expecting title, author(s), date")
}
return nil
}
func (block *MetadataBlock) Marshal() ([]byte, error) {
return json.Marshal(block)
}
func fmtPandocError(err error) error {
if err == nil {
return nil
}
parts := []string{
"Pandoc error (see https://pandoc.org), ",
fmt.Sprintf("%s", err),
}
// Provide context where error is related to the PATH
if strings.Contains(parts[1], "PATH") {
parts = append(parts, fmt.Sprintf("PATH is %q", os.Getenv("PATH")))
}
return fmt.Errorf("%s", strings.Join(parts, "\n "))
}
// Return the Pandoc version that will be used when calling Pandoc.
func GetPandocVersion() (string, error) {
var (
out, eOut bytes.Buffer
)
pandoc, err := exec.LookPath("pandoc")
if err != nil {
return "", fmtPandocError(err)
}
cmd := exec.Command(pandoc, "--version")
cmd.Stdout = &out
cmd.Stderr = &eOut
err = cmd.Run()
if err != nil {
if eOut.Len() > 0 {
err = fmt.Errorf("%q says, %s\n%s", pandoc, eOut.String(), err)
} else {
err = fmt.Errorf("%q exit error, %s", pandoc, err)
}
return "", fmtPandocError(err)
}
if eOut.Len() > 0 {
fmt.Fprintf(os.Stderr, "%q warns, %s", pandoc, eOut.String())
}
return out.String(), fmtPandocError(err)
}
// pandocProcessor accepts an array of bytes as input and returns
// a `pandoc -f {From} -t html` output of an array if
// bytes and error.
func pandocProcessor(input []byte, from string, to string) ([]byte, error) {
var (
out, eOut bytes.Buffer
)
if from == "" {
from = PandocFrom
}
if to == "" {
to = PandocTo
}
pandoc, err := exec.LookPath("pandoc")
if err != nil {
return nil, fmtPandocError(err)
}
options := []string{}
if from != "" {
options = append(options, "-f", from)
}
if to != "" {
options = append(options, "-t", to)
}
cmd := exec.Command(pandoc, options...)
cmd.Stdin = bytes.NewReader(input)
cmd.Stdout = &out
cmd.Stderr = &eOut
err = cmd.Run()
if err != nil {
if eOut.Len() > 0 {
err = fmt.Errorf("%q says, %s\n%s", pandoc, eOut.String(), err)
} else {
err = fmt.Errorf("%q exit error, %s", pandoc, err)
}
return nil, fmtPandocError(err)
}
if eOut.Len() > 0 {
fmt.Fprintf(os.Stderr, "%q warns, %s", pandoc, eOut.String())
}
return out.Bytes(), fmtPandocError(err)
}
// MakePandoc resolves key/value map rendering metadata suitable for processing with pandoc along with template information
// rendering and returns an error if something goes wrong
func MakePandoc(wr io.Writer, templateName string, keyValues map[string]string) error {
var (
out, eOut bytes.Buffer
options []string
)
pandoc, err := exec.LookPath("pandoc")
if err != nil {
return fmtPandocError(err)
}
data, err := ResolveData(keyValues)
if err != nil {
return fmt.Errorf("Data resolution error: %s", err)
}
// NOTE: If a template is not provided (empty string) then
// see is one is specified in the metadata
if templateName == "" {
if val, ok := data["template"]; ok == true {
templateName = val.(string)
}
}
// NOTE: Pandocs default template expects content to be called $body$.
// we need to remap from data["content"] to data["body"] otherwise
// we need to look in data to see if a template was specified.
if templateName == "" {
if val, ok := data["content"]; ok == true {
delete(data, "content")
data["body"] = val
}
}
// NOTE: when using a template, title metadata is required.
if _, ok := data["title"]; !ok {
// Insert a title to prevent warning.
data["title"] = "..."
}
src, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("Marshal error, %q", err)
}
metadata, err := ioutil.TempFile(".", "pandoc.*.json")
if err != nil {
return fmt.Errorf("Cannot create temp metadata file, %s", err)
}
if _, err := metadata.Write(src); err != nil {
return fmt.Errorf("Write error, %q", err)
}
defer os.Remove(metadata.Name())
// Check if document has front matter, split and write to temp files.
options = []string{}
if PandocFrom != "" {
options = append(options, "-f", PandocFrom)
}
if PandocTo != "" {
options = append(options, "-t", PandocTo)
}
options = append(options, "--metadata-file", metadata.Name())
if templateName != "" {
options = append(options, []string{"--template", templateName}...)
} else {
options = append(options, "--standalone")
}
cmd := exec.Command(pandoc, options...)
cmd.Stdout = &out
cmd.Stderr = &eOut
err = cmd.Run()
if err != nil {
if eOut.Len() > 0 {
err = fmt.Errorf("%q says, %s\n%s", pandoc, eOut.String(), err)
} else {
err = fmt.Errorf("%q exit error, %s", pandoc, err)
}
return fmtPandocError(err)
}
if eOut.Len() > 0 {
fmt.Fprintf(os.Stderr, "%q warns, %s", pandoc, eOut.String())
}
wr.Write(out.Bytes())
return fmtPandocError(err)
}
// MakePandocString resolves key/value map rendering metadata suitable for processing with pandoc along with template information
// rendering and returns an error if something goes wrong
func MakePandocString(tmplSrc string, keyValues map[string]string) (string, error) {
var (
out, eOut bytes.Buffer
options []string
)
pandoc, err := exec.LookPath("pandoc")
if err != nil {
return "", fmtPandocError(err)
}
data, err := ResolveData(keyValues)
if err != nil {
return "", fmt.Errorf("Data resolution error: %s", err)
}
src, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf("Marshal error, %q", err)
}
metadata, err := ioutil.TempFile(".", "pandoc.*.json")
if err != nil {
return "", fmt.Errorf("Cannot create temp metadata file, %s", err)
}
if _, err := metadata.Write(src); err != nil {
return "", fmt.Errorf("Write error, %q", err)
}
defer os.Remove(metadata.Name())
options = []string{}
if PandocFrom != "" {
options = append(options, "-f", PandocFrom)
}
if PandocTo != "" {
options = append(options, "-t", PandocTo)
}
options = append(options, "--metadata-file", metadata.Name())
if tmplSrc != "" {
// Pandoc expects to read the template from disc so write
// out to a temp file.
// Check if document has front matter, split and write to temp files.
template, err := ioutil.TempFile(".", "pandoc.*.tmpl")
if err != nil {
return "", fmt.Errorf("Cannot create temp template file, %s", err)
}
if _, err := template.Write([]byte(tmplSrc)); err != nil {
return "", fmt.Errorf("Write error, %q", err)
}
defer os.Remove(template.Name())
options = append(options, []string{"--template", template.Name()}...)
} else {
options = append(options, "--standalone")
}
cmd := exec.Command(pandoc, options...)
cmd.Stdout = &out
cmd.Stderr = &eOut
err = cmd.Run()
if err != nil {
if eOut.Len() > 0 {
err = fmt.Errorf("%q says, %s\n%s", pandoc, eOut.String(), err)
} else {
err = fmt.Errorf("%q exit error, %s", pandoc, err)
}
return "", fmtPandocError(err)
}
if eOut.Len() > 0 {
return "", fmt.Errorf("%q warns, %s", pandoc, eOut.String())
}
return fmt.Sprintf("%s", out.Bytes()), nil
}
// PandocBlock will attempt to convert a src byte array from
// one to another formats. If conversion is successful it returns
// a converted string, if unsuccessful it returns the original
// byte array as a string.
func PandocBlock(src string, from string, to string) string {
if buf, err := pandocProcessor([]byte(src), from, to); err == nil {
return fmt.Sprintf("%s", buf)
}
return src
}