-
Notifications
You must be signed in to change notification settings - Fork 7
/
generator.ts
202 lines (183 loc) · 5.49 KB
/
generator.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
import { exec } from "child_process";
// import * as fs from "fs";
import {
readdirSync,
statSync,
readFileSync,
existsSync,
rmSync,
writeFileSync,
} from "fs";
const srcDirectory = "./src";
const distFile = "./dist.ts";
const distFileJS = "./dist.js";
const metadataFile = "./metadata.json";
const menuHTMLFile = "./menu.html";
type metadata = {
name: string;
namespace: string;
version: string;
description: string;
author: string;
match: string[];
grant: string[];
license: string;
supportURL: string;
require: string[];
resource: { [key: string]: string };
};
/**
* 处理传入的文件内容
* @param content 文件内容
* @returns 修剪过的文件内容
*/
function handleFileContent(content: string): string {
const resultContent: string[] = [];
let importsEnd = false;
for (let line of content.split(/\r?\n/)) {
// 把 unicode 文本转换为 utf-8 文本
line = unicodeToText(line);
// 跳过 `import` 段
if (line === "/// imports end") {
importsEnd = true;
continue;
}
if (importsEnd) {
// 删除每一行的 `export`
line = line.replace("export ", "");
// 删除注释
const pure = line.trim();
if (
!pure.startsWith("/*") &&
!pure.startsWith("*") &&
!pure.startsWith("//")
) {
resultContent.push(line);
}
}
}
return resultContent.join("\n");
}
/**
* 将 unicode 文本转换为普通文本
* @param text 带有 unicode 的文本
* @returns 普通文本
*/
function unicodeToText(text: string) {
return text.replace(/\\u[\dA-F]{4}/gi, (match) => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
/**
* 获取指定文件目录下所有文件的路径(包括子目录)
* @param directoryPath 要获取的文件目录的相对或绝对路径
*/
function getAllFilePaths(directoryPath: string): string[] {
const result: string[] = [];
const files = readdirSync(directoryPath);
for (const filePath of files) {
const path = `${directoryPath}/${filePath}`;
const stats = statSync(path);
if (stats.isDirectory()) {
result.push(...getAllFilePaths(path));
} else {
result.push(path);
}
}
return result;
}
/**
* 根据 `./src` 目录下的所有文件(不包括 `.d.ts`),将内容整合进一个文件中
*/
(function () {
let resultFileContent: string[] = [];
// 解析元信息
const metadataContent = readFileSync(metadataFile, "utf-8");
const metadata: metadata = JSON.parse(metadataContent);
const metadataLines: string[] = [];
metadataLines.push("// ==UserScript==");
// 获取最长长度,以便对齐
let maxLength = 0;
for (const key in metadata) {
const value = metadata[key];
if (value instanceof Object) {
for (const iKey in value) {
const realKey = `${key} ${iKey}`;
const length = realKey.length;
maxLength = Math.max(maxLength, length);
}
} else {
const length = key.length;
maxLength = Math.max(maxLength, length);
}
}
for (const key in metadata) {
const value = metadata[key];
if (value instanceof Array) {
const spaces = Array(maxLength - key.length)
.fill(" ")
.join("");
for (const content of value) {
metadataLines.push(`// @${key}${spaces} ${content}`);
}
} else if (value instanceof Object) {
for (const iKey in value) {
const spaces = Array(maxLength - `${key} ${iKey}`.length)
.fill(" ")
.join("");
const content = value[iKey];
metadataLines.push(`// @${key} ${iKey}${spaces} ${content}`);
}
} else {
const spaces = Array(maxLength - key.length)
.fill(" ")
.join("");
metadataLines.push(`// @${key}${spaces} ${value}`);
}
}
metadataLines.push("// ==/UserScript==");
// 添加元信息到文件
resultFileContent.push(...metadataLines);
// 遍历 `./src` 目录下的所有文件
const files = getAllFilePaths(srcDirectory);
for (const filePath of files) {
// 跳过 `.d.ts`
if (!filePath.endsWith(".d.ts")) {
const content = readFileSync(filePath, "utf-8");
if (content !== undefined) {
const resultContent = handleFileContent(content);
resultFileContent.push(resultContent);
}
}
}
// 添加菜单 HTML 解析
const menuHTML = readFileSync(menuHTMLFile);
resultFileContent.push(`const container = document.createElement("div");`);
resultFileContent.push(`container.setAttribute("id", "qjh-menu");`);
resultFileContent.push("container.innerHTML = `" + menuHTML + "`;");
resultFileContent.push(`container.style.display = "none";`);
resultFileContent.push("document.body.appendChild(container); ");
resultFileContent.push("function showMenu() {");
resultFileContent.push(` container.style.display = "unset";`);
resultFileContent.push("}");
// 生成文件
[distFile, distFileJS].forEach((path) => {
if (existsSync(path)) {
rmSync(path);
}
});
const result = resultFileContent.join("\n");
writeFileSync(distFile, result, "utf-8");
// 执行编译
exec(`tsc ${distFile} --noEmitHelpers --target ES2017`, (_, stdout) => {
for (const line of stdout.split("\n")) {
if (line.lastIndexOf("Cannot find name") === -1) {
console.log(line);
}
}
// tsc 编译后又会变成 unicode
// 因此需要两次转 utf-8
const content = readFileSync(distFileJS, "utf-8");
writeFileSync(distFileJS, unicodeToText(content), "utf-8");
});
})();