import { existsSync, readFileSync } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // 读取配置文件 export function loadConfig() { try { const configPath = path.join(__dirname, '..', 'adb-path-config.js'); if (existsSync(configPath)) { const configContent = readFileSync(configPath, 'utf-8'); // 解析 CommonJS 格式的配置文件 // 移除 module.exports = 和分号,转换为纯 JSON let jsonContent = configContent .replace(/module\.exports\s*=\s*/g, '') // 移除 module.exports = .replace(/;[\s]*$/, '') // 移除末尾分号 .replace(/\/\/.*$/gm, '') // 移除单行注释 .replace(/,(\s*[}\]])/g, '$1') // 移除尾随逗号 .trim(); // 将单引号字符串转换为双引号字符串(JSON 要求) // 匹配单引号字符串,包括转义的单引号 jsonContent = jsonContent.replace(/'((?:[^'\\]|\\.)*)'/g, (match, content) => { // 转义双引号和反斜杠,然后用双引号包裹 // 注意:反斜杠需要先转义,因为后续的替换可能会影响它们 const escaped = content .replace(/\\/g, '\\\\') // 转义反斜杠(先处理) .replace(/"/g, '\\"'); // 转义双引号 return `"${escaped}"`; }); return JSON.parse(jsonContent); } } catch (error) { console.warn('Failed to load adb-path-config.js:', error.message); } return null; } // 查找 ADB 可执行文件路径 function getAdbPath() { // 首先尝试从配置文件读取 const config = loadConfig(); if (config && config['adb-path']) { const configAdbPath = path.join(config['adb-path'], 'adb.exe'); if (existsSync(configAdbPath)) { console.log('Using ADB path from adb-path-config.js:', configAdbPath); return configAdbPath; } // 如果配置的路径不存在,尝试直接使用配置的路径(可能已经是完整路径) if (existsSync(config['adb-path'])) { console.log('Using ADB path from adb-path-config.js:', config['adb-path']); return config['adb-path']; } } // 如果配置文件没有或路径不存在,使用常见 ADB 安装位置(按优先级排序) const possiblePaths = [ path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk', 'platform-tools', 'adb.exe'), path.join(process.env.USERPROFILE || '', 'AppData', 'Local', 'Android', 'Sdk', 'platform-tools', 'adb.exe'), path.join(process.env.ProgramFiles || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'), path.join(process.env['ProgramFiles(x86)'] || '', 'Android', 'android-sdk', 'platform-tools', 'adb.exe'), ]; // 检查常见位置 for (const adbPath of possiblePaths) { if (existsSync(adbPath)) { return adbPath; } } // 如果都找不到,尝试使用 PATH 中的 adb return 'adb'; } // 缓存 ADB 路径 let adbPathCache = null; export function getCachedAdbPath() { if (!adbPathCache) { adbPathCache = getAdbPath(); } return adbPathCache; }