Skip to content

Commit e535b0e

Browse files
Copilothuangyiirene
andcommitted
Refactor translation utility for better maintainability
Co-authored-by: huangyiirene <[email protected]>
1 parent 18f7c3d commit e535b0e

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

packages/cli/src/utils/translate.mjs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ import fs from 'node:fs';
22
import path from 'node:path';
33
import OpenAI from 'openai';
44

5+
// Supported language suffixes for i18n
6+
const LANGUAGE_SUFFIXES = ['.cn.mdx', '.en.mdx'];
7+
const TARGET_LANGUAGE_SUFFIX = '.cn.mdx';
8+
9+
/**
10+
* Check if a file has a language suffix
11+
* @param {string} filePath - The file path to check
12+
* @returns {boolean} - True if file has a language suffix
13+
*/
14+
function hasLanguageSuffix(filePath) {
15+
return LANGUAGE_SUFFIXES.some(suffix => filePath.endsWith(suffix));
16+
}
17+
518
export function getAllMdxFiles(dir) {
619
let results = [];
720
if (!fs.existsSync(dir)) return results;
@@ -14,7 +27,7 @@ export function getAllMdxFiles(dir) {
1427
results = results.concat(getAllMdxFiles(file));
1528
} else {
1629
// Only include .mdx files that don't have language suffix
17-
if (file.endsWith('.mdx') && !file.endsWith('.cn.mdx') && !file.endsWith('.en.mdx')) {
30+
if (file.endsWith('.mdx') && !hasLanguageSuffix(file)) {
1831
results.push(path.relative(process.cwd(), file));
1932
}
2033
}
@@ -25,17 +38,17 @@ export function getAllMdxFiles(dir) {
2538
export function resolveTranslatedFilePath(enFilePath) {
2639
// Strategy: Use dot parser convention
2740
// content/docs/path/to/file.mdx -> content/docs/path/to/file.cn.mdx
28-
// Skip files that already have language suffix (.cn.mdx or .en.mdx)
41+
// Skip files that already have language suffix
2942
const absPath = path.resolve(enFilePath);
3043

31-
// Skip if already has .cn.mdx or .en.mdx suffix
32-
if (absPath.endsWith('.cn.mdx') || absPath.endsWith('.en.mdx')) {
44+
// Skip if already has a language suffix
45+
if (hasLanguageSuffix(absPath)) {
3346
return absPath;
3447
}
3548

36-
// Replace .mdx with .cn.mdx
49+
// Replace .mdx with target language suffix
3750
if (absPath.endsWith('.mdx')) {
38-
return absPath.replace(/\.mdx$/, '.cn.mdx');
51+
return absPath.replace(/\.mdx$/, TARGET_LANGUAGE_SUFFIX);
3952
}
4053

4154
return absPath;

0 commit comments

Comments
 (0)