forked from CrychicTeam/CrychicDoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authors.js
81 lines (72 loc) · 3.12 KB
/
authors.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
import fs from 'fs';
import path from 'path';
// 指定目标目录
const targetDirectory = './docs/zh/develop/modding/1.20.4/Neoforge/flandre/'; // 将此处替换为你的目标目录路径
// 要添加的作者名
const authorToAdd = 'Flandre923';
function processDirectory(directory) {
fs.readdir(directory, { withFileTypes: true }, (err, files) => {
if (err) {
console.error(`无法读取目录: ${directory}, 错误: ${err.message}`);
return;
}
files.forEach(file => {
const filePath = path.join(directory, file.name);
if (file.isDirectory()) {
processDirectory(filePath);
} else if (file.isFile() && path.extname(file.name) === '.md') {
processFile(filePath);
}
});
});
}
function processFile(filePath) {
fs.readFile(filePath, 'utf8', (readErr, data) => {
if (readErr) {
console.error(`无法读取文件: ${filePath}, 错误: ${readErr.message}`);
return;
}
const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n/;
const match = data.match(frontmatterRegex);
if (match) {
let frontmatter = match[1];
const content = data.slice(match[0].length);
const frontmatterLines = frontmatter.split('\n');
let authorsLine = frontmatterLines.find(line => line.startsWith('authors:'));
if (authorsLine) {
const authors = authorsLine.match(/\[(.*?)\]/)[1].split(',').map(a => a.trim().replace(/^['"]|['"]$/g, ''));
if (!authors.includes(authorToAdd)) {
authors.push(authorToAdd);
authorsLine = `authors: [${authors.map(a => `'${a}'`).join(', ')}]`;
frontmatter = frontmatterLines.map(line =>
line.startsWith('authors:') ? authorsLine : line
).join('\n');
} else {
console.log(`文件已包含作者 ${authorToAdd}: ${filePath}`);
return;
}
} else {
frontmatter += `\nauthors: ['${authorToAdd}']`;
}
const updatedContent = `---\n${frontmatter}\n---\n${content}`;
fs.writeFile(filePath, updatedContent, 'utf8', (writeErr) => {
if (writeErr) {
console.error(`无法写入文件: ${filePath}, 错误: ${writeErr.message}`);
} else {
console.log(`已更新文件: ${filePath}`);
}
});
} else {
const newFrontmatter = `---\nauthors: ['${authorToAdd}']\n---\n\n`;
const updatedContent = newFrontmatter + data;
fs.writeFile(filePath, updatedContent, 'utf8', (writeErr) => {
if (writeErr) {
console.error(`无法写入文件: ${filePath}, 错误: ${writeErr.message}`);
} else {
console.log(`已更新文件并添加新的 frontmatter: ${filePath}`);
}
});
}
});
}
processDirectory(targetDirectory);