Files
marka/template/blocks.go
2025-09-24 18:18:57 +02:00

71 lines
1.6 KiB
Go

// Package blocks contains the logic for parsing template blocks.
package template
import (
"fmt"
"strings"
)
// TemplateType represents whether a template is short, long, or invalid.
type TemplateType int
const (
InvalidTemplate TemplateType = iota
ShortTemplate
ExtendedTemplate
)
// DetectTemplateType checks if the template is short or long.
func DetectTemplateType(tmpl string) TemplateType {
trimmed := strings.TrimSpace(tmpl)
// Short type: starts with "{" and ends with "}" on a single line,
// and contains "|" or "," inside for inline definition
// Matchs for example { name | text,required }
if strings.HasPrefix(trimmed, "{") &&
strings.HasSuffix(trimmed, "}") &&
!strings.Contains(trimmed, "\n") {
return ShortTemplate
}
// Long type: multiline and contains keys like "path:" or "codec:" inside
// Matches for example:
// {
// path: name
// codec: text
// required: true
// }
if strings.Contains(trimmed, "\n") &&
(strings.Contains(trimmed, "path:") || strings.Contains(trimmed, "codec:")) {
return ExtendedTemplate
}
return InvalidTemplate
}
func cleanTemplate(input string) string {
s := strings.TrimSpace(input)
s = strings.TrimPrefix(s, "{")
s = strings.TrimSuffix(s, "}")
s = strings.Trim(s, "\n")
return s
}
func ParseTemplateBlock(template string, blockType BlockType) (block Block, err error) {
if blockType == MatchingBlock {
return Block{
Type: MatchingBlock,
content: template,
}, nil
}
switch DetectTemplateType(template) {
case ShortTemplate:
return parseShortTemplate(template)
case ExtendedTemplate:
return parseYamlTemplate(template)
}
return block, fmt.Errorf("invalid template")
}