d33-fix-brandcolor-strings.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env node
  2. /**
  3. * D33: 修复 C 批遗留 bug —— 脚本/样式中的 'BrandColors.x' 字符串字面量
  4. * (字符串不是变量引用,作为颜色值无效:canvas setFillStyle、渐变拼接、色板数组等)
  5. * 统一改为真正的变量引用 BrandColors.x(键均已在 utils/brand-colors.js 存在)
  6. */
  7. const fs = require('fs');
  8. const path = require('path');
  9. const ROOT = path.resolve(__dirname, '..');
  10. const EXCLUDE_DIRS = new Set(['node_modules', 'dist', 'unpackage', '.git', 'scripts', '.tmp_equiv']);
  11. function walk(dir, out = []) {
  12. for (const name of fs.readdirSync(dir)) {
  13. if (EXCLUDE_DIRS.has(name)) continue;
  14. const p = path.join(dir, name);
  15. const st = fs.statSync(p);
  16. if (st.isDirectory()) walk(p, out);
  17. else if (name.endsWith('.vue')) out.push(p);
  18. }
  19. return out;
  20. }
  21. let files = 0;
  22. let count = 0;
  23. for (const abs of walk(ROOT)) {
  24. const src = fs.readFileSync(abs, 'utf8');
  25. if (!/['"]BrandColors\.\w+['"]/.test(src)) continue;
  26. let n = 0;
  27. let out = src.replace(/['"]BrandColors\.(\w+)['"]/g, (m, key) => {
  28. n++;
  29. return 'BrandColors.' + key;
  30. });
  31. if (!/import\s*\{[^}]*\bBrandColors\b[^}]*\}\s*from\s*['"][^'"]*brand-colors/.test(out) &&
  32. !/import\s*\{[^}]*\bBrandColors\b[^}]*\}\s*from\s*['"][^'"]*brand-colors/.test(src)) {
  33. const rel = path.relative(path.dirname(abs), path.join(ROOT, 'utils/brand-colors.js')).split(path.sep).join('/');
  34. const existing = out.match(/import\s*\{([^}]*)\}\s*from\s*(['"][^'"]*brand-colors(?:\.js)?['"])/);
  35. if (existing) {
  36. out = out.replace(existing[0], 'import {' + existing[1].replace(/\s*$/, '') + (existing[1].trim().endsWith(',') ? ' ' : ', ') + 'BrandColors } from ' + existing[2]);
  37. } else {
  38. const t = out.match(/<script[^>]*>\r?\n/);
  39. if (t) out = out.replace(t[0], t[0] + "import { BrandColors } from '" + rel + "'" + (t[0].includes('\r\n') ? '\r\n' : '\n'));
  40. }
  41. }
  42. fs.writeFileSync(abs, out, 'utf8');
  43. files++;
  44. count += n;
  45. console.log(String(n).padStart(3) + ' ' + path.relative(ROOT, abs).split(path.sep).join('/'));
  46. }
  47. console.log('文件:', files, '修复字符串引用:', count);