Skip to content

Commit bdb6a4e

Browse files
style: reformat code
1 parent 139a7f8 commit bdb6a4e

File tree

2 files changed

+377
-348
lines changed

2 files changed

+377
-348
lines changed

migrate/migrate-bot.ts

Lines changed: 71 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,20 @@ if (!OPENROUTER_API_KEY) {
2727

2828
const octokit = new Octokit({ auth: GITHUB_TOKEN });
2929

30-
async function retry<T>(fn: () => Promise<T>, retries = 3, delay = 1000): Promise<T> {
30+
async function retry<T>(
31+
fn: () => Promise<T>,
32+
retries = 3,
33+
delay = 1000
34+
): Promise<T> {
3135
let lastError: unknown;
3236
for (let attempt = 1; attempt <= retries; attempt++) {
3337
try {
3438
return await fn();
3539
} catch (error) {
3640
lastError = error;
37-
console.warn(`Attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}`);
41+
console.warn(
42+
`Attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}`
43+
);
3844
if (attempt < retries) {
3945
await new Promise((res) => setTimeout(res, delay));
4046
}
@@ -53,7 +59,9 @@ function hasPRReference(title: string): boolean {
5359
return /\[#\d+\]/.test(title);
5460
}
5561

56-
async function fetchPageContent(url: string): Promise<{ html: string; title: string; url: string; innerText: string }> {
62+
async function fetchPageContent(
63+
url: string
64+
): Promise<{ html: string; title: string; url: string; innerText: string }> {
5765
const response = await fetch(url);
5866
if (!response.ok) {
5967
throw new Error(`Failed to fetch ${url}: ${response.status}`);
@@ -73,14 +81,18 @@ async function fetchPageContent(url: string): Promise<{ html: string; title: str
7381
};
7482
}
7583

76-
async function convertToMDX(html: string, title: string, url: string): Promise<string> {
84+
async function convertToMDX(
85+
html: string,
86+
title: string,
87+
url: string
88+
): Promise<string> {
7789
const prompt = (await readFile(__dirname + "/PROMPT.md", "utf8")).replace(
7890
"{{LLM_DOCS}}",
7991
await readFile(
8092
__dirname +
81-
"/../src/content/docs/development/guide/component-docs-for-llm.mdx",
82-
"utf8",
83-
),
93+
"/../src/content/docs/development/guide/component-docs-for-llm.mdx",
94+
"utf8"
95+
)
8496
);
8597

8698
console.log("Prompt:", prompt);
@@ -111,15 +123,17 @@ ${html}
111123
},
112124
],
113125
}),
114-
},
126+
}
115127
);
116128

117129
if (!response.ok) {
118130
const error = await response.text();
119131
throw new Error(`OpenRouter API error: ${error}`);
120132
}
121133

122-
const data = await response.json() as { choices: Array<{ message: { content: string } }> };
134+
const data = (await response.json()) as {
135+
choices: Array<{ message: { content: string } }>;
136+
};
123137
let content = data.choices[0].message.content.trim();
124138

125139
console.log("Raw content:", content);
@@ -154,7 +168,8 @@ ${html}
154168
];
155169

156170
const usedComponents = components.filter(
157-
(comp: string) => content.includes(`<${comp} `) || content.includes(`<${comp}>`),
171+
(comp: string) =>
172+
content.includes(`<${comp} `) || content.includes(`<${comp}>`)
158173
);
159174

160175
// Remove all existing import statements
@@ -218,13 +233,14 @@ function getRelativeHTMLPath(url: string): string {
218233
}
219234

220235
function getLocalMDXPath(url: string): string {
221-
return path.join(
222-
__dirname,
223-
"..", getRelativeMDXPath(url)
224-
);
236+
return path.join(__dirname, "..", getRelativeMDXPath(url));
225237
}
226238

227-
async function writeMDXFile(filePath: string, content: string, title: string): Promise<void> {
239+
async function writeMDXFile(
240+
filePath: string,
241+
content: string,
242+
title: string
243+
): Promise<void> {
228244
const dir = path.dirname(filePath);
229245
await fs.mkdir(dir, { recursive: true });
230246
const frontmatter = `---
@@ -240,34 +256,44 @@ async function uploadImageToImgBB(imageBuffer: Buffer): Promise<string> {
240256
const formData = new FormData();
241257
formData.append("image", new Blob([new Uint8Array(imageBuffer)]), "diff.svg");
242258

243-
const response = await fetch(`https://api.imgbb.com/1/upload?expiration=600&key=${IMGBB_API_KEY}`, {
244-
method: "POST",
245-
body: formData,
246-
});
259+
const response = await fetch(
260+
`https://api.imgbb.com/1/upload?expiration=600&key=${IMGBB_API_KEY}`,
261+
{
262+
method: "POST",
263+
body: formData,
264+
}
265+
);
247266

248267
if (!response.ok) {
249268
const error = await response.text();
250269
throw new Error(`ImgBB API error: ${error}`);
251270
}
252271

253-
const data = await response.json() as { data: { url: string } };
272+
const data = (await response.json()) as { data: { url: string } };
254273
return data.data.url;
255274
}
256275

