forked from rainycape/gondola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
articles.go
98 lines (88 loc) · 2.01 KB
/
articles.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package articles
import (
"path"
"strings"
"gondola/app"
"gondola/apps/articles/article"
"gondola/util/generic"
"github.com/rainycape/vfs"
)
const (
articlesKey = "articles"
)
var (
extensions = map[string]bool{
".html": true,
".md": true,
".txt": true,
}
)
// List returns the articles found in the given directory in
// the fs argument, recursively.
func List(fs vfs.VFS, dir string) ([]*article.Article, error) {
files, err := fs.ReadDir(dir)
if err != nil {
return nil, err
}
var articles []*article.Article
for _, v := range files {
p := path.Join(dir, v.Name())
if v.IsDir() {
dirArticles, err := List(fs, p)
if err != nil {
return nil, err
}
articles = append(articles, dirArticles...)
continue
}
if !extensions[strings.ToLower(path.Ext(p))] {
// Not a recognized extension
continue
}
article, err := article.Open(fs, p)
if err != nil {
return nil, err
}
articles = append(articles, article)
}
sortArticles(articles)
return articles, nil
}
// Load loads articles from the given directory in the given fs
// into the given app.
func (a *App) Load(fs vfs.VFS, dir string) ([]*article.Article, error) {
articles, err := List(fs, dir)
if err != nil {
return nil, err
}
data := a.Data().(*appData)
data.Articles = append(data.Articles, articles...)
sortArticles(data.Articles)
return articles, nil
}
// LoadDir works like Load, but loads the articles from the given directory
// in the local filesystem.
func (a *App) LoadDir(dir string) ([]*article.Article, error) {
fs, err := vfs.FS(dir)
if err != nil {
return nil, err
}
return a.Load(fs, "/")
}
func sortArticles(articles []*article.Article) {
generic.SortFunc(articles, func(a1, a2 *article.Article) bool {
if a1.Priority < a2.Priority {
return true
}
if a1.Created().Sub(a2.Created()) > 0 {
return true
}
return a1.Title() < a2.Title()
})
}
func getArticles(ctx *app.Context) []*article.Article {
if data := articlesData(ctx); data != nil {
return data.Articles
}
return nil
}