summaryrefslogtreecommitdiff
path: root/src/cmd/export/posts.go
blob: 569ff6b644a0d3084bafaf5cad50da33c16ec37b (plain)
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
package main

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	txttpl "text/template"

	gmnhg "github.com/tdemin/gmnhg"

	"dev.mediocregopher.com/mediocre-blog.git/src/gmi"
	"dev.mediocregopher.com/mediocre-blog.git/src/http"
	"dev.mediocregopher.com/mediocre-blog.git/src/post"
	"dev.mediocregopher.com/mediocre-blog.git/src/render"
	"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
	"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
)

var postFileExtensions = map[post.Format]string{
	post.FormatGemtext:  "gmi",
	post.FormatMarkdown: "md",
}

func postTargetFormat(p post.StoredPost) post.Format {
	if p.Format == post.FormatMarkdown && strings.Contains(p.Body, `</`) {
		return post.FormatMarkdown
	}
	return post.FormatGemtext
}

func writePostBody(p post.StoredPost, path, body string) error {
	f, err := os.Create(path)
	if err != nil {
		return fmt.Errorf("opening file: %w", err)
	}
	defer func() { _ = f.Close() }()

	writeString := func(str string) {
		if err != nil {
			return
		}
		_, err = f.WriteString(str)
	}

	if f := postTargetFormat(p); f == post.FormatGemtext {
		writeString("=> ../posts/ Back to All Posts\n\n")
	} else if f == post.FormatMarkdown {
		writeString(fmt.Sprintf("---\nTitle: %q\n---\n", p.Title))
		writeString("[Back to All Posts](../posts/)\n\n")
	}
	writeString(fmt.Sprintf("# %s\n\n", p.Title))
	if p.Description != "" {
		writeString(fmt.Sprintf("> %s\n\n", p.Description))
	}
	writeString(body)
	writeString(fmt.Sprintf("\n-----\n\nPublished %s\n", p.PublishedAt.Format("2006-01-02")))

	return err
}

func writePosts(
	urlBuilder render.URLBuilder, posts []post.StoredPost, path string,
) error {
	f, err := os.Create(path)
	if err != nil {
		return fmt.Errorf("opening file: %w", err)
	}
	defer func() { _ = f.Close() }()

	writeString := func(str string) {
		if err != nil {
			return
		}
		_, err = f.WriteString(str)
	}

	writeString("# Posts\n\n")
	for _, p := range posts {
		var (
			targetFormat = postTargetFormat(p)
			u            = urlBuilder.Post(p.ID)
		)

		if targetFormat == post.FormatMarkdown {
			u = u.HTTP()
		}

		writeString(fmt.Sprintf(
			"=> %s %s - %s\n\n",
			u.String(),
			p.PublishedAt.Format("2006-01-02"),
			p.Title,
		))
	}

	return err
}

func exportPosts(
	ctx context.Context,
	logger *mlog.Logger,
	postStore post.Store,
	urlBuilder render.URLBuilder,
	exportDirPath string,
) error {
	var (
		postsDir        = filepath.Join(exportDirPath, "posts")
		preprocessFuncs = map[post.Format]post.PreprocessFunctions{
			post.FormatGemtext:  gmi.PostPreprocessFuncs{URLBuilder: urlBuilder},
			post.FormatMarkdown: http.NewPostPreprocessFuncs(urlBuilder),
		}
	)

	if err := os.MkdirAll(postsDir, 0755); err != nil {
		return fmt.Errorf("creating posts dir %q: %w", postsDir, err)
	}

	logger.Info(ctx, "Getting posts")
	posts, _, err := postStore.Get(0, 10000)
	if err != nil {
		return fmt.Errorf("getting posts: %w", err)
	}

	{
		postsIndexPath := filepath.Join(postsDir, "index.gmi")
		ctx := mctx.Annotate(ctx, "path", postsIndexPath)
		logger.Info(ctx, "Writing posts index page")
		err = writePosts(urlBuilder, posts, postsIndexPath)
		if err != nil {
			return fmt.Errorf("writing posts index page: %w", err)
		}
	}

	for _, p := range posts {
		var (
			targetFormat = postTargetFormat(p)
			ext          = postFileExtensions[targetFormat]
			postFilePath = filepath.Join(postsDir, p.ID+"."+ext)

			ctx = mctx.Annotate(
				ctx,
				"post_id", p.ID,
				"post_title", p.Title,
				"post_format", p.Format,
				"target_format", targetFormat,
			)

			body = new(bytes.Buffer)
		)

		logger.Info(ctx, "Rendering post body")
		tpl := txttpl.New("")

		tpl, err := tpl.Parse(p.Body)
		if err != nil {
			return fmt.Errorf("parsing post %q body as template: %w", p.ID, err)
		}

		err = tpl.Execute(body, struct {
			RootURL render.URLBuilder
			post.PreprocessFunctions
		}{
			urlBuilder, preprocessFuncs[targetFormat],
		})
		if err != nil {
			return fmt.Errorf("executing post %q body as template: %w", p.ID, err)
		}

		if p.Format == post.FormatMarkdown && targetFormat == post.FormatGemtext {
			gemtextBodyBytes, err := gmnhg.RenderMarkdown(body.Bytes(), 0)
			if err != nil {
				return fmt.Errorf("converting post %q from markdown: %w", p.ID, err)
			}
			body = bytes.NewBuffer(gemtextBodyBytes)
		}

		if err := writePostBody(p, postFilePath, body.String()); err != nil {
			return fmt.Errorf("writing post %q body to file %q: %w", p.ID, postFilePath, err)
		}
	}

	return nil
}