🎨 Improve parsing of YAML Front Matter when importing Markdown https://github.com/siyuan-note/siyuan/issues/12962

This commit is contained in:
Daniel 2024-10-30 10:43:58 +08:00
parent 3560fed496
commit da3a6fee16
No known key found for this signature in database
GPG key ID: 86211BA83DF03017
2 changed files with 89 additions and 44 deletions

View file

@ -34,6 +34,7 @@ import (
"github.com/88250/lute/html"
"github.com/88250/lute/lex"
"github.com/88250/lute/parse"
"github.com/araddon/dateparse"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/cache"
@ -566,22 +567,62 @@ func normalizeTree(tree *parse.Tree) {
parseErr := yaml.Unmarshal(n.Tokens, &attrs)
if parseErr != nil {
logging.LogWarnf("parse YAML front matter [%s] failed: %s", n.Tokens, parseErr)
} else {
for attrK, attrV := range attrs {
validKeyName := true
for i := 0; i < len(attrK); i++ {
if !lex.IsASCIILetterNumHyphen(attrK[i]) {
validKeyName = false
break
return ast.WalkContinue
}
for attrK, attrV := range attrs {
// Improve parsing of YAML Front Matter when importing Markdown https://github.com/siyuan-note/siyuan/issues/12962
if "title" == attrK {
tree.Root.SetIALAttr("title", fmt.Sprint(attrV))
continue
}
if "date" == attrK {
created, parseTimeErr := dateparse.ParseIn(fmt.Sprint(attrV), time.Local)
if nil == parseTimeErr {
docID := created.Format("20060102150405") + "-" + gulu.Rand.String(7)
tree.Root.ID = docID
tree.Root.SetIALAttr("id", docID)
}
continue
}
if "lastmod" == attrK {
updated, parseTimeErr := dateparse.ParseIn(fmt.Sprint(attrV), time.Local)
if nil == parseTimeErr {
tree.Root.SetIALAttr("updated", updated.Format("20060102150405"))
}
continue
}
if "tags" == attrK {
var tags string
for i, tag := range attrV.([]any) {
tagStr := strings.TrimSpace(tag.(string))
if "" == tag {
continue
}
tagStr = strings.TrimLeft(tagStr, "#,'\"")
tagStr = strings.TrimRight(tagStr, "#,'\"")
tags += tagStr
if i < len(attrV.([]any))-1 {
tags += ","
}
}
if !validKeyName {
logging.LogWarnf("invalid YAML key [%s] in [%s]", attrK, n.ID)
continue
}
tree.Root.SetIALAttr("custom-"+attrK, fmt.Sprint(attrV))
tree.Root.SetIALAttr("tags", tags)
continue
}
validKeyName := true
for i := 0; i < len(attrK); i++ {
if !lex.IsASCIILetterNumHyphen(attrK[i]) {
validKeyName = false
break
}
}
if !validKeyName {
logging.LogWarnf("invalid YAML key [%s] in [%s]", attrK, n.ID)
continue
}
tree.Root.SetIALAttr("custom-"+attrK, fmt.Sprint(attrV))
}
}