-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
409 lines (334 loc) · 10.6 KB
/
main.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/fs"
"log"
"log/slog"
"net/http"
"os"
"path/filepath"
"slices"
"github.com/calvinmclean/article-sync/api"
"github.com/fogleman/gg"
)
// Article is used to show which fields can read/write to local file
type Article struct {
ID int `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Description string `json:"description"`
URL string `json:"url"`
Tags []string `json:"tags"`
CoverImage string `json:"cover_image"`
Gopher string `json:"gopher"`
new bool
updated bool
}
type commentData struct {
NewArticles []*Article
UpdatedArticles []*Article
}
func main() {
var apiKey, path, prComment, commit, repositoryName, branch string
var dryRun, createImage, init bool
flag.StringVar(&apiKey, "api-key", "", "API key for accessing dev.to")
flag.StringVar(&path, "path", "./articles", "root path to scan for articles")
flag.StringVar(&prComment, "pr-comment", "", "file to write the PR comment into")
flag.StringVar(&commit, "commit", "", "file to write the commit message into")
flag.StringVar(&repositoryName, "repo", "", "repository name. Used for cover image URL")
flag.StringVar(&branch, "branch", "", "main branch name. Used for cover image URL")
flag.BoolVar(&dryRun, "dry-run", false, "dry-run to print which changes will be made without doing them")
flag.BoolVar(&createImage, "create-image", false, "create gopher cover image even if using dry-run")
flag.BoolVar(&init, "init", false, "download articles from profile and create directories")
flag.Parse()
if apiKey == "" {
apiKey = os.Getenv("API_KEY")
if apiKey == "" {
log.Fatalf("missing required argument --api-key or env var API_KEY")
}
}
client, err := newClient(apiKey, dryRun, createImage)
if err != nil {
log.Fatalf("error creating API client: %v", err)
}
if init {
err = client.init(path)
if err != nil {
log.Fatalf("error initializing: %v", err)
}
return
}
if branch != "" || repositoryName != "" {
client.repositoryName = repositoryName
client.branch = branch
}
var data commentData
err = client.syncArticlesFromRootDirectory(path, &data)
if err != nil {
log.Fatalf("error synchronizing directory: %v", err)
}
if prComment != "" {
err = renderTemplateToFile(prComment, commentTemplate, data)
if err != nil {
log.Fatalf("error writing PR comment: %v", err)
}
}
if commit != "" {
err = renderTemplateToFile(commit, commitTemplate, data)
if err != nil {
log.Fatalf("error writing commit: %v", err)
}
}
}
type client struct {
*api.ClientWithResponses
dryRun, createImage bool
logger *slog.Logger
repositoryName, branch string
}
func newClient(apikey string, dryRun, createImage bool) (*client, error) {
c, err := api.NewClientWithResponses("https://dev.to", api.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
req.Header.Add("api-key", apikey)
return nil
}))
if err != nil {
return nil, fmt.Errorf("error creating client: %w", err)
}
return &client{c, dryRun, createImage, slog.New(slog.NewTextHandler(os.Stdout, nil)), "", ""}, nil
}
func (c *client) init(path string) error {
err := os.MkdirAll(path, 0755)
if err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
articles, err := c.getPublishedArticles()
if err != nil {
return fmt.Errorf("error getting articles: %w", err)
}
c.logger.Info("fetched articles", "count", len(articles))
existingArticles, err := c.getExistingArticleIDs(path)
if err != nil {
return fmt.Errorf("error getting existing article IDs: %w", err)
}
c.logger.Info("existing articles", "count", len(existingArticles))
for _, a := range articles {
logger := c.logger.With("id", a.Id)
logger.Info("creating article locally")
_, exists := existingArticles[int(a.Id)]
if exists {
logger.Info("article exists")
continue
}
fullArticle, err := c.getArticle(int(a.Id))
if err != nil {
logger.Error("error getting article", "error", err)
continue
}
logger.Info("got full article details")
articleDir := filepath.Join(path, a.Slug)
err = os.MkdirAll(articleDir, 0755)
if err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
logger.Info("created directory", "dir", articleDir)
err = writeArticleFile(articleDir, &Article{
ID: int(a.Id),
Slug: a.Slug,
Title: a.Title,
Description: a.Description,
URL: a.Url,
Tags: a.TagList,
})
if err != nil {
return fmt.Errorf("error writing article JSON file: %w", err)
}
articleMarkdown, ok := fullArticle["body_markdown"].(string)
if !ok {
return fmt.Errorf("error checking body_markdown")
}
err = os.WriteFile(filepath.Join(articleDir, "article.md"), []byte(articleMarkdown), 0644)
if err != nil {
return fmt.Errorf("error writing article markdown file: %w", err)
}
logger.Info("added files", "dir", articleDir)
}
return nil
}
func (c *client) getExistingArticleIDs(rootDir string) (map[int]struct{}, error) {
result := map[int]struct{}{}
err := filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("error accessing path %s: %w", path, err)
}
if path == rootDir {
return nil
}
if !d.IsDir() {
return nil
}
c.logger.Info("checking for article", "directory", path)
data, err := os.ReadFile(filepath.Join(path, "article.json"))
if err != nil {
return fmt.Errorf("error reading JSON file: %w", err)
}
var article *Article
err = json.Unmarshal(data, &article)
if err != nil {
return fmt.Errorf("error parsing article details: %w", err)
}
c.logger.Info("found article", "id", article.ID)
result[article.ID] = struct{}{}
return nil
})
return result, err
}
func (c *client) syncArticlesFromRootDirectory(rootDir string, data *commentData) error {
return filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("error accessing path %s: %w", path, err)
}
if path == rootDir {
return nil
}
if !d.IsDir() {
return nil
}
c.logger.Info("sychronizing article", "directory", path)
article, err := c.syncArticleFromDirectory(path)
if err != nil {
return fmt.Errorf("error synchronizing article from path %s: %w", path, err)
}
switch {
case article.new:
data.NewArticles = append(data.NewArticles, article)
case article.updated:
data.UpdatedArticles = append(data.UpdatedArticles, article)
}
return nil
})
}
// syncArticleFromDirectory will read the article files from a directory and:
// - If no ID is provided, create a new article and record ID
// - Otherwise, get article by ID and compare text to local text. If the file is
// recently changed, it will be updated by API
func (c *client) syncArticleFromDirectory(dir string) (*Article, error) {
markdownBody, err := os.ReadFile(filepath.Join(dir, "article.md"))
if err != nil {
return nil, fmt.Errorf("error reading markdown: %w", err)
}
data, err := os.ReadFile(filepath.Join(dir, "article.json"))
if err != nil {
return nil, fmt.Errorf("error reading JSON file: %w", err)
}
var article *Article
err = json.Unmarshal(data, &article)
if err != nil {
return nil, fmt.Errorf("error parsing article details: %w", err)
}
logger := c.logger.With("directory", dir).With("title", article.Title)
var respBody []byte
switch article.ID {
case 0:
article.new = true
logger.Info("creating new article")
if article.Gopher != "" {
logger.With("gopher", article.Gopher).Info("creating gopher cover image")
}
if article.Gopher != "" && (c.createImage || !c.dryRun) {
coverImg, err := createCoverImage(article.Gopher, article.Title)
if err != nil {
return nil, fmt.Errorf("error creating cover image: %w", err)
}
err = gg.SavePNG(filepath.Join(dir, "cover_image.png"), coverImg)
if err != nil {
return nil, fmt.Errorf("error saving image: %w", err)
}
}
img := ""
_, err = os.Stat(filepath.Join(dir, "cover_image.png"))
if err == nil {
img = fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/cover_image.png", c.repositoryName, c.branch, dir)
logger.With("url", img).Info("adding image to article")
}
if c.dryRun {
return article, nil
}
respBody, err = c.createArticle(article, string(markdownBody), img)
if err != nil {
return nil, fmt.Errorf("error creating article: %w", err)
}
default:
logger = logger.With("id", article.ID)
shouldUpdate, err := c.shouldUpdateArticle(string(markdownBody), article)
if err != nil {
return nil, fmt.Errorf("error checking if article needs update: %w", err)
}
if shouldUpdate == "" {
logger.Info("article is up-to-date")
return article, nil
}
logger.With("reason", shouldUpdate).Info("updating article")
article.updated = true
if c.dryRun {
return article, nil
}
respBody, err = c.updateArticle(dir, article, string(markdownBody))
if err != nil {
return nil, fmt.Errorf("error updating article: %w", err)
}
}
err = json.Unmarshal(respBody, &article)
if err != nil {
return nil, fmt.Errorf("error unmarshaling response JSON: %w", err)
}
// article was created so logger doesn't already have ID
if article.new {
logger = logger.With("id", article.ID)
}
logger.Info("successfully synchronized article")
err = writeArticleFile(dir, article)
if err != nil {
return nil, fmt.Errorf("error writing article JSON file: %w", err)
}
return article, nil
}
func writeArticleFile(path string, article *Article) error {
data, err := json.MarshalIndent(article, "", " ")
if err != nil {
return fmt.Errorf("error marshaling response JSON to write to file: %w", err)
}
err = os.WriteFile(filepath.Join(path, "article.json"), data, 0640)
if err != nil {
return fmt.Errorf("error writing JSON file: %w", err)
}
return nil
}
func (c *client) shouldUpdateArticle(markdownBody string, article *Article) (string, error) {
articleData, err := c.getArticle(article.ID)
if err != nil {
return "", fmt.Errorf("error getting article: %w", err)
}
articleMarkdown, ok := articleData["body_markdown"].(string)
if !ok {
return "", fmt.Errorf("error checking body_markdown")
}
article.URL, ok = articleData["url"].(string)
if !ok {
return "", fmt.Errorf("error getting article url")
}
if articleMarkdown != markdownBody {
return "body changed", nil
}
articleTags := articleData["tags"].([]interface{})
existingTags := []string{}
for _, tag := range articleTags {
existingTags = append(existingTags, tag.(string))
}
if !slices.Equal[[]string, string](existingTags, article.Tags) {
return "different tags", nil
}
return "", nil
}