~samwhited/blogsync

ref: 714259c49a5a4d838f926f2eceab7c4e370f60aa blogsync/publish.go -rw-r--r-- 8.5 KiB
714259c4Sam Whited blogsync: fix formatting directives 1 year, 10 months ago
                                                                                
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
// Copyright 2019 The Blog Sync Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"text/template"

	"github.com/russross/blackfriday/v2"
	"github.com/writeas/go-writeas/v2"
	"mellium.im/blogsync/internal/blog"
	"mellium.im/cli"
)

const defTmpl = "{{.Body}}"

type tmplData struct {
	Body   string
	Meta   blog.Metadata
	Config Config
}

func publishCmd(siteConfig Config, client *writeas.Client, logger, debug *log.Logger) *cli.Command {
	var (
		collection = ""
		del        = false
		dryRun     = false
		force      = false
		content    = "content/"
		tmpl       = defTmpl
	)
	flags := flag.NewFlagSet("publish", flag.ContinueOnError)
	flags.BoolVar(&del, "delete", del, "Delete pages for which matching files cannot be found")
	flags.BoolVar(&dryRun, "dry-run", dryRun, "Perform a trial run with no changes made")
	flags.BoolVar(&force, "f", force, "Force publishing, even if no updates exist")
	flags.StringVar(&collection, "collection", siteConfig.Collection, "The default collection for pages that don't include `collection' in their frontmatter")
	flags.StringVar(&content, "content", orDef(siteConfig.Content, content), "A directory containing pages")
	flags.StringVar(&tmpl, "tmpl", orDef(siteConfig.Tmpl, tmpl), "A template using Go's html/template format, to load from a file use @filename")

	return &cli.Command{
		Usage: "publish [options]",
		Description: fmt.Sprintf(`Publishes Markdown files to write.as.

Expects an API token to be exported as $%s.`, envToken),
		Flags: flags,
		Run: func(cmd *cli.Command, args ...string) error {
			compiledTmpl := template.New("root")
			var err error
			if tmplFile := strings.TrimPrefix(tmpl, "@"); tmpl != tmplFile {
				// If the template argument starts with "@" it is a filename that we
				// should load.
				compiledTmpl, err = template.ParseFiles(tmplFile)
				if err != nil {
					return fmt.Errorf("error compiling template file %s: %v", tmplFile, err)
				}
			} else {
				// Otherwise, it is a raw template and we should compile it.
				compiledTmpl, err = compiledTmpl.Parse(tmpl)
				if err != nil {
					return fmt.Errorf("error compiling template: %v", err)
				}
			}

			var posts []writeas.Post
			p, err := client.GetUserPosts()
			if err != nil {
				return fmt.Errorf("error fetching users posts: %v", err)
			}
			// For now, the writeas SDK returns things with a lot of unnecessary
			// indirection that makes the library hard to use.
			// Go ahead and unwrap this and we can remove this workaround if they ever
			// fix it.
			// See: https://github.com/writeas/go-writeas/pull/19
			posts = *p

			err = blog.WalkPages(content, func(path string, info os.FileInfo, err error) error {
				debug.Printf("opening %s", path)
				fd, err := os.Open(path)
				if err != nil {
					logger.Printf("error opening %s, skipping: %v", path, err)
					return nil
				}
				defer func() {
					if err := fd.Close(); err != nil {
						debug.Printf("error closing %s: %v", path, err)
					}
				}()

				f := bufio.NewReader(fd)
				meta := make(blog.Metadata)
				header, err := meta.Decode(f)
				if err != nil {
					logger.Printf("error decoding metadata for %s, skipping: %v", path, err)
					return nil
				}
				// This may seem unnecessary, but I don't plan on supporting YAML
				// headers forever to keep things simple, so go ahead and forbid
				// publishing with them to encourage people to convert their blogs over.
				if header == blog.HeaderYAML {
					logger.Printf(`file %s has a YAML header, try converting it by running "%s convert", skipping`, path, os.Args[0])
					return nil
				}

				draft := meta.GetBool("draft")
				if draft {
					debug.Printf("skipping draft %s", path)
					return nil
				}

				title := meta.GetString("title")
				if title == "" {
					logger.Printf("invalid or empty title in %s, skipping", path)
					return nil
				}

				// Deliberately shadow collection so that we don't end up mutating
				// something outside the closure.
				collection := collection
				if col := meta.GetString("collection"); col != "" {
					collection = col
				}

				body, err := ioutil.ReadAll(f)
				if err != nil {
					logger.Printf("error reading body from %s, skipping: %v", path, err)
					return nil
				}
				body = bytes.TrimSpace(body)
				body = blackfriday.Run(body, blackfriday.WithRenderer(&unwrapRenderer{
					debug: debug,
				}))

				var bodyBuf strings.Builder
				err = compiledTmpl.Execute(&bodyBuf, tmplData{
					Body:   string(body),
					Meta:   meta,
					Config: siteConfig,
				})
				if err != nil {
					logger.Printf("error executing template for file %s: %v", path, err)
					return nil
				}
				if bodyBuf.Len() == 0 {
					// Apparently write.as doesn't like posts that don't have a body.
					logger.Printf("post %s has no body, skipping", path)
					return nil
				}

				slug := blog.Slug(path, meta)
				var existingPost *writeas.Post
				for i, post := range posts {
					var postCollection string
					if post.Collection != nil {
						postCollection = post.Collection.Alias
					}

					if slug == post.Slug && collection == postCollection {
						existingPost = &post
						posts = append(posts[:i], posts[i+1:]...)
						break
					}
				}

				created := timeOrDef(meta.GetTime("publishDate"), meta.GetTime("date"))
				createdPtr := &created
				if created.IsZero() {
					createdPtr = nil
				}
				rtl := meta.GetBool("rtl")
				lang := meta.GetString("lang")
				if lang == "" {
					lang = siteConfig.Language
				}
				updated := timeOrDef(meta.GetTime("lastmod"), created)

				var postID, postTok string
				if existingPost != nil {
					postID = existingPost.ID
					postTok = existingPost.Token
				}
				params := &writeas.PostParams{
					ID:    postID,
					Token: postTok,

					Content:  bodyBuf.String(),
					Created:  createdPtr,
					Font:     orDef(meta.GetString("font"), "norm"),
					IsRTL:    &rtl,
					Language: &lang,
					Slug:     slug,
					Title:    title,
					Updated:  &updated,

					Collection: collection,
				}

				var skipUpdate bool
				if existingPost == nil {
					debug.Printf("publishing %s from %s", slug, path)
				} else {
					if eqParams(existingPost, params) && !force {
						debug.Printf("no updates needed for %s, skipping", slug)
						skipUpdate = true
					} else {
						debug.Printf("updating /%s (%q) from %s", slug, postID, path)
					}
				}

				if !dryRun && !skipUpdate {
					if postID == "" {
						post, err := client.CreatePost(params)
						if err != nil {
							logger.Printf("error creating post from %s: %v", path, err)
							return nil
						}
						postID = post.ID
					} else {
						// Write.as returns a generic 500 error if you set Created when
						// updating a post, even if it's unchanged.
						params.Created = nil
						post, err := client.UpdatePost(postID, postTok, params)
						if err != nil {
							logger.Printf("error updating post %q from %s: %v", postID, path, err)
							return nil
						}
						postID = post.ID
					}
				}

				// Right now there is no way to check if a post is pinned, so we have to
				// assume that all posts may be pinned and always attempt to unpin them
				// then re-pin any that should actually be pinned every time.
				// This is not ideal.
				debug.Printf("attempting to unpin post %s…", slug)
				if !dryRun {
					err = client.UnpinPost(collection, &writeas.PinnedPostParams{
						ID: postID,
					})
					if err != nil {
						debug.Println("error unpinning post %s: %v", slug, err)
					}
				}

				pin, pinExists := meta["pin"]
				ipin, pinInt := pin.(int64)
				if pinExists && pinInt {
					debug.Printf("attempting to pin post %s to position %d…", slug, int(ipin))
					if !dryRun {
						err = client.PinPost(collection, &writeas.PinnedPostParams{
							ID:       postID,
							Position: int(ipin),
						})
						if err != nil {
							debug.Printf("error pinning post %s to position %d: %v", slug, int(ipin), err)
						}
					}
				}

				return nil
			})
			if err != nil {
				return err
			}

			// Delete remaining posts for which we couldn't find a matching file.
			for _, post := range posts {
				if del {
					debug.Printf("no file found matching post %q, deleting", post.Slug)
					if !dryRun {
						err := client.DeletePost(post.ID, post.Token)
						if err != nil {
							logger.Printf("error deleting post %q: %v", post.Slug, err)
						}
					}
					continue
				}
				logger.Printf("no file found matching post %q, re-run with --delete to remove", post.Slug)
			}
			return nil
		},
	}
}