config.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // 解析 JSON(移除可能的注释和尾随逗号)
  13. const jsonContent = configContent.replace(/\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1');
  14. return JSON.parse(jsonContent);
  15. }
  16. } catch (error) {
  17. console.warn('Failed to load config.js:', error.message);
  18. }
  19. return null;
  20. }
  21. // 查找 ADB 可执行文件路径
  22. function getAdbPath() {
  23. // 首先尝试从配置文件读取
  24. const config = loadConfig();
  25. if (config && config['adb-path']) {
  26. const configAdbPath = path.join(config['adb-path'], 'adb.exe');
  27. if (existsSync(configAdbPath)) {
  28. console.log('Using ADB path from config.js:', configAdbPath);
  29. return configAdbPath;
  30. }
  31. // 如果配置的路径不存在,尝试直接使用配置的路径(可能已经是完整路径)
  32. if (existsSync(config['adb-path'])) {
  33. console.log('Using ADB path from config.js:', config['adb-path']);
  34. return config['adb-path'];
  35. }
  36. }
  37. // 如果配置文件没有或路径不存在,使用常见 ADB 安装位置(按优先级排序)
  38. const possiblePaths = [
  39. path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  40. path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'Android', 'Sdk', 'platform-tools', 'adb.exe'),
  41. path.join(process.env.ProgramFiles || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  42. path.join(process.env['ProgramFiles(x86)'] || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'),
  43. ];
  44. // 检查常见位置
  45. for (const adbPath of possiblePaths) {
  46. if (existsSync(adbPath)) {
  47. return adbPath;
  48. }
  49. }
  50. // 如果都找不到,尝试使用 PATH 中的 adb
  51. return 'adb';
  52. }
  53. // 缓存 ADB 路径
  54. let adbPathCache = null;
  55. export function getCachedAdbPath() {
  56. if (!adbPathCache) {
  57. adbPathCache = getAdbPath();
  58. }
  59. return adbPathCache;
  60. }