-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.go
More file actions
226 lines (206 loc) · 5.46 KB
/
posts.go
File metadata and controls
226 lines (206 loc) · 5.46 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/imdario/mergo"
"gopkg.in/russross/blackfriday.v2"
)
// getLocalPosts reads posts from local directory
func getLocalPosts() (posts []Post) {
files, err := ioutil.ReadDir("./posts")
if err != nil {
log.Info("Error reading posts directory: %v", err)
}
for _, file := range files {
if strings.Contains(file.Name(), ".md") {
post := Post{}
post.LocalFile = file.Name()
post.ModDate = file.ModTime()
posts = append(posts, post)
}
}
return posts
}
// getRemotePosts reads posts from json file
func getRemotePosts() (posts []Post) {
// check if file exists, return empty
// likely scenario would be first run
if _, err := os.Stat("posts.json"); os.IsNotExist(err) {
if !setup { // dont alert about missing file when known init
log.Debug("posts.json does not exist")
}
return posts
}
file, err := ioutil.ReadFile("posts.json")
if err != nil {
log.Warn("Error reading posts.json, permissions?", err)
} else {
if err := json.Unmarshal(file, &posts); err != nil {
log.Warn("Error parsing JSON from posts.json", err)
}
}
return posts
}
// comparePosts returns local posts that do not exist in remote
func comparePosts(local, remote []Post) (newPosts, updatePosts []Post) {
for _, lp := range local {
exists := false
for _, rp := range remote {
if lp.LocalFile == rp.LocalFile {
exists = true
lp.Id = rp.Id // set Id from remote
if lp.ModDate.After(rp.SyncDate) {
log.Debug("Local File: ", lp.LocalFile)
log.Debug(" Local ModDate : ", lp.ModDate.Unix())
log.Debug(" Remote SyncDate: ", rp.SyncDate.Unix())
updatePosts = append(updatePosts, lp)
} else {
log.Debug("Skipping ", lp.LocalFile)
}
}
}
if !exists {
newPosts = append(newPosts, lp)
}
}
return newPosts, updatePosts
}
// createPosts loops through posts and uploads
// posts are returned with Id/Url set
func createPosts(newPosts []Post) (createdPosts []Post) {
for _, p := range newPosts {
if confirmPrompt(fmt.Sprintf("New post %s, Continue (y/N)? ", p.LocalFile)) {
rp, err := createPost(p)
if err == nil {
rp.LocalFile = p.LocalFile // do I need to merge all data
rp.SyncDate = time.Now()
log.Info(fmt.Sprintf("New post: %s %s", p.LocalFile, rp.URL))
createdPosts = append(createdPosts, rp)
}
}
}
return createdPosts
}
func loadPostsFromFiles(posts []Post) (loadedPosts []Post) {
for _, p := range posts {
lp := loadPostFromFile(p)
loadedPosts = append(loadedPosts, lp)
}
return loadedPosts
}
func loadPostFromFile(p Post) Post {
post := readParseFile(p.LocalFile)
mergo.Merge(&post, p)
return post
}
// updatePosts loops through posts and updates
// posts are returned with new Date set
func updatePosts(posts []Post) (updatedPosts []Post) {
for _, p := range posts {
if confirmPrompt(fmt.Sprintf("Update post %s, Continue (y/N)? ", p.LocalFile)) {
rp, err := updatePost(p)
if err == nil {
rp.SyncDate = time.Now()
log.Info(fmt.Sprintf("Updated post: %s %s", p.LocalFile, rp.URL))
log.Debug("Updated SyncDate to:", rp.SyncDate.Unix())
updatedPosts = append(updatedPosts, rp)
} else {
log.Warn("Error updating post", err)
}
}
}
return updatedPosts
}
// writeRemotePosts
func writeRemotePosts(newPosts, updatedPosts []Post) {
if len(newPosts) == 0 && len(updatedPosts) == 0 {
log.Info("No posts to write.")
return
}
// append new post json
existingPosts := getRemotePosts()
// Merge existingPosts and updatedPosts
// need to update the date
for i, ep := range existingPosts {
for _, up := range updatedPosts {
if ep.LocalFile == up.LocalFile {
existingPosts[i].SyncDate = up.SyncDate
}
}
}
existingPosts = append(existingPosts, newPosts...)
// write file
json, err := json.Marshal(existingPosts)
if err != nil {
log.Warn("JSON Encoding Error", err)
} else {
err = ioutil.WriteFile("posts.json", json, 0644)
if err != nil {
log.Warn("Error writing posts.json", err)
} else {
log.Debug("posts.json written")
}
}
}
// readParseFile reads a markdown file and returns a Post struct
func readParseFile(filename string) (post Post) {
// setup default data
post = Post{
Title: "",
Content: "",
Category: "",
Date: time.Now().Format(time.RFC3339),
Tags: "",
Status: "publish",
}
var data, err = ioutil.ReadFile(filepath.Join("posts", filename))
if err != nil {
log.Warn(">>Error: can't read file:", filename)
}
// parse front matter from --- to ---
var lines = strings.Split(string(data), "\n")
var found = 0
for i, line := range lines {
line = strings.TrimSpace(line)
if found == 1 {
// parse line for param
colonIndex := strings.Index(line, ":")
if colonIndex > 0 {
key := strings.TrimSpace(line[:colonIndex])
value := strings.TrimSpace(line[colonIndex+1:])
value = strings.Trim(value, "\"") //remove quotes
switch key {
case "title":
post.Title = value
case "date":
d, err := time.Parse("2006-01-02", value)
if err == nil {
post.Date = d.Format(time.RFC3339)
}
case "category":
post.Category = value
case "tags":
post.Tags = value
case "status":
post.Status = value
}
}
} else if found >= 2 {
// params over
lines = lines[i:]
break
}
if line == "---" {
found += 1
}
}
// slurp rest of content
content := strings.Join(lines, "\n")
post.Content = string(blackfriday.Run([]byte(content)))
return post
}