-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
282 lines (239 loc) · 7.22 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
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
package main
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
var styles = map[string]Style{
".bash": {LineComment: "#"},
".css": {BlockDo: "/*", BlockDone: "*/"},
".go": {LineComment: "//"},
".haml": {LineComment: "-#"},
".html": {BlockDo: "<!--", BlockDone: "-->"},
".js": {LineComment: "//", BlockDo: "/*", BlockDone: "*/"},
".lua": {LineComment: "--"},
".rb": {LineComment: "#"},
".scss": {LineComment: "//", BlockDo: "/*", BlockDone: "*/"},
".sh": {LineComment: "#"},
".sql": {LineComment: "--"},
".ts": {LineComment: "//", BlockDo: "/*", BlockDone: "*/"},
}
type ProcessState struct {
filesInProcess map[string]bool
}
type Style struct {
LineComment string
BlockDo string
BlockDone string
}
func main() {
state := &ProcessState{
filesInProcess: make(map[string]bool),
}
if err := processMD(os.Stdin, os.Stdout, state); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// processMD reads Markdown from input and writes to output, processing embed blocks
func processMD(input io.Reader, output io.Writer, state *ProcessState) error {
scanner := bufio.NewScanner(input)
inEmbedBlock := false // Flag to track if we're inside an embed block
var lines []string // Collects lines within an embed block
for scanner.Scan() {
line := scanner.Text()
if !inEmbedBlock {
if line == "```embed" {
// Start of embed block
inEmbedBlock = true
lines = []string{}
} else {
// Write line directly to output
fmt.Fprintln(output, line)
}
} else {
if line == "```" {
// End of an embed block
if err := processEmbed(lines, output, state); err != nil {
return err
}
inEmbedBlock = false
} else {
// Collect lines in embed block
lines = append(lines, line)
}
}
}
if inEmbedBlock {
return fmt.Errorf("unterminated ```embed code block")
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
// processEmbed processes lines collected within an embed block
func processEmbed(lines []string, output io.Writer, state *ProcessState) error {
for i, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
filename := parts[0] // Required filename
blockName := "" // Optional block name
if len(parts) == 2 {
blockName = parts[1]
} else if len(parts) > 2 {
return fmt.Errorf("invalid format in embed code block: %s", line)
}
content, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read file %s: %v", filename, err)
}
fileContent := string(content)
if err := processFile(filename, blockName, fileContent, output, state); err != nil {
return err
}
// Add newline between multiple code blocks
if i < len(lines)-1 {
fmt.Fprintln(output)
}
}
return nil
}
// processFile processes an individual file, handling circular embeddings
func processFile(filename, blockName, fileContent string, output io.Writer, state *ProcessState) error {
if state.filesInProcess[filename] {
return fmt.Errorf("circular embedding detected for file %s", filename)
}
// Mark the file as being processed
state.filesInProcess[filename] = true
defer delete(state.filesInProcess, filename)
ext := filepath.Ext(filename)
if ext == ".md" {
// Process Markdown files recursively
reader := strings.NewReader(fileContent)
if err := processMD(reader, output, state); err != nil {
return fmt.Errorf("processing markdown file %s failed: %v", filename, err)
}
} else {
// Process other files as code blocks
if err := processCodeFile(filename, blockName, fileContent, output); err != nil {
return err
}
}
return nil
}
// processCodeFile processes non-Markdown files and embeds their content in code fences
func processCodeFile(filename, blockName, fileContent string, output io.Writer) error {
ext := filepath.Ext(filename)
lang := strings.TrimPrefix(ext, ".")
// Get comment style based on file extension
style, ok := styles[ext]
if !ok {
return fmt.Errorf("unsupported file type: %s", ext)
}
// Prepare filename comment
var fileName string
if style.LineComment != "" {
fileName = style.LineComment + " " + filename
} else if style.BlockDo != "" && style.BlockDone != "" {
fileName = fmt.Sprintf("%s %s %s", style.BlockDo, filename, style.BlockDone)
}
// If a block name is specified, extract block between marks
if blockName != "" {
doMark, doneMark := getBlockMarkers(style, blockName)
extractedContent, err := extractBlock(fileContent, doMark, doneMark)
if err != nil {
return fmt.Errorf("%v in file %s", err, filename)
}
fileContent = extractedContent
}
// Clean up content
fileContent = strings.Trim(fileContent, "\n")
fileContent = dedent(fileContent)
// Write code block to output
fmt.Fprintf(output, "```%s\n", lang)
fmt.Fprintf(output, "%s\n", fileName)
fmt.Fprintf(output, "%s", fileContent)
fmt.Fprintf(output, "\n```\n")
return nil
}
// getBlockMarkers generates the start and end markers for a block in a file
func getBlockMarkers(style Style, blockName string) (string, string) {
blockName = strings.TrimSpace(blockName)
var doMark, doneMark string
if style.LineComment != "" {
// Line comment marks
doMark = strings.TrimSpace(fmt.Sprintf("%s emdo %s", style.LineComment, blockName))
doneMark = strings.TrimSpace(fmt.Sprintf("%s emdone %s", style.LineComment, blockName))
} else if style.BlockDo != "" && style.BlockDone != "" {
// Block comment marks
beginContent := strings.TrimSpace(fmt.Sprintf("emdo %s", blockName))
endContent := strings.TrimSpace(fmt.Sprintf("emdone %s", blockName))
doMark = fmt.Sprintf("%s %s %s", style.BlockDo, beginContent, style.BlockDone)
doneMark = fmt.Sprintf("%s %s %s", style.BlockDo, endContent, style.BlockDone)
} else {
return "", ""
}
return doMark, doneMark
}
// extractBlock extracts the content between doMark and doneMark, ignoring leading and trailing whitespace
func extractBlock(fileContent, doMark, doneMark string) (string, error) {
lines := strings.Split(fileContent, "\n")
var inBlock bool
var blockLines []string
for _, line := range lines {
trimmedLine := strings.TrimSpace(line)
if !inBlock {
if trimmedLine == doMark {
inBlock = true
}
} else {
if trimmedLine == doneMark {
inBlock = false
break
}
blockLines = append(blockLines, line)
}
}
if inBlock {
return "", fmt.Errorf("done mark '%s' not found", doneMark)
}
if len(blockLines) == 0 {
return "", fmt.Errorf("no content found between do mark '%s' and done mark '%s'", doMark, doneMark)
}
return strings.Join(blockLines, "\n"), nil
}
// dedent removes common leading whitespace from all lines
func dedent(s string) string {
lines := strings.Split(s, "\n")
minIndent := -1
// Find minimum indentation level
for _, line := range lines {
trimmed := strings.TrimLeft(line, " \t")
if trimmed == "" {
continue // Skip empty or whitespace-only lines
}
indent := len(line) - len(trimmed)
if minIndent == -1 || indent < minIndent {
minIndent = indent
}
}
// Remove minimum indentation from each line
if minIndent > 0 {
for i, line := range lines {
if len(line) >= minIndent {
lines[i] = line[minIndent:]
}
}
}
return strings.Join(lines, "\n")
}