arns-lt-gemini/formatter.go
Arnas Udovic ca57b910de
All checks were successful
continuous-integration/drone/push Build is passing
fix url making
2025-01-12 01:26:06 +02:00

109 lines
2.4 KiB
Go

package main
import (
"bytes"
"errors"
"fmt"
"net/url"
"regexp"
"sort"
"strings"
)
func (fileContent *FileContent) FormatContent() string {
content := fileContent.Content
content = strings.Trim(content, "/n")
badChars := make(map[string]string)
badChars["ā"] = "ā"
badChars["ē"] = "ē"
badChars["ī"] = "ī"
badChars["ō"] = "ō"
badChars["ū"] = "ū"
for k, v := range badChars {
content = strings.ReplaceAll(content, k, v)
}
var buffer []byte
data := []byte(content)
re := regexp.MustCompile(`!?\[([^\]*]*)\]\(([^ ]*?)\)`)
for i, match := range re.FindAllSubmatch(data, -1) {
if "!" == string(match[0][0:1]) {
uPath := string(match[2][:])
if strings.HasPrefix(uPath, "__a") {
uPath = "/" + uPath
}
link := fmt.Sprintf("=> %s %s\n", uPath, match[1])
data = bytes.Replace(data, match[0], []byte(link), 1)
} else {
replaceWithIndex := append(match[1], fmt.Sprintf("[%d]", i+1)...)
data = bytes.Replace(data, match[0], replaceWithIndex, 1)
// append entry to buffer to be added later
link := fmt.Sprintf("=> %s %d: %s\n", match[2], i+1, match[1])
buffer = append(buffer, link...)
}
}
// append links to that paragraph
if len(buffer) > 0 {
data = append(data, []byte("\n\n")...)
data = append(data, buffer...)
}
return string(data)
}
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)
}
func (file *TreeFile) CategoryPath() string {
return "/" + strings.Join(file.Category, "/")
}
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")
}
func GetLastFiles(files []*TreeFile) []*TreeFile {
sortingFiles := make(map[string]*TreeFile)
for _, f := range files {
sortingFiles[f.Created] = f
}
keys := make([]string, 0, len(sortingFiles))
for k := range sortingFiles {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
length := 10
if len(keys) < 10 {
length = len(keys)
}
lastFiles := make([]*TreeFile, 0, length)
for i, k := range keys {
if i == length {
break
}
lastFiles = append(lastFiles, sortingFiles[k])
}
return lastFiles
}