feat: sorting psots
This commit is contained in:
37
hugo.go
37
hugo.go
@ -2,19 +2,26 @@ package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PostWithDate struct {
|
||||
Post string
|
||||
Date time.Time
|
||||
}
|
||||
|
||||
func getAllPosts(dir string) ([]string, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return []string{}, err
|
||||
}
|
||||
|
||||
posts := make([]string, 0)
|
||||
posts := make([]PostWithDate, 0)
|
||||
for _, entry := range entries {
|
||||
if filepath.Ext(entry.Name()) != ".md" {
|
||||
continue
|
||||
@ -25,10 +32,31 @@ func getAllPosts(dir string) ([]string, error) {
|
||||
return []string{}, err
|
||||
}
|
||||
|
||||
posts = append(posts, string(content))
|
||||
postInfo, err := getPostInfo(string(content))
|
||||
if err != nil {
|
||||
return []string{}, err
|
||||
}
|
||||
|
||||
posts = append(posts, PostWithDate{
|
||||
Post: string(content),
|
||||
Date: postInfo.Date,
|
||||
})
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
slices.SortFunc(posts, func(a PostWithDate, b PostWithDate) int {
|
||||
if a.Date.Before(b.Date) {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
})
|
||||
|
||||
justPosts := make([]string, len(posts))
|
||||
for i, v := range posts {
|
||||
justPosts[i] = v.Post
|
||||
}
|
||||
|
||||
return justPosts, nil
|
||||
}
|
||||
|
||||
type postInfo struct {
|
||||
@ -61,7 +89,8 @@ func getPostInfo(post string) (postInfo, error) {
|
||||
case "title":
|
||||
info.Title = splitLine[1]
|
||||
case "date":
|
||||
t, err := time.Parse(time.DateOnly, splitLine[1])
|
||||
fmt.Println(splitLine[1])
|
||||
t, err := time.Parse(time.DateOnly, splitLine[1][1:len(splitLine[1])-1])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
Reference in New Issue
Block a user