From 2d7b8501cbc191bb4428d8893ea8f3b4d14f56d7 Mon Sep 17 00:00:00 2001 From: xihale Date: Sat, 24 Jan 2026 11:36:32 +0800 Subject: [PATCH] chore: cleanup temporary scripts and add autocorrect config --- .autocorrectignore | 8 ++ .autocorrectrc | 8 ++ convert_figure_to_image_link.js | 50 ---------- convert_link_format.js | 107 ---------------------- convert_md_to_smd.js | 157 -------------------------------- format.ts | 153 ------------------------------- 6 files changed, 16 insertions(+), 467 deletions(-) create mode 100644 .autocorrectignore create mode 100644 .autocorrectrc delete mode 100644 convert_figure_to_image_link.js delete mode 100644 convert_link_format.js delete mode 100644 convert_md_to_smd.js delete mode 100644 format.ts diff --git a/.autocorrectignore b/.autocorrectignore new file mode 100644 index 0000000..b625742 --- /dev/null +++ b/.autocorrectignore @@ -0,0 +1,8 @@ +# 忽略所有文件 +* + +# 只允许 content 目录下的 smd 文件 +!content/**/*.smd + +# 只允许 layouts 目录下的 shtml 文件 +!layouts/**/*.shtml diff --git a/.autocorrectrc b/.autocorrectrc new file mode 100644 index 0000000..1210625 --- /dev/null +++ b/.autocorrectrc @@ -0,0 +1,8 @@ +file_types: + smd: markdown + shtml: html + +rules: + space_word: 1 + space_punctuation: 1 + fullwidth: 1 diff --git a/convert_figure_to_image_link.js b/convert_figure_to_image_link.js deleted file mode 100644 index 0c41967..0000000 --- a/convert_figure_to_image_link.js +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -// 递归遍历目录,处理所有 .smd 文件 -function processDirectory(dirPath) { - const items = fs.readdirSync(dirPath); - for (const item of items) { - const fullPath = path.join(dirPath, item); - const stat = fs.statSync(fullPath); - if (stat.isDirectory()) { - processDirectory(fullPath); - } else if (item.endsWith('.smd')) { - processFile(fullPath); - } - } -} - -// 处理单个文件 -function processFile(filePath) { - let content = fs.readFileSync(filePath, 'utf8'); - const newContent = replaceFigure(content); - if (newContent !== content) { - fs.writeFileSync(filePath, newContent, 'utf8'); - console.log(`✓ Converted figure in: ${filePath}`); - } -} - -// 替换 figure 块为图片链接 -function replaceFigure(content) { - // 支持 figure 块跨多行,捕获 src 路径和 caption - return content.replace(/\{\{\\<\s*figure\s+src="([^"]+)"[^>]*caption="([^"]*)"[^>]*\\>\}\}/g, - (match, src, caption) => { - // 去掉 src 开头的 / - const cleanSrc = src.replace(/^\//, ''); - return `[${caption}]($image.siteAsset('${cleanSrc}'))\n`; - } - ); -} - -// 主程序 -function main() { - const rootDir = path.join(__dirname, 'content'); - processDirectory(rootDir); -} - -if (require.main === module) { - main(); -} \ No newline at end of file diff --git a/convert_link_format.js b/convert_link_format.js deleted file mode 100644 index 21a3d3b..0000000 --- a/convert_link_format.js +++ /dev/null @@ -1,107 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -// 配置 -const config = { - sourceDir: './content/' -}; - -// 转换链接格式 -function convertLinkFormat(content) { - // 将 $link.page('filename') 转换为 $link.sub('filename') - content = content.replace(/\$link\.page\('([^']+)'\)/g, (match, filename) => { - return `$link.sub('${filename}')`; - }); - - return content; -} - -// 处理单个文件 -function processFile(filePath) { - try { - const content = fs.readFileSync(filePath, 'utf8'); - const convertedContent = convertLinkFormat(content); - - // 如果内容有变化,写回文件 - if (content !== convertedContent) { - fs.writeFileSync(filePath, convertedContent, 'utf8'); - console.log(`✓ Converted links in: ${filePath}`); - return true; - } else { - console.log(`- No changes needed: ${filePath}`); - return false; - } - } catch (error) { - console.error(`✗ Error processing ${filePath}:`, error.message); - return false; - } -} - -// 递归处理目录 -function processDirectory(dirPath) { - try { - const items = fs.readdirSync(dirPath); - let convertedCount = 0; - let totalCount = 0; - - for (const item of items) { - const fullPath = path.join(dirPath, item); - const stat = fs.statSync(fullPath); - - if (stat.isDirectory()) { - // 递归处理子目录 - const result = processDirectory(fullPath); - convertedCount += result.converted; - totalCount += result.total; - } else if (item.endsWith('.smd')) { - // 处理 smd 文件 - const converted = processFile(fullPath); - if (converted) convertedCount++; - totalCount++; - } - } - - return { converted: convertedCount, total: totalCount }; - } catch (error) { - console.error(`✗ Error processing directory ${dirPath}:`, error.message); - return { converted: 0, total: 0 }; - } -} - -// 主函数 -function main() { - console.log('🔄 Starting link format conversion...'); - console.log(`📁 Source directory: ${config.sourceDir}`); - console.log('🔄 Converting $link.page to $link.sub'); - console.log(''); - - if (!fs.existsSync(config.sourceDir)) { - console.error(`✗ Source directory does not exist: ${config.sourceDir}`); - process.exit(1); - } - - const result = processDirectory(config.sourceDir); - - console.log(''); - console.log('📊 Conversion Summary:'); - console.log(`✓ Converted links in: ${result.converted}/${result.total} files`); - - if (result.converted > 0) { - console.log('🎉 Link format conversion completed!'); - } else { - console.log('ℹ️ No link format conversion needed'); - } -} - -// 运行脚本 -if (require.main === module) { - main(); -} - -module.exports = { - convertLinkFormat, - processFile, - processDirectory -}; \ No newline at end of file diff --git a/convert_md_to_smd.js b/convert_md_to_smd.js deleted file mode 100644 index 18ea8d7..0000000 --- a/convert_md_to_smd.js +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env node - -const fs = require("fs"); -const path = require("path"); - -// 配置 -const config = { - sourceDir: "./content/monthly", - author: "ZigCC", - time: "2024", - layout: "monthly.shtml", -}; - -// 转换 markdown frontmatter 到 smd 格式 -function convertFrontmatter(content) { - const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n/); - if (!frontmatterMatch) { - return content; - } - - const frontmatter = frontmatterMatch[1]; - const body = content.replace(/^---\n[\s\S]*?\n---\n/, ""); - - // 解析现有的 frontmatter - const lines = frontmatter.split("\n"); - const metadata = {}; - - for (const line of lines) { - const match = line.match(/^(\w+):\s*(.+)$/); - if (match) { - metadata[match[1]] = match[2].replace(/^["']|["']$/g, ""); // 移除引号 - } - } - - let hasCustomFrontmatter = Object.keys(metadata).length > 3; - - // 构建新的 smd frontmatter - const newFrontmatter = [ - "---", - `.title = "${metadata.title || "Untitled"}",`, - `.date = @date("${metadata.date || config.time}"),`, - `.author = "${metadata.author || config.author}",`, - `.layout = "${config.layout}",`, - `.draft = false,`, - hasCustomFrontmatter?`.custom = {\n${Object.entries(metadata) - .filter(([k]) => !["title", "date", "author"].includes(k)) - .map(([k, v]) => ` .${k} = "${v}",`) - .join("\n")}\n},\n---`:"---", - "", - ].join("\n"); - - return newFrontmatter + body; -} - -// 转换 markdown 链接格式 -function convertLinks(content) { - // 转换 {{< ref "filename.md" >}} 格式到相对链接 - content = content.replace(/\{\{<\s*ref\s+"([^"]+\.md)"\s*>\}\}/g, "[$1]($1)"); - - // 转换其他可能的 markdown 链接格式 - // 这里可以根据需要添加更多转换规则 - - return content; -} - -// 处理单个文件 -function processFile(filePath) { - try { - const content = fs.readFileSync(filePath, "utf8"); - const convertedContent = convertLinks(convertFrontmatter(content)); - - // 创建新的 smd 文件路径 - const dir = path.dirname(filePath); - const basename = path.basename(filePath, ".md"); - const newPath = path.join(dir, `${basename}.smd`); - - // 写入新文件 - fs.writeFileSync(newPath, convertedContent, "utf8"); - console.log(`✓ Converted: ${filePath} -> ${newPath}`); - - return true; - } catch (error) { - console.error(`✗ Error processing ${filePath}:`, error.message); - return false; - } -} - -// 递归处理目录 -function processDirectory(dirPath) { - try { - const items = fs.readdirSync(dirPath); - let successCount = 0; - let totalCount = 0; - - for (const item of items) { - const fullPath = path.join(dirPath, item); - const stat = fs.statSync(fullPath); - - if (stat.isDirectory()) { - // 递归处理子目录 - const result = processDirectory(fullPath); - successCount += result.success; - totalCount += result.total; - } else if (item.endsWith(".md")) { - // 处理 markdown 文件 - const success = processFile(fullPath); - if (success) successCount++; - totalCount++; - } - } - - return { success: successCount, total: totalCount }; - } catch (error) { - console.error(`✗ Error processing directory ${dirPath}:`, error.message); - return { success: 0, total: 0 }; - } -} - -// 主函数 -function main() { - console.log("🚀 Starting markdown to smd conversion..."); - console.log(`📁 Source directory: ${config.sourceDir}`); - console.log(`👤 Author: ${config.author}`); - console.log(`📅 Time: ${config.time}`); - console.log(""); - - if (!fs.existsSync(config.sourceDir)) { - console.error(`✗ Source directory does not exist: ${config.sourceDir}`); - process.exit(1); - } - - const result = processDirectory(config.sourceDir); - - console.log(""); - console.log("📊 Conversion Summary:"); - console.log( - `✓ Successfully converted: ${result.success}/${result.total} files` - ); - - if (result.success === result.total) { - console.log("🎉 All files converted successfully!"); - } else { - console.log("⚠️ Some files failed to convert"); - } -} - -// 运行脚本 -if (require.main === module) { - main(); -} - -module.exports = { - convertFrontmatter, - convertLinks, - processFile, - processDirectory, -}; diff --git a/format.ts b/format.ts deleted file mode 100644 index 6101365..0000000 --- a/format.ts +++ /dev/null @@ -1,153 +0,0 @@ -import * as fs from 'fs/promises'; -import * as path from 'path'; -import * as tencentcloud from 'tencentcloud-sdk-nodejs'; - -// 腾讯云 TMT 客户端 -const TmtClient = tencentcloud.tmt.v20180321.Client; - -// 配置腾讯云凭证 -const clientConfig = { - credential: { - secretId: process.env.TENCENT_SECRET_ID || 'YOUR_SECRET_ID', // 替换为您的 SecretId - secretKey: process.env.TENCENT_SECRET_KEY || 'YOUR_SECRET_KEY', // 替换为您的 SecretKey - }, - region: 'ap-guangzhou', // 选择合适的区域,例如广州 - profile: { - httpProfile: { - endpoint: 'tmt.tencentcloudapi.com', - }, - }, -}; - -// 初始化 TMT 客户端 -const client = new TmtClient(clientConfig); - -// 翻译接口:使用腾讯云 TMT 批量翻译 API -async function translateToEnglish(texts: string[]): Promise { - try { - const params = { - SourceTextList: texts, - Source: 'zh', - Target: 'en', - ProjectId: 0, // 替换为您的项目 ID(通常为 0 即可) - }; - - const response = await client.TextTranslateBatch(params); - return response.TargetTextList || texts; // 翻译失败时返回原文本 - } catch (error) { - console.error(`Batch translation error for texts:`, error); - return texts; // 翻译失败时返回原文本 - } -} - -// 检查是否为中文 -function isChinese(text: string): boolean { - return /[\u4e00-\u9fa5]/.test(text); -} - -// 检查 ID 是否符合规范(只包含小写字母、数字和连字符) -function isValidIdFormat(id: string): boolean { - return /^[a-z0-9-]+$/.test(id); -} - -// 格式化 ID:转换为小写,用连字符替换空格,移除特殊字符 -function formatId(id: string): string { - return id - .toLowerCase() - .replace(/\s+/g, '-') - .replace(/[^a-z0-9-]/g, ''); -} - -// 处理单个文件 -async function processFile(filePath: string): Promise { - try { - let content = await fs.readFile(filePath, 'utf-8'); - const headingIdRegex = /heading\.id\(['"](.*?)['"]\)/g; - const matches = [...content.matchAll(headingIdRegex)]; - const chineseIds: string[] = []; - const idMap: { [original: string]: string } = {}; - let modified = false; - - // 收集需要翻译的中文 ID 和需要格式化的英文 ID - for (const match of matches) { - const id = match[1]; - if (isChinese(id) || !isValidIdFormat(id)) { - if (isChinese(id)) { - chineseIds.push(id); - } - idMap[id] = match[0]; // 存储原始匹配字符串 - } - } - - if (Object.keys(idMap).length > 0) { - // 批量翻译中文 ID - const translatedIds = chineseIds.length > 0 ? await translateToEnglish(chineseIds) : []; - - // 替换所有不符合规范的 ID - for (const originalId of Object.keys(idMap)) { - let formattedId: string; - if (isChinese(originalId)) { - // 中文 ID:使用翻译结果 - const index = chineseIds.indexOf(originalId); - const translated = translatedIds[index] || originalId; // 回退到原文本 - formattedId = formatId(translated); - } else { - // 英文 ID:直接格式化 - formattedId = formatId(originalId); - } - content = content.replace(idMap[originalId], `heading.id('${formattedId}')`); - modified = true; - } - - if (modified) { - await fs.writeFile(filePath, content, 'utf-8'); - console.log(`Processed: ${filePath}`); - } - } - } catch (error) { - console.error(`Error processing ${filePath}:`, error); - } -} - -// 处理目录 -async function processDirectory(dirPath: string): Promise { - try { - const entries = await fs.readdir(dirPath, { withFileTypes: true }); - - for (const entry of entries) { - const fullPath = path.join(dirPath, entry.name); - if (entry.isDirectory()) { - await processDirectory(fullPath); - } else if (entry.isFile() && (entry.name.endsWith('.smd'))) { - await processFile(fullPath); - } - } - } catch (error) { - console.error(`Error processing directory ${dirPath}:`, error); - } -} - -// 主函数 -async function main(): Promise { - const targetPath = process.argv[2]; - - if (!targetPath) { - console.error('Please provide a file or directory path'); - process.exit(1); - } - - try { - const stats = await fs.stat(targetPath); - if (stats.isDirectory()) { - await processDirectory(targetPath); - } else { - await processFile(targetPath); - } - console.log('Processing completed'); - } catch (error) { - console.error('Error:', error); - process.exit(1); - } -} - -main(); \ No newline at end of file