-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcooklang.go
More file actions
2365 lines (2160 loc) · 75 KB
/
cooklang.go
File metadata and controls
2365 lines (2160 loc) · 75 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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cooklang
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/bcicen/go-units"
"github.com/hilli/cooklang/parser"
)
// Recipe represents a parsed Cooklang recipe with its metadata and step-by-step instructions.
// The Recipe struct provides access to all recipe information including ingredients, cookware,
// timers, and cooking instructions organized as a linked list of steps.
//
// Recipes can be created by parsing Cooklang files using ParseFile, ParseString, or ParseBytes.
//
// Example:
//
// recipe, err := cooklang.ParseFile("lasagna.cook")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(recipe.Title)
// ingredients := recipe.GetIngredients()
type Recipe struct {
Title string `json:"title,omitempty"` // Recipe title from frontmatter
Cuisine string `json:"cuisine,omitempty"` // Cuisine type (e.g., "Italian", "Mexican")
Date time.Time `json:"date,omitempty"` // Recipe date in YYYY-MM-DD format
Description string `json:"description,omitempty"` // Brief recipe description
Difficulty string `json:"difficulty,omitempty"` // Difficulty level (e.g., "easy", "medium", "hard")
PrepTime string `json:"prep_time,omitempty"` // Preparation time (e.g., "15 minutes")
TotalTime string `json:"total_time,omitempty"` // Total cooking time
Metadata Metadata `json:"metadata,omitempty"` // Additional custom metadata fields
Author string `json:"author,omitempty"` // Recipe author name
Images []string `json:"images,omitempty"` // Image filenames associated with the recipe
Servings float32 `json:"servings,omitempty"` // Number of servings this recipe makes
Tags []string `json:"tags,omitempty"` // Recipe tags for categorization
FirstStep *Step `json:"first_step,omitempty"` // First step in the linked list of recipe steps
CooklangRenderable
}
// CooklangRenderable provides rendering capabilities for recipe components.
// It allows custom rendering functions to be attached to recipes and their components.
type CooklangRenderable struct {
RenderFunc func() string `json:"-"` // Custom rendering function
}
// Metadata stores arbitrary key-value pairs for recipe metadata not covered by structured fields.
// This allows recipes to include custom fields beyond the standard ones.
//
// Example:
//
// metadata := Metadata{
// "source": "Grandma's cookbook",
// "category": "dessert",
// }
type Metadata map[string]string
// UnitSystem defines supported unit systems for easy conversion
type UnitSystem string
const (
UnitSystemMetric UnitSystem = "metric"
UnitSystemImperial UnitSystem = "imperial"
UnitSystemUS UnitSystem = "us"
)
// canonicalUnits maps quantity types to preferred units for each system
var canonicalUnits = map[UnitSystem]map[string]string{
UnitSystemMetric: {
"mass": "g",
"volume": "ml",
"length": "cm",
"temperature": "c",
},
UnitSystemImperial: {
"mass": "oz",
"volume": "ml", // Will be converted to appropriate units via mappings
"length": "in",
"temperature": "f",
},
UnitSystemUS: {
"mass": "oz",
"volume": "ml", // Will be converted to appropriate units via mappings
"length": "in",
"temperature": "f",
},
}
// commonUnitMappings provides alternative units for better recipe display
var commonUnitMappings = map[UnitSystem]map[string]map[string]string{
UnitSystemMetric: {
"volume": {
"large": "l", // for volumes >= 1000ml
"small": "ml", // for volumes < 1000ml
},
"mass": {
"large": "kg", // for mass >= 1000g
"small": "g", // for mass < 1000g
},
},
UnitSystemUS: {
"volume": {
"large": "qt", // for large volumes
"medium": "cup", // for medium volumes
"small": "tbsp", // for small volumes
"tiny": "tsp", // for very small volumes
},
},
UnitSystemImperial: {
"volume": {
"large": "pt", // for large volumes
"medium": "fl_oz", // for medium volumes
"small": "tbsp", // for small volumes
"tiny": "tsp", // for very small volumes
},
},
}
// cookingUnitConversions provides conversions for common cooking units to ml (for volume)
// This supplements the go-units library which doesn't have all cooking units
var cookingUnitConversions = map[string]float64{
// Volume conversions to ml
"cup": 236.588,
"tbsp": 14.7868,
"tsp": 4.92892,
"qt": 946.353,
"pt": 473.176,
"fl_oz": 29.5735,
"gallon": 3785.41,
// Keep metric units
"ml": 1.0,
"l": 1000.0,
}
// cookingMassConversions provides conversions for mass units to grams
var cookingMassConversions = map[string]float64{
// Mass conversions to grams
"oz": 28.3495,
"lb": 453.592,
"kg": 1000.0,
"g": 1.0,
}
// convertCookingUnit converts between common cooking units using ml or grams as an intermediate.
// Supports volume units (ml, cup, tbsp, etc.) and mass units (g, kg, oz, lb).
func convertCookingUnit(value float64, fromUnit, toUnit string) (float64, error) {
// Try volume conversion first
if fromMl, okFrom := cookingUnitConversions[fromUnit]; okFrom {
if toMl, okTo := cookingUnitConversions[toUnit]; okTo {
// Convert from -> ml -> to
mlValue := value * fromMl
return mlValue / toMl, nil
}
}
// Try mass conversion
if fromG, okFrom := cookingMassConversions[fromUnit]; okFrom {
if toG, okTo := cookingMassConversions[toUnit]; okTo {
// Convert from -> g -> to
gValue := value * fromG
return gValue / toG, nil
}
}
return 0, fmt.Errorf("cannot convert from %s to %s", fromUnit, toUnit)
}
// isCookingUnit checks if a unit is a recognized cooking unit that can be converted.
func isCookingUnit(unit string) bool {
_, isVolume := cookingUnitConversions[unit]
_, isMass := cookingMassConversions[unit]
return isVolume || isMass
}
// getCookingUnitType returns "volume" or "mass" for recognized cooking units, empty string otherwise.
func getCookingUnitType(unit string) string {
if _, isVolume := cookingUnitConversions[unit]; isVolume {
return "volume"
}
if _, isMass := cookingMassConversions[unit]; isMass {
return "mass"
}
return ""
}
// StepComponent represents a component within a recipe step (ingredient, instruction, timer, or cookware).
// Components are organized as a linked list within each step, allowing iteration through the sequence of actions.
type StepComponent interface {
isStepComponent() // Marker method
Render() string // Renders the component as Cooklang syntax
SetNext(StepComponent) // Sets the next component in the linked list
GetNext() StepComponent // Gets the next component in the linked list
}
// Step represents a single step in a recipe's instructions.
// Each step contains a linked list of components (ingredients, cookware, timers, text instructions)
// and a link to the next step.
//
// Steps are traversed by following the NextStep pointer to iterate through the recipe's instructions.
type Step struct {
FirstComponent StepComponent `json:"first_component,omitempty"` // First component in this step
NextStep *Step `json:"next_step,omitempty"` // Next step in the recipe
CooklangRenderable
}
// HasDisplayableContent returns true if the step contains any content that should be displayed
// to users (ingredients, cookware, timers, non-whitespace text, sections, or notes).
// Steps containing only comments or whitespace-only text return false.
func (s *Step) HasDisplayableContent() bool {
if s == nil || s.FirstComponent == nil {
return false
}
current := s.FirstComponent
for current != nil {
switch comp := current.(type) {
case *Ingredient, *Cookware, *Timer, *Section, *Note:
return true
case *Instruction:
// Check if text has any non-whitespace content
if strings.TrimSpace(comp.Text) != "" {
return true
}
case *Comment:
// Comments alone don't make a step displayable
}
current = current.GetNext()
}
return false
}
func (Instruction) isStepComponent() {}
func (Timer) isStepComponent() {}
func (Cookware) isStepComponent() {}
func (Ingredient) isStepComponent() {}
func (Section) isStepComponent() {}
func (Comment) isStepComponent() {}
func (Note) isStepComponent() {}
// Render returns the Cooklang syntax representation of this ingredient.
// Examples: "@flour{500%g}", "@salt{}", "@milk{2%cups}(cold)", "@yeast{=1%packet}", "@?thyme{2%sprigs}"
func (i Ingredient) Render() string {
var result string
prefix := "@"
if i.Optional {
prefix = "@?"
}
fixedPrefix := ""
if i.Fixed {
fixedPrefix = "="
}
if i.Quantity > 0 {
result = fmt.Sprintf("%s%s{%s%g%%%s}", prefix, i.Name, fixedPrefix, i.Quantity, i.Unit)
} else if i.Quantity == -1 {
// -1 indicates "some" quantity
result = fmt.Sprintf("%s%s{}", prefix, i.Name)
} else {
result = fmt.Sprintf("%s%s{}", prefix, i.Name)
}
if i.Annotation != "" {
result += fmt.Sprintf("(%s)", i.Annotation)
}
return result
}
// RenderDisplay returns ingredient in plain text format suitable for display.
// Examples: "2 cups flour", "500 g flour", "salt", "2 sprigs thyme (optional)"
// Uses bartender-friendly fraction formatting (e.g., "1/2 oz" instead of "0.5 oz")
// When quantity is unspecified (e.g., @salt{}), returns just the ingredient name.
// Optional ingredients have "(optional)" appended.
func (i Ingredient) RenderDisplay() string {
var result string
if i.Quantity > 0 && i.Unit != "" {
qtyStr := FormatAsFractionDefault(float64(i.Quantity))
result = fmt.Sprintf("%s %s %s", qtyStr, i.Unit, i.Name)
} else if i.Quantity > 0 {
qtyStr := FormatAsFractionDefault(float64(i.Quantity))
result = fmt.Sprintf("%s %s", qtyStr, i.Name)
} else {
// Quantity == -1 (unspecified) or 0: just use the ingredient name
result = i.Name
}
if i.Optional {
result += " (optional)"
}
return result
}
// Render returns the plain text instruction.
func (inst Instruction) Render() string {
return inst.Text
}
// RenderDisplay returns instruction text suitable for display (same as Render for Instruction).
func (inst Instruction) RenderDisplay() string {
return inst.Text
}
// Render returns the Cooklang syntax representation of this timer.
// Examples: "~{10%minutes}", "~boil{15%min}"
func (t Timer) Render() string {
var result string
if t.Name != "" {
result = fmt.Sprintf("~%s{%s}", t.Name, t.Duration)
} else {
result = fmt.Sprintf("~{%s}", t.Duration)
}
if t.Annotation != "" {
result += fmt.Sprintf("(%s)", t.Annotation)
}
return result
}
// RenderDisplay returns timer in plain text format suitable for display.
// Returns the duration with unit if available, or just the duration.
// If the timer has a name but no duration, returns the name.
func (t Timer) RenderDisplay() string {
// If there's a duration, show it (optionally with unit)
if t.Duration != "" {
if t.Unit != "" {
return t.Duration + " " + t.Unit
}
return t.Duration
}
// Fall back to name if no duration
if t.Name != "" {
return t.Name
}
return ""
}
// Render returns the Cooklang syntax representation of this cookware.
// Examples: "#pot{}", "#bowl{2}", "#oven{}(preheated)"
func (c Cookware) Render() string {
var result string
if c.Quantity > 1 {
result = fmt.Sprintf("#%s{%d}", c.Name, c.Quantity)
} else {
result = fmt.Sprintf("#%s{}", c.Name)
}
if c.Annotation != "" {
result += fmt.Sprintf("(%s)", c.Annotation)
}
return result
}
// RenderDisplay returns cookware in plain text format suitable for display.
// Returns just the cookware name.
func (c Cookware) RenderDisplay() string {
return c.Name
}
// Render returns the Cooklang syntax representation of this section.
// Examples: "== Section Name =="
func (s Section) Render() string {
if s.Name != "" {
return fmt.Sprintf("== %s ==", s.Name)
}
return "=="
}
// RenderDisplay returns section name suitable for display.
func (s Section) RenderDisplay() string {
return s.Name
}
// Render returns the Cooklang syntax representation of this comment.
// Examples: "-- comment text" for line comments, "[- comment text -]" for block comments
func (cm Comment) Render() string {
if cm.IsBlock {
return fmt.Sprintf("[- %s -]", cm.Text)
}
return fmt.Sprintf("-- %s", cm.Text)
}
// RenderDisplay returns comment text suitable for display.
func (cm Comment) RenderDisplay() string {
return cm.Text
}
// Render returns the Cooklang syntax representation of this note.
// Example: "> This is a note"
func (n Note) Render() string {
return fmt.Sprintf("> %s", n.Text)
}
// RenderDisplay returns note text suitable for display.
func (n Note) RenderDisplay() string {
return n.Text
}
// Ingredient represents a recipe ingredient with quantity, unit, and optional annotations.
// Ingredients support unit conversion and consolidation for shopping lists.
//
// Example Cooklang syntax: @flour{500%g}, @salt{}, @milk{2%cups}
//
// The Quantity field uses -1 to represent "some" (unspecified amount).
// The Fixed field indicates a quantity that should not scale with servings (e.g., @salt{=1%tsp}).
// The Optional field indicates an optional ingredient (e.g., @?thyme{2%sprigs}).
type Ingredient struct {
Name string `json:"name,omitempty"` // Ingredient name (e.g., "flour", "sugar")
Quantity float32 `json:"quantity,omitempty"` // Amount (-1 means "some", 0 means none specified)
Unit string `json:"unit,omitempty"` // Unit of measurement (e.g., "g", "cup", "tbsp")
Fixed bool `json:"fixed,omitempty"` // Fixed quantity doesn't scale with servings
Optional bool `json:"optional,omitempty"` // Optional ingredient (can be omitted)
TypedUnit *units.Unit `json:"typed_unit,omitempty"` // Typed unit for conversion operations
Subinstruction string `json:"value,omitempty"` // Additional preparation instructions
Annotation string `json:"annotation,omitempty"` // Optional annotation (e.g., "finely chopped")
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// NewIngredient creates a new Ingredient with proper unit typing for conversion operations.
// This constructor ensures that the TypedUnit field is properly initialized, which is required
// for unit conversion methods like ConvertTo and ConvertToSystem to work correctly.
//
// Parameters:
// - name: The ingredient name (e.g., "vodka", "sugar")
// - quantity: The amount (-1 means "some" unspecified amount)
// - unit: The unit of measurement (e.g., "ml", "oz", "g", "cups")
//
// Example:
//
// ing := cooklang.NewIngredient("vodka", 50, "ml")
// converted := ing.ConvertToSystem(cooklang.UnitSystemUS)
// fmt.Printf("%v %s\n", converted.Quantity, converted.Unit) // "1.69 oz"
func NewIngredient(name string, quantity float32, unit string) *Ingredient {
return &Ingredient{
Name: name,
Quantity: quantity,
Unit: unit,
TypedUnit: CreateTypedUnit(unit),
}
}
// Instruction represents a text instruction within a recipe step.
// This is plain text that provides cooking directions.
type Instruction struct {
Text string `json:"text,omitempty"` // Instruction text
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// Timer represents a duration timer in a recipe step.
// Timers specify how long to perform an action.
//
// Example Cooklang syntax: ~{10%minutes}, ~boil{15%min}
type Timer struct {
Duration string `json:"duration,omitempty"` // Duration value (e.g., "10")
Name string `json:"name,omitempty"` // Timer name/description (e.g., "boil", "rest")
Text string `json:"text,omitempty"` // Full timer text
Unit string `json:"unit,omitempty"` // Time unit (e.g., "minutes", "hours")
Annotation string `json:"annotation,omitempty"` // Optional annotation
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// Cookware represents a cooking utensil or equipment needed for a recipe.
//
// Example Cooklang syntax: #pot{}, #bowl{2}, #oven{}
type Cookware struct {
Name string `json:"name,omitempty"` // Cookware name (e.g., "pot", "bowl", "oven")
Quantity int `json:"quantity,omitempty"` // Number of items needed (default 1)
Annotation string `json:"annotation,omitempty"` // Optional annotation (e.g., "large", "non-stick")
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// Section represents a section header in a recipe.
// Sections divide complex recipes into logical parts (e.g., "Dough", "Filling").
//
// Example Cooklang syntax: = Dough, == Filling ==
type Section struct {
Name string `json:"name,omitempty"` // Section name (e.g., "Dough", "Filling")
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// Comment represents a comment in a recipe.
// Comments are notes that don't affect the cooking instructions.
//
// Example Cooklang syntax:
// - Line comment: -- This is a comment
// - Block comment: [- This is a block comment -]
type Comment struct {
Text string `json:"text,omitempty"` // Comment text
IsBlock bool `json:"is_block,omitempty"` // True if this is a block comment [- -]
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// Note represents a note block in a recipe.
// Notes are supplementary information that appears in recipe details but not during cooking mode.
// They are used for background stories, tips, or personal anecdotes related to the recipe.
//
// Example Cooklang syntax:
// > This dish is even better the next day, after the flavors have melded overnight.
// > This is a multi-line note
// > that continues here.
type Note struct {
Text string `json:"text,omitempty"` // Note text
NextComponent StepComponent `json:"next_component,omitempty"` // Next component in the step
CooklangRenderable
}
// ParseFile reads and parses a Cooklang recipe file, returning a Recipe object.
// It automatically detects and includes associated image files matching the recipe filename.
//
// Image detection looks for files with the same base name:
// - Recipe.cook → Recipe.jpg, Recipe.png, Recipe.jpeg
// - Recipe.cook → Recipe-1.jpg, Recipe-2.png, etc. (numbered variants)
//
// Parameters:
// - filename: Path to the .cook file to parse
//
// Returns:
// - *Recipe: The parsed recipe with all metadata, steps, and detected images
// - error: Any error encountered during file reading or parsing
//
// Example:
//
// recipe, err := cooklang.ParseFile("recipes/lasagna.cook")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Recipe: %s\n", recipe.Title)
// fmt.Printf("Servings: %.0f\n", recipe.Servings)
func ParseFile(filename string) (*Recipe, error) {
content, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
p := parser.New()
parsedRecipe, err := p.ParseBytes(content)
if err != nil {
return nil, err
}
recipe := ToCooklangRecipe(parsedRecipe)
// Auto-detect and add images from filesystem
detectedImages := findRecipeImages(filename)
if len(detectedImages) > 0 {
// Merge detected images with existing ones, avoiding duplicates
recipe.Images = mergeUniqueStrings(recipe.Images, detectedImages)
// Update metadata to reflect the merged images
if len(recipe.Images) > 0 {
recipe.Metadata["images"] = strings.Join(recipe.Images, ", ")
}
}
return recipe, nil
}
// findRecipeImages looks for image files matching the recipe filename pattern.
// For a recipe file "Recipe.cook", it searches for:
// - Recipe.jpg, Recipe.jpeg, Recipe.png (base image)
// - Recipe-1.jpg, Recipe-2.jpg, etc. (numbered variants)
// Returns just the filenames (not full paths) of found images.
func findRecipeImages(cookFilePath string) []string {
dir := filepath.Dir(cookFilePath)
baseName := strings.TrimSuffix(filepath.Base(cookFilePath), ".cook")
var images []string
extensions := []string{".jpg", ".jpeg", ".png"}
// Check for base image (e.g., Recipe.jpg)
for _, ext := range extensions {
imagePath := filepath.Join(dir, baseName+ext)
if fileExists(imagePath) {
images = append(images, baseName+ext)
}
}
// Check for numbered images (e.g., Recipe-1.jpg, Recipe-2.jpg)
// We'll check up to 99 numbered variants
for i := 1; i <= 99; i++ {
foundAny := false
for _, ext := range extensions {
numberedName := fmt.Sprintf("%s-%d%s", baseName, i, ext)
imagePath := filepath.Join(dir, numberedName)
if fileExists(imagePath) {
images = append(images, numberedName)
foundAny = true
}
}
// If we didn't find any images for this number, stop searching
if !foundAny {
break
}
}
return images
}
// fileExists checks if a file exists and is not a directory.
func fileExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return !info.IsDir()
}
// mergeUniqueStrings merges two string slices, removing duplicates and empty strings.
func mergeUniqueStrings(slice1, slice2 []string) []string {
seen := make(map[string]bool)
result := make([]string, 0, len(slice1)+len(slice2))
// Add all items from slice1
for _, item := range slice1 {
if item != "" && !seen[item] {
seen[item] = true
result = append(result, item)
}
}
// Add items from slice2 that aren't already present
for _, item := range slice2 {
if item != "" && !seen[item] {
seen[item] = true
result = append(result, item)
}
}
return result
}
// ParseBytes parses Cooklang recipe content from a byte slice.
// This is useful for parsing recipes from memory, HTTP responses, or other byte sources.
//
// Unlike ParseFile, this function does not perform image detection since no filename is available.
//
// Parameters:
// - content: The raw Cooklang recipe content as bytes
//
// Returns:
// - *Recipe: The parsed recipe with all metadata and steps
// - error: Any error encountered during parsing
//
// Example:
//
// content := []byte("---\ntitle: Quick Pasta\n---\n\nBoil @water{2%L} and add @pasta{100%g}.")
// recipe, err := cooklang.ParseBytes(content)
func ParseBytes(content []byte) (*Recipe, error) {
p := parser.New()
parsedRecipe, err := p.ParseBytes(content)
if err != nil {
return nil, err
}
return ToCooklangRecipe(parsedRecipe), nil
}
// ParseString parses Cooklang recipe content from a string.
// This is a convenience wrapper around ParseBytes for string input.
//
// Parameters:
// - content: The Cooklang recipe content as a string
//
// Returns:
// - *Recipe: The parsed recipe with all metadata and steps
// - error: Any error encountered during parsing
//
// Example:
//
// content := "---\ntitle: Quick Pasta\n---\n\nBoil @water{2%L}."
// recipe, err := cooklang.ParseString(content)
func ParseString(content string) (*Recipe, error) {
p := parser.New()
recipe, err := p.ParseString(content)
if err != nil {
return nil, err
}
return ToCooklangRecipe(recipe), nil
}
// CreateTypedUnit attempts to find a unit in go-units or creates a new one if not found.
// This function is used internally when parsing Cooklang content and can be used externally
// when programmatically creating Ingredient structs that need unit conversion support.
//
// If the unit string is empty, nil is returned.
// If the unit is found in the go-units library, a pointer to that unit is returned.
// Otherwise, a new unit is created with the given string as both name and symbol.
func CreateTypedUnit(unitStr string) *units.Unit {
if unitStr == "" {
return nil
}
// Try to find the unit first
if foundUnit, err := units.Find(unitStr); err == nil {
return &foundUnit
}
// If not found, create a new unit (returns by value, so we take address)
newUnit := units.NewUnit(unitStr, unitStr)
return &newUnit
}
// ToCooklangRecipe converts a parser.Recipe to a cooklang.Recipe.
// This is the internal function that transforms the parser's output into the high-level Recipe structure
// with all metadata fields populated and step components organized as linked lists.
//
// Most users should use ParseFile, ParseString, or ParseBytes instead of calling this directly.
func ToCooklangRecipe(pRecipe *parser.Recipe) *Recipe {
recipe := &Recipe{}
// Copy metadata to recipe fields
recipe.Metadata = Metadata(pRecipe.Metadata)
if title, ok := pRecipe.Metadata["title"]; ok {
recipe.Title = title
}
if cuisine, ok := pRecipe.Metadata["cuisine"]; ok {
recipe.Cuisine = cuisine
}
if description, ok := pRecipe.Metadata["description"]; ok {
recipe.Description = description
}
if difficulty, ok := pRecipe.Metadata["difficulty"]; ok {
recipe.Difficulty = difficulty
}
if prepTime, ok := pRecipe.Metadata["prep_time"]; ok {
recipe.PrepTime = prepTime
}
if totalTime, ok := pRecipe.Metadata["total_time"]; ok {
recipe.TotalTime = totalTime
}
if author, ok := pRecipe.Metadata["author"]; ok {
recipe.Author = author
}
if servingsStr, ok := pRecipe.Metadata["servings"]; ok {
if servings, err := strconv.ParseFloat(servingsStr, 32); err == nil {
recipe.Servings = float32(servings)
}
}
// Default to 1 serving if not specified or invalid
if recipe.Servings <= 0 {
recipe.Servings = 1
}
if dateStr, ok := pRecipe.Metadata["date"]; ok {
if date, err := time.Parse("2006-01-02", dateStr); err == nil {
recipe.Date = date
}
}
if imgsStr, ok := pRecipe.Metadata["images"]; ok {
// Assuming images are comma-separated
recipe.Images = strings.Split(strings.TrimSpace(imgsStr), ",")
for i := range recipe.Images {
recipe.Images[i] = strings.TrimSpace(recipe.Images[i])
}
}
if tagsStr, ok := pRecipe.Metadata["tags"]; ok {
// Assuming tags are comma-separated
recipe.Tags = strings.Split(strings.TrimSpace(tagsStr), ",")
for i := range recipe.Tags {
recipe.Tags[i] = strings.TrimSpace(recipe.Tags[i])
}
}
var prevStep *Step
for _, step := range pRecipe.Steps {
newStep := &Step{}
var prevComponent StepComponent
for _, component := range step.Components {
var stepComp StepComponent
switch component.Type {
case "ingredient":
var quant float32
if component.Quantity == "some" {
quant = -1 // Use -1 to indicate "some" quantity
} else {
quant64, err := strconv.ParseFloat(component.Quantity, 32)
if err != nil {
quant = -1 // Default to "some" if parsing fails
} else {
quant = float32(quant64)
}
}
stepComp = &Ingredient{
Name: component.Name,
Quantity: quant,
Unit: component.Unit,
Fixed: component.Fixed,
Optional: component.Optional,
TypedUnit: CreateTypedUnit(component.Unit),
Annotation: component.Value,
}
case "cookware":
cookwareQuant, err := strconv.Atoi(component.Quantity)
if err != nil {
cookwareQuant = 1 // Default to 1 if parsing fails
}
stepComp = &Cookware{
Name: component.Name,
Quantity: cookwareQuant,
Annotation: component.Value,
}
case "timer":
stepComp = &Timer{
Duration: component.Quantity,
Unit: component.Unit,
Name: component.Name,
Annotation: component.Value,
}
case "text":
stepComp = &Instruction{
Text: component.Value,
}
case "section":
stepComp = &Section{
Name: component.Name,
}
case "comment":
stepComp = &Comment{
Text: component.Value,
IsBlock: false,
}
case "blockComment":
stepComp = &Comment{
Text: component.Value,
IsBlock: true,
}
case "note":
stepComp = &Note{
Text: component.Value,
}
}
if stepComp != nil {
if newStep.FirstComponent == nil {
newStep.FirstComponent = stepComp
} else {
prevComponent.SetNext(stepComp)
}
prevComponent = stepComp
}
}
// Only add steps that have displayable content (skip comment-only or empty steps)
if newStep.HasDisplayableContent() {
if recipe.FirstStep == nil {
recipe.FirstStep = newStep
} else {
prevStep.NextStep = newStep
}
prevStep = newStep
}
}
return recipe
}
// Render returns a human-readable representation of the recipe.
// If a custom renderer has been set via SetRenderer or SetRendererFunc, it will be used.
// Otherwise, a default text format is used showing metadata, ingredients, and steps.
//
// Example:
//
// recipe, _ := cooklang.ParseFile("lasagna.cook")
// fmt.Println(recipe.Render())
func (r *Recipe) Render() string {
if r.RenderFunc != nil {
return r.RenderFunc()
}
// Default rendering logic
result := fmt.Sprintf("Title: %s\n", r.Title)
result += fmt.Sprintf("Cuisine: %s\n", r.Cuisine)
result += fmt.Sprintf("Date: %s\n", r.Date.Format("2006-01-02"))
result += fmt.Sprintf("Description: %s\n", r.Description)
result += fmt.Sprintf("Difficulty: %s\n", r.Difficulty)
result += fmt.Sprintf("Prep Time: %s\n", r.PrepTime)
result += fmt.Sprintf("Total Time: %s\n", r.TotalTime)
result += fmt.Sprintf("Author: %s\n", r.Author)
result += fmt.Sprintf("Servings: %.2f\n", r.Servings)
if len(r.Images) > 0 {
result += "Images:\n"
for _, img := range r.Images {
result += fmt.Sprintf("- %s\n", img)
}
}
if len(r.Tags) > 0 {
result += "Tags:\n"
for _, tag := range r.Tags {
result += fmt.Sprintf("- %s\n", tag)
}
}
// Iterate through linked list of steps
stepNum := 1
currentStep := r.FirstStep
for currentStep != nil {
result += fmt.Sprintf("Step %d:\n", stepNum)
// Iterate through linked list of components in this step
currentComponent := currentStep.FirstComponent
for currentComponent != nil {
result += currentComponent.Render()
currentComponent = currentComponent.GetNext()
}
currentStep = currentStep.NextStep
stepNum++
}
return result
}
// ConvertTo converts the ingredient to a different unit if possible.
// The conversion uses either custom cooking unit conversions (for common units like cups, tbsp, oz)
// or the go-units library for scientific units.
//
// Parameters:
// - targetUnitStr: The target unit to convert to (e.g., "g", "cup", "ml")
//
// Returns:
// - *Ingredient: A new ingredient with the converted quantity and unit
// - error: Error if conversion is not possible (incompatible units, "some" quantity, etc.)
//
// Example:
//
// ingredient := &Ingredient{Name: "flour", Quantity: 2, Unit: "cup"}
// converted, err := ingredient.ConvertTo("g")
// if err == nil {
// fmt.Printf("%.0f %s\n", converted.Quantity, converted.Unit) // "473 g"
// }
func (i *Ingredient) ConvertTo(targetUnitStr string) (*Ingredient, error) {
if i.TypedUnit == nil {
return nil, fmt.Errorf("ingredient has no typed unit")
}
if i.Quantity == -1 {
return nil, fmt.Errorf("cannot convert ingredients with 'some' quantity")
}
// Try custom cooking unit conversions first
if isCookingUnit(i.Unit) && isCookingUnit(targetUnitStr) {
convertedValue, err := convertCookingUnit(float64(i.Quantity), i.Unit, targetUnitStr)
if err == nil {
targetUnit := CreateTypedUnit(targetUnitStr)
converted := &Ingredient{
Name: i.Name,
Quantity: float32(convertedValue),
Unit: targetUnitStr,
TypedUnit: targetUnit,
Subinstruction: i.Subinstruction,
NextComponent: i.NextComponent,
}
return converted, nil
}
}
// Fall back to go-units for other conversions
targetUnit, err := units.Find(targetUnitStr)
if err != nil {
// If unit not found, create a new one
targetUnit = units.NewUnit(targetUnitStr, targetUnitStr)
}
// Convert using go-units
convertedValue, err := units.ConvertFloat(float64(i.Quantity), *i.TypedUnit, targetUnit)
if err != nil {
return nil, fmt.Errorf("cannot convert from %s to %s: %v", i.Unit, targetUnitStr, err)
}
// Create a new ingredient with converted values
converted := &Ingredient{
Name: i.Name,
Quantity: float32(convertedValue.Float()),
Unit: targetUnitStr,
TypedUnit: &targetUnit,
Subinstruction: i.Subinstruction,
NextComponent: i.NextComponent,
}
return converted, nil
}
// CanConvertTo checks if the ingredient can be converted to the target unit.
// This allows validating conversions before attempting them.
//
// Parameters:
// - targetUnitStr: The unit to check conversion compatibility with
//
// Returns:
// - bool: true if conversion is possible, false otherwise
//
// Example:
//
// ingredient := &Ingredient{Name: "water", Quantity: 250, Unit: "ml"}
// if ingredient.CanConvertTo("cup") {
// converted, _ := ingredient.ConvertTo("cup")
// fmt.Printf("Can convert: %.2f %s\n", converted.Quantity, converted.Unit)