-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
build.ts
767 lines (724 loc) · 24.9 KB
/
build.ts
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
import { CSS, groupBy, jsonfeedToAtom, mustache } from "./deps.ts";
import { fs, path } from "./deps.ts";
import {
DayInfo,
FeedInfo,
File,
FileInfo,
FileMetaWithSource,
Item,
List,
ListItem,
RunOptions,
WeekOfYear,
} from "./interface.ts";
import renderMarkdown from "./render-markdown.ts";
import {
GITHUB_NAV,
GITHUB_REPO,
INDEX_MARKDOWN_PATH,
PROD_DOMAIN,
SEARCH_NAV,
SUBSCRIPTION_URL,
TOP_REPOS_COUNT,
WEBSITE_NAV,
} from "./constant.ts";
import {
exists,
formatHumanTime,
formatNumber,
getBaseFeed,
getDayNumber,
getDbIndex,
getDbMeta,
getDistRepoContentPath,
getDistRepoGitUrl,
getDistRepoPath,
getIndexFileConfig,
getnextPaginationTextByNumber,
getPaginationHtmlByNumber,
getPaginationTextByNumber,
getPublicPath,
getRepoHTMLURL,
getStaticPath,
getWeekNumber,
pathnameToFeedUrl,
pathnameToFilePath,
pathnameToUrl,
readTextFile,
slug,
walkFile,
writeDbMeta,
writeJSONFile,
writeTextFile,
} from "./util.ts";
import log from "./log.ts";
import { getItemsByDays, getUpdatedDays, getUpdatedFiles } from "./db.ts";
import buildBySource from "./build-by-source.ts";
import buildByTime, { itemsToFeedItemsByDate } from "./build-by-time.ts";
export default async function buildMarkdown(options: RunOptions) {
const config = options.config;
const sourcesConfig = config.sources;
const siteConfig = config.site;
const sourcesKeys = Object.keys(sourcesConfig);
const isBuildSite = options.html;
const specificSourceIdentifiers = options.sourceIdentifiers;
const isBuildMarkdown = options.markdown;
const now = new Date();
if (!isBuildSite && !isBuildMarkdown) {
log.info("skip build site or markdown");
return;
}
const dbMeta = await getDbMeta();
const dbIndex = await getDbIndex();
const dbSources = dbMeta.sources;
let dbSourcesKeys = Object.keys(dbSources);
// delete all dbMeta item that does not exist in config
// compare sources keys and dbSourcesKeys
const dbSourcesKeysToDelete = dbSourcesKeys.filter(
(key) => !sourcesKeys.includes(key),
);
dbSourcesKeysToDelete.forEach((key) => {
log.info(`delete source ${key} from dbMeta`);
delete dbSources[key];
});
dbSourcesKeys = Object.keys(dbSources);
let dbItemsLatestUpdatedAt = new Date(0);
const htmlIndexTemplateContent = await readTextFile(
"./templates/index.html.mu",
);
const htmlSearchTemplateContent = await readTextFile(
"./templates/search.html.mu",
);
for (const sourceIdentifier of dbSourcesKeys) {
const source = dbSources[sourceIdentifier];
const files = source.files;
for (const fileKey of Object.keys(files)) {
const file = files[fileKey];
if (
new Date(file.updated_at).getTime() > dbItemsLatestUpdatedAt.getTime()
) {
dbItemsLatestUpdatedAt = new Date(file.updated_at);
}
}
}
const startTime = new Date();
log.info("start build markdown at " + startTime);
// get last update time
let lastCheckedAt = dbMeta.checked_at;
if (options.force) {
lastCheckedAt = "1970-01-01T00:00:00.000Z";
}
let allUpdatedFiles: File[] = [];
if (specificSourceIdentifiers.length > 0) {
// build specific source
for (const sourceIdentifier of specificSourceIdentifiers) {
const sourceConfig = sourcesConfig[sourceIdentifier];
const sourceFilesKeys = Object.keys(sourceConfig.files);
for (const file of sourceFilesKeys) {
allUpdatedFiles.push({
source_identifier: sourceIdentifier,
file,
});
}
}
} else {
// is any updates
log.info(`check updates since ${lastCheckedAt}`);
allUpdatedFiles = getUpdatedFiles({
since_date: new Date(lastCheckedAt),
source_identifiers: specificSourceIdentifiers,
}, dbIndex);
}
if (options.limit && options.limit > 0) {
allUpdatedFiles = allUpdatedFiles.slice(0, options.limit);
}
log.debug(
`allUpdatedFiles (${allUpdatedFiles.length}) `,
);
if (allUpdatedFiles.length > 0) {
log.info(`found ${allUpdatedFiles.length} updated files`);
const dbSources = dbMeta.sources;
const distRepoPath = getDistRepoPath();
// is exist
if (options.push) {
let isExist = await exists(distRepoPath);
// is exist, check is a git root dir
if (isExist) {
const isGitRootExist = await exists(path.join(distRepoPath, ".git"));
if (!isGitRootExist) {
// remote dir
await Deno.remove(distRepoPath, {
recursive: true,
});
isExist = false;
}
}
if (!isExist) {
// try to sync from remote
log.info("cloning from remote...");
const p = Deno.run({
cmd: ["git", "clone", getDistRepoGitUrl(), distRepoPath],
});
await p.status();
} else {
log.info(`dist repo already exist, skip updates`);
// try to sync
const p = Deno.run({
cmd: [
"git",
"--git-dir",
path.join(distRepoPath, ".git"),
"--work-tree",
distRepoPath,
"pull",
],
});
await p.status();
}
}
if (options.cleanMarkdown) {
log.info("clean markdown files");
// remove all dist repo path files, except .git
const walker = await walkFile(distRepoPath);
for await (const entry of walker) {
const relativePath = path.relative(distRepoPath, entry.path);
if (relativePath.startsWith(".git")) {
continue;
} else {
await Deno.remove(entry.path);
}
}
}
if (options.cleanHtml) {
log.info("clean html files");
// remove all dist repo path files, except .git
await Deno.remove(getPublicPath(), {
recursive: true,
});
}
const rootTemplateContent = await readTextFile(
"./templates/root-readme.md.mu",
);
const htmlTemplate = await readTextFile("./templates/index.html.mu");
let commitMessage = "Automated update\n\n";
// start to build
log.info(
"start to build sources markdown... total: " + allUpdatedFiles.length,
);
const startBuildSourceTime = new Date();
let updatedFileIndex = 0;
for (const file of allUpdatedFiles) {
const sourceConfig = sourcesConfig[file.source_identifier];
const fileInfo: FileInfo = {
sourceConfig: sourceConfig,
sourceMeta: dbSources[sourceConfig.identifier],
filepath: file.file,
};
updatedFileIndex++;
log.info(
`[${updatedFileIndex}/${allUpdatedFiles.length}] ${file.source_identifier}/${file.file}`,
);
const builtInfo = await buildBySource(
fileInfo,
options,
{
paginationHtml: "",
dbMeta,
paginationText: "",
dbIndex,
},
);
// commitMessage += builtInfo.commitMessage + "\n";
}
const endBuildSourceTime = new Date();
const buildSourceTime = endBuildSourceTime.getTime() -
startBuildSourceTime.getTime();
log.info(
"build single markdown done, cost ",
(buildSourceTime / 1000).toFixed(2),
" seconds",
);
const allDays = getUpdatedDays(dbIndex, {
since_date: new Date(0),
}, true);
const allWeeks = getUpdatedDays(dbIndex, {
since_date: new Date(0),
}, false);
// only updated when there is no specific source
if (options.dayMarkdown) {
// update day file
let updatedDays = getUpdatedDays(dbIndex, {
since_date: new Date(lastCheckedAt),
source_identifiers: specificSourceIdentifiers,
}, true);
if (options.limit && options.limit > 0) {
updatedDays = updatedDays.slice(0, options.limit);
}
let updatedDayIndex = 0;
log.info("start to build day markdown..., total: " + updatedDays.length);
const startBuildDayTime = new Date();
for (const day of updatedDays) {
const builtInfo = await buildByTime(day.number, options, {
paginationText: getPaginationTextByNumber(day.number, allDays),
paginationHtml: getPaginationHtmlByNumber(day.number, allDays),
dbMeta,
dbIndex,
});
updatedDayIndex++;
log.debug(
`build day markdown [${updatedDayIndex}/${updatedDays.length}] ${day.path}`,
);
// commitMessage += builtInfo.commitMessage + "\n";
}
const endBuildDayTime = new Date();
const buildDayTime = endBuildDayTime.getTime() -
startBuildDayTime.getTime();
log.info(
"build day markdown done, cost ",
(buildDayTime / 1000).toFixed(2),
" seconds",
);
const startBuildWeekTime = new Date();
// update week file
let updatedWeeks = getUpdatedDays(dbIndex, {
since_date: new Date(lastCheckedAt),
source_identifiers: specificSourceIdentifiers,
}, false);
if (options.limit && options.limit > 0) {
updatedWeeks = updatedWeeks.slice(0, options.limit);
}
let updatedWeekIndex = 0;
log.info(
"start to build week markdown..., total: " + updatedWeeks.length,
);
for (const day of updatedWeeks) {
updatedWeekIndex++;
log.debug(
`build week markdown [${updatedWeekIndex}/${updatedWeeks.length}] ${day.path}`,
);
const builtInfo = await buildByTime(day.number, options, {
paginationText: getPaginationTextByNumber(day.number, allWeeks),
paginationHtml: getPaginationHtmlByNumber(day.number, allWeeks),
dbMeta,
dbIndex,
});
// commitMessage += builtInfo.commitMessage + "\n";
}
const endBuildWeekTime = new Date();
const buildWeekTime = endBuildWeekTime.getTime() -
startBuildWeekTime.getTime();
log.info(
"build week markdown done, cost ",
(buildWeekTime / 1000).toFixed(2),
" seconds",
);
} else {
log.info("skip build day markdown");
}
const allFilesMeta: FileMetaWithSource[] = [];
for (const sourceIdentifier of dbSourcesKeys) {
const sourceMeta = dbSources[sourceIdentifier];
const filesMeta = sourceMeta.files;
const filesMetaKeys = Object.keys(filesMeta);
for (const originalFilepath of filesMetaKeys) {
const fileMeta = filesMeta[originalFilepath];
allFilesMeta.push({
...fileMeta,
sourceIdentifier,
filepath: originalFilepath,
});
}
}
// top 50 repos
// https://bearblog.dev/discover/
// Score = log10(U) + (S / D * 8600)
const sortedRepos = dbSourcesKeys.sort(
(aSourceIdentifier, bSourceIdentifier) => {
const sourceMeta = dbSources[aSourceIdentifier];
const aMeta = dbSources[aSourceIdentifier];
const bMeta = dbSources[bSourceIdentifier];
const aSourceConfig = sourcesConfig[aSourceIdentifier];
const bSourceConfig = sourcesConfig[bSourceIdentifier];
try {
const aIndexFileConfig = getIndexFileConfig(aSourceConfig.files);
const bIndexFileConfig = getIndexFileConfig(bSourceConfig.files);
const aIndexFileMeta = aMeta.files[aIndexFileConfig.filepath];
const bIndexFileMeta = bMeta.files[bIndexFileConfig.filepath];
const aUpdated = new Date(aIndexFileMeta.updated_at);
const bUpdated = new Date(bIndexFileMeta.updated_at);
const unmaintainedTime = new Date().getTime() -
2 * 365 * 24 * 60 * 60 * 1000;
// const flagTime = new Date("2020-01-01");
const aUnmaintained = aUpdated.getTime() <
unmaintainedTime;
const bUnmaintained = bUpdated.getTime() <
unmaintainedTime;
if (aUnmaintained && !bUnmaintained) {
return 1;
}
if (!aUnmaintained && bUnmaintained) {
return -1;
}
if (aUnmaintained && bUnmaintained) {
return 0;
}
const aScore = aMeta.meta.stargazers_count;
const aLogScore = Math.log2(aScore);
const bScore = bMeta.meta.stargazers_count;
const bLogScore = Math.log2(bScore);
// console.log("aLogScore", aLogScore);
// console.log("bLogScore", bLogScore);
const aUpdatedScore = (now.getTime() - aUpdated.getTime()) / 1000 /
604800;
const bUpdatedScore = (now.getTime() - bUpdated.getTime()) / 1000 /
604800;
const result = (bLogScore - bUpdatedScore) -
(aLogScore - aUpdatedScore);
// console.log("result", result);
return result;
} catch (e) {
log.error(
`failed to sort ${aSourceIdentifier} ${bSourceIdentifier}`,
e,
);
throw e;
}
// return score;
},
).slice(0, TOP_REPOS_COUNT).map((sourceIdentifier, index) => {
const sourceConfig = sourcesConfig[sourceIdentifier];
const sourceFileConfig = getIndexFileConfig(sourceConfig.files);
const sourceMeta = dbSources[sourceIdentifier].meta;
const dbFileInfo =
dbSources[sourceIdentifier].files[sourceFileConfig.filepath];
return {
order: index + 1,
name: sourceFileConfig.name,
url: pathnameToFilePath(sourceFileConfig.pathname),
star: formatNumber(sourceMeta.stargazers_count),
source_url: sourceFileConfig.index ? sourceMeta.url : getRepoHTMLURL(
sourceConfig.url,
sourceMeta.default_branch,
sourceFileConfig.filepath,
),
meta: sourceMeta,
updated: formatHumanTime(new Date(dbFileInfo.updated_at)),
};
});
// write dbMeta
dbMeta.checked_at = new Date().toISOString();
for (let i = 0; i < 2; i++) {
const isDay = i === 0;
let lastItems: Record<string, Item> = {};
let jsonFeedItems: Record<string, Item> = {};
if (isDay) {
lastItems = await getItemsByDays(
allDays.slice(0, 3).map((item) => item.number),
dbIndex,
isDay,
);
jsonFeedItems = await getItemsByDays(
allDays.slice(1, 15).map((item) => item.number),
dbIndex,
isDay,
);
} else {
lastItems = await getItemsByDays(
allWeeks.slice(0, 1).map((item) => item.number),
dbIndex,
isDay,
);
jsonFeedItems = await getItemsByDays(
allWeeks.slice(1, 4).map((item) => item.number),
dbIndex,
isDay,
);
}
// console.log("lastItems", lastItems);
const feedItems = itemsToFeedItemsByDate(lastItems, config, isDay);
const jsonFeedItemsByDate = itemsToFeedItemsByDate(
jsonFeedItems,
config,
isDay,
);
const indexMarkdownDistPath = path.join(
getDistRepoContentPath(),
isDay ? INDEX_MARKDOWN_PATH : `week/${INDEX_MARKDOWN_PATH}`,
);
const baseFeed = getBaseFeed();
let indexNav = "";
if (isDay) {
indexNav = `[📅 Weekly](/week/README.md) · [${SEARCH_NAV}](${
pathnameToUrl("/search/")
}) · [🔥 Feed](${
pathnameToFeedUrl("/", true)
}) · [📮 Subscribe](${SUBSCRIPTION_URL}) · [❤️ Sponsor](https://github.com/sponsors/theowenyoung) · [${GITHUB_NAV}](${GITHUB_REPO}) · [${WEBSITE_NAV}](${PROD_DOMAIN}) · 📝 ${
formatHumanTime(dbItemsLatestUpdatedAt)
} · ✅ ${formatHumanTime(new Date(dbMeta.checked_at))}`;
} else {
indexNav = `[🏠 Home](/README.md) · [${SEARCH_NAV}](${
pathnameToUrl("/search/")
}) · [🔥 Feed](${
pathnameToFeedUrl("/week/", true)
}) · [📮 Subscribe](${SUBSCRIPTION_URL}) · [❤️ Sponsor](https://github.com/sponsors/theowenyoung) · [${GITHUB_NAV}](${GITHUB_REPO}) · [${WEBSITE_NAV}](${PROD_DOMAIN}) · 📝 ${
formatHumanTime(dbItemsLatestUpdatedAt)
} · ✅ ${formatHumanTime(new Date(dbMeta.checked_at))}`;
}
const indexFeed: FeedInfo = {
...baseFeed,
title: "Track Awesome List Updates " + (isDay ? "Daily" : "Weekly"),
_site_title: siteConfig.title,
description: config.site.description,
_seo_title:
`${config.site.title} - Track your Favorite Github Awesome List ${
isDay ? "Daily" : "Weekly"
}`,
home_page_url: config.site.url + (isDay ? "/" : "/week/"),
feed_url: config.site.url + (isDay ? "/" : "/week/") + "feed.json",
};
const groupByCategory = (sourceIdentifier: string) => {
const sourceConfig = sourcesConfig[sourceIdentifier];
return sourceConfig.category;
};
const listGroups = groupBy(sourcesKeys, groupByCategory);
const list: List[] = Object.keys(listGroups).sort().map((category) => {
const sourceIdentifiers = listGroups[category];
const items = sourceIdentifiers.map((sourceIdentifier: string) => {
const sourceConfig = sourcesConfig[sourceIdentifier];
const indexFileConfig = getIndexFileConfig(sourceConfig.files);
const sourceMeta = dbSources[sourceIdentifier]?.meta;
const dbFileInfo =
dbSources[sourceIdentifier]?.files[indexFileConfig.filepath];
const item: ListItem = {
name: indexFileConfig.name,
meta: sourceMeta,
updated: formatHumanTime(new Date(dbFileInfo?.updated_at ?? 0)),
url: pathnameToFilePath(indexFileConfig.pathname),
star: formatNumber(sourceMeta?.stargazers_count ?? 0),
source_url: sourceConfig.url,
};
return item;
}).sort((a: ListItem, b: ListItem) => a.name.localeCompare(b.name));
return {
category,
items,
};
});
const lastItem = feedItems[feedItems.length - 1];
const lastItemDate = lastItem.date_published;
const lastItemDateObj = new Date(lastItemDate);
let lastDayNumber = 0;
if (isDay) {
lastDayNumber = getDayNumber(lastItemDateObj);
} else {
lastDayNumber = getWeekNumber(lastItemDateObj);
}
const indexPageData = {
sortedRepos,
items: feedItems,
list,
feed: indexFeed,
navText: indexNav,
paginationText: getnextPaginationTextByNumber(
lastDayNumber,
isDay ? allDays : allWeeks,
),
};
// build summary.md
let summary = "# Track Awesome List\n\n [README](README.md)\n\n";
let allRepos = "\n- [All Tracked List](all-repos/README.md)";
const topReposText = sortedRepos.reduce((acc, item) => {
return acc + `\n - [${item.name}](${pathnameToFilePath(item.url)})`;
}, "\n- [Top Repos](top/README.md)");
Object.keys(listGroups).forEach((category) => {
const sourceIdentifiers = listGroups[category];
allRepos += `\n - [${category}](${slug(category)}/README.md)`;
const items = sourceIdentifiers.map((sourceIdentifier: string) => {
const sourceConfig = sourcesConfig[sourceIdentifier];
const indexFileConfig = getIndexFileConfig(sourceConfig.files);
const filename = indexFileConfig.name;
allRepos += `\n - [${filename}](${
pathnameToFilePath(indexFileConfig.pathname)
})
- [weekly](${pathnameToFilePath(indexFileConfig.pathname + "week/")})
- [overview](${
pathnameToFilePath(indexFileConfig.pathname + "readme/")
})`;
});
});
// add days and weeks to summary
// group days by utc year, month
const daysByYear = groupBy(allDays, "year");
let daysText = "\n- [Days](daily/README.md)";
Object.keys(daysByYear).sort((a, b) => Number(b) - Number(a))
.forEach(
(year) => {
daysText += `\n - [${year}](${year}/month/README.md)`;
const daysByMonth = groupBy(daysByYear[year], "month");
Object.keys(daysByMonth).sort((a, b) => Number(b) - Number(a))
.forEach((month) => {
daysText +=
`\n - [${month}](${year}/${month}/day/README.md)`;
const days = daysByMonth[month] as DayInfo[];
days.sort((a: DayInfo, b: DayInfo) =>
Number(b.day) - Number(a.day)
)
.forEach(
(day: DayInfo) => {
daysText +=
`\n - [${day.name}](${day.path}/README.md)`;
},
);
});
},
);
// group weeks by utc year, month
// add weeks to summary
const weeksByYear = groupBy(allWeeks, "year");
let weeksText = "\n- [Weeks](week/README.md)";
Object.keys(weeksByYear).sort((a, b) => Number(b) - Number(a))
.forEach((year) => {
weeksText += `\n - [${year}](${year}/week/README.md)`;
const weeks = weeksByYear[year] as WeekOfYear[];
weeks.sort((a, b) => Number(b.week) - Number(a.week)).forEach(
(week: WeekOfYear) => {
weeksText += `\n - [${week.name}](${week.path}/README.md)`;
},
);
});
summary += topReposText + allRepos + daysText + weeksText;
const summaryMarkdownDistPath = path.join(
getDistRepoContentPath(),
"SUMMARY.md",
);
await Deno.writeTextFile(summaryMarkdownDistPath, summary);
// write to index
const itemMarkdownContentRendered = mustache.render(
rootTemplateContent,
indexPageData,
);
if (isBuildMarkdown) {
await writeTextFile(indexMarkdownDistPath, itemMarkdownContentRendered);
log.info(`build ${indexMarkdownDistPath} success`);
}
if (isBuildSite) {
const body = renderMarkdown(itemMarkdownContentRendered);
const htmlDoc = mustache.render(htmlIndexTemplateContent, {
...indexFeed,
body,
CSS,
});
const htmlPath = path.join(
getPublicPath(),
isDay ? "index.html" : "week/index.html",
);
await writeTextFile(htmlPath, htmlDoc);
// build feed json
const feedJsonDistPath = path.join(
getPublicPath(),
isDay ? "feed.json" : `week/feed.json`,
);
const finalFeed = {
...indexFeed,
items: jsonFeedItemsByDate,
};
await writeJSONFile(feedJsonDistPath, finalFeed);
// build rss
const rssFeed = { ...finalFeed };
rssFeed.items = rssFeed.items.map(({ content_text: _, ...rest }) =>
rest
);
// @ts-ignore: node modules
const feedOutput = jsonfeedToAtom(rssFeed, {
language: "en",
});
const rssDistPath = path.join(
getPublicPath(),
isDay ? "rss.xml" : `week/rss.xml`,
);
await writeTextFile(rssDistPath, feedOutput);
}
}
// build week data
// copy static files
if (isBuildSite) {
log.info("copy static files...");
const staticPath = getStaticPath();
// copy all files from static to public
// walk files
for await (const entry of await walkFile(staticPath)) {
const relativePath = path.relative(staticPath, entry.path);
const distPath = path.join(getPublicPath(), relativePath);
await fs.copy(entry.path, distPath, {
overwrite: true,
});
}
}
// copy readme to dist
const contentReadmePath = path.join(
getDistRepoContentPath(),
"README.md",
);
const readmeDistPath = path.join(getDistRepoPath(), "README.md");
await Deno.copyFile(contentReadmePath, readmeDistPath);
const endTime = new Date();
log.info(
`build success, cost ${
((endTime.getTime() - startTime.getTime()) / 1000 / 60).toFixed(2)
}ms`,
);
if (options.push) {
// try to push updates
log.info("start to push updates...");
const p1 = Deno.run({
cmd: [
"git",
"--git-dir",
path.join(distRepoPath, ".git"),
"--work-tree",
distRepoPath,
"add",
":/*.md",
],
});
await p1.status();
const p2 = Deno.run({
cmd: [
"git",
"-c",
"user.name=github-actions[bot]",
"-c",
"user.email=github-actions[bot]@users.noreply.github.com",
"--git-dir",
path.join(distRepoPath, ".git"),
"--work-tree",
distRepoPath,
"commit",
"--author='github-actions[bot] <github-actions[bot]@users.noreply.github.com>'",
"-m",
commitMessage,
],
});
await p2.status();
const p3 = Deno.run({
cmd: [
"git",
"--git-dir",
path.join(distRepoPath, ".git"),
"--work-tree",
distRepoPath,
"push",
],
});
await p3.status();
} else {
log.info("skip push updates...");
}
} else {
log.info("no updated files, skip build markdown");
// write dbMeta
dbMeta.checked_at = new Date().toISOString();
}
writeDbMeta(dbMeta);
}