67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package article
|
|
|
|
import (
|
|
"TheAdversary/config"
|
|
"TheAdversary/parse"
|
|
"TheAdversary/schema"
|
|
"github.com/gomarkdown/markdown/ast"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func LoadArticle(path string) (*schema.Article, error) {
|
|
node, err := parse.Parse(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
article := &schema.Article{
|
|
Name: ArticleName(path),
|
|
Added: time.Now().Unix(),
|
|
}
|
|
children := node.GetChildren()
|
|
to := 3
|
|
if len(children) < to {
|
|
to = len(children)
|
|
}
|
|
for _, child := range children[0:to] {
|
|
switch child.(type) {
|
|
case *ast.Heading:
|
|
if article.Title != "" {
|
|
article.Summary = extractText(child.(*ast.Heading).Container)
|
|
} else {
|
|
article.Title = extractText(child.(*ast.Heading).Container)
|
|
}
|
|
case *ast.Paragraph:
|
|
if article.Summary == "" {
|
|
article.Summary = extractText(child.(*ast.Paragraph).Container)
|
|
}
|
|
case *ast.BlockQuote:
|
|
if article.Summary == "" {
|
|
article.Summary = extractText(child.(*ast.BlockQuote).Container)
|
|
}
|
|
case *ast.Image:
|
|
article.Image = string(child.(*ast.Image).Destination)
|
|
}
|
|
}
|
|
|
|
if article.Title == "" {
|
|
article.Title = strings.ReplaceAll(strings.ReplaceAll(ArticleName(path), "-", " "), "_", " ")
|
|
}
|
|
|
|
return article, err
|
|
}
|
|
|
|
func extractText(container ast.Container) string {
|
|
return string(container.GetChildren()[0].(*ast.Text).Literal)
|
|
}
|
|
|
|
func ArticleName(path string) string {
|
|
ext := filepath.Ext(path)
|
|
if ext != ".md" {
|
|
return strings.TrimPrefix(path, config.ArticleRoot)
|
|
} else {
|
|
return strings.TrimSuffix(strings.TrimPrefix(path, config.ArticleRoot), filepath.Ext(path))
|
|
}
|
|
}
|