-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcmd.js
173 lines (169 loc) · 5.77 KB
/
cmd.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
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
const path = require('path');
const fs = require('fs');
const day = require('dayjs');
const fm = require('front-matter');
const mark = require('marked');
const omit = require('lodash/omit')
const { execSync } = require('child_process');
const targetDir = path.resolve(__dirname, 'source/_posts');
const docsDir = path.resolve(__dirname, 'docs')
const ignoreDir = [
'work', 'myStory', '杂记.md', 'QQMusicApi.md', 'engineering', 'discipline', 'static', '树莓派入门到实战.md', 'Docker 安装 Jenkins.md', '视频工厂.md',
'WebComponent.md', 'centos 安装 puppeteer.md', ];
const renderer = new mark.Renderer();
const CMDMap = {
server: 'npx hexo server',
build: 'npx hexo generate'
}
// 将mermaid换成hexo的格式
const replaceMermaid = (text) => {
const reg = /(```mermaid)|(``````mermaid)/;
if (!reg.test(text)) return text;
const textArr = text.split(/\n/);
const obj = textArr.reduce((prev,curr, currentIndex) => {
if (['```mermaid', '``````mermaid'].includes(curr)) {
if (!prev.position.length) {
prev.position.push(currentIndex)
}
}
if (['```', '``````'].includes(curr)) {
if (prev.position.length === 1) {
prev.position.push(currentIndex)
}
}
prev.arr.push(curr);
if (prev.position.length === 2) {
prev.total = prev.total + 1;
const [start, end] = prev.position;
prev.arr[start] = '{% mermaid %}';
prev.arr[end] = '{% endmermaid %}';
prev.position = [];
}
return prev;
}, {total: 0, position: [], arr: []})
return obj.arr.join('\n')
}
// 复制之前先清空
const delDir = (path) => {
let files = [];
if(fs.existsSync(path)){
files = fs.readdirSync(path);
files.forEach((file, index) => {
let curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()){
delDir(curPath); //递归删除文件夹
} else {
fs.unlinkSync(curPath); //删除文件
}
});
}
return true
}
const wreiteFile = (params) => {
const content = fs.readFileSync(params.fullpath, {encoding: 'utf-8'});
const {attributes, body} = fm(content)
let description = [];
renderer.text = (text, level) => {
description.push(text)
};
mark.marked(body, { renderer: renderer });
description = description.reduce((prev,curr) => {
if (prev.length > 140) {
return prev;
}
return `${prev}${curr.replace(/[\n:]/,' ')}`
}, '')
const {categories, title} = params;
categories.reduce((prev,curr) => {
const dirPath = path.resolve(targetDir, ...prev, curr);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath)
}
prev.push(curr);
return prev;
}, []);
const meta = {...params, ...attributes, description: attributes.description || description};
const newmeta = omit(meta, ['fullpath'])
// 新meta
const metaStr = Object.entries(newmeta).reduce((prev,[key,value], currindex, arr) => {
let valueStr = '';
if (Array.isArray(value) && value.length) {
value.forEach(item => {
valueStr += `\n - ${item}`
})
}
if (typeof value === 'string') {
valueStr = value || ' ';
}
if (!prev) {
prev = `---\n${key}: ${valueStr}`
} else {
prev = `${prev}\n${key}: ${valueStr}`
}
if (currindex === arr.length - 1) {
prev = `${prev}\n---`
}
return prev
}, '')
let word;
if (attributes && Object.keys(attributes) && Object.keys(attributes).length) {
const reg = /(---(\n|.)*(---))/;
reg.test(content);
const contentMeta = RegExp.$1.split('---')[1]
word = content.replace(`---${contentMeta}---`, metaStr)
} else {
word = `${metaStr}\n${content}`
}
const text = replaceMermaid(word);
const targetPosition = path.resolve(targetDir, ...categories, `${title}.md`)
console.log('要写入文件了', targetPosition)
fs.writeFileSync(targetPosition, text, {encoding: 'utf-8'})
}
const listFile = (dir) => {
let arr = fs.readdirSync(dir, {encoding: 'utf-8', withFileTypes: false});
console.log('===========执行命令目录下所有文件', arr)
arr = arr.filter(item => !item.startsWith('.') && !ignoreDir.includes(item))
arr.forEach(item => {
const fullpath = path.join(dir, item);
const stats = fs.statSync(fullpath);
console.log('==============是否是目录', stats.isDirectory());
if (stats.isDirectory()) {
listFile(fullpath)
} else if (fullpath.endsWith('.md')) {
const updated = day(stats.mtime).format('YYYY/MM/DD HH:mm:ss'); // 更新日期
const date = day(stats.ctime).format('YYYY/MM/DD HH:mm:ss'); // 创建日期
const fileInfo = fullpath.replace(docsDir,'').split('/').reduce((prev, curr) => {
if (!curr) {
return prev;
}
if (!curr.endsWith('.md')) {
prev.categories.push(curr);
return prev;
}
prev.title = curr.replace('.md','')
prev.post_title = curr.replace('.md','')
return prev;
}, {categories: [], title: '', post_title: ''})
console.log('==============获取文件路径', fullpath);
wreiteFile({updated, date, ...fileInfo, comments: 'true', fullpath});
}
});
}
const run = () => {
console.log('当前目录下所有文件=============')
execSync('ls', {stdio: 'inherit'})
console.log('node 版本 =============')
execSync('node -v', {stdio: 'inherit'})
console.log('npm 版本 =============')
execSync('npm -v', {stdio: 'inherit'})
console.log('===========开始删除目标目录', targetDir)
delDir(targetDir);
console.log('===========递归文档目录', docsDir)
listFile(docsDir);
console.log('===========递归完成')
console.log('===========执行命令--start', process.argv)
const cmdstr = CMDMap[process.argv[2]];
console.log('===========执行命令--end', cmdstr)
execSync(cmdstr, {stdio: 'inherit'})
}
run()