// electron/utils/readConfig.js const fs = require('fs'); const path = require('path'); const { app } = require('electron'); const defaultConfig = require('./config.default'); const configPath = path.join(app.getPath("userData"),'config.default.json'); // Smart Shooter 5 的历史默认安装目录。用户目录里的旧配置会盖掉代码默认值, // 只有仍停在这套出厂值时才自动切到 6;手动选过别的目录则保持不动。 const LEGACY_SMARTSHOOTER5 = { controlType: "SmartShooter", controlPath: "C:\\Program Files\\Smart Shooter 5", } function migrateLegacySmartShooter(config) { if (!config || config.smartShooter6Migrated) return { config, changed: false } const stillFactoryDefault = config.controlType === LEGACY_SMARTSHOOTER5.controlType && config.controlPath === LEGACY_SMARTSHOOTER5.controlPath config.smartShooter6Migrated = true if (!stillFactoryDefault) return { config, changed: true } config.controlType = defaultConfig.controlType config.controlPath = defaultConfig.controlPath config.SmartShooterPath = config.SmartShooterPath || LEGACY_SMARTSHOOTER5.controlPath config.SmartShooter6Path = defaultConfig.SmartShooter6Path return { config, changed: true } } /** * 读取配置文件 */ function readConfigFile() { try { if (fs.existsSync(configPath)) { const data = fs.readFileSync(configPath, 'utf8'); const parsed = JSON.parse(data); const { config: merged, changed } = migrateLegacySmartShooter({ ...defaultConfig, ...parsed, }); if (changed) { fs.writeFileSync(configPath, JSON.stringify(merged, null, 2), 'utf8'); } return merged; } else { console.log('配置文件不存在'); // 创建空白JSON文件 fs.writeFileSync(configPath, '{}', 'utf8'); return { ...defaultConfig, }; } } catch (error) { console.error('读取配置文件出错:', error); return null; } } function loadConfigFile() { if (!fs.existsSync(configPath)) { return { ...defaultConfig } } const data = fs.readFileSync(configPath, 'utf8'); return { ...defaultConfig, ...JSON.parse(data), } } /** * 一次写入多项配置,避免 controlType 和安装目录被分成几次写入后互相覆盖 */ function updateConfigFile(partial) { try { const config = { ...loadConfigFile(), ...partial, } fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(`成功写入配置项: ${Object.keys(partial).join(', ')}`); } catch (error) { console.error('写入配置文件出错:', error); } } /** * 写入配置文件 * @param {string} key - 要写入的配置项键名 * @param {*} value - 要写入的配置项值 */ function writeConfigFile(key, value) { updateConfigFile({ [key]: value }) } module.exports = { readConfigFile, writeConfigFile, updateConfigFile };