-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.go
More file actions
426 lines (366 loc) · 12.1 KB
/
main.go
File metadata and controls
426 lines (366 loc) · 12.1 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"bytes"
"crypto/rand"
_ "embed"
"encoding/base64"
"encoding/hex"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/browser"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/text"
"go.abhg.dev/goldmark/mermaid"
)
var appVersion string
// imgSrcRegex matches <img> tags with src attributes
// Captures: 1=prefix, 2=opening quote, 3=src path, 4=closing quote
var imgSrcRegex = regexp.MustCompile(`(<img[^>]*\ssrc=)(["']?)([^"'\s>]+)(["']?)`)
//go:embed github-markdown.css
var style string
//go:embed template.html
var template string
//go:embed mermaid.min.js
var mermaidJS 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)
// Convert relative image links to data URIs in the markdown source
baseDir := filepath.Dir(inputFilename)
processedMarkdown := processMarkdownImages(string(dat), baseDir)
processedBytes := []byte(processedMarkdown)
// Create Goldmark markdown processor with extensions
md := goldmark.New(
goldmark.WithExtensions(
extension.GFM, // GitHub Flavored Markdown (includes tables)
extension.Typographer, // Smart quotes, dashes, etc.
&mermaid.Extender{
NoScript: true, // Don't add CDN script tags - we'll add our own embedded version
},
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(), // Auto-generate heading IDs
),
goldmark.WithRendererOptions(
html.WithUnsafe(), // Allow raw HTML (equivalent to markdown.HTML(true))
),
)
// Parse markdown to AST
doc := md.Parser().Parse(text.NewReader(processedBytes))
// Extract title from AST
title := getTitleFromAST(doc, processedBytes)
// Render to HTML
var buf bytes.Buffer
if err := md.Renderer().Render(&buf, processedBytes, doc); err != nil {
log.Fatal(err)
}
htmlContent := buf.String()
// Add embedded Mermaid.js and initialization script when diagrams are present
htmlContent = embedMermaidScript(htmlContent)
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, htmlContent)
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 errors.Is(e, fs.ErrPermission) {
fmt.Println("There was a permission error accessing the file.")
}
if errors.Is(e, fs.ErrNotExist) {
fmt.Println("mdview was unable to find 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 getTitleFromAST(doc ast.Node, source []byte) string {
var title string
ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
if heading, ok := n.(*ast.Heading); ok && heading.Level == 1 {
// Extract all text from heading and its children recursively
var buf bytes.Buffer
extractText(heading, source, &buf)
title = strings.TrimSpace(buf.String())
return ast.WalkStop, nil
}
return ast.WalkContinue, nil
})
return title
}
// extractText recursively extracts text from a node and its children
func extractText(node ast.Node, source []byte, buf *bytes.Buffer) {
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
switch n := child.(type) {
case *ast.Text:
buf.Write(n.Segment.Value(source))
case *ast.String:
buf.Write(n.Value)
default:
// Recursively extract text from other node types (emphasis, strong, links, etc.)
extractText(child, source, buf)
}
}
}
func isSnap() bool {
return os.Getenv("SNAP_USER_COMMON") != ""
}
// processMarkdownImages processes markdown source and converts relative image paths to data URIs
func processMarkdownImages(markdown string, baseDir string) string {
// Process markdown image syntax: 
imgMarkdownRegex := regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
markdown = imgMarkdownRegex.ReplaceAllStringFunc(markdown, func(match string) string {
parts := imgMarkdownRegex.FindStringSubmatch(match)
if len(parts) < 3 {
return match
}
alt := parts[1]
imgPath := parts[2]
if isRelativePath(imgPath) {
if dataURI := imageToDataURI(imgPath, baseDir); dataURI != "" {
return fmt.Sprintf("", alt, dataURI)
}
}
return match
})
// Process HTML img tags in markdown
markdown = processHTMLImages(markdown, baseDir)
return markdown
}
// processHTMLImages processes HTML content and converts relative image src attributes to data URIs
func processHTMLImages(html string, baseDir string) string {
// Use the package-level regex to match <img> tags with src attributes
result := imgSrcRegex.ReplaceAllStringFunc(html, func(match string) string {
// Extract the parts using the regex
parts := imgSrcRegex.FindStringSubmatch(match)
if len(parts) != 5 {
return match
}
prefix := parts[1] // "<img...src="
openQuote := parts[2] // " or ' or empty
srcPath := parts[3] // the actual path
closeQuote := parts[4] // " or ' or empty
// If quotes don't match, return original (malformed HTML)
if openQuote != closeQuote {
return match
}
// Check if the path is relative
if isRelativePath(srcPath) {
if dataURI := imageToDataURI(srcPath, baseDir); dataURI != "" {
return prefix + openQuote + dataURI + closeQuote
}
}
return match
})
return result
}
// isRelativePath checks if a path is relative (not http://, https://, //, or absolute path)
func isRelativePath(path string) bool {
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return false
}
if strings.HasPrefix(path, "//") {
return false
}
if strings.HasPrefix(path, "data:") {
return false
}
if filepath.IsAbs(path) {
return false
}
return true
}
// imageToDataURI reads an image file and converts it to a base64 data URI
func imageToDataURI(imagePath string, baseDir string) string {
// Resolve the full path relative to the markdown file
fullPath := filepath.Join(baseDir, imagePath)
// Clean and validate the path to prevent path traversal attacks
cleanedPath, err := filepath.Abs(fullPath)
if err != nil {
log.Printf("Warning: Invalid image path %s: %v", fullPath, err)
return ""
}
// Ensure the resolved path is within or relative to the base directory
cleanedBase, err := filepath.Abs(baseDir)
if err != nil {
log.Printf("Warning: Invalid base directory %s: %v", baseDir, err)
return ""
}
// Check if the cleaned path starts with the base directory or is a reasonable relative reference
// We allow accessing parent directories for flexibility with markdown repos
if !strings.HasPrefix(cleanedPath, cleanedBase) {
relPath, err := filepath.Rel(cleanedBase, cleanedPath)
if err != nil {
log.Printf("Warning: Unable to determine relative path for %s: %v", imagePath, err)
return ""
}
// If the path goes outside the base directory, check parent traversal limits
if strings.HasPrefix(relPath, "..") {
// Allow up to 3 levels of parent directory traversal for flexibility
// Count the number of ".." path components
components := strings.Split(filepath.ToSlash(relPath), "/")
parentLevels := 0
for _, component := range components {
if component == ".." {
parentLevels++
}
}
if parentLevels > 3 {
log.Printf("Warning: Image path %s goes too many levels above base directory", imagePath)
return ""
}
}
}
// Check file size before reading (limit to 10MB to prevent memory issues)
fileInfo, err := os.Stat(cleanedPath)
if err != nil {
log.Printf("Warning: Unable to stat image file %s: %v", cleanedPath, err)
return ""
}
const maxSize = 10 * 1024 * 1024 // 10MB
if fileInfo.Size() > maxSize {
log.Printf("Warning: Image file %s is too large (%d bytes, max %d bytes)", cleanedPath, fileInfo.Size(), maxSize)
return ""
}
// Read the image file
data, err := os.ReadFile(cleanedPath)
if err != nil {
log.Printf("Warning: Unable to read image file %s: %v", cleanedPath, err)
return ""
}
// Determine MIME type based on file extension
mimeType := getMimeType(cleanedPath)
// Encode to base64
encoded := base64.StdEncoding.EncodeToString(data)
// Return data URI
return fmt.Sprintf("data:%s;base64,%s", mimeType, encoded)
}
// getMimeType returns the MIME type based on file extension
func getMimeType(path string) string {
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".jpg", ".jpeg":
return "image/jpeg"
case ".png":
return "image/png"
case ".gif":
return "image/gif"
case ".svg":
return "image/svg+xml"
case ".webp":
return "image/webp"
case ".bmp":
return "image/bmp"
case ".ico":
return "image/x-icon"
default:
// For unknown extensions, log a warning but try with generic image type
log.Printf("Warning: Unknown image extension %s for file %s, using image/* MIME type", ext, path)
return "image/*"
}
}
// embedMermaidScript adds the embedded Mermaid.js library to the HTML content
// Since we set NoScript: true on the Mermaid extender, we need to manually add the script
func embedMermaidScript(htmlContent string) string {
// Check if there are any mermaid diagrams in the content
// The Goldmark mermaid extension uses class="mermaid" for diagram blocks
if !strings.Contains(htmlContent, `class="mermaid"`) {
return htmlContent // No mermaid diagrams, don't add the script
}
// Escape any </script> tags (with closing >) inside the mermaid.js code
// to prevent premature script closure. The standard way is to escape the forward slash.
escapedMermaidJS := strings.ReplaceAll(mermaidJS, "</script>", "<\\/script>")
// Add the embedded Mermaid.js and initialization at the end of the content
// Initialize mermaid with theme detection
initScript := `
var isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
mermaid.initialize({
startOnLoad: true,
theme: isDarkMode ? 'dark' : 'default',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
curve: 'linear'
},
securityLevel: 'strict'
});
`
inlineScript := fmt.Sprintf("<script>%s</script><script>%s</script>", escapedMermaidJS, initScript)
return htmlContent + inlineScript
}