/
gopandoc.go
85 lines (70 loc) · 1.57 KB
/
gopandoc.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
package gopandoc
import (
"bytes"
"fmt"
gopandoc "github.com/theplant/pandora/clients/go"
"log"
"os/exec"
"runtime/debug"
"strings"
)
const (
op_html = `html`
op_markdown = `markdown-escaped_line_breaks` // Don't auto generate id for header
op_atx_headers = `--atx-headers` // User atx header with "#"
no_wrap = "--no-wrap"
)
var (
EnablePandocZMQMode = false
)
func Check() error {
path, err := exec.LookPath("pandoc")
log.Println(path)
return err
}
func ToHtml(mdStr string) (htmlStr string, err error) {
if EnablePandocZMQMode {
return gopandoc.ToHTML(mdStr)
}
htmlStr, err = bash(fmt.Sprintf("pandoc -f %s -t %s %s",
op_markdown, op_html, op_atx_headers), mdStr)
if err != nil {
return
}
return
}
func ToMarkdown(htmlStr string) (mdStr string, err error) {
if EnablePandocZMQMode {
return gopandoc.ToMarkdown(htmlStr)
}
mdStr, err = bash(fmt.Sprintf("pandoc -f %s -t %s %s %s", op_html,
op_markdown, op_atx_headers, no_wrap), htmlStr)
if err != nil {
return
}
return
}
func bash(bash, content string) (out string, err error) {
var buf bytes.Buffer
cmd := exec.Command("/bin/sh", "-c", bash)
cmd.Stdin = strings.NewReader(content)
cmd.Stderr = &buf
cmd.Stdout = &buf
err = cmd.Run()
if err != nil {
printStackAndError(err)
cmd.Process.Release()
buf.Reset()
return
}
out = buf.String()
// Clean up resource
cmd.Process.Kill()
buf.Reset()
debug.FreeOSMemory()
return
}
func printStackAndError(err error) {
log.Printf("********** Debug Error message: %+v ***********\n", err)
debug.PrintStack()
}