-
Notifications
You must be signed in to change notification settings - Fork 354
Expand file tree
/
Copy pathfrontmatter_content.go
More file actions
278 lines (241 loc) · 9.95 KB
/
frontmatter_content.go
File metadata and controls
278 lines (241 loc) · 9.95 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
package parser
import (
"bufio"
"bytes"
"errors"
"fmt"
"path/filepath"
"regexp"
"strings"
"github.com/goccy/go-yaml"
)
// FrontmatterResult holds parsed frontmatter and markdown content
type FrontmatterResult struct {
Frontmatter map[string]any
Markdown string
// Additional fields for error context
FrontmatterLines []string // Original frontmatter lines for error context
FrontmatterStart int // Line number where frontmatter starts (1-based)
}
// ExtractFrontmatterFromContent parses YAML frontmatter from markdown content string
func ExtractFrontmatterFromContent(content string) (*FrontmatterResult, error) {
log.Printf("Extracting frontmatter from content: size=%d bytes", len(content))
// Fast-path: inspect only the first line to determine whether frontmatter exists.
firstNewline := strings.IndexByte(content, '\n')
firstLine := content
if firstNewline >= 0 {
firstLine = content[:firstNewline]
}
// Check if file starts with frontmatter delimiter.
if strings.TrimSpace(firstLine) != "---" {
log.Print("No frontmatter delimiter found, returning content as markdown")
// No frontmatter, return entire content as markdown
return &FrontmatterResult{
Frontmatter: make(map[string]any),
Markdown: content,
FrontmatterLines: []string{},
FrontmatterStart: 0,
}, nil
}
// Find end of frontmatter by scanning line-by-line without splitting the entire document.
searchStart := len(content)
if firstNewline >= 0 {
searchStart = firstNewline + 1
}
frontmatterEndStart := -1
markdownStart := len(content)
for cursor := searchStart; cursor <= len(content); {
lineStart := cursor
lineEnd := len(content)
nextCursor := len(content) + 1
if cursor < len(content) {
if relNewline := strings.IndexByte(content[cursor:], '\n'); relNewline >= 0 {
lineEnd = cursor + relNewline
nextCursor = lineEnd + 1
}
}
if strings.TrimSpace(content[lineStart:lineEnd]) == "---" {
frontmatterEndStart = lineStart
markdownStart = nextCursor
break
}
if nextCursor > len(content) {
break
}
cursor = nextCursor
}
if frontmatterEndStart == -1 {
return nil, errors.New("frontmatter not properly closed")
}
// Extract frontmatter YAML
frontmatterYAML := content[searchStart:frontmatterEndStart]
frontmatterLines := []string{}
if frontmatterYAML != "" {
frontmatterLines = strings.Split(frontmatterYAML, "\n")
// Preserve previous behavior from lines[1:endIndex]: a trailing newline before
// the closing delimiter does not create an additional empty frontmatter line.
if strings.HasSuffix(frontmatterYAML, "\n") {
frontmatterLines = frontmatterLines[:len(frontmatterLines)-1]
}
}
// Sanitize no-break whitespace characters (U+00A0) which break the YAML parser
frontmatterYAML = strings.ReplaceAll(frontmatterYAML, "\u00A0", " ")
// Parse YAML
var frontmatter map[string]any
if err := yaml.Unmarshal([]byte(frontmatterYAML), &frontmatter); err != nil {
// Use FormatYAMLError to provide source-positioned error output with adjusted line numbers
// FrontmatterStart is 2 (line 2 is where frontmatter content starts after opening ---)
formattedErr := FormatYAMLError(err, 2, frontmatterYAML)
return nil, fmt.Errorf("failed to parse frontmatter:\n%s", formattedErr)
}
// Ensure frontmatter is never nil (yaml.Unmarshal sets it to nil for empty YAML)
if frontmatter == nil {
frontmatter = make(map[string]any)
}
// Extract markdown content (everything after the closing ---)
markdown := ""
if markdownStart <= len(content) {
markdown = content[markdownStart:]
}
log.Printf("Successfully extracted frontmatter: fields=%d, markdown_size=%d bytes", len(frontmatter), len(markdown))
return &FrontmatterResult{
Frontmatter: frontmatter,
Markdown: strings.TrimSpace(markdown),
FrontmatterLines: frontmatterLines,
FrontmatterStart: 2, // Line 2 is where frontmatter content starts (after opening ---)
}, nil
}
// ExtractFrontmatterFromBuiltinFile is a caching wrapper around ExtractFrontmatterFromContent
// for builtin virtual files. Because builtin files are registered once at startup and never
// change, the parsed FrontmatterResult is identical across calls. This function caches the
// first parse result in builtinFrontmatterCache and returns the cached (shared) value on
// subsequent calls, avoiding repeated YAML parsing for frequently imported engine definition
// files.
//
// IMPORTANT: The returned *FrontmatterResult is a shared, read-only reference.
// Callers MUST NOT mutate the result or any of its fields (Frontmatter map, slices, etc.).
// Use ExtractFrontmatterFromContent directly when you need a mutable copy.
//
// path must start with BuiltinPathPrefix ("@builtin:"); an error is returned otherwise.
func ExtractFrontmatterFromBuiltinFile(path string, content []byte) (*FrontmatterResult, error) {
if !strings.HasPrefix(path, BuiltinPathPrefix) {
return nil, fmt.Errorf("ExtractFrontmatterFromBuiltinFile: path %q does not start with %q", path, BuiltinPathPrefix)
}
if cached, ok := GetBuiltinFrontmatterCache(path); ok {
return cached, nil
}
result, err := ExtractFrontmatterFromContent(string(content))
if err != nil {
return nil, err
}
// SetBuiltinFrontmatterCache uses LoadOrStore so concurrent races are safe.
return SetBuiltinFrontmatterCache(path, result), nil
}
// ExtractMarkdownSection extracts a specific section from markdown content
// Supports H1-H3 headers and proper nesting (matches bash implementation)
func ExtractMarkdownSection(content, sectionName string) (string, error) {
log.Printf("Extracting markdown section: section=%s, content_size=%d bytes", sectionName, len(content))
scanner := bufio.NewScanner(strings.NewReader(content))
var sectionContent bytes.Buffer
inSection := false
var sectionLevel int
// Create regex pattern to match headers at any level (H1-H3) with flexible spacing
headerPattern := regexp.MustCompile(`^(#{1,3})[\s\t]+` + regexp.QuoteMeta(sectionName) + `[\s\t]*$`)
levelPattern := regexp.MustCompile(`^(#{1,3})[\s\t]+`)
for scanner.Scan() {
line := scanner.Text()
// Check if this line matches our target section
if matches := headerPattern.FindStringSubmatch(line); matches != nil {
inSection = true
sectionLevel = len(matches[1]) // Number of # characters
sectionContent.WriteString(line + "\n")
continue
}
// If we're in the section, check if we've hit another header at same or higher level
if inSection {
if levelMatches := levelPattern.FindStringSubmatch(line); levelMatches != nil {
currentLevel := len(levelMatches[1])
// Stop if we encounter same or higher level header
if currentLevel <= sectionLevel {
break
}
}
sectionContent.WriteString(line + "\n")
}
}
if !inSection {
log.Printf("Section not found: %s", sectionName)
return "", fmt.Errorf("section '%s' not found", sectionName)
}
extractedContent := strings.TrimSpace(sectionContent.String())
log.Printf("Successfully extracted section: size=%d bytes", len(extractedContent))
return extractedContent, nil
}
// ExtractMarkdownContent extracts only the markdown content (excluding frontmatter)
// This matches the bash extract_markdown function
func ExtractMarkdownContent(content string) (string, error) {
result, err := ExtractFrontmatterFromContent(content)
if err != nil {
return "", err
}
return result.Markdown, nil
}
// ExtractWorkflowNameFromMarkdownBody extracts the workflow name from an already-extracted
// markdown body (i.e. the content after the frontmatter has been stripped). This is more
// efficient than ExtractWorkflowNameFromMarkdown or ExtractWorkflowNameFromContent because it
// avoids the redundant file-read and YAML-parse that those functions perform when the caller
// already holds the parsed FrontmatterResult.
func ExtractWorkflowNameFromMarkdownBody(markdownBody string, virtualPath string) (string, error) {
log.Printf("Extracting workflow name from markdown body: virtualPath=%s, size=%d bytes", virtualPath, len(markdownBody))
scanner := bufio.NewScanner(strings.NewReader(markdownBody))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "# ") {
workflowName := strings.TrimSpace(line[2:])
log.Printf("Found workflow name from H1 header: %s", workflowName)
return workflowName, nil
}
}
defaultName := generateDefaultWorkflowName(virtualPath)
log.Printf("No H1 header found, using default name: %s", defaultName)
return defaultName, nil
}
// ExtractWorkflowNameFromContent extracts the workflow name from markdown content string.
// This is the in-memory equivalent of ExtractWorkflowNameFromMarkdown, used by Wasm builds
// where filesystem access is unavailable.
func ExtractWorkflowNameFromContent(content string, virtualPath string) (string, error) {
log.Printf("Extracting workflow name from content: virtualPath=%s, size=%d bytes", virtualPath, len(content))
markdownContent, err := ExtractMarkdownContent(content)
if err != nil {
return "", err
}
scanner := bufio.NewScanner(strings.NewReader(markdownContent))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "# ") {
workflowName := strings.TrimSpace(line[2:])
log.Printf("Found workflow name from H1 header: %s", workflowName)
return workflowName, nil
}
}
defaultName := generateDefaultWorkflowName(virtualPath)
log.Printf("No H1 header found, using default name: %s", defaultName)
return defaultName, nil
}
// generateDefaultWorkflowName creates a default workflow name from filename
// This matches the bash implementation's fallback behavior
func generateDefaultWorkflowName(filePath string) string {
// Get base filename without extension
baseName := filepath.Base(filePath)
baseName = strings.TrimSuffix(baseName, filepath.Ext(baseName))
// Convert hyphens to spaces
baseName = strings.ReplaceAll(baseName, "-", " ")
// Capitalize first letter of each word
words := strings.Fields(baseName)
for i, word := range words {
if len(word) > 0 {
words[i] = strings.ToUpper(word[:1]) + word[1:]
}
}
return strings.Join(words, " ")
}