|
| 1 | +import fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | +import frontmatter from "front-matter"; |
| 4 | +import { I18nConfig } from "./config.ts"; |
| 5 | + |
| 6 | +export class FileProcessor { |
| 7 | + constructor(private config: I18nConfig) {} |
| 8 | + |
| 9 | + processMarkdown(content: string) { |
| 10 | + const { attributes, body } = frontmatter(content); |
| 11 | + const { ignoreBlocks, i11nBlocks } = this.parseComments(body); |
| 12 | + |
| 13 | + return { |
| 14 | + frontmatter: attributes, |
| 15 | + content: body, |
| 16 | + ignoreBlocks, |
| 17 | + i11nBlocks, |
| 18 | + }; |
| 19 | + } |
| 20 | + |
| 21 | + processJson(content: string) { |
| 22 | + const data = JSON.parse(content); |
| 23 | + const ignoredKeys = new Set<string>(); |
| 24 | + const i11nKeys = new Map<string, string>(); |
| 25 | + |
| 26 | + for (const [key, value] of Object.entries(data)) { |
| 27 | + if (key.startsWith("//")) { |
| 28 | + if (Array.isArray(value) && value.includes("i18n-ignore")) { |
| 29 | + ignoredKeys.add(key.replace("//", "")); |
| 30 | + } |
| 31 | + if (Array.isArray(value) && value.some((v) => v.startsWith("i11n:"))) { |
| 32 | + const msg = |
| 33 | + value.find((v) => v.startsWith("i11n:"))?.split(":")[1] || ""; |
| 34 | + i11nKeys.set(key.replace("//", ""), msg); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return { data, ignoredKeys, i11nKeys }; |
| 40 | + } |
| 41 | + |
| 42 | + private parseComments(content: string) { |
| 43 | + const ignoreRegex = |
| 44 | + /<!-- i18n-ignore-start -->([\s\S]*?)<!-- i18n-ignore-end -->/g; |
| 45 | + const i11nRegex = /<!-- i11n-start: (.*?) -->([\s\S]*?)<!-- i11n-end -->/g; |
| 46 | + |
| 47 | + return { |
| 48 | + ignoreBlocks: [...content.matchAll(ignoreRegex)], |
| 49 | + i11nBlocks: [...content.matchAll(i11nRegex)], |
| 50 | + }; |
| 51 | + } |
| 52 | + |
| 53 | + walkDir(dir: string) { |
| 54 | + const results: string[] = []; |
| 55 | + const list = fs.readdirSync(dir); |
| 56 | + |
| 57 | + list.forEach((file) => { |
| 58 | + const fullPath = path.join(dir, file); |
| 59 | + const stat = fs.statSync(fullPath); |
| 60 | + |
| 61 | + if (this.config.ignore?.some((isIgnore) => isIgnore(fullPath))) return; |
| 62 | + |
| 63 | + if (stat?.isDirectory()) { |
| 64 | + results.push(...this.walkDir(fullPath)); |
| 65 | + } else if (this.isTargetFile(fullPath)) { |
| 66 | + results.push(fullPath); |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + return results; |
| 71 | + } |
| 72 | + |
| 73 | + private isTargetFile(filePath: string) { |
| 74 | + const ext = path.extname(filePath); |
| 75 | + return [".md", ".json"].includes(ext); |
| 76 | + } |
| 77 | +} |
0 commit comments