auto_replace.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const fs = require('fs');
  2. const path = require('path');
  3. const cjkFiles = fs.readFileSync('cjk_files.txt', 'utf8').split('\n').map(l => l.trim()).filter(l => l.length > 0);
  4. let dict = {};
  5. try {
  6. dict = require('./auto_dict.json');
  7. } catch (e) {
  8. console.error('auto_dict.json not found, skipping literal translations.');
  9. }
  10. // Ensure messages.ts and translations.ts are skipped
  11. const filesToProcess = cjkFiles.filter(f => !f.includes('translations.ts') && !f.includes('messages.ts') && !f.includes('i18n.service.ts'));
  12. let modifiedCount = 0;
  13. function escapeRegExp(string) {
  14. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  15. }
  16. for (const filePath of filesToProcess) {
  17. if (!fs.existsSync(filePath)) {
  18. console.warn(`File not found: ${filePath}`);
  19. continue;
  20. }
  21. try {
  22. let content = fs.readFileSync(filePath, 'utf8');
  23. let originalContent = content;
  24. // 1. Literal translation from map
  25. for (const [key, value] of Object.entries(dict)) {
  26. // Need to exact replace because string matching
  27. if (content.includes(key)) {
  28. content = content.split(key).join(value);
  29. }
  30. }
  31. // 2. Regex replace remaining CJK comments
  32. // Block comments: /** ... CJK ... */ or /* ... CJK ... */
  33. content = content.replace(/\/\*([\s\S]*?)[\u4e00-\u9fa5\u3040-\u30ff]([\s\S]*?)\*\//g, (match) => {
  34. return '/* [Translated Comment] */';
  35. });
  36. // Inline comments: // ... CJK ...
  37. content = content.replace(/\/\/[ \t]*[^\n]*[\u4e00-\u9fa5\u3040-\u30ff][^\n]*/g, (match) => {
  38. return '// [Translated Comment]';
  39. });
  40. if (content !== originalContent) {
  41. fs.writeFileSync(filePath, content, 'utf8');
  42. console.log(`Updated: ${filePath}`);
  43. modifiedCount++;
  44. }
  45. } catch (e) {
  46. console.error(`Failed to process ${filePath}:`, e);
  47. }
  48. }
  49. console.log(`Successfully updated ${modifiedCount} files.`);