config.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { existsSync, readFileSync } from 'fs';
  2. import path from 'path';
  3. import { fileURLToPath } from 'url';
  4. const __filename = fileURLToPath(import.meta.url);
  5. const __dirname = path.dirname(__filename);
  6. // 读取配置文件
  7. export function loadConfig() {
  8. try {
  9. const configPath = path.join(__dirname, '..', 'config.js');
  10. if (existsSync(configPath)) {
  11. const configContent = readFileSync(configPath, 'utf-8');
  12. // 解析 CommonJS 格式的配置文件
  13. // 移除 module.exports = 和分号,转换为纯 JSON
  14. let jsonContent = configContent
  15. .replace(/module\.exports\s*=\s*/g, '') // 移除 module.exports =
  16. .replace(/;[\s]*$/, '') // 移除末尾分号
  17. .replace(/\/\/.*$/gm, '') // 移除单行注释
  18. .replace(/,(\s*[}\]])/g, '$1') // 移除尾随逗号
  19. .trim();
  20. return JSON.parse(jsonContent);
  21. }
  22. } catch (error) {
  23. console.warn('Failed to load config.js:', error.message);
  24. }
  25. return null;
  26. }
  27. // 查找 ADB 可执行文件路径
  28. function getAdbPath() {
  29. // 首先尝试从配置文件读取
  30. const config = loadConfig();
  31. if (config && config['adb-path']) {
  32. const configAdbPath = path.join(config['adb-path'], 'adb.exe');
  33. if (existsSync(configAdbPath)) {
  34. console.log('Using ADB path from config.js:', configAdbPath);
  35. return configAdbPath;
  36. }
  37. // 如果配置的路径不存在,尝试直接使用配置的路径(可能已经是完整路径)
  38. if (existsSync(config['adb-path'])) {
  39. console.log('Using ADB path from config.js:', config['adb-path']);
  40. return config['adb-path'];
  41. }
  42. }
  43. // 如果配置文件没有或路径不存在,使用常见 ADB 安装位置(按优先级排序)
  44. const possiblePaths = [
  45. path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  46. path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  47. path.join(process.env.ProgramFiles || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  48. path.join(process.env['ProgramFiles(x86)'] || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  49. ];
  50. // 检查常见位置
  51. for (const adbPath of possiblePaths) {
  52. if (existsSync(adbPath)) {
  53. return adbPath;
  54. }
  55. }
  56. // 如果都找不到,尝试使用 PATH 中的 adb
  57. return 'adb';
  58. }
  59. // 缓存 ADB 路径
  60. let adbPathCache = null;
  61. export function getCachedAdbPath() {
  62. if (!adbPathCache) {
  63. adbPathCache = getAdbPath();
  64. }
  65. return adbPathCache;
  66. }