Files
marka/parser/blocks/blocks.go
2025-08-17 01:21:15 +02:00

81 lines
1.7 KiB
Go

package blocks
import (
"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
}
type BlockType string
const (
DataBlock BlockType = "data" // content between lines "{" and "}"
MatchingBlock BlockType = "matching" // everything outside data blocks
)
type BlockField struct {
Path string
CodecType CodecType
Required bool
}
type TemplateBlock struct {
Type BlockType
Path string
Codec CodecType
Required bool
Fields []BlockField
content string
}
func (b TemplateBlock) GetContent() string {
return b.content
}
func (p *TemplateBlock) Parse(input string) (key string, value any, err error) {
switch p.Codec {
case CodecText:
return p.Path, input, nil
case CodecYaml:
return p.ParseYamlBlock(input)
case CodecList:
return p.ParseListBlock(input)
}
return p.Path, "", nil
}