-
Notifications
You must be signed in to change notification settings - Fork 1
/
export2hugo.js
executable file
·71 lines (66 loc) · 1.77 KB
/
export2hugo.js
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
const path = require("path");
const fs = require('fs');
const del = require('del');
const Database = require('better-sqlite3');
const db = new Database('typecho.db', { verbose: console.log, readonly: true });
const tmpFolder = path.resolve(__dirname, 'typecho2hugo');
if (fs.existsSync(tmpFolder)) {
del.sync(path.resolve(tmpFolder, '*'));
} else {
fs.mkdirSync(tmpFolder, 0744);
}
const prefix = 'typecho_'
const stmt = db.prepare(`SELECT cid,title,text,created,slug,type FROM ${prefix}contents`);
const relationships = db.prepare(`SELECT cid,mid FROM ${prefix}relationships`).all().reduce((obj, cur) => {
if (Array.isArray(obj[cur.cid])) {
obj[cur.cid].push(cur.mid);
} else {
obj[cur.cid] = [cur.mid];
}
return obj;
}, {});
const metas = db.prepare(`SELECT mid,name,type FROM ${prefix}metas`).all().reduce((obj, cur) => {
obj[cur.mid] = {
...cur,
};
return obj;
}, {});
for (const post of stmt.iterate()) {
const { cid, title, slug, created, text, type } = post;
if (type !== 'post' || !text) {
continue;
}
const metaIds = relationships[cid];
const categories = [];
const tags = [];
if (metaIds) {
metaIds.forEach((mid) => {
const meta = metas[mid];
switch (meta.type) {
case 'category':
if (meta.name !== 'Uncategorized') {
categories.push(`- ${meta.name}`)
}
break;
case 'tag':
tags.push(`- ${meta.name}`)
break;
default:
}
});
}
const postMD =
`---
title: "${title}"
slug: "${slug}"
date: ${(new Date(created * 1000)).toISOString()}
categories:
${categories.join('\n')}
tags:
${tags.join('\n')}
---
${text.replace('<!--markdown-->', '')}
`
const filePath = path.resolve(tmpFolder, `${slug}.md`);
fs.writeFileSync(filePath, postMD);
}