-
Notifications
You must be signed in to change notification settings - Fork 26
/
entry.go
313 lines (273 loc) · 6.76 KB
/
entry.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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"fmt"
"io"
"log"
"net/url"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/x-motemen/blogsync/atom"
"gopkg.in/yaml.v2"
)
const timeFormat = "2006-01-02T15:04:05-07:00"
type entryURL struct {
*url.URL
}
type entryHeader struct {
Title string `yaml:"Title"`
Category []string `yaml:"Category,omitempty"`
Date *time.Time `yaml:"Date,omitempty"`
URL *entryURL `yaml:"URL,omitempty"`
EditURL string `yaml:"EditURL"`
PreviewURL string `yaml:"PreviewURL,omitempty"`
IsDraft bool `yaml:"Draft,omitempty"`
CustomPath string `yaml:"CustomPath,omitempty"`
}
func (eu *entryURL) MarshalYAML() (interface{}, error) {
return eu.String(), nil
}
func (eu *entryURL) UnmarshalYAML(unmarshal func(v interface{}) error) error {
var s string
err := unmarshal(&s)
if err != nil {
return err
}
u, err := url.Parse(s)
if err != nil {
return err
}
eu.URL = u
return nil
}
func (eh *entryHeader) blogID() (string, error) {
// EditURL: https://blog.hatena.ne.jp/Songmu/songmu.hateblog.jp/atom/entry/...
// "songmu.hateblog.jp" is blogID in above case.
paths := strings.Split(eh.EditURL, "/")
if len(paths) < 5 {
return "", fmt.Errorf("failed to get blogID form EditURL: %s", eh.EditURL)
}
return paths[4], nil
}
func (eh *entryHeader) isBlogEntry() bool {
return strings.Contains(eh.EditURL, "/atom/entry/")
}
func (eh *entryHeader) isStaticPage() bool {
return strings.Contains(eh.EditURL, "/atom/page/")
}
// Entry is an entry stored on remote blog providers
type entry struct {
*entryHeader
LastModified *time.Time
Content string
ContentType string
localPath string
}
func (e *entry) HeaderString() string {
d, err := yaml.Marshal(e.entryHeader)
if err != nil {
log.Fatalf("error: %v", err)
}
headers := []string{
"---",
string(d),
}
return strings.Join(headers, "\n") + "---\n\n"
}
func (e *entry) fullContent() string {
c := e.HeaderString() + e.Content
if !strings.HasSuffix(c, "\n") {
// fill newline for suppressing diff "No newline at end of file"
c += "\n"
}
return c
}
func (e *entry) atom() *atom.Entry {
atomEntry := &atom.Entry{
Title: e.Title,
Content: atom.Content{
Content: e.Content,
},
}
categories := make([]atom.Category, 0)
for _, c := range e.Category {
categories = append(categories, atom.Category{Term: c})
}
atomEntry.Category = categories
if e.Date != nil {
atomEntry.Updated = e.Date
}
if e.IsDraft {
atomEntry.Control = &atom.Control{
Draft: "yes",
Preview: "yes",
}
}
if e.CustomPath != "" {
atomEntry.CustomURL = e.CustomPath
}
return atomEntry
}
func entryFromAtom(e *atom.Entry) (*entry, error) {
alternateLink := e.Links.Find("alternate")
if alternateLink == nil {
return nil, fmt.Errorf("could not find link[rel=alternate]")
}
u, err := url.Parse(alternateLink.Href)
if err != nil {
return nil, err
}
editLink := e.Links.Find("edit")
if editLink == nil {
return nil, fmt.Errorf("could not find link[rel=edit]")
}
var previewLink string
p := e.Links.Find("preview")
if p != nil {
previewLink = p.Href
}
categories := make([]string, 0)
for _, c := range e.Category {
categories = append(categories, c.Term)
}
var isDraft bool
if e.Control != nil && e.Control.Draft == "yes" {
isDraft = true
}
// Set the updated to nil when the entry is still draft.
// But if the date is in the future, don't set to nil because it may be a reserved post.
updated := e.Updated
if updated != nil && isDraft && !time.Now().Before(*updated) {
updated = nil
}
return &entry{
entryHeader: &entryHeader{
URL: &entryURL{u},
EditURL: editLink.Href,
PreviewURL: previewLink,
Title: e.Title,
Category: categories,
Date: updated,
IsDraft: isDraft,
},
LastModified: e.Edited,
Content: e.Content.Content,
ContentType: e.Content.Type,
}, nil
}
var delimReg = regexp.MustCompile(`---\n+`)
func entryFromReader(source io.Reader) (*entry, error) {
b, err := io.ReadAll(source)
if err != nil {
return nil, err
}
content := string(b)
isNew := !strings.HasPrefix(content, "---\n")
eh := entryHeader{}
if !isNew {
c := delimReg.Split(content, 3)
if len(c) != 3 || c[0] != "" {
return nil, fmt.Errorf("entry format is invalid")
}
err = yaml.Unmarshal([]byte(c[1]), &eh)
if err != nil {
return nil, err
}
// Set the updated to nil when the entry is still draft.
// But if the date is in the future, don't set to nil because it may be a reserved post.
if eh.IsDraft && eh.Date != nil && !time.Now().Before(*eh.Date) {
eh.Date = nil
}
content = c[2]
}
entry := &entry{
entryHeader: &eh,
Content: content,
}
if f, ok := source.(*os.File); ok {
if runtime.GOOS == "windows" && f.Name() == os.Stdin.Name() {
t := time.Now()
entry.LastModified = &t
} else {
ti, err := modTime(f.Name())
if err != nil {
return nil, err
}
entry.LastModified = &ti
}
}
return entry, nil
}
func entryFromFile(fpath string) (*entry, error) {
f, err := os.Open(fpath)
if err != nil {
return nil, err
}
defer f.Close()
e, err := entryFromReader(f)
if err != nil {
return nil, err
}
e.localPath = fpath
return e, nil
}
func asEntry(atomEntry *atom.Entry, err error) (*entry, error) {
if err != nil {
return nil, err
}
return entryFromAtom(atomEntry)
}
var getGit = sync.OnceValue(func() func(...string) (string, error) {
g, err := exec.LookPath("git")
if err != nil || g == "" {
return nil
}
git := func(args ...string) (string, error) {
bb, err := exec.Command(g, args...).Output()
return strings.TrimSpace(string(bb)), err
}
if boolStr, err := git("rev-parse", "--is-shallow-repository"); err != nil {
return nil
} else if boolStr == "true" {
if _, err := git("fetch", "--unshallow"); err != nil {
return nil
}
}
return git
})
func modTime(fpath string) (time.Time, error) {
fi, err := os.Stat(fpath)
if err != nil {
return time.Time{}, err
}
ti := fi.ModTime()
if git := getGit(); git != nil {
// ref. https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt-emaiem
// %aI means "author date, strict ISO 8601 format"
timeStr, err := git("log", "-1", "--format=%aI", "--", fpath)
if err == nil && timeStr != "" {
// check if the file is clean (not modified) on git
out, err := git("status", "-s", "--", fpath)
// if the output is empty, it means the file has not been modified
if err == nil && out == "" {
t, err := time.Parse(time.RFC3339, timeStr)
if err == nil {
ti = t
}
}
}
}
return ti, nil
}
func extractEntryPath(p string) (subdir string, entryPath string) {
stuffs := strings.SplitN(p, "/entry/", 2)
if len(stuffs) != 2 {
return "", ""
}
entryPath = strings.TrimSuffix(stuffs[1], entryExt)
return stuffs[0], entryPath
}