257-
async function createPullRequest(issue: { number: number; title: string }, filePath: string, url: string, originalInnerText: string): Promise<number> {
276+
async function createPullRequest(
277+
issue: { number: number; title: string },
278+
filePath: string,
279+
url: string,
280+
originalInnerText: string
281+
): Promise<number> {
258282
const branchName = `migrate/${issue.number}-${Date.now().toString(36)}`;
259283
const page = url.split("/w/").pop();
260284
const pageName = page ? page.replace(".html", "") : "unknown";
261285
const prTitle = `feat: migrate ${pageName} from cppref [#${issue.number}]`;
262286
const commitMessage = prTitle;
263287

264-
const newInnerText = await readFile(getRelativeHTMLPath(url), "utf8").then((data) => {
265-
const dom = new JSDOM(data);
266-
const contentElement = dom.window.document.querySelector("main");
267-
return contentElement?.textContent?.trim() || "";
268-
}).catch(() => "");
288+
const newInnerText = await readFile(getRelativeHTMLPath(url), "utf8")
289+
.then((data) => {
290+
const dom = new JSDOM(data);
291+
const contentElement = dom.window.document.querySelector("main");
292+
return contentElement?.textContent?.trim() || "";
293+
})
294+
.catch(() => "");
269295

270-
let imageUrl = null
296+
let imageUrl = null;
271297
if (originalInnerText && newInnerText) {
272298
const svg = visualizeTextDiff(originalInnerText, newInnerText);
273299
if (svg) {
@@ -289,14 +315,17 @@ ${imageUrl ? `![Text Diff](${imageUrl})` : "(无文本差异图像)"}
289315
try {
290316
execSync(`git config user.name "github-actions[bot]"`);
291317
execSync(
292-
`git config user.email "github-actions[bot]@users.noreply.github.com"`,
318+
`git config user.email "github-actions[bot]@users.noreply.github.com"`
293319
);
294320
execSync(`git checkout -b ${branchName}`);
295321
execSync(`git add "${filePath}"`);
296322
execSync(`git commit -m "${commitMessage}"`);
297323
execSync(`git push origin ${branchName}`);
298324
} catch (error) {
299-
console.error("Git操作失败:", error instanceof Error ? error.message : String(error));
325+
console.error(
326+
"Git操作失败:",
327+
error instanceof Error ? error.message : String(error)
328+
);
300329
throw error;
301330
}
302331

@@ -313,7 +342,11 @@ ${imageUrl ? `![Text Diff](${imageUrl})` : "(无文本差异图像)"}
313342
return pr.number;
314343
}
315344

316-
async function updateIssue(issue: { number: number; title: string }, prNumber: number | null, error: unknown = null): Promise<void> {
345+
async function updateIssue(
346+
issue: { number: number; title: string },
347+
prNumber: number | null,
348+
error: unknown = null
349+
): Promise<void> {
317350
const newTitle = `[#${prNumber}] ${issue.title.replace(/\[#\d+\]\s*/, "")}`;
318351
await octokit.issues.update({
319352
owner: REPO_OWNER,
@@ -371,7 +404,11 @@ async function main() {
371404
}
372405

373406
console.log(` 获取 ${url}`);
374-
const { html, title, innerText } = await retry(() => fetchPageContent(url), 3, 2000);
407+
const { html, title, innerText } = await retry(
408+
() => fetchPageContent(url),
409+
3,
410+
2000
411+
);
375412

376413
console.log(` 转换HTML为MDX...`);
377414
const mdx = await retry(() => convertToMDX(html, title, url), 3, 2000);
@@ -383,7 +420,9 @@ async function main() {
383420
console.log(` 尝试构建...`);
384421
const res = spawnSync(`npm run build`, { stdio: "inherit" });
385422
if (res.status !== 0) {
386-
throw new Error("构建失败,可能生成的MDX有问题:" + res.stderr?.toString());
423+
throw new Error(
424+
"构建失败,可能生成的MDX有问题:" + res.stderr?.toString()
425+
);
387426
}
388427

389428
console.log(` 创建PR...`);

0 commit comments

Comments
 (0)