From f1c56bdf8bc8ee28a3f6487fcc8206c6a1625b4b Mon Sep 17 00:00:00 2001 From: John Costa Date: Sat, 7 Jun 2025 12:31:25 +0100 Subject: [PATCH] feat: sorting psots --- hugo.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/hugo.go b/hugo.go index edab02a..5aa7b76 100644 --- a/hugo.go +++ b/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 }