code-simplifier 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Code-Simplifier 自动更新管理
5
+ */
6
+
7
+ const chalk = require('chalk')
8
+ const ora = require('ora')
9
+ const { exec } = require('child_process')
10
+ const util = require('util')
11
+ const execPromise = util.promisify(exec)
12
+ const fs = require('fs-extra')
13
+ const path = require('path')
14
+
15
+ class AutoUpdater {
16
+ constructor() {
17
+ this.currentVersion = require('../package.json').version
18
+ this.updateUrl = 'https://registry.npmjs.org/code-simplifier'
19
+ this.backupDir = '.code-simplifier-backup'
20
+ }
21
+
22
+ /**
23
+ * 运行更新管理
24
+ */
25
+ async run(options = {}) {
26
+ if (options.check) {
27
+ await this.checkForUpdates()
28
+ } else if (options.force) {
29
+ await this.update(true)
30
+ } else {
31
+ await this.checkForUpdates()
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 检查更新
37
+ */
38
+ async checkForUpdates() {
39
+ const spinner = ora(chalk.blue('检查工具更新...')).start()
40
+
41
+ try {
42
+ const latestVersion = await this.getLatestVersion()
43
+ spinner.stop()
44
+
45
+ if (latestVersion === this.currentVersion) {
46
+ console.log(chalk.green('✅ 工具已是最新版本'))
47
+ return { needsUpdate: false }
48
+ } else {
49
+ console.log(chalk.yellow(`ℹ️ 发现新版本: ${latestVersion} (当前: ${this.currentVersion})`))
50
+ console.log(chalk.cyan('运行 ') + chalk.yellow('code-simplifier update --force') + chalk.cyan(' 更新'))
51
+ return { needsUpdate: true, latestVersion }
52
+ }
53
+ } catch (error) {
54
+ spinner.fail(chalk.red('更新检查失败'))
55
+ console.error(chalk.gray(error.message))
56
+ return { needsUpdate: false, error: error.message }
57
+ }
58
+ }
59
+
60
+ /**
61
+ * 获取最新版本
62
+ */
63
+ async getLatestVersion() {
64
+ try {
65
+ const { stdout } = await execPromise(`npm view code-simplifier version --json`)
66
+ const versions = JSON.parse(stdout.trim())
67
+ return Array.isArray(versions) ? versions[versions.length - 1] : versions
68
+ } catch (error) {
69
+ // 如果是本地开发环境,模拟版本检查
70
+ return this.currentVersion
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 执行更新
76
+ */
77
+ async update(force = false) {
78
+ console.log(chalk.cyan.bold('\n🔧 Code-Simplifier 工具更新'))
79
+ console.log(chalk.gray('='.repeat(70)))
80
+
81
+ const latestInfo = await this.checkForUpdates()
82
+
83
+ if (!latestInfo.needsUpdate && !force) {
84
+ console.log(chalk.yellow('ℹ️ 已是最新版本,无需更新'))
85
+ return
86
+ }
87
+
88
+ // 确认更新
89
+ if (!force) {
90
+ const { confirm } = await require('inquirer').prompt([
91
+ {
92
+ type: 'confirm',
93
+ name: 'confirm',
94
+ message: '是否确认更新到最新版本?',
95
+ default: true
96
+ }
97
+ ])
98
+
99
+ if (!confirm) {
100
+ console.log(chalk.yellow('已取消更新'))
101
+ return
102
+ }
103
+ }
104
+
105
+ // 备份当前版本
106
+ const spinner1 = ora(chalk.blue('备份当前版本...')).start()
107
+ await this.createBackup()
108
+ spinner1.succeed(chalk.green('备份完成'))
109
+
110
+ // 执行更新
111
+ const spinner2 = ora(chalk.blue('更新工具...')).start()
112
+ try {
113
+ await this.performUpdate()
114
+ spinner2.succeed(chalk.green('工具更新成功'))
115
+ } catch (error) {
116
+ spinner2.fail(chalk.red('更新失败'))
117
+ console.error(chalk.red(error.message))
118
+
119
+ // 询问是否恢复备份
120
+ const { restore } = await require('inquirer').prompt([
121
+ {
122
+ type: 'confirm',
123
+ name: 'restore',
124
+ message: '是否从备份恢复?',
125
+ default: true
126
+ }
127
+ ])
128
+
129
+ if (restore) {
130
+ const spinner3 = ora(chalk.blue('恢复备份...')).start()
131
+ await this.restoreBackup()
132
+ spinner3.succeed(chalk.green('备份已恢复'))
133
+ }
134
+
135
+ process.exit(1)
136
+ }
137
+
138
+ console.log(chalk.green('\n✅ 更新完成'))
139
+ console.log(chalk.cyan('\n运行 ') + chalk.yellow('code-simplifier --help') + chalk.cyan(' 查看新功能'))
140
+ }
141
+
142
+ /**
143
+ * 创建备份
144
+ */
145
+ async createBackup() {
146
+ await fs.ensureDir(this.backupDir)
147
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
148
+ const backupPath = path.join(this.backupDir, `backup-${timestamp}`)
149
+
150
+ // 备份配置文件
151
+ const configFiles = ['.code-simplifier.json', '.code-simplifier-*.json']
152
+ for (const pattern of configFiles) {
153
+ try {
154
+ await exec(`cp ${pattern} ${backupPath}/ 2>/dev/null || true`)
155
+ } catch (error) {
156
+ // 忽略
157
+ }
158
+ }
159
+
160
+ // 备份知识库
161
+ if (await fs.pathExists('.code-simplifier')) {
162
+ await fs.copy('.code-simplifier', path.join(backupPath, 'knowledge-base'))
163
+ }
164
+
165
+ // 清理旧备份
166
+ await this.cleanupOldBackups()
167
+ }
168
+
169
+ /**
170
+ * 恢复备份
171
+ */
172
+ async restoreBackup() {
173
+ const backups = await fs.readdir(this.backupDir)
174
+ if (backups.length === 0) {
175
+ throw new Error('没有可用的备份')
176
+ }
177
+
178
+ const latestBackup = backups.sort().reverse()[0]
179
+ const backupPath = path.join(this.backupDir, latestBackup)
180
+
181
+ // 恢复配置文件
182
+ const configFiles = await fs.readdir(backupPath)
183
+ for (const file of configFiles) {
184
+ if (file.startsWith('.code-simplifier')) {
185
+ await fs.copy(path.join(backupPath, file), file)
186
+ }
187
+ }
188
+
189
+ // 恢复知识库
190
+ if (await fs.pathExists(path.join(backupPath, 'knowledge-base'))) {
191
+ if (await fs.pathExists('.code-simplifier')) {
192
+ await fs.remove('.code-simplifier')
193
+ }
194
+ await fs.copy(path.join(backupPath, 'knowledge-base'), '.code-simplifier')
195
+ }
196
+ }
197
+
198
+ /**
199
+ * 清理旧备份
200
+ */
201
+ async cleanupOldBackups() {
202
+ const backups = await fs.readdir(this.backupDir)
203
+ if (backups.length > 5) {
204
+ const sorted = backups.sort().reverse()
205
+ for (let i = 5; i < sorted.length; i++) {
206
+ await fs.remove(path.join(this.backupDir, sorted[i]))
207
+ }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * 执行实际更新
213
+ */
214
+ async performUpdate() {
215
+ try {
216
+ // 更新npm包
217
+ await execPromise('npm install -g code-simplifier@latest')
218
+
219
+ // 验证更新
220
+ const { stdout } = await execPromise('code-simplifier --version')
221
+ const newVersion = stdout.trim()
222
+ console.log(chalk.gray(`已更新到: ${newVersion}`))
223
+ } catch (error) {
224
+ throw new Error('npm更新失败: ' + error.message)
225
+ }
226
+ }
227
+
228
+ /**
229
+ * 获取更新历史
230
+ */
231
+ async getUpdateHistory() {
232
+ const historyPath = path.join(this.backupDir, 'update-history.json')
233
+ if (await fs.pathExists(historyPath)) {
234
+ return await fs.readJson(historyPath)
235
+ }
236
+ return []
237
+ }
238
+
239
+ /**
240
+ * 记录更新历史
241
+ */
242
+ async recordUpdate(fromVersion, toVersion) {
243
+ const historyPath = path.join(this.backupDir, 'update-history.json')
244
+ const history = await this.getUpdateHistory()
245
+
246
+ history.push({
247
+ fromVersion,
248
+ toVersion,
249
+ timestamp: new Date().toISOString()
250
+ })
251
+
252
+ await fs.writeJson(historyPath, history, { spaces: 2 })
253
+ }
254
+ }
255
+
256
+ module.exports = new AutoUpdater()
package/lib/config.js ADDED
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Code-Simplifier 配置管理
5
+ */
6
+
7
+ const fs = require('fs-extra')
8
+ const path = require('path')
9
+ const chalk = require('chalk')
10
+ const inquirer = require('inquirer')
11
+
12
+ class ConfigManager {
13
+ constructor() {
14
+ this.configDir = '.code-simplifier'
15
+ this.configPath = path.join(this.configDir, 'config.json')
16
+ this.defaultConfig = {
17
+ quality: {
18
+ threshold: 70,
19
+ autoFix: false,
20
+ reportFormat: 'md'
21
+ },
22
+ monitor: {
23
+ port: 3000,
24
+ interval: 300000,
25
+ autoOpen: true
26
+ },
27
+ update: {
28
+ autoCheck: true,
29
+ channel: 'stable'
30
+ },
31
+ report: {
32
+ outputDir: 'reports',
33
+ openAfterGenerate: false
34
+ },
35
+ knowledge: {
36
+ dataDir: '.code-simplifier',
37
+ autoUpdate: true
38
+ }
39
+ }
40
+ this.config = { ...this.defaultConfig }
41
+ }
42
+
43
+ /**
44
+ * 运行配置管理
45
+ */
46
+ async run(options = {}) {
47
+ await this.load()
48
+
49
+ if (options.get) {
50
+ this.get(options.get)
51
+ } else if (options.set) {
52
+ await this.set(options.set, options.value)
53
+ } else if (options.list) {
54
+ this.list()
55
+ } else if (options.reset) {
56
+ await this.reset()
57
+ } else if (options.interactive) {
58
+ await this.interactive()
59
+ } else {
60
+ this.list()
61
+ }
62
+ }
63
+
64
+ /**
65
+ * 加载配置
66
+ */
67
+ async load() {
68
+ await fs.ensureDir(this.configDir)
69
+ if (await fs.pathExists(this.configPath)) {
70
+ try {
71
+ const saved = await fs.readJson(this.configPath)
72
+ this.config = this.mergeConfig(this.defaultConfig, saved)
73
+ } catch (error) {
74
+ console.warn(chalk.yellow('⚠️ 配置文件损坏,使用默认配置'))
75
+ this.config = { ...this.defaultConfig }
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * 保存配置
82
+ */
83
+ async save() {
84
+ await fs.ensureDir(this.configDir)
85
+ await fs.writeJson(this.configPath, this.config, { spaces: 2 })
86
+ }
87
+
88
+ /**
89
+ * 合并配置
90
+ */
91
+ mergeConfig(defaults, saved) {
92
+ const result = { ...defaults }
93
+ for (const key of Object.keys(saved)) {
94
+ if (typeof saved[key] === 'object' && !Array.isArray(saved[key])) {
95
+ result[key] = { ...defaults[key], ...saved[key] }
96
+ } else {
97
+ result[key] = saved[key]
98
+ }
99
+ }
100
+ return result
101
+ }
102
+
103
+ /**
104
+ * 获取配置值
105
+ */
106
+ get(key) {
107
+ const keys = key.split('.')
108
+ let value = this.config
109
+
110
+ for (const k of keys) {
111
+ if (value && typeof value === 'object' && k in value) {
112
+ value = value[k]
113
+ } else {
114
+ console.log(chalk.yellow(`配置项 "${key}" 不存在`))
115
+ return undefined
116
+ }
117
+ }
118
+
119
+ console.log(chalk.cyan(`${key} = `) + chalk.green(JSON.stringify(value)))
120
+ return value
121
+ }
122
+
123
+ /**
124
+ * 设置配置值
125
+ */
126
+ async set(key, value) {
127
+ const keys = key.split('.')
128
+ let target = this.config
129
+
130
+ for (let i = 0; i < keys.length - 1; i++) {
131
+ const k = keys[i]
132
+ if (!(k in target)) {
133
+ target[k] = {}
134
+ }
135
+ target = target[k]
136
+ }
137
+
138
+ const lastKey = keys[keys.length - 1]
139
+
140
+ // 类型转换
141
+ let parsedValue = value
142
+ if (value === 'true') parsedValue = true
143
+ else if (value === 'false') parsedValue = false
144
+ else if (!isNaN(value) && value !== '') parsedValue = Number(value)
145
+
146
+ target[lastKey] = parsedValue
147
+ await this.save()
148
+
149
+ console.log(chalk.green(`✅ 已设置 ${key} = ${JSON.stringify(parsedValue)}`))
150
+ }
151
+
152
+ /**
153
+ * 列出所有配置
154
+ */
155
+ list() {
156
+ console.log(chalk.cyan.bold('\n⚙️ Code-Simplifier 配置'))
157
+ console.log(chalk.gray('='.repeat(50)))
158
+ this.printConfig(this.config, '')
159
+ console.log('')
160
+ }
161
+
162
+ /**
163
+ * 递归打印配置
164
+ */
165
+ printConfig(obj, prefix) {
166
+ for (const [key, value] of Object.entries(obj)) {
167
+ const fullKey = prefix ? `${prefix}.${key}` : key
168
+ if (typeof value === 'object' && !Array.isArray(value)) {
169
+ console.log(chalk.yellow(`\n [${key}]`))
170
+ this.printConfig(value, fullKey)
171
+ } else {
172
+ console.log(chalk.gray(` ${key}: `) + chalk.green(JSON.stringify(value)))
173
+ }
174
+ }
175
+ }
176
+
177
+ /**
178
+ * 重置配置
179
+ */
180
+ async reset() {
181
+ const { confirm } = await inquirer.prompt([
182
+ {
183
+ type: 'confirm',
184
+ name: 'confirm',
185
+ message: '确定要重置所有配置吗?',
186
+ default: false
187
+ }
188
+ ])
189
+
190
+ if (confirm) {
191
+ this.config = { ...this.defaultConfig }
192
+ await this.save()
193
+ console.log(chalk.green('✅ 配置已重置为默认值'))
194
+ } else {
195
+ console.log(chalk.yellow('已取消'))
196
+ }
197
+ }
198
+
199
+ /**
200
+ * 交互式配置
201
+ */
202
+ async interactive() {
203
+ console.log(chalk.cyan.bold('\n⚙️ 交互式配置向导'))
204
+ console.log(chalk.gray('='.repeat(50)))
205
+
206
+ const answers = await inquirer.prompt([
207
+ {
208
+ type: 'number',
209
+ name: 'threshold',
210
+ message: '质量评分阈值 (0-100):',
211
+ default: this.config.quality.threshold
212
+ },
213
+ {
214
+ type: 'confirm',
215
+ name: 'autoFix',
216
+ message: '启用自动修复:',
217
+ default: this.config.quality.autoFix
218
+ },
219
+ {
220
+ type: 'list',
221
+ name: 'reportFormat',
222
+ message: '报告格式:',
223
+ choices: ['md', 'json', 'html'],
224
+ default: this.config.quality.reportFormat
225
+ },
226
+ {
227
+ type: 'number',
228
+ name: 'port',
229
+ message: '监控服务端口:',
230
+ default: this.config.monitor.port
231
+ },
232
+ {
233
+ type: 'confirm',
234
+ name: 'autoCheck',
235
+ message: '启用自动更新检查:',
236
+ default: this.config.update.autoCheck
237
+ }
238
+ ])
239
+
240
+ this.config.quality.threshold = answers.threshold
241
+ this.config.quality.autoFix = answers.autoFix
242
+ this.config.quality.reportFormat = answers.reportFormat
243
+ this.config.monitor.port = answers.port
244
+ this.config.update.autoCheck = answers.autoCheck
245
+
246
+ await this.save()
247
+ console.log(chalk.green('\n✅ 配置已保存'))
248
+ }
249
+
250
+ /**
251
+ * 获取完整配置
252
+ */
253
+ getAll() {
254
+ return { ...this.config }
255
+ }
256
+ }
257
+
258
+ module.exports = new ConfigManager()