-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
166 lines (140 loc) · 3.78 KB
/
main.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
package main
import (
"crypto/rand"
_ "embed"
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/pkg/browser"
"gitlab.com/golang-commonmark/markdown"
)
var appVersion string
//go:embed github-markdown.css
var style string
//go:embed template.html
var template string
func main() {
var outfilePtr = flag.String("o", "", "Output filename. (Optional)")
var versionPtr = flag.Bool("version", false, "Prints mdview version.")
var helpPtr = flag.Bool("help", false, "Prints mdview help message.")
var barePtr = flag.Bool("bare", false, "Bare HTML with no style applied.")
flag.BoolVar(versionPtr, "v", false, "Prints mdview version.")
flag.BoolVar(helpPtr, "h", false, "Prints mdview help message.")
flag.BoolVar(barePtr, "b", false, "Bare HTML with no style applied.")
flag.Parse()
inputFilename := flag.Arg(0)
if *versionPtr {
fmt.Println(appVersion)
os.Exit(0)
}
if inputFilename == "" || *helpPtr {
os.Stderr.WriteString("Usage:\nmdview [options] <filename>\nFormats markdown and launches it in a browser.\nIf the environment variable MDVIEW_DIR is set, the temporary file will be written there.\n")
flag.PrintDefaults()
os.Exit(1)
}
dat, err := os.ReadFile(inputFilename)
check(err)
md := markdown.New(
markdown.HTML(true),
markdown.Nofollow(true),
markdown.Tables(true),
markdown.Typographer(true))
markdownTokens := md.Parse(dat)
html := md.RenderTokensToString(markdownTokens)
title := getTitle(markdownTokens)
outfilePath := *outfilePtr
if outfilePath == "" {
outfilePath = tempFileName("mdview", ".html")
}
f, err := os.Create(outfilePath)
check(err)
defer f.Close()
var actualStyle string
if *barePtr {
actualStyle = ""
} else {
actualStyle = style
}
_, err = fmt.Fprintf(f, template, actualStyle, title, html)
check(err)
f.Sync()
browser.Stderr = nil
browser.Stdout = nil
err = browser.OpenFile(outfilePath)
check(err)
}
func tempFileName(prefix, suffix string) string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return filepath.Join(getTempDir(), prefix+hex.EncodeToString(randBytes)+suffix)
}
func getTempDir() string {
if os.Getenv("MDVIEW_DIR") != "" {
var tempDir = os.Getenv(("MDVIEW_DIR"))
if _, err := os.Stat(tempDir); os.IsNotExist(err) {
err = os.Mkdir(tempDir, 0700)
check(err)
}
return tempDir
}
if isSnap() {
var tmpdir = os.Getenv("HOME") + "/mdview-temp"
if _, err := os.Stat(tmpdir); os.IsNotExist(err) {
err = os.Mkdir(tmpdir, 0700)
check(err)
}
return tmpdir
}
return os.TempDir()
}
func check(e error) {
if e != nil {
if os.IsPermission(e) {
fmt.Println("There was a permission error accessing the file.")
if isSnap() {
fmt.Println("Since mdview was installed as a Snap, it can only access files in your HOME directory.")
fmt.Println("If you need to use it with files outside of your HOME directory, choose a different installation method.")
fmt.Println("https://github.com/mapitman/mdview?tab=readme-ov-file#installation\n")
}
}
log.Fatal(e)
}
}
func getTitle(tokens []markdown.Token) string {
var result string
if len(tokens) > 0 {
for i := 0; i < len(tokens); i++ {
if topLevelHeading, ok := tokens[i].(*markdown.HeadingOpen); ok {
for j := i + 1; j < len(tokens); j++ {
if token, ok := tokens[j].(*markdown.HeadingClose); ok && token.Lvl == topLevelHeading.Lvl {
break
}
result += getText(tokens[j])
}
result = strings.TrimSpace(result)
break
}
}
}
return result
}
func getText(token markdown.Token) string {
switch token := token.(type) {
case *markdown.Text:
return token.Content
case *markdown.Inline:
result := ""
for _, token := range token.Children {
result += getText(token)
}
return result
}
return ""
}
func isSnap() bool {
return os.Getenv("SNAP_USER_COMMON") != ""
}