arns-lt-gemini/formatter.go

123 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
2022-08-23 11:58:18 +00:00
"bufio"
"bytes"
2022-08-20 20:46:31 +00:00
"errors"
2022-08-23 11:58:18 +00:00
"fmt"
"io"
2022-08-20 20:46:31 +00:00
"net/url"
"sort"
2022-08-20 20:46:31 +00:00
"strings"
2022-08-23 11:58:18 +00:00
"github.com/n0x1m/md2gmi/mdproc"
"github.com/n0x1m/md2gmi/pipe"
)
2022-08-23 11:58:18 +00:00
func source(r io.Reader) pipe.Source {
return func() chan pipe.StreamItem {
data := make(chan pipe.StreamItem)
s := bufio.NewScanner(r)
go func() {
i := 0
for s.Scan() {
data <- pipe.NewItem(i, s.Bytes())
i++
}
close(data)
}()
return data
}
}
func sink(w *bytes.Buffer) pipe.Sink {
return func(dest chan pipe.StreamItem) {
for b := range dest {
_, err := fmt.Fprintf(w, string(b.Payload()))
if err != nil {
fmt.Println(err)
}
}
}
}
2022-08-23 10:20:07 +00:00
func (fileContent *FileContent) FormatContent() string {
content := fileContent.Content
badChars := make(map[string]string)
2022-08-23 10:39:25 +00:00
badChars["ā"] = "ā"
badChars["ē"] = "ē"
badChars["ī"] = "ī"
badChars["ō"] = "ō"
badChars["ū"] = "ū"
2022-08-23 10:20:07 +00:00
for k, v := range badChars {
content = strings.ReplaceAll(content, k, v)
}
2022-08-23 11:58:18 +00:00
var writer bytes.Buffer
s := pipe.New()
s.Use(mdproc.Preprocessor())
s.Use(mdproc.FormatLinks)
s.Handle(source(strings.NewReader(content)), sink(&writer))
return writer.String()
2022-08-23 10:20:07 +00:00
}
2022-08-20 20:46:31 +00:00
func (file *TreeFile) CategoriesAsUrl() string {
escapedCategories := []string{}
for _, c := range file.Category {
escapedCategories = append(escapedCategories, url.QueryEscape(c))
}
return strings.Join(escapedCategories, "/")
}
func (file *TreeFile) GmiName() string {
return strings.Replace(file.Name, ".md", ".gmi", 1)
}
2022-08-20 22:33:27 +00:00
func (file *TreeFile) CategoryPath() string {
return "/" + strings.Join(file.Category, "/")
}
2022-08-20 20:46:31 +00:00
func (tree *Tree) GetIndexFile() (*TreeFile, error) {
for _, file := range tree.RootFiles {
if file.Name == "index.md" {
return file, nil
}
}
return nil, errors.New("index file not found")
}
2022-08-19 22:03:57 +00:00
func GetLastFiles(files []*TreeFile) []*TreeFile {
sortingFiles := make(map[string]*TreeFile)
for _, f := range files {
2022-08-22 20:28:09 +00:00
sortingFiles[f.Id] = f
}
keys := make([]string, 0, len(sortingFiles))
for k := range sortingFiles {
keys = append(keys, k)
}
2022-08-22 20:28:09 +00:00
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
length := 10
if len(keys) < 10 {
length = len(keys)
}
2022-08-19 22:03:57 +00:00
lastFiles := make([]*TreeFile, 0, length)
for i, k := range keys {
if i == length {
break
}
lastFiles = append(lastFiles, sortingFiles[k])
}
return lastFiles
}