Skip to content

Commit

Permalink
封装JSON5的方法,简化部分代码
Browse files Browse the repository at this point in the history
  • Loading branch information
wangliang181230 committed Apr 10, 2024
1 parent d39379f commit a7dd755
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 37 deletions.
47 changes: 31 additions & 16 deletions packages/core/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const fs = require('fs')
const Shell = require('./shell')
const lodash = require('lodash')
const defConfig = require('./config/index.js')
const JSON5 = require('json5').default
const jsonApi = require('./json.js')
const request = require('request')
const path = require('path')
const log = require('./utils/util.log')
Expand Down Expand Up @@ -66,29 +66,41 @@ const configApi = {
return
}
if (response && response.statusCode === 200) {
const originalRemoteSavePath = _getRemoteSavePath('original_')
fs.writeFileSync(originalRemoteSavePath, body)
log.info('保存原来的远程配置文件成功:', originalRemoteSavePath)
if (body == null || body.length < 3) {
log.warn('下载远程配置成功,但内容为空:', remoteConfigUrl)
resolve()
return
} else {
log.info('下载远程配置成功:', remoteConfigUrl)
}

// 尝试解析远程配置,如果解析失败,则不保存它
let remoteConfig
try {
remoteConfig = JSON5.parse(body)
remoteConfig = jsonApi.parse(body)
} catch (e) {
log.error(`远程配置内容格式不正确, url: ${remoteConfigUrl}, body: ${body}`)
remoteConfig = null
}

if (remoteConfig != null) {
const remoteSavePath = _getRemoteSavePath()
fs.writeFileSync(remoteSavePath, JSON.stringify(remoteConfig, null, '\t'))
fs.writeFileSync(remoteSavePath, body)
log.info('保存远程配置文件成功:', remoteSavePath)
} else {
log.warn('远程配置对象为空:', remoteConfigUrl)
}

resolve()
} else {
const message = '下载远程配置失败:' + response.message + ',code:' + response.statusCode
log.error(message)
log.error('下载远程配置失败, response:', response, ', body:', body)

let message
if (response) {
message = '下载远程配置失败: ' + response.message + ', code: ' + response.statusCode
} else {
message = '下载远程配置失败: response: ' + response
}
reject(new Error(message))
}
})
Expand All @@ -101,9 +113,9 @@ const configApi = {
const path = _getRemoteSavePath()
try {
if (fs.existsSync(path)) {
log.info('读取远程配置文件:', path)
const file = fs.readFileSync(path)
return JSON5.parse(file.toString())
log.info('读取远程配置文件成功:', path)
return jsonApi.parse(file.toString())
} else {
log.warn('远程配置文件不存在:', path)
}
Expand Down Expand Up @@ -148,11 +160,11 @@ const configApi = {
// 计算新配置与默认配置(启用远程配置时,含远程配置)的差异,并保存到 config.json 中
const diffConfig = mergeApi.doDiff(defConfig, newConfig)
const configPath = _getConfigPath()
fs.writeFileSync(configPath, JSON.stringify(diffConfig, null, '\t'))
fs.writeFileSync(configPath, jsonApi.stringify(diffConfig))
log.info('保存自定义配置文件成功:', configPath)

// 重载配置
const allConfig = configApi.reload()
const allConfig = configApi.set(diffConfig)

return {
diffConfig,
Expand All @@ -166,13 +178,16 @@ const configApi = {
* @returns {*}
*/
reload () {
const path = _getConfigPath()
const configPath = _getConfigPath()
let userConfig
if (!fs.existsSync(path)) {
if (!fs.existsSync(configPath)) {
userConfig = {}
log.info('config.json 文件不存在:', configPath)
} else {
const file = fs.readFileSync(path)
userConfig = JSON5.parse(file.toString())
const file = fs.readFileSync(configPath)
log.info('读取 config.json 成功:', configPath)
const fileStr = file.toString()
userConfig = fileStr && fileStr.length > 2 ? jsonApi.parse(fileStr) : {}
}

const config = configApi.set(userConfig)
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
let JSON5 = require('json5')
if (JSON5.default) {
JSON5 = JSON5.default
}

module.exports = {
parse (str) {
return JSON5.parse(str)
},
stringify (obj) {
return JSON.stringify(obj, null, '\t')
}
}
3 changes: 2 additions & 1 deletion packages/core/src/modules/plugin/node/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const nodeConfig = require('./config')
const jsonApi = require('../../../json.js')
const NodePlugin = function (context) {
const { config, shell, event, log } = context
const nodeApi = {
Expand Down Expand Up @@ -31,7 +32,7 @@ const NodePlugin = function (context) {
const ret = await shell.exec(['npm config list --json'], { type: 'cmd' })
if (ret != null) {
const json = ret.substring(ret.indexOf('{'))
return JSON.parse(json)
return jsonApi.parse(json)
}
return {}
},
Expand Down
11 changes: 4 additions & 7 deletions packages/core/src/modules/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ const fork = require('child_process').fork
const log = require('../../utils/util.log')
const fs = require('fs')
const path = require('path')
let JSON5 = require('json5')
if (JSON5.default) {
JSON5 = JSON5.default
}
const jsonApi = require('../../json')

let server = null
function fireStatus (status) {
Expand Down Expand Up @@ -75,8 +72,8 @@ const serverApi = {
// fireStatus('ing') // 启动中
const basePath = serverConfig.setting.userBasePath
const runningConfigPath = path.join(basePath, '/running.json')
fs.writeFileSync(runningConfigPath, JSON.stringify(serverConfig, null, '\t'))
log.info('保存运行时配置文件成功:', runningConfigPath)
fs.writeFileSync(runningConfigPath, jsonApi.stringify(serverConfig))
log.info('保存 running.json 成功:', runningConfigPath)
const serverProcess = fork(mitmproxyPath, [runningConfigPath])
server = {
id: serverProcess.pid,
Expand All @@ -98,7 +95,7 @@ const serverApi = {
log.error('server process uncaughtException:', err)
})
serverProcess.on('message', function (msg) {
log.info('收到子进程消息', msg.type, msg.event.key, msg.message)
log.info('收到子进程消息:', JSON.stringify(msg))
if (msg.type === 'status') {
fireStatus(msg.event)
} else if (msg.type === 'error') {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/shell/scripts/get-npm-env.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
* 获取环境变量
*/
const Shell = require('../shell')
const jsonApi = require('../../json')
const execute = Shell.execute
const executor = {
async windows (exec) {
const ret = await exec(['npm config list --json'], { type: 'cmd' })
if (ret != null) {
const json = ret.substring(ret.indexOf('{'))
return JSON.parse(json)
return jsonApi.parse(json)
}
return {}
},
Expand Down
7 changes: 5 additions & 2 deletions packages/core/start/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const JSON5 = require('json5')
const jsonApi = require('../src/json.js')
const DevSidecar = require('../index')
const fs = require('fs')
const log = require('../src/utils/util.log')

// 启动服务
const mitmproxyPath = './start/mitmproxy'
async function startup () {
Expand All @@ -10,7 +12,8 @@ async function startup () {
const configPath = './start/user_config.json5'
if (fs.existsSync(configPath)) {
const file = fs.readFileSync(configPath)
const userConfig = JSON5.parse(file.toString())
const userConfig = jsonApi.parse(file.toString())
log.info('读取 user_config.json5 成功:', configPath)
DevSidecar.api.config.set(userConfig)
}

Expand Down
9 changes: 6 additions & 3 deletions packages/core/start/mitmproxy.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// eslint-disable-next-line no-unused-vars
const server = require('@docmirror/mitmproxy')
const JSON5 = require('json5')
const jsonApi = require('../src/json.js')
const path = require('path')
const home = process.env.USER_HOME || process.env.HOME || 'C:/Users/Administrator/'
const log = require('../src/utils/util.log')

let configPath
if (process.argv && process.argv.length > 3) {
configPath = process.argv[2]
Expand All @@ -12,10 +13,12 @@ if (process.argv && process.argv.length > 3) {

const fs = require('fs')
const configJson = fs.readFileSync(configPath)
const config = JSON5.parse(configJson)
log.info('读取 running.json by core 成功:', configPath)
const config = jsonApi.parse(configJson.toString())
// const scriptDir = '../../gui/extra/scripts/'
// config.setting.script.defaultDir = path.join(__dirname, scriptDir)
// const pacFilePath = '../../gui/extra/pac/pac.txt'
// config.plugin.overwall.pac.customPacFilePath = path.join(__dirname, pacFilePath)
config.setting.rootDir = path.join(__dirname, '../../gui/')
log.info(`start mitmproxy config by core: 读取配置文件: ${configPath}`)
server.start(config)
26 changes: 22 additions & 4 deletions packages/gui/src/bridge/api/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ import lodash from 'lodash'
import DevSidecar from '@docmirror/dev-sidecar'
import { ipcMain } from 'electron'
import fs from 'fs'
import JSON5 from 'json5'
import path from 'path'
const pk = require('../../../package.json')
const mitmproxyPath = path.join(__dirname, 'mitmproxy.js')
process.env.DS_EXTRA_PATH = path.join(__dirname, '../extra/')
const jsonApi = require('@docmirror/dev-sidecar/src/json.js')
const log = require('../../utils/util.log')

const getDefaultConfigBasePath = function () {
return DevSidecar.api.config.get().server.setting.userBasePath
}

const localApi = {
/**
* 返回所有api列表,供vue来ipc调用
Expand Down Expand Up @@ -47,7 +49,12 @@ const localApi = {
let setting = {}
if (fs.existsSync(settingPath)) {
const file = fs.readFileSync(settingPath)
setting = JSON5.parse(file.toString())
try {
setting = jsonApi.parse(file.toString())
log.info('读取 setting.json 成功:', settingPath)
} catch (e) {
log.error('读取 setting.json 失败:', settingPath, ', error:', e)
}
if (setting == null) {
setting = {}
}
Expand All @@ -57,15 +64,26 @@ const localApi = {
}

if (setting.installTime == null) {
// 设置安装时间
setting.installTime = new Date().getTime()

// 初始化 rootCa.setuped
if (setting.rootCa == null) {
setting.rootCa = {
setuped: false,
desc: '根证书未安装'
}
}

// 保存 setting.json
localApi.setting.save(setting)
}
return setting
},
save (setting = {}) {
const settingPath = _getSettingsPath()
fs.writeFileSync(settingPath, JSON.stringify(setting, null, '\t'))
log.info('保存setting配置文件成功', settingPath)
fs.writeFileSync(settingPath, jsonApi.stringify(setting))
log.info('保存 setting.json 配置文件成功:', settingPath)
}
},
/**
Expand Down
7 changes: 5 additions & 2 deletions packages/gui/src/bridge/mitmproxy.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
// eslint-disable-next-line no-unused-vars
const log = require('../utils/util.log')
const server = require('@docmirror/mitmproxy')
const JSON5 = require('json5').default
const jsonApi = require('@docmirror/dev-sidecar/src/json.js')
const configPath = process.argv[2]
const fs = require('fs')
const path = require('path')
const configJson = fs.readFileSync(configPath)
const config = JSON5.parse(configJson)
log.info('读取 running.json by gui bridge 成功:', configPath)
const config = jsonApi.parse(configJson.toString())
// const scriptDir = '../extra/scripts/'
// config.setting.script.defaultDir = path.join(__dirname, scriptDir)
// const pacFilePath = '../extra/pac/pac.txt'
// config.plugin.overwall.pac.customPacFilePath = path.join(__dirname, pacFilePath)
config.setting.rootDir = path.join(__dirname, '../')
log.info(`start mitmproxy config by gui bridge: ${configPath}`)
server.start(config)
9 changes: 8 additions & 1 deletion packages/gui/src/view/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export default {
},
onCancel: () => {
this.setting.rootCa = this.setting.rootCa || {}
// const rootCa = this.setting.rootCa
// const rootCa = this.setting.rootCa
// rootCa.noTip = true
// this.$api.setting.save(this.setting)
}
Expand All @@ -252,6 +252,13 @@ export default {
// 根证书已安装
rootCa.setuped = true
// 保存安装时间
rootCa.setupTime = new Date().getTime()
// 保存安装描述
rootCa.desc = '根证书已安装'
// 删除noTip数据
// delete rootCa.noTip
this.$set(this, 'setting', this.setting)
this.$api.setting.save(this.setting)
},
Expand Down

0 comments on commit a7dd755

Please sign in to comment.