~samwhited/blogsync

blogsync/publish.go -rw-r--r-- 11.0 KiB
5083f77dSam Whited .builds: verify DCO 1 year, 5 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// 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"
	"path"
	"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}}"
	defTmplName = "root"
)

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

type publishOptions struct {
	createCollections bool
	del               bool
	dryRun            bool
	force             bool
	collection        string
	content           string
	tmpl              string
}

type minimalPost struct {
	filename string
	id       string
	slug     string
	token    string
}

func newPublishOpts(siteConfig Config) publishOptions {
	return publishOptions{
		collection: siteConfig.Collection,
		content:    orDef(siteConfig.Content, "content/"),
		tmpl:       orDef(siteConfig.Tmpl, defTmpl),
	}
}

func publishCmd(siteConfig Config, client *writeas.Client, logger, debug *log.Logger) *cli.Command {
	opts := newPublishOpts(siteConfig)

	flags := flag.NewFlagSet("publish", flag.ContinueOnError)
	flags.BoolVar(&opts.del, "delete", opts.del, "Delete pages for which matching files cannot be found")
	flags.BoolVar(&opts.dryRun, "dry-run", opts.dryRun, "Perform a trial run with no changes made")
	flags.BoolVar(&opts.force, "f", opts.force, "Force publishing, even if no updates exist")
	flags.StringVar(&opts.collection, "collection", opts.collection, "The default collection for pages that don't include `collection' in their frontmatter")
	flags.StringVar(&opts.content, "content", opts.content, "A directory containing pages")
	flags.StringVar(&opts.tmpl, "tmpl", opts.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 {
			_, _, _, err := publish(opts, siteConfig, client, logger, debug)
			return err
		},
	}
}

func publish(opts publishOptions, siteConfig Config, client *writeas.Client, logger, debug *log.Logger) (*template.Template, []minimalPost, []writeas.Collection, error) {
	var collections []writeas.Collection

	if opts.createCollections {
		colls, err := client.GetUserCollections()
		if err != nil {
			logger.Printf("error fetching existing collections: %v", err)
		}
		collections = *colls

		collections = createCollectionIfNotExist(collections, client, debug, &writeas.CollectionParams{
			Alias:       siteConfig.Collection,
			Title:       siteConfig.Title,
			Description: siteConfig.Description,
		})
	}

	compiledTmpl := template.New(defTmplName).Funcs(map[string]interface{}{
		"join": path.Join,
	})
	tmplFile := strings.TrimPrefix(opts.tmpl, "@")
	var err error
	if opts.tmpl != tmplFile {
		// If the template argument starts with "@" it is a filename that we
		// should load.
		compiledTmpl, err = compiledTmpl.ParseFiles(tmplFile)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("error compiling template file %s: %v", tmplFile, err)
		}
		compiledTmpl = compiledTmpl.Lookup(tmplFile)
	} else {
		tmplFile = defTmplName
		// Otherwise, it is a raw template and we should compile it.
		compiledTmpl, err = compiledTmpl.Parse(opts.tmpl)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("error compiling template: %v", err)
		}
	}

	var posts []writeas.Post
	p, err := client.GetUserPosts()
	if err != nil {
		return nil, nil, nil, 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

	posted := make([]minimalPost, 0, len(posts))
	err = blog.WalkPages(opts.content, func(pagePath string, info os.FileInfo, err error) error {
		newPost, err := publishPost(pagePath, opts, siteConfig, posts, collections, compiledTmpl, client, logger, debug)
		if newPost != nil {
			posted = append(posted, *newPost)
		}
		return err
	})
	if err != nil {
		return nil, nil, nil, err
	}

	// Delete remaining posts for which we couldn't find a matching file.
	for _, post := range posts {
		if opts.del {
			debug.Printf("no file found matching post %q, deleting", post.Slug)
			if !opts.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 compiledTmpl, posted, collections, nil
}

func publishPost(pagePath string, opts publishOptions, siteConfig Config, posts []writeas.Post, collections []writeas.Collection, compiledTmpl *template.Template, client *writeas.Client, logger, debug *log.Logger) (post *minimalPost, err error) {
	debug.Printf("opening %s", pagePath)
	fd, err := os.Open(pagePath)
	if err != nil {
		logger.Printf("error opening %s, skipping: %v", pagePath, err)
		return nil, nil
	}
	defer func() {
		if err := fd.Close(); err != nil {
			debug.Printf("error closing %s: %v", pagePath, 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", pagePath, err)
		return nil, 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`, pagePath, os.Args[0])
		return nil, nil
	}

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

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

	// Deliberately shadow collection so that we don't end up mutating the
	// options struct.
	collection := opts.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", pagePath, err)
		return nil, nil
	}
	body = bytes.TrimSpace(body)
	body = blackfriday.Run(body,
		blackfriday.WithNoExtensions(),
		blackfriday.WithExtensions(
			blackfriday.CommonExtensions|blackfriday.Footnotes,
		),
		blackfriday.WithRenderer(&unwrapRenderer{
			debug: debug,
			htmlRenderer: blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
				Flags: blackfriday.FootnoteReturnLinks,
			}),
		}))

	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", pagePath, err)
		return nil, 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", pagePath)
		return nil, nil
	}

	slug := blog.Slug(pagePath, 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, pagePath)
	} else {
		if eqParams(existingPost, params) && !opts.force {
			debug.Printf("no updates needed for %s, skipping", slug)
			skipUpdate = true
		} else {
			debug.Printf("updating /%s (%q) from %s", slug, postID, pagePath)
		}
	}

	if !opts.dryRun && !skipUpdate {
		if opts.createCollections {
			collections = createCollectionIfNotExist(collections, client, debug, &writeas.CollectionParams{
				Alias: params.Collection,
				Title: params.Collection,
			})
		}
		if postID == "" {
			post, err := client.CreatePost(params)
			if err != nil {
				logger.Printf("error creating post from %s: %v", pagePath, err)
				return nil, nil
			}
			postID = post.ID
			postTok = post.Token
		} 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, pagePath, err)
				return nil, nil
			}
			postID = post.ID
			postTok = post.Token
		}
	}

	// 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 !opts.dryRun {
		err = client.UnpinPost(collection, &writeas.PinnedPostParams{
			ID: postID,
		})
		if err != nil {
			debug.Printf("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 !opts.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 &minimalPost{
		filename: pagePath,
		slug:     slug,
		id:       postID,
		token:    postTok,
	}, nil
}

func createCollectionIfNotExist(colls []writeas.Collection, client *writeas.Client, debug *log.Logger, coll *writeas.CollectionParams) []writeas.Collection {
	for _, c := range colls {
		if c.Alias == coll.Alias {
			return colls
		}
	}
	debug.Printf("creating collection %s…", coll.Alias)
	newColl, err := client.CreateCollection(coll)
	if err != nil {
		debug.Printf("error creating collection %s: %v", coll.Alias, err)
	}
	if coll != nil {
		colls = append(colls, *newColl)
	}
	return colls
}