-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontmatter.go
More file actions
631 lines (591 loc) · 17.6 KB
/
frontmatter.go
File metadata and controls
631 lines (591 loc) · 17.6 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
package cooklang
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
)
// FrontmatterEditor provides CRUD operations for recipe frontmatter metadata.
// It allows reading, updating, and managing recipe metadata without manually parsing YAML.
//
// The editor works with the structured Recipe fields (title, cuisine, servings, etc.)
// as well as custom metadata fields, providing a unified interface for metadata management.
//
// Example:
//
// editor, err := cooklang.NewFrontmatterEditor("recipe.cook")
// if err != nil {
// log.Fatal(err)
// }
// editor.SetMetadata("title", "Improved Pasta")
// editor.SetMetadata("servings", "4")
// editor.Save()
type FrontmatterEditor struct {
filePath string
content string
recipe *Recipe
}
// NewFrontmatterEditor creates a new FrontmatterEditor for the given recipe file.
// It reads and parses the file, making the metadata available for manipulation.
//
// Parameters:
// - filePath: Path to the .cook file to edit
//
// Returns:
// - *FrontmatterEditor: An editor instance ready for metadata operations
// - error: Any error encountered during file reading or parsing
//
// Example:
//
// editor, err := cooklang.NewFrontmatterEditor("lasagna.cook")
// if err != nil {
// log.Fatal(err)
// }
// title, _ := editor.GetMetadata("title")
// fmt.Println(title)
func NewFrontmatterEditor(filePath string) (*FrontmatterEditor, error) {
content, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
recipe, err := ParseBytes(content)
if err != nil {
return nil, fmt.Errorf("failed to parse recipe: %w", err)
}
return &FrontmatterEditor{
filePath: filePath,
content: string(content),
recipe: recipe,
}, nil
}
// GetMetadata retrieves a metadata value by key.
// It checks structured fields first (title, cuisine, etc.) then falls back to the generic metadata map.
//
// For array fields (tags, images), the value is returned as a comma-separated string.
// Use [FrontmatterEditor.AppendToArray] and [FrontmatterEditor.RemoveFromArray] for
// individual item operations.
//
// Parameters:
// - key: The metadata key to retrieve
//
// Returns:
// - string: The metadata value (comma-separated for array fields)
// - bool: true if the key exists, false otherwise
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// if title, ok := editor.GetMetadata("title"); ok {
// fmt.Printf("Recipe title: %s\n", title)
// }
// if tags, ok := editor.GetMetadata("tags"); ok {
// fmt.Printf("Tags: %s\n", tags) // e.g., "italian, pasta, quick"
// }
func (fe *FrontmatterEditor) GetMetadata(key string) (string, bool) {
// Check structured fields first
switch key {
case "title":
if fe.recipe.Title != "" {
return fe.recipe.Title, true
}
case "cuisine":
if fe.recipe.Cuisine != "" {
return fe.recipe.Cuisine, true
}
case "description":
if fe.recipe.Description != "" {
return fe.recipe.Description, true
}
case "difficulty":
if fe.recipe.Difficulty != "" {
return fe.recipe.Difficulty, true
}
case "prep_time":
if fe.recipe.PrepTime != "" {
return fe.recipe.PrepTime, true
}
case "total_time":
if fe.recipe.TotalTime != "" {
return fe.recipe.TotalTime, true
}
case "author":
if fe.recipe.Author != "" {
return fe.recipe.Author, true
}
case "servings":
if fe.recipe.Servings > 0 {
return fmt.Sprintf("%g", fe.recipe.Servings), true
}
case "date":
if !fe.recipe.Date.IsZero() {
return fe.recipe.Date.Format("2006-01-02"), true
}
case "tags":
if len(fe.recipe.Tags) > 0 {
return strings.Join(fe.recipe.Tags, ", "), true
}
case "images", "image":
if len(fe.recipe.Images) > 0 {
return strings.Join(fe.recipe.Images, ", "), true
}
}
// Check generic metadata map
if val, ok := fe.recipe.Metadata[key]; ok {
return val, true
}
return "", false
}
// GetAllMetadata returns all metadata as a map.
// This includes both structured fields (title, cuisine, etc.) and custom metadata.
//
// Returns:
// - map[string]string: All metadata key-value pairs
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// allMeta := editor.GetAllMetadata()
// for key, value := range allMeta {
// fmt.Printf("%s: %s\n", key, value)
// }
func (fe *FrontmatterEditor) GetAllMetadata() map[string]string {
result := make(map[string]string)
// Add structured fields
if fe.recipe.Title != "" {
result["title"] = fe.recipe.Title
}
if fe.recipe.Cuisine != "" {
result["cuisine"] = fe.recipe.Cuisine
}
if fe.recipe.Description != "" {
result["description"] = fe.recipe.Description
}
if fe.recipe.Difficulty != "" {
result["difficulty"] = fe.recipe.Difficulty
}
if fe.recipe.PrepTime != "" {
result["prep_time"] = fe.recipe.PrepTime
}
if fe.recipe.TotalTime != "" {
result["total_time"] = fe.recipe.TotalTime
}
if fe.recipe.Author != "" {
result["author"] = fe.recipe.Author
}
if fe.recipe.Servings > 0 {
result["servings"] = fmt.Sprintf("%g", fe.recipe.Servings)
}
if !fe.recipe.Date.IsZero() {
result["date"] = fe.recipe.Date.Format("2006-01-02")
}
if len(fe.recipe.Tags) > 0 {
result["tags"] = strings.Join(fe.recipe.Tags, ", ")
}
if len(fe.recipe.Images) > 0 {
result["images"] = strings.Join(fe.recipe.Images, ", ")
}
// Add generic metadata
for k, v := range fe.recipe.Metadata {
result[k] = v
}
return result
}
// SetMetadata sets or updates a metadata value.
// For array fields (tags, images), the value should be comma-separated; it will be
// split and stored as a []string internally. To add/remove individual items without
// replacing the entire array, use [FrontmatterEditor.AppendToArray] and
// [FrontmatterEditor.RemoveFromArray] instead.
//
// For structured fields (servings, date), the value is validated and parsed.
//
// Parameters:
// - key: The metadata key to set
// - value: The value to set (comma-separated for array fields)
//
// Returns:
// - error: Validation error for structured fields (e.g., invalid date format)
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// editor.SetMetadata("title", "Amazing Lasagna")
// editor.SetMetadata("servings", "6")
// editor.SetMetadata("tags", "italian, pasta, main course") // replaces all tags
// editor.SetMetadata("date", "2024-01-15")
// editor.Save()
func (fe *FrontmatterEditor) SetMetadata(key, value string) error {
// Update the recipe object
switch key {
case "title":
fe.recipe.Title = value
fe.recipe.Metadata[key] = value
case "cuisine":
fe.recipe.Cuisine = value
fe.recipe.Metadata[key] = value
case "description":
fe.recipe.Description = value
fe.recipe.Metadata[key] = value
case "difficulty":
fe.recipe.Difficulty = value
fe.recipe.Metadata[key] = value
case "prep_time":
fe.recipe.PrepTime = value
fe.recipe.Metadata[key] = value
case "total_time":
fe.recipe.TotalTime = value
fe.recipe.Metadata[key] = value
case "author":
fe.recipe.Author = value
fe.recipe.Metadata[key] = value
case "servings":
servings, err := strconv.ParseFloat(value, 32)
if err != nil {
return fmt.Errorf("invalid servings value: %w", err)
}
fe.recipe.Servings = float32(servings)
fe.recipe.Metadata[key] = value
case "date":
date, err := time.Parse("2006-01-02", value)
if err != nil {
return fmt.Errorf("invalid date format (use YYYY-MM-DD): %w", err)
}
fe.recipe.Date = date
fe.recipe.Metadata[key] = value
case "tags":
fe.recipe.Tags = splitAndTrim(value)
fe.recipe.Metadata[key] = value
case "images", "image":
fe.recipe.Images = splitAndTrim(value)
fe.recipe.Metadata["images"] = value
if key == "image" {
fe.recipe.Metadata["image"] = value
}
default:
// Store in generic metadata
fe.recipe.Metadata[key] = value
}
return nil
}
// DeleteMetadata removes a metadata key from the recipe.
// For structured fields, this clears the value. For custom fields, it removes the entry.
//
// Parameters:
// - key: The metadata key to delete
//
// Returns:
// - error: Currently always returns nil (reserved for future validation)
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// editor.DeleteMetadata("author")
// editor.DeleteMetadata("custom_field")
// editor.Save()
func (fe *FrontmatterEditor) DeleteMetadata(key string) error {
// Clear structured fields
switch key {
case "title":
fe.recipe.Title = ""
delete(fe.recipe.Metadata, key)
case "cuisine":
fe.recipe.Cuisine = ""
delete(fe.recipe.Metadata, key)
case "description":
fe.recipe.Description = ""
delete(fe.recipe.Metadata, key)
case "difficulty":
fe.recipe.Difficulty = ""
delete(fe.recipe.Metadata, key)
case "prep_time":
fe.recipe.PrepTime = ""
delete(fe.recipe.Metadata, key)
case "total_time":
fe.recipe.TotalTime = ""
delete(fe.recipe.Metadata, key)
case "author":
fe.recipe.Author = ""
delete(fe.recipe.Metadata, key)
case "servings":
fe.recipe.Servings = 0
delete(fe.recipe.Metadata, key)
case "date":
fe.recipe.Date = time.Time{}
delete(fe.recipe.Metadata, key)
case "tags":
fe.recipe.Tags = nil
delete(fe.recipe.Metadata, key)
case "images", "image":
fe.recipe.Images = nil
delete(fe.recipe.Metadata, key)
delete(fe.recipe.Metadata, "images")
delete(fe.recipe.Metadata, "image")
default:
// Remove from generic metadata
delete(fe.recipe.Metadata, key)
}
return nil
}
// Save writes the updated recipe back to the original file.
// The recipe body (instructions) is preserved; only the frontmatter is updated.
//
// Returns:
// - error: Any error encountered during file writing
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// editor.SetMetadata("title", "Updated Title")
// if err := editor.Save(); err != nil {
// log.Fatal(err)
// }
func (fe *FrontmatterEditor) Save() error {
return fe.SaveAs(fe.filePath)
}
// SaveAs writes the updated recipe to a specified file path.
// The recipe body (instructions) is preserved; only the frontmatter is updated.
//
// Parameters:
// - filePath: The destination file path
//
// Returns:
// - error: Any error encountered during file writing
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// editor.SetMetadata("title", "Updated Recipe")
// editor.SaveAs("recipe_v2.cook")
func (fe *FrontmatterEditor) SaveAs(filePath string) error {
// Get the recipe content after frontmatter
recipeBody := fe.extractRecipeBody()
// Render the frontmatter
frontmatter := fe.renderFrontmatter()
// Combine frontmatter and body
newContent := frontmatter + "\n" + recipeBody
// Write to file
if err := os.WriteFile(filePath, []byte(newContent), 0644); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
// Update internal state if saving to the same file
if filePath == fe.filePath {
fe.content = newContent
}
return nil
}
// GetContent returns the original file content as read from disk.
//
// Returns:
// - string: The original file content
func (fe *FrontmatterEditor) GetContent() string {
return fe.content
}
// GetUpdatedContent returns the updated content without saving to disk.
// This is useful for previewing changes before committing them.
//
// Returns:
// - string: The complete file content with updated frontmatter
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// editor.SetMetadata("title", "Preview")
// preview := editor.GetUpdatedContent()
// fmt.Println(preview) // See changes without saving
func (fe *FrontmatterEditor) GetUpdatedContent() string {
recipeBody := fe.extractRecipeBody()
frontmatter := fe.renderFrontmatter()
return frontmatter + "\n" + recipeBody
}
// extractRecipeBody extracts the recipe content (instructions) after the frontmatter.
func (fe *FrontmatterEditor) extractRecipeBody() string {
// Match YAML frontmatter delimited by ---
re := regexp.MustCompile(`(?s)^---\n.*?\n---\n`)
body := re.ReplaceAllString(fe.content, "")
// If no frontmatter found, return original content
if body == fe.content {
// Check if content starts with frontmatter
if strings.HasPrefix(fe.content, "---\n") {
// Find the end of frontmatter
parts := strings.SplitN(fe.content, "\n---\n", 2)
if len(parts) == 2 {
return parts[1]
}
}
return fe.content
}
return strings.TrimLeft(body, "\n")
}
// renderFrontmatter renders the current recipe metadata as YAML frontmatter.
func (fe *FrontmatterEditor) renderFrontmatter() string {
var lines []string
lines = append(lines, "---")
// Add structured fields in a logical order
if fe.recipe.Title != "" {
lines = append(lines, renderYAMLValue("title", fe.recipe.Title)...)
}
if fe.recipe.Cuisine != "" {
lines = append(lines, renderYAMLValue("cuisine", fe.recipe.Cuisine)...)
}
if fe.recipe.Description != "" {
lines = append(lines, renderYAMLValue("description", fe.recipe.Description)...)
}
if fe.recipe.Difficulty != "" {
lines = append(lines, renderYAMLValue("difficulty", fe.recipe.Difficulty)...)
}
if fe.recipe.Author != "" {
lines = append(lines, renderYAMLValue("author", fe.recipe.Author)...)
}
if !fe.recipe.Date.IsZero() {
lines = append(lines, fmt.Sprintf("date: %s", fe.recipe.Date.Format("2006-01-02")))
}
if fe.recipe.Servings > 0 {
lines = append(lines, fmt.Sprintf("servings: %g", fe.recipe.Servings))
}
if fe.recipe.PrepTime != "" {
lines = append(lines, renderYAMLValue("prep_time", fe.recipe.PrepTime)...)
}
if fe.recipe.TotalTime != "" {
lines = append(lines, renderYAMLValue("total_time", fe.recipe.TotalTime)...)
}
if len(fe.recipe.Tags) > 0 {
lines = append(lines, "tags:")
for _, tag := range fe.recipe.Tags {
lines = append(lines, fmt.Sprintf(" - %s", tag))
}
}
if len(fe.recipe.Images) > 0 {
lines = append(lines, "images:")
for _, img := range fe.recipe.Images {
lines = append(lines, fmt.Sprintf(" - %s", img))
}
}
// Add generic metadata fields (alphabetically)
keys := make([]string, 0, len(fe.recipe.Metadata))
for k := range fe.recipe.Metadata {
// Skip fields we've already added
if !isStandardField(k) {
keys = append(keys, k)
}
}
// Simple sort
for i := 0; i < len(keys); i++ {
for j := i + 1; j < len(keys); j++ {
if keys[i] > keys[j] {
keys[i], keys[j] = keys[j], keys[i]
}
}
}
for _, key := range keys {
value := fe.recipe.Metadata[key]
lines = append(lines, renderYAMLValue(key, value)...)
}
lines = append(lines, "---")
return strings.Join(lines, "\n")
}
// renderYAMLValue renders a key-value pair, using block scalar syntax for multi-line values.
func renderYAMLValue(key, value string) []string {
// Check if value contains newlines
if strings.Contains(value, "\n") {
// Use literal block scalar with strip chomping (|-)
lines := []string{fmt.Sprintf("%s: |-", key)}
for _, line := range strings.Split(value, "\n") {
lines = append(lines, " "+line)
}
return lines
}
// Single-line value - use inline format
return []string{fmt.Sprintf("%s: %s", key, value)}
}
// isStandardField checks if a key is a standard structured field.
func isStandardField(key string) bool {
standardFields := []string{
"title", "cuisine", "description", "difficulty", "author",
"date", "servings", "prep_time", "total_time", "tags", "images", "image",
}
for _, field := range standardFields {
if field == key {
return true
}
}
return false
}
// splitAndTrim splits a comma-separated string and trims whitespace from each part.
func splitAndTrim(s string) []string {
parts := strings.Split(s, ",")
result := make([]string, 0, len(parts))
for _, part := range parts {
trimmed := strings.TrimSpace(part)
if trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
// AppendToArray appends a value to an array field (tags or images).
// Unlike [FrontmatterEditor.SetMetadata], this adds a single item without replacing existing values.
// The underlying storage is []string, not a comma-separated string.
//
// Parameters:
// - key: The array field name ("tags" or "images")
// - value: The single value to append
//
// Returns:
// - error: An error if the field is not an array field
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// // Assuming tags are currently ["italian"]
// editor.AppendToArray("tags", "vegetarian") // tags: ["italian", "vegetarian"]
// editor.AppendToArray("tags", "healthy") // tags: ["italian", "vegetarian", "healthy"]
// editor.Save()
func (fe *FrontmatterEditor) AppendToArray(key, value string) error {
switch key {
case "tags":
fe.recipe.Tags = append(fe.recipe.Tags, value)
case "images", "image":
fe.recipe.Images = append(fe.recipe.Images, value)
default:
return fmt.Errorf("field %s is not an array field", key)
}
return nil
}
// RemoveFromArray removes a value from an array field (tags or images).
// All occurrences of the value are removed. The underlying storage is []string.
//
// Parameters:
// - key: The array field name ("tags" or "images")
// - value: The single value to remove
//
// Returns:
// - error: An error if the field is not an array field
//
// Example:
//
// editor, _ := cooklang.NewFrontmatterEditor("recipe.cook")
// // Assuming tags are currently ["italian", "unhealthy", "quick"]
// editor.RemoveFromArray("tags", "unhealthy") // tags: ["italian", "quick"]
// editor.Save()
func (fe *FrontmatterEditor) RemoveFromArray(key, value string) error {
switch key {
case "tags":
fe.recipe.Tags = removeFromSlice(fe.recipe.Tags, value)
case "images", "image":
fe.recipe.Images = removeFromSlice(fe.recipe.Images, value)
default:
return fmt.Errorf("field %s is not an array field", key)
}
return nil
}
// removeFromSlice removes all occurrences of a value from a slice.
func removeFromSlice(slice []string, value string) []string {
result := make([]string, 0, len(slice))
for _, item := range slice {
if item != value {
result = append(result, item)
}
}
return result
}