mirror of
https://github.com/rememberber/MooTool.git
synced 2026-12-01 03:18:19 +08:00
[next]+[java]feat:System environment variable tool, which supports direct modification.
This commit is contained in:
1 parent
1c4acedf5f
commit
6794de2453
18 files changed
+1221
-42
No files matched your search
@@ -286,7 +286,7 @@ type AppSettings = {
|
||||
| 开发 | `java` | 代码运行 | Java/Python/Node.js 三个 Tab、编辑器、格式化、运行结果、历史;Java Tab 兼容旧版 Java/Groovy | P6 | 待对齐验收 |
|
||||
| 开发 | `ymlProperties` | 配置转换 | 转换 Tab、校验、历史 | P3 | 待对齐验收 |
|
||||
| 开发 | `protobuf` | Protobuf | JSON/二进制、Wire、Hex/Base64 三个 Tab | P4 | 待对齐验收 |
|
||||
| 开发 | `variables` | 环境变量 | 系统变量/Java Properties Tab、表格、导出 | P5 | 待对齐验收 |
|
||||
| 开发 | `variables` | 环境变量 | 用户/系统变量直接修改、Java Properties Tab、表格、导出 | P5 | 待对齐验收 |
|
||||
| 网络 | `http` | HTTP 请求 | 请求列表、请求编辑、响应 Body/Header/Cookie、历史 | P5 | 待对齐验收 |
|
||||
| 网络 | `host` | Host | Host 列表、编辑器、查找替换、导入导出 | P5 | 待对齐验收 |
|
||||
| 网络 | `net` | 网络/IP | 功能选择、参数区、结果区 | P5 | 待对齐验收 |
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
| 翻译 | 翻译/单词本/历史三 Tab、源/目标语言、翻译器、自动翻译 | 500 ms 自动翻译、Google/Bing 轻量双实现与 fallback、代理/超时/取消、单词本 CRUD/重译和历史 | 待对齐验收 |
|
||||
| Host | 方案列表、文本编辑、查找替换、导入导出、当前系统 Hosts、切换 | 方案 CRUD、编辑/查找替换、文件导入导出、系统 Hosts 查看、按平台提权写入和 DNS 刷新 | 待对齐验收 |
|
||||
| 网络/IP | 命令输出与 IPv4、ping、DNS、地址解析、WHOIS、本机地址 | 白名单系统命令、IPv4/Long 双向转换、DNS 解析、WHOIS、本机 IPv4/IPv6、停止与错误码 | 待对齐验收 |
|
||||
| 环境变量 | 系统变量/Java Properties Tab、搜索、表格、导出 | 系统环境变量/Electron 运行属性 Tab、搜索、逐项复制、刷新和完整导出 | 待对齐验收 |
|
||||
| 环境变量 | 用户/系统变量直接新增、编辑、删除;Java Properties Tab、表格、导出 | 用户/系统变量直接新增、编辑、删除;当前进程/Electron 运行属性只读视图、搜索、复制、刷新和完整导出 | 待对齐验收 |
|
||||
| 系统信息 | 系统/CPU/内存/存储/网络五 Tab | `systeminformation` 结构化采集、五 Tab、刷新、复制、序列号脱敏 | 待对齐验收 |
|
||||
|
||||
## 2. 主进程与设置边界
|
||||
@@ -33,7 +33,7 @@
|
||||
- [x] 翻译保留翻译/单词本/历史 Tab 顺序,单词本或历史回填不会触发重复在线翻译。
|
||||
- [x] Host 保留“左侧方案 + 右侧工具栏/编辑器”,系统 Hosts 通过独立对话框查看。
|
||||
- [x] 网络/IP 保留“左侧命令结果 + 右侧功能区”的桌面宽屏结构。
|
||||
- [x] 环境变量和系统信息保留 Java 版 Tab、表格/键值结构与刷新、复制、导出操作。
|
||||
- [x] 环境变量和系统信息保留 Java 版 Tab、表格/键值结构与刷新、复制、导出操作;两版均支持直接修改用户/系统环境变量。
|
||||
- [x] 所有页面具有简体中文、英文、日文文案,并跟随系统明暗主题。
|
||||
- [x] 1440 x 920 浅色与 1080 x 720 深色共 12 张页面截图已建立。
|
||||
- [x] 两组视口下六页均无窗口级或工作区级横向溢出、控件遮挡和空白渲染。
|
||||
|
||||
@@ -92,6 +92,8 @@ import { QuickNoteVaultRepository } from './quickNoteVaultRepository'
|
||||
import { RuntimeExecutionService } from './runtimeExecutionService'
|
||||
import {
|
||||
normalizeHostInput,
|
||||
normalizeDeleteEnvironmentVariableInput,
|
||||
normalizeEnvironmentVariableInput,
|
||||
normalizeHttpRequest,
|
||||
normalizeHttpResponse,
|
||||
normalizeHttpSendInput,
|
||||
@@ -699,6 +701,8 @@ function registerIpc(): void {
|
||||
ipcMain.handle('system:network-command', (_event, value: unknown) => systemService.runNetwork(normalizeNetworkInput(value)))
|
||||
ipcMain.handle('system:cancel', (_event, requestId: unknown) => systemService.cancel(normalizeRequestId(requestId)))
|
||||
ipcMain.handle('system:environment', () => systemService.getEnvironment())
|
||||
ipcMain.handle('system:environment-set', (_event, value: unknown) => systemService.setEnvironmentVariable(normalizeEnvironmentVariableInput(value)))
|
||||
ipcMain.handle('system:environment-delete', (_event, value: unknown) => systemService.deleteEnvironmentVariable(normalizeDeleteEnvironmentVariableInput(value)))
|
||||
ipcMain.handle('system:local-addresses', () => systemService.getLocalAddresses())
|
||||
ipcMain.handle('system:info', () => systemService.getSystemInfo())
|
||||
ipcMain.handle('runtime:run', (event, value: unknown) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { httpMethods, normalizeTranslationLanguagePair, type HttpCookieEntry, type HttpRequestDraft, type HttpResponseResult, type HttpSendInput, type KeyValueEntry, type SaveTranslationHistoryInput, type SaveTranslationWordInput, type TranslationInput } from '../../src/shared/contracts/network'
|
||||
import type { NetworkCommandInput, SaveHostProfileInput } from '../../src/shared/contracts/system'
|
||||
import type { DeleteEnvironmentVariableInput, EnvironmentVariableInput, NetworkCommandInput, SaveHostProfileInput } from '../../src/shared/contracts/system'
|
||||
|
||||
const networkActions = ['interfaces', 'connections', 'ping', 'ping-range', 'port-scan', 'flush-dns', 'resolve', 'whois'] as const
|
||||
|
||||
@@ -88,10 +88,44 @@ export function normalizeNetworkInput(value: unknown): NetworkCommandInput {
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeEnvironmentVariableInput(value: unknown): EnvironmentVariableInput {
|
||||
const record = objectValue(value, 'Invalid environment variable')
|
||||
return {
|
||||
scope: environmentScope(record.scope),
|
||||
key: environmentKey(record.key),
|
||||
value: environmentValue(record.value)
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeDeleteEnvironmentVariableInput(value: unknown): DeleteEnvironmentVariableInput {
|
||||
const record = objectValue(value, 'Invalid environment variable')
|
||||
return {
|
||||
scope: environmentScope(record.scope),
|
||||
key: environmentKey(record.key)
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeKeyword(value: unknown): string {
|
||||
return typeof value === 'string' ? value.slice(0, 200) : ''
|
||||
}
|
||||
|
||||
function environmentScope(value: unknown): EnvironmentVariableInput['scope'] {
|
||||
if (value !== 'user' && value !== 'system') throw new Error('Invalid environment variable scope')
|
||||
return value
|
||||
}
|
||||
|
||||
function environmentKey(value: unknown): string {
|
||||
const key = stringValue(value, 256)
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error('Invalid environment variable name')
|
||||
return key
|
||||
}
|
||||
|
||||
function environmentValue(value: unknown): string {
|
||||
const result = stringValue(value, 65_535)
|
||||
if (/[\0\r\n]/.test(result)) throw new Error('Environment variable values cannot contain line breaks')
|
||||
return result
|
||||
}
|
||||
|
||||
export function normalizePositiveId(value: unknown): number {
|
||||
const id = optionalId(value)
|
||||
if (!id) throw new Error('Invalid id')
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
|
||||
import { access, readFile, unlink, writeFile } from 'node:fs/promises'
|
||||
import { access, mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
||||
import { constants } from 'node:fs'
|
||||
import { lookup } from 'node:dns/promises'
|
||||
import { createConnection, type Socket } from 'node:net'
|
||||
import { networkInterfaces } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { homedir, networkInterfaces } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import si from 'systeminformation'
|
||||
import type {
|
||||
DeleteEnvironmentVariableInput,
|
||||
EnvironmentEntry,
|
||||
EnvironmentScope,
|
||||
EnvironmentSnapshot,
|
||||
EnvironmentVariableInput,
|
||||
NetworkAction,
|
||||
NetworkCommandInput,
|
||||
NetworkCommandResult,
|
||||
@@ -22,6 +25,8 @@ const maxCommandOutput = 2 * 1024 * 1024
|
||||
const maxCustomPorts = 4096
|
||||
const ipRangeConcurrency = 32
|
||||
const portScanConcurrency = 96
|
||||
const environmentAssignment = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/
|
||||
const environmentProfileMarker = '# >>> MooTool environment >>>'
|
||||
const commonPorts = new Map<number, string>([
|
||||
[20, 'ftp-data'], [21, 'ftp'], [22, 'ssh'], [23, 'telnet'], [25, 'smtp'], [53, 'dns'],
|
||||
[67, 'dhcp'], [68, 'dhcp'], [69, 'tftp'], [80, 'http'], [110, 'pop3'], [123, 'ntp'],
|
||||
@@ -96,7 +101,7 @@ export class SystemService {
|
||||
return true
|
||||
}
|
||||
|
||||
getEnvironment(): EnvironmentSnapshot {
|
||||
async getEnvironment(): Promise<EnvironmentSnapshot> {
|
||||
const environment = Object.entries(process.env)
|
||||
.map(([key, value]) => ({ key, value: value ?? '' }))
|
||||
.sort(compareEntries)
|
||||
@@ -112,7 +117,29 @@ export class SystemService {
|
||||
['process.locale', Intl.DateTimeFormat().resolvedOptions().locale],
|
||||
['process.timeZone', Intl.DateTimeFormat().resolvedOptions().timeZone]
|
||||
].map(([key, value]) => ({ key, value })).sort(compareEntries)
|
||||
return { environment, runtime }
|
||||
const [user, system] = await Promise.all([
|
||||
this.listPersistentEnvironment('user'),
|
||||
this.listPersistentEnvironment('system')
|
||||
])
|
||||
return { environment, runtime, user, system }
|
||||
}
|
||||
|
||||
async setEnvironmentVariable(input: EnvironmentVariableInput): Promise<void> {
|
||||
if (process.platform === 'win32') {
|
||||
await writeWindowsEnvironment(input.scope, input.key, input.value)
|
||||
} else {
|
||||
await this.writeUnixEnvironment(input.scope, input.key, input.value)
|
||||
}
|
||||
await this.syncCurrentProcessEnvironment(input.key)
|
||||
}
|
||||
|
||||
async deleteEnvironmentVariable(input: DeleteEnvironmentVariableInput): Promise<void> {
|
||||
if (process.platform === 'win32') {
|
||||
await writeWindowsEnvironment(input.scope, input.key)
|
||||
} else {
|
||||
await this.writeUnixEnvironment(input.scope, input.key)
|
||||
}
|
||||
await this.syncCurrentProcessEnvironment(input.key)
|
||||
}
|
||||
|
||||
getLocalAddresses(): LocalAddressSnapshot {
|
||||
@@ -283,12 +310,165 @@ export class SystemService {
|
||||
const script = `Copy-Item -LiteralPath '${psQuote(temporary)}' -Destination '${psQuote(destination)}' -Force`
|
||||
await execFilePromise('powershell.exe', ['-NoProfile', '-Command', `Start-Process powershell.exe -Verb RunAs -Wait -ArgumentList @('-NoProfile','-Command',${psString(script)})`], 120_000)
|
||||
} else {
|
||||
await execFilePromise('pkexec', ['/bin/cp', temporary, destination], 120_000)
|
||||
await execFilePromise('pkexec', ['/bin/sh', '-c', '/bin/cp "$1" "$2" && /bin/chmod 644 "$2"', 'mootool', temporary, destination], 120_000)
|
||||
}
|
||||
} finally {
|
||||
await unlink(temporary).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
private async listPersistentEnvironment(scope: EnvironmentScope): Promise<EnvironmentEntry[]> {
|
||||
if (process.platform === 'win32') return readWindowsEnvironment(scope)
|
||||
const path = unixEnvironmentPath(scope)
|
||||
const content = await readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return ''
|
||||
throw error
|
||||
})
|
||||
return parseEnvironmentContent(content)
|
||||
}
|
||||
|
||||
private async writeUnixEnvironment(scope: EnvironmentScope, key: string, value?: string): Promise<void> {
|
||||
const destination = unixEnvironmentPath(scope)
|
||||
const current = await readFile(destination, 'utf8').catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return ''
|
||||
throw error
|
||||
})
|
||||
const content = updateEnvironmentContent(current, key, value, scope === 'user' || process.platform === 'darwin')
|
||||
if (scope === 'user') {
|
||||
await mkdir(dirname(destination), { recursive: true })
|
||||
await writeFile(destination, content, { encoding: 'utf8', mode: 0o600 })
|
||||
await ensureUnixEnvironmentProfile(destination)
|
||||
if (process.platform === 'darwin') {
|
||||
const args = value === undefined ? ['unsetenv', key] : ['setenv', key, value]
|
||||
await execFilePromise('/bin/launchctl', args, 30_000).catch(() => undefined)
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
await writeFile(destination, content, 'utf8')
|
||||
} catch (error) {
|
||||
if (!isPermissionError(error)) throw error
|
||||
await this.writeEnvironmentElevated(destination, content)
|
||||
}
|
||||
}
|
||||
|
||||
private async syncCurrentProcessEnvironment(key: string): Promise<void> {
|
||||
const [user, system] = await Promise.all([
|
||||
this.listPersistentEnvironment('user'),
|
||||
this.listPersistentEnvironment('system')
|
||||
])
|
||||
const matches = (entry: EnvironmentEntry): boolean => process.platform === 'win32'
|
||||
? entry.key.toLowerCase() === key.toLowerCase()
|
||||
: entry.key === key
|
||||
const effective = user.find(matches) ?? system.find(matches)
|
||||
if (effective) process.env[key] = effective.value
|
||||
else delete process.env[key]
|
||||
}
|
||||
|
||||
private async writeEnvironmentElevated(destination: string, content: string): Promise<void> {
|
||||
const temporary = join(this.tempDirectory, `mootool-environment-${process.pid}-${Date.now()}`)
|
||||
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 })
|
||||
try {
|
||||
if (process.platform === 'darwin') {
|
||||
const command = `/bin/cp ${shellQuote(temporary)} ${shellQuote(destination)} && /bin/chmod 644 ${shellQuote(destination)}`
|
||||
await execFilePromise('/usr/bin/osascript', ['-e', `do shell script ${appleScriptString(command)} with administrator privileges`], 120_000)
|
||||
} else {
|
||||
await execFilePromise('pkexec', ['/bin/sh', '-c', '/bin/cp "$1" "$2" && /bin/chmod 644 "$2"', 'mootool', temporary, destination], 120_000)
|
||||
}
|
||||
} finally {
|
||||
await unlink(temporary).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseEnvironmentContent(content: string): EnvironmentEntry[] {
|
||||
const values = new Map<string, string>()
|
||||
for (const line of content.split(/\r?\n/)) {
|
||||
const match = line.match(environmentAssignment)
|
||||
if (!match) continue
|
||||
values.set(match[1], unquoteEnvironmentValue(match[2].trim()))
|
||||
}
|
||||
return [...values].map(([key, value]) => ({ key, value })).sort(compareEntries)
|
||||
}
|
||||
|
||||
export function updateEnvironmentContent(content: string, key: string, value: string | undefined, shellExport: boolean): string {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error('Invalid environment variable name')
|
||||
if (value !== undefined && (value.length > 65_535 || /[\0\r\n]/.test(value))) throw new Error('Invalid environment variable value')
|
||||
const replacement = value === undefined ? undefined : serializeEnvironmentValue(key, value, shellExport)
|
||||
const lines = content.split(/\r?\n/)
|
||||
const result: string[] = []
|
||||
let replaced = false
|
||||
for (const line of lines) {
|
||||
const match = line.match(environmentAssignment)
|
||||
if (match?.[1] === key) {
|
||||
if (!replaced && replacement !== undefined) {
|
||||
result.push(replacement)
|
||||
replaced = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
result.push(line)
|
||||
}
|
||||
while (result.at(-1) === '') result.pop()
|
||||
if (replacement !== undefined && !replaced) result.push(replacement)
|
||||
return result.length ? `${result.join('\n')}\n` : ''
|
||||
}
|
||||
|
||||
async function readWindowsEnvironment(scope: EnvironmentScope): Promise<EnvironmentEntry[]> {
|
||||
const target = scope === 'user' ? 'User' : 'Machine'
|
||||
const script = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; `
|
||||
+ `[Environment]::GetEnvironmentVariables([EnvironmentVariableTarget]::${target}).GetEnumerator() `
|
||||
+ `| Sort-Object Name | ForEach-Object { [PSCustomObject]@{ key=[string]$_.Key; value=[string]$_.Value } } `
|
||||
+ '| ConvertTo-Json -Compress'
|
||||
const output = (await execFileText('powershell.exe', ['-NoProfile', '-Command', script], 30_000)).trim()
|
||||
if (!output) return []
|
||||
const parsed = JSON.parse(output) as EnvironmentEntry | EnvironmentEntry[]
|
||||
return (Array.isArray(parsed) ? parsed : [parsed]).sort(compareEntries)
|
||||
}
|
||||
|
||||
async function writeWindowsEnvironment(scope: EnvironmentScope, key: string, value?: string): Promise<void> {
|
||||
const target = scope === 'user' ? 'User' : 'Machine'
|
||||
const psValue = value === undefined ? '$null' : `'${psQuote(value)}'`
|
||||
const script = `[Environment]::SetEnvironmentVariable('${psQuote(key)}',${psValue},[EnvironmentVariableTarget]::${target})`
|
||||
const encoded = Buffer.from(script, 'utf16le').toString('base64')
|
||||
if (scope === 'user') {
|
||||
await execFilePromise('powershell.exe', ['-NoProfile', '-EncodedCommand', encoded], 30_000)
|
||||
return
|
||||
}
|
||||
const elevated = `$p=Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -ArgumentList @('-NoProfile','-EncodedCommand','${encoded}'); exit $p.ExitCode`
|
||||
await execFilePromise('powershell.exe', ['-NoProfile', '-Command', elevated], 120_000)
|
||||
}
|
||||
|
||||
function unixEnvironmentPath(scope: EnvironmentScope): string {
|
||||
if (scope === 'user') return join(homedir(), '.MooTool', 'environment')
|
||||
return process.platform === 'darwin' ? '/etc/zshenv' : '/etc/environment'
|
||||
}
|
||||
|
||||
async function ensureUnixEnvironmentProfile(environmentPath: string): Promise<void> {
|
||||
const profile = join(homedir(), process.platform === 'darwin' ? '.zshenv' : '.profile')
|
||||
const current = await readFile(profile, 'utf8').catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return ''
|
||||
throw error
|
||||
})
|
||||
if (current.includes(environmentProfileMarker)) return
|
||||
const separator = !current || current.endsWith('\n') ? '' : '\n'
|
||||
const block = `${environmentProfileMarker}\n[ -f ${shellQuote(environmentPath)} ] && . ${shellQuote(environmentPath)}\n# <<< MooTool environment <<<\n`
|
||||
await writeFile(profile, `${current}${separator}${block}`, 'utf8')
|
||||
}
|
||||
|
||||
function serializeEnvironmentValue(key: string, value: string, shellExport: boolean): string {
|
||||
if (shellExport) return `export ${key}='${value.replace(/'/g, `'\\''`)}'`
|
||||
return `${key}="${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
||||
}
|
||||
|
||||
function unquoteEnvironmentValue(value: string): string {
|
||||
if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
|
||||
return value.slice(1, -1).replace(/'\\''/g, "'")
|
||||
}
|
||||
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
|
||||
return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\')
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export function ipv4ToLong(value: string): number {
|
||||
@@ -534,6 +714,10 @@ function execFilePromise(file: string, args: string[], timeout: number): Promise
|
||||
return new Promise((resolve, reject) => execFile(file, args, { timeout, windowsHide: true }, (error) => error ? reject(error) : resolve()))
|
||||
}
|
||||
|
||||
function execFileText(file: string, args: string[], timeout: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => execFile(file, args, { timeout, windowsHide: true, encoding: 'utf8' }, (error, stdout) => error ? reject(error) : resolve(stdout)))
|
||||
}
|
||||
|
||||
function shellQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, `'"'"'`)}'`
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import type { CreateQuickNoteInput, MoveQuickNoteEntryInput, QuickNoteAttachment
|
||||
import type { VaultGitActionInput, VaultGitActionResult, VaultGitCommit, VaultGitDiffInput, VaultGitDiffResult, VaultGitStatus } from '../../src/shared/contracts/vaultGit'
|
||||
import type { FavoriteKind, FavoriteRecord, SaveFavoriteInput } from '../../src/shared/contracts/favorites'
|
||||
import type { HttpRequestDraft, HttpRequestHistory, HttpResponseResult, HttpSendInput, SaveTranslationHistoryInput, SaveTranslationWordInput, SavedHttpRequest, TranslationHistory, TranslationInput, TranslationResult, TranslationWord } from '../../src/shared/contracts/network'
|
||||
import type { EnvironmentSnapshot, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from '../../src/shared/contracts/system'
|
||||
import type { DeleteEnvironmentVariableInput, EnvironmentSnapshot, EnvironmentVariableInput, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from '../../src/shared/contracts/system'
|
||||
import type { RuntimeExecutionInput, RuntimeExecutionResult, RuntimeOutputEvent } from '../../src/shared/contracts/runtime'
|
||||
import type { BackupExportResult, BackupInfo, BackupKind, BackupLocation } from '../../src/shared/contracts/backup'
|
||||
import type { LegacyMigrationInput, LegacyMigrationPreview, LegacyMigrationResult } from '../../src/shared/contracts/migration'
|
||||
@@ -83,6 +83,8 @@ contextBridge.exposeInMainWorld('mootool', {
|
||||
runNetworkCommand: (input: NetworkCommandInput): Promise<NetworkCommandResult> => ipcRenderer.invoke('system:network-command', input),
|
||||
cancelSystemCommand: (requestId: string): Promise<boolean> => ipcRenderer.invoke('system:cancel', requestId),
|
||||
getEnvironmentSnapshot: (): Promise<EnvironmentSnapshot> => ipcRenderer.invoke('system:environment'),
|
||||
setEnvironmentVariable: (input: EnvironmentVariableInput): Promise<void> => ipcRenderer.invoke('system:environment-set', input),
|
||||
deleteEnvironmentVariable: (input: DeleteEnvironmentVariableInput): Promise<void> => ipcRenderer.invoke('system:environment-delete', input),
|
||||
getLocalAddresses: (): Promise<LocalAddressSnapshot> => ipcRenderer.invoke('system:local-addresses'),
|
||||
getSystemInfo: (): Promise<SystemInfoSnapshot> => ipcRenderer.invoke('system:info'),
|
||||
chooseDirectory: (initialPath?: string): Promise<string | null> => ipcRenderer.invoke('dialog:choose-directory', initialPath),
|
||||
|
||||
@@ -1,50 +1,215 @@
|
||||
import { ClipboardCopy, Download, RefreshCw, Search } from 'lucide-react'
|
||||
import { ClipboardCopy, Download, Pencil, Plus, RefreshCw, Search, Trash2 } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Dialog } from '@/shared/components/Dialog'
|
||||
import { ToolPageHeader, ToolTabs } from '@/shared/components/ToolPage'
|
||||
import type { EnvironmentEntry, EnvironmentSnapshot } from '@/shared/contracts/system'
|
||||
import type { EnvironmentEntry, EnvironmentScope, EnvironmentSnapshot } from '@/shared/contracts/system'
|
||||
import { useToolActions } from '@/shared/hooks/useToolActions'
|
||||
import { useI18n } from '@/shared/i18n/I18nProvider'
|
||||
|
||||
type VariableTab = 'environment' | 'runtime'
|
||||
type DisplayScope = 'process' | EnvironmentScope
|
||||
|
||||
const emptySnapshot: EnvironmentSnapshot = { environment: [], runtime: [], user: [], system: [] }
|
||||
|
||||
export function VariablesTool() {
|
||||
const { t } = useI18n()
|
||||
const actions = useToolActions('variables')
|
||||
const [tab, setTab] = useState<VariableTab>('environment')
|
||||
const [snapshot, setSnapshot] = useState<EnvironmentSnapshot>({ environment: [], runtime: [] })
|
||||
const [scope, setScope] = useState<DisplayScope>('process')
|
||||
const [targetScope, setTargetScope] = useState<EnvironmentScope>('user')
|
||||
const [snapshot, setSnapshot] = useState<EnvironmentSnapshot>(emptySnapshot)
|
||||
const [query, setQuery] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const entries = useMemo(() => snapshot[tab].filter((entry) => !query || `${entry.key}\n${entry.value}`.toLowerCase().includes(query.toLowerCase())), [query, snapshot, tab])
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editing, setEditing] = useState<EnvironmentEntry | null | undefined>(undefined)
|
||||
const [keyValue, setKeyValue] = useState('')
|
||||
const [value, setValue] = useState('')
|
||||
const sourceEntries = tab === 'runtime'
|
||||
? snapshot.runtime
|
||||
: scope === 'process' ? snapshot.environment : snapshot[scope]
|
||||
const entries = useMemo(
|
||||
() => sourceEntries.filter((entry) => !query || `${entry.key}\n${entry.value}`.toLowerCase().includes(query.toLowerCase())),
|
||||
[query, sourceEntries]
|
||||
)
|
||||
const canEdit = tab === 'environment'
|
||||
const canDelete = tab === 'environment' && scope !== 'process'
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
setLoading(true)
|
||||
try { setSnapshot(await window.mootool.getEnvironmentSnapshot()) } catch (error) { actions.reportError(error) } finally { setLoading(false) }
|
||||
try {
|
||||
setSnapshot(await window.mootool.getEnvironmentSnapshot())
|
||||
} catch (error) {
|
||||
actions.reportError(error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { void refresh() }, [])
|
||||
|
||||
async function exportValues(): Promise<void> {
|
||||
const content = formatEnvironment(snapshot.environment, snapshot.runtime)
|
||||
try { await window.mootool.saveTextFile({ kind: 'text', defaultName: 'mootool-environment.txt', content }) } catch (error) { actions.reportError(error) }
|
||||
const content = formatEnvironment(snapshot)
|
||||
try {
|
||||
await window.mootool.saveTextFile({ kind: 'text', defaultName: 'mootool-environment.txt', content })
|
||||
} catch (error) {
|
||||
actions.reportError(error)
|
||||
}
|
||||
}
|
||||
|
||||
function openEditor(entry?: EnvironmentEntry): void {
|
||||
setEditing(entry ?? null)
|
||||
setKeyValue(entry?.key ?? '')
|
||||
setValue(entry?.value ?? '')
|
||||
setTargetScope(scope === 'process' ? 'user' : scope)
|
||||
}
|
||||
|
||||
async function saveVariable(): Promise<void> {
|
||||
setSaving(true)
|
||||
try {
|
||||
await window.mootool.setEnvironmentVariable({ scope: targetScope, key: keyValue.trim(), value })
|
||||
setEditing(undefined)
|
||||
await refresh()
|
||||
actions.toast.success(t('variables.saved'))
|
||||
} catch (error) {
|
||||
actions.reportError(error)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteVariable(entry: EnvironmentEntry): Promise<void> {
|
||||
if (scope === 'process' || !window.confirm(t('variables.confirmDelete', { key: entry.key }))) return
|
||||
setSaving(true)
|
||||
try {
|
||||
await window.mootool.deleteEnvironmentVariable({ scope, key: entry.key })
|
||||
await refresh()
|
||||
actions.toast.success(t('variables.deleted'))
|
||||
} catch (error) {
|
||||
actions.reportError(error)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="tool-page p5-tool variables-tool-page">
|
||||
<ToolPageHeader title={t('variables.title')} actions={<><button className="toolbar-button" type="button" disabled={loading} onClick={() => { void refresh() }}><RefreshCw size={14} className={loading ? 'spin' : undefined} />{t('common.refresh')}</button><button className="toolbar-button" type="button" onClick={() => { void exportValues() }}><Download size={14} />{t('common.export')}</button></>} />
|
||||
<ToolPageHeader
|
||||
title={t('variables.title')}
|
||||
actions={<>
|
||||
{tab === 'environment' && <button className="toolbar-button" type="button" disabled={saving} onClick={() => openEditor()}><Plus size={14} />{t('variables.add')}</button>}
|
||||
<button className="toolbar-button" type="button" disabled={loading || saving} onClick={() => { void refresh() }}><RefreshCw size={14} className={loading ? 'spin' : undefined} />{t('common.refresh')}</button>
|
||||
<button className="toolbar-button" type="button" onClick={() => { void exportValues() }}><Download size={14} />{t('common.export')}</button>
|
||||
</>}
|
||||
/>
|
||||
<div className="local-tool-shell variables-workspace">
|
||||
<header><ToolTabs tabs={(['environment', 'runtime'] as VariableTab[]).map((id) => ({ id, label: t(`variables.tab.${id}` as 'variables.tab.environment') }))} active={tab} onChange={setTab} /><div className="compact-search"><Search size={13} /><input value={query} placeholder={t('common.search')} aria-label={t('common.search')} onChange={(event) => setQuery(event.target.value)} /></div></header>
|
||||
<EnvironmentTable entries={entries} onCopy={(entry) => { void actions.copy(`${entry.key}=${entry.value}`) }} />
|
||||
<footer>{t('variables.count', { count: String(entries.length), total: String(snapshot[tab].length) })}</footer>
|
||||
<header>
|
||||
<ToolTabs tabs={(['environment', 'runtime'] as VariableTab[]).map((id) => ({ id, label: t(`variables.tab.${id}` as 'variables.tab.environment') }))} active={tab} onChange={setTab} />
|
||||
{tab === 'environment' && (
|
||||
<label className="environment-scope">
|
||||
<span>{t('variables.scope')}</span>
|
||||
<select value={scope} onChange={(event) => setScope(event.target.value as DisplayScope)}>
|
||||
<option value="user">{t('variables.scope.user')}</option>
|
||||
<option value="system">{t('variables.scope.system')}</option>
|
||||
<option value="process">{t('variables.scope.process')}</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<div className="compact-search"><Search size={13} /><input value={query} placeholder={t('common.search')} aria-label={t('common.search')} onChange={(event) => setQuery(event.target.value)} /></div>
|
||||
</header>
|
||||
<EnvironmentTable
|
||||
entries={entries}
|
||||
canEdit={canEdit}
|
||||
canDelete={canDelete}
|
||||
onCopy={(entry) => { void actions.copy(`${entry.key}=${entry.value}`) }}
|
||||
onEdit={openEditor}
|
||||
onDelete={(entry) => { void deleteVariable(entry) }}
|
||||
/>
|
||||
<footer>
|
||||
<span>{t('variables.count', { count: String(entries.length), total: String(sourceEntries.length) })}</span>
|
||||
{tab === 'environment' && <span>{t(`variables.scopeHint.${scope}` as 'variables.scopeHint.user')}</span>}
|
||||
</footer>
|
||||
</div>
|
||||
<Dialog
|
||||
title={t(editing ? 'variables.editTitle' : 'variables.addTitle')}
|
||||
open={editing !== undefined}
|
||||
width={560}
|
||||
onClose={() => setEditing(undefined)}
|
||||
footer={<>
|
||||
<button className="dialog-button" type="button" disabled={saving} onClick={() => setEditing(undefined)}>{t('common.cancel')}</button>
|
||||
<button className="dialog-button dialog-button--primary" type="button" disabled={saving || !keyValue.trim()} onClick={() => { void saveVariable() }}>{t('common.save')}</button>
|
||||
</>}
|
||||
>
|
||||
<div className="environment-editor">
|
||||
<label className="dialog-field">
|
||||
<span>{t('variables.key')}</span>
|
||||
<input autoFocus readOnly={Boolean(editing)} value={keyValue} placeholder="JAVA_HOME" onChange={(event) => setKeyValue(event.target.value)} />
|
||||
</label>
|
||||
<label className="dialog-field">
|
||||
<span>{t('variables.value')}</span>
|
||||
<textarea value={value} onChange={(event) => setValue(event.target.value)} />
|
||||
</label>
|
||||
{scope === 'process' && (
|
||||
<label className="dialog-field">
|
||||
<span>{t('variables.targetScope')}</span>
|
||||
<select value={targetScope} onChange={(event) => setTargetScope(event.target.value as EnvironmentScope)}>
|
||||
<option value="user">{t('variables.scope.user')}</option>
|
||||
<option value="system">{t('variables.scope.system')}</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<p>{t('variables.applyHint')}</p>
|
||||
</div>
|
||||
</Dialog>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function EnvironmentTable({ entries, onCopy }: { entries: EnvironmentEntry[]; onCopy: (entry: EnvironmentEntry) => void }) {
|
||||
function EnvironmentTable({ entries, canEdit, canDelete, onCopy, onEdit, onDelete }: {
|
||||
entries: EnvironmentEntry[]
|
||||
canEdit: boolean
|
||||
canDelete: boolean
|
||||
onCopy: (entry: EnvironmentEntry) => void
|
||||
onEdit: (entry: EnvironmentEntry) => void
|
||||
onDelete: (entry: EnvironmentEntry) => void
|
||||
}) {
|
||||
const { t } = useI18n()
|
||||
return <div className="environment-table-wrap"><table className="environment-table"><thead><tr><th>{t('variables.key')}</th><th>{t('variables.value')}</th><th /></tr></thead><tbody>{entries.map((entry) => <tr key={entry.key}><td><code>{entry.key}</code></td><td>{entry.value}</td><td><button className="icon-button" type="button" aria-label={t('common.action.copy')} onClick={() => onCopy(entry)}><ClipboardCopy size={13} /></button></td></tr>)}</tbody></table></div>
|
||||
return (
|
||||
<div className="environment-table-wrap">
|
||||
<table className="environment-table">
|
||||
<thead><tr><th>{t('variables.key')}</th><th>{t('variables.value')}</th><th /></tr></thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr key={entry.key} onDoubleClick={() => { if (canEdit) onEdit(entry) }}>
|
||||
<td><code>{entry.key}</code></td>
|
||||
<td title={entry.value}>{entry.value}</td>
|
||||
<td>
|
||||
<div className="environment-row-actions">
|
||||
<button className="icon-button" type="button" aria-label={t('common.action.copy')} onClick={() => onCopy(entry)}><ClipboardCopy size={13} /></button>
|
||||
{canEdit && <button className="icon-button" type="button" aria-label={t('variables.edit')} onClick={() => onEdit(entry)}><Pencil size={13} /></button>}
|
||||
{canDelete && <button className="icon-button" type="button" aria-label={t('common.action.delete')} onClick={() => onDelete(entry)}><Trash2 size={13} /></button>}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!entries.length && <tr><td className="environment-empty" colSpan={3}>{t('variables.empty')}</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatEnvironment(environment: EnvironmentEntry[], runtime: EnvironmentEntry[]): string {
|
||||
return ['------------System.getenv---------------', ...environment.map((entry) => `${entry.key}=${entry.value}`), '', '------------Electron runtime---------------', ...runtime.map((entry) => `${entry.key}=${entry.value}`)].join('\n')
|
||||
function formatEnvironment(snapshot: EnvironmentSnapshot): string {
|
||||
return [
|
||||
'------------Persistent user environment---------------',
|
||||
...snapshot.user.map((entry) => `${entry.key}=${entry.value}`),
|
||||
'',
|
||||
'------------Persistent system environment---------------',
|
||||
...snapshot.system.map((entry) => `${entry.key}=${entry.value}`),
|
||||
'',
|
||||
'------------Current process environment---------------',
|
||||
...snapshot.environment.map((entry) => `${entry.key}=${entry.value}`),
|
||||
'',
|
||||
'------------Electron runtime---------------',
|
||||
...snapshot.runtime.map((entry) => `${entry.key}=${entry.value}`)
|
||||
].join('\n')
|
||||
}
|
||||
@@ -46,9 +46,24 @@ export type EnvironmentEntry = {
|
||||
value: string
|
||||
}
|
||||
|
||||
export type EnvironmentScope = 'user' | 'system'
|
||||
|
||||
export type EnvironmentVariableInput = {
|
||||
scope: EnvironmentScope
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export type DeleteEnvironmentVariableInput = {
|
||||
scope: EnvironmentScope
|
||||
key: string
|
||||
}
|
||||
|
||||
export type EnvironmentSnapshot = {
|
||||
environment: EnvironmentEntry[]
|
||||
runtime: EnvironmentEntry[]
|
||||
user: EnvironmentEntry[]
|
||||
system: EnvironmentEntry[]
|
||||
}
|
||||
|
||||
export type LocalAddressSnapshot = {
|
||||
|
||||
@@ -998,6 +998,23 @@ export const messages = {
|
||||
,'variables.key': '键'
|
||||
,'variables.value': '值'
|
||||
,'variables.count': '显示 {count} / {total} 项'
|
||||
,'variables.scope': '范围'
|
||||
,'variables.scope.user': '用户变量'
|
||||
,'variables.scope.system': '系统变量'
|
||||
,'variables.scope.process': '当前进程'
|
||||
,'variables.scopeHint.user': '持久写入当前用户;新终端和应用启动后生效'
|
||||
,'variables.scopeHint.system': '写入全局环境,可能需要管理员授权'
|
||||
,'variables.scopeHint.process': '完整显示当前环境;编辑后可保存为用户变量或系统变量'
|
||||
,'variables.targetScope': '保存到'
|
||||
,'variables.add': '新增'
|
||||
,'variables.edit': '编辑'
|
||||
,'variables.addTitle': '新增环境变量'
|
||||
,'variables.editTitle': '编辑环境变量'
|
||||
,'variables.applyHint': '保存后会直接修改系统配置。已运行的程序通常需要重启才能读取新值。'
|
||||
,'variables.confirmDelete': '确定删除环境变量“{key}”吗?'
|
||||
,'variables.saved': '环境变量已更新'
|
||||
,'variables.deleted': '环境变量已删除'
|
||||
,'variables.empty': '暂无变量,点击“新增”创建'
|
||||
,'runtime.title': '代码运行'
|
||||
,'runtime.tab.java': 'Java / Groovy'
|
||||
,'runtime.tab.python': 'Python'
|
||||
@@ -2194,6 +2211,23 @@ export const messages = {
|
||||
,'variables.key': 'Key'
|
||||
,'variables.value': 'Value'
|
||||
,'variables.count': 'Showing {count} of {total}'
|
||||
,'variables.scope': 'Scope'
|
||||
,'variables.scope.user': 'User'
|
||||
,'variables.scope.system': 'System'
|
||||
,'variables.scope.process': 'Current process'
|
||||
,'variables.scopeHint.user': 'Saved for this user; applies to newly started terminals and applications'
|
||||
,'variables.scopeHint.system': 'Saved globally and may require administrator approval'
|
||||
,'variables.scopeHint.process': 'Shows the complete current environment; edits can be saved for the user or system'
|
||||
,'variables.targetScope': 'Save to'
|
||||
,'variables.add': 'Add'
|
||||
,'variables.edit': 'Edit'
|
||||
,'variables.addTitle': 'Add Environment Variable'
|
||||
,'variables.editTitle': 'Edit Environment Variable'
|
||||
,'variables.applyHint': 'Saving updates the operating-system configuration directly. Running applications usually need to restart to read the new value.'
|
||||
,'variables.confirmDelete': 'Delete environment variable "{key}"?'
|
||||
,'variables.saved': 'Environment variable updated'
|
||||
,'variables.deleted': 'Environment variable deleted'
|
||||
,'variables.empty': 'No variables yet. Select Add to create one.'
|
||||
,'runtime.title': 'Code Runner'
|
||||
,'runtime.tab.java': 'Java / Groovy'
|
||||
,'runtime.tab.python': 'Python'
|
||||
@@ -3390,6 +3424,23 @@ export const messages = {
|
||||
,'variables.key': 'キー'
|
||||
,'variables.value': '値'
|
||||
,'variables.count': '{count} / {total} 件を表示'
|
||||
,'variables.scope': '範囲'
|
||||
,'variables.scope.user': 'ユーザー'
|
||||
,'variables.scope.system': 'システム'
|
||||
,'variables.scope.process': '現在のプロセス'
|
||||
,'variables.scopeHint.user': 'このユーザーに保存され、新しく起動するターミナルとアプリに反映されます'
|
||||
,'variables.scopeHint.system': 'システム全体に保存され、管理者の承認が必要な場合があります'
|
||||
,'variables.scopeHint.process': '現在の環境をすべて表示し、編集内容をユーザーまたはシステムに保存できます'
|
||||
,'variables.targetScope': '保存先'
|
||||
,'variables.add': '追加'
|
||||
,'variables.edit': '編集'
|
||||
,'variables.addTitle': '環境変数を追加'
|
||||
,'variables.editTitle': '環境変数を編集'
|
||||
,'variables.applyHint': '保存すると OS の設定が直接更新されます。実行中のアプリは通常、再起動後に新しい値を読み込みます。'
|
||||
,'variables.confirmDelete': '環境変数「{key}」を削除しますか?'
|
||||
,'variables.saved': '環境変数を更新しました'
|
||||
,'variables.deleted': '環境変数を削除しました'
|
||||
,'variables.empty': '変数がありません。「追加」から作成できます。'
|
||||
,'runtime.title': 'コード実行'
|
||||
,'runtime.tab.java': 'Java / Groovy'
|
||||
,'runtime.tab.python': 'Python'
|
||||
|
||||
@@ -8574,6 +8574,25 @@ select:not([multiple]) {
|
||||
width: min(260px, 38%);
|
||||
}
|
||||
|
||||
.environment-scope {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--text-faint);
|
||||
font-size: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.environment-scope select {
|
||||
height: 26px;
|
||||
padding: 0 24px 0 8px;
|
||||
color: var(--text-body);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-control);
|
||||
border-radius: 5px;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.environment-table-wrap {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
@@ -8607,7 +8626,7 @@ select:not([multiple]) {
|
||||
}
|
||||
|
||||
.environment-table th:last-child {
|
||||
width: 42px;
|
||||
width: 116px;
|
||||
}
|
||||
|
||||
.environment-table td {
|
||||
@@ -8625,7 +8644,22 @@ select:not([multiple]) {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.environment-row-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.environment-table td.environment-empty {
|
||||
height: 120px;
|
||||
color: var(--text-faint);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.variables-workspace > footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 30px;
|
||||
padding: 8px 11px;
|
||||
color: var(--text-faint);
|
||||
@@ -8634,6 +8668,36 @@ select:not([multiple]) {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.environment-editor {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.environment-editor textarea {
|
||||
width: 100%;
|
||||
min-height: 120px;
|
||||
padding: 9px 10px;
|
||||
resize: vertical;
|
||||
color: var(--text-body);
|
||||
background: var(--workspace);
|
||||
border: 1px solid var(--border-control);
|
||||
border-radius: 6px;
|
||||
outline: none;
|
||||
font: 11px/1.5 var(--font-mono);
|
||||
}
|
||||
|
||||
.environment-editor textarea:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 18%, transparent);
|
||||
}
|
||||
|
||||
.environment-editor p {
|
||||
margin: 0;
|
||||
color: var(--text-faint);
|
||||
font-size: 10px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.hardware-workspace > header > div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createServer } from 'node:net'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { SystemService, ipv4ToLong, longToIpv4, normalizeHostsContent, parseIpv4Range, parsePortSpec } from '../../electron/main/systemService'
|
||||
import { SystemService, ipv4ToLong, longToIpv4, normalizeHostsContent, parseEnvironmentContent, parseIpv4Range, parsePortSpec, updateEnvironmentContent } from '../../electron/main/systemService'
|
||||
import { normalizeDeleteEnvironmentVariableInput, normalizeEnvironmentVariableInput } from '../../electron/main/p5Validation'
|
||||
|
||||
describe('system helpers', () => {
|
||||
it('converts IPv4 and unsigned long values in both directions', () => {
|
||||
@@ -31,6 +32,32 @@ describe('system helpers', () => {
|
||||
expect(() => parsePortSpec('1-5000')).toThrow('INVALID_TARGET')
|
||||
})
|
||||
|
||||
it('parses and safely updates persistent environment files', () => {
|
||||
const source = `# keep this comment
|
||||
export JAVA_HOME='/old jdk'
|
||||
OTHER="value"
|
||||
`
|
||||
const updated = updateEnvironmentContent(source, 'JAVA_HOME', "/opt/jdk's", true)
|
||||
expect(updated).toBe(`# keep this comment
|
||||
export JAVA_HOME='/opt/jdk'\\''s'
|
||||
OTHER="value"
|
||||
`)
|
||||
expect(parseEnvironmentContent(updated)).toEqual([
|
||||
{ key: 'JAVA_HOME', value: "/opt/jdk's" },
|
||||
{ key: 'OTHER', value: 'value' }
|
||||
])
|
||||
expect(updateEnvironmentContent(updated, 'JAVA_HOME', undefined, true)).toBe('# keep this comment\nOTHER="value"\n')
|
||||
})
|
||||
|
||||
it('validates environment mutations at the IPC boundary', () => {
|
||||
expect(normalizeEnvironmentVariableInput({ scope: 'user', key: 'JAVA_HOME', value: '/opt/jdk' }))
|
||||
.toEqual({ scope: 'user', key: 'JAVA_HOME', value: '/opt/jdk' })
|
||||
expect(normalizeDeleteEnvironmentVariableInput({ scope: 'system', key: 'JAVA_HOME' }))
|
||||
.toEqual({ scope: 'system', key: 'JAVA_HOME' })
|
||||
expect(() => normalizeEnvironmentVariableInput({ scope: 'user', key: 'BAD-NAME', value: 'x' })).toThrow()
|
||||
expect(() => normalizeEnvironmentVariableInput({ scope: 'user', key: 'SAFE', value: 'one\ntwo' })).toThrow()
|
||||
})
|
||||
|
||||
it('reports an open TCP port from a real local listener', async () => {
|
||||
const server = createServer()
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
|
||||
Vendored
+3
-1
@@ -12,7 +12,7 @@ import type { CreateQuickNoteInput, MoveQuickNoteEntryInput, QuickNoteAttachment
|
||||
import type { VaultGitActionInput, VaultGitActionResult, VaultGitCommit, VaultGitDiffInput, VaultGitDiffResult, VaultGitStatus } from './src/shared/contracts/vaultGit'
|
||||
import type { FavoriteKind, FavoriteRecord, SaveFavoriteInput } from './src/shared/contracts/favorites'
|
||||
import type { HttpRequestDraft, HttpRequestHistory, HttpResponseResult, HttpSendInput, SaveTranslationHistoryInput, SaveTranslationWordInput, SavedHttpRequest, TranslationHistory, TranslationInput, TranslationResult, TranslationWord } from './src/shared/contracts/network'
|
||||
import type { EnvironmentSnapshot, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from './src/shared/contracts/system'
|
||||
import type { DeleteEnvironmentVariableInput, EnvironmentSnapshot, EnvironmentVariableInput, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from './src/shared/contracts/system'
|
||||
import type { RuntimeExecutionInput, RuntimeExecutionResult, RuntimeOutputEvent } from './src/shared/contracts/runtime'
|
||||
import type { BackupExportResult, BackupInfo, BackupKind, BackupLocation } from './src/shared/contracts/backup'
|
||||
import type { LegacyMigrationInput, LegacyMigrationPreview, LegacyMigrationResult } from './src/shared/contracts/migration'
|
||||
@@ -76,6 +76,8 @@ declare global {
|
||||
runNetworkCommand: (input: NetworkCommandInput) => Promise<NetworkCommandResult>
|
||||
cancelSystemCommand: (requestId: string) => Promise<boolean>
|
||||
getEnvironmentSnapshot: () => Promise<EnvironmentSnapshot>
|
||||
setEnvironmentVariable: (input: EnvironmentVariableInput) => Promise<void>
|
||||
deleteEnvironmentVariable: (input: DeleteEnvironmentVariableInput) => Promise<void>
|
||||
getLocalAddresses: () => Promise<LocalAddressSnapshot>
|
||||
getSystemInfo: () => Promise<SystemInfoSnapshot>
|
||||
chooseDirectory: (initialPath?: string) => Promise<string | null>
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.intellij.uiDesigner.core.GridLayoutManager;
|
||||
import com.luoboduner.moo.tool.App;
|
||||
import com.luoboduner.moo.tool.ui.component.ToolbarUiUtil;
|
||||
import com.luoboduner.moo.tool.ui.dialog.SystemEnvResultDialog;
|
||||
import com.luoboduner.moo.tool.util.EnvironmentVariableService;
|
||||
import com.luoboduner.moo.tool.util.I18n;
|
||||
import com.luoboduner.moo.tool.util.I18nUiUtil;
|
||||
import com.luoboduner.moo.tool.util.ScrollUtil;
|
||||
@@ -19,8 +20,13 @@ import javax.swing.table.DefaultTableModel;
|
||||
import javax.swing.table.TableColumn;
|
||||
import javax.swing.table.TableColumnModel;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static com.formdev.flatlaf.FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT;
|
||||
|
||||
@@ -34,6 +40,10 @@ public class VariablesForm {
|
||||
private JScrollPane scrollPane2;
|
||||
private JButton refreshButton;
|
||||
private JButton exportButton;
|
||||
private JButton addButton;
|
||||
private JButton editButton;
|
||||
private JButton deleteButton;
|
||||
private JComboBox<EnvironmentVariableService.Scope> scopeComboBox;
|
||||
|
||||
private static VariablesForm variablesForm;
|
||||
|
||||
@@ -73,6 +83,10 @@ public class VariablesForm {
|
||||
I18nUiUtil.setTabTitle(tabbedPane1, 1, "variables.tab.javaProps");
|
||||
I18nUiUtil.setToolTip(refreshButton, "common.refresh");
|
||||
I18nUiUtil.setToolTip(exportButton, "common.export");
|
||||
I18nUiUtil.setToolTip(addButton, "variables.action.add");
|
||||
I18nUiUtil.setToolTip(editButton, "variables.action.edit");
|
||||
I18nUiUtil.setToolTip(deleteButton, "common.delete");
|
||||
scopeComboBox.repaint();
|
||||
updateTableHeaders();
|
||||
}
|
||||
|
||||
@@ -102,6 +116,39 @@ public class VariablesForm {
|
||||
|
||||
JToolBar trailing = new JToolBar();
|
||||
ToolbarUiUtil.configure(trailing);
|
||||
|
||||
variablesForm.scopeComboBox = new JComboBox<>(EnvironmentVariableService.Scope.values());
|
||||
variablesForm.scopeComboBox.setRenderer(new DefaultListCellRenderer() {
|
||||
@Override
|
||||
public Component getListCellRendererComponent(JList<?> list, Object value, int index,
|
||||
boolean isSelected, boolean cellHasFocus) {
|
||||
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
|
||||
if (value instanceof EnvironmentVariableService.Scope scope) {
|
||||
setText(I18n.get(switch (scope) {
|
||||
case CURRENT -> "variables.scope.current";
|
||||
case USER -> "variables.scope.user";
|
||||
case SYSTEM -> "variables.scope.system";
|
||||
}));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
});
|
||||
variablesForm.scopeComboBox.addActionListener(e -> initSysEnvVarTable());
|
||||
|
||||
variablesForm.addButton = new JButton(new FlatSVGIcon("icon/add.svg"));
|
||||
variablesForm.addButton.addActionListener(e -> variablesForm.showEnvironmentEditor(null));
|
||||
|
||||
variablesForm.editButton = new JButton(new FlatSVGIcon("icon/edit.svg"));
|
||||
variablesForm.editButton.addActionListener(e -> variablesForm.editSelectedEnvironmentVariable());
|
||||
|
||||
variablesForm.deleteButton = new JButton(new FlatSVGIcon("icon/remove.svg"));
|
||||
variablesForm.deleteButton.addActionListener(e -> variablesForm.deleteSelectedEnvironmentVariable());
|
||||
|
||||
trailing.add(variablesForm.scopeComboBox);
|
||||
trailing.addSeparator();
|
||||
trailing.add(variablesForm.addButton);
|
||||
trailing.add(variablesForm.editButton);
|
||||
trailing.add(variablesForm.deleteButton);
|
||||
trailing.add(Box.createHorizontalGlue());
|
||||
|
||||
variablesForm.refreshButton = new JButton(new FlatSVGIcon("icon/refresh.svg"));
|
||||
@@ -117,10 +164,22 @@ public class VariablesForm {
|
||||
try {
|
||||
SystemEnvResultDialog dialog = new SystemEnvResultDialog();
|
||||
|
||||
dialog.appendTextArea("------------System.getenv---------------");
|
||||
Map<String, String> map = System.getenv();
|
||||
for (Map.Entry<String, String> envEntry : map.entrySet()) {
|
||||
dialog.appendTextArea(envEntry.getKey() + "=" + envEntry.getValue());
|
||||
dialog.appendTextArea("------------Current process environment---------------");
|
||||
for (EnvironmentVariableService.Entry entry
|
||||
: EnvironmentVariableService.list(EnvironmentVariableService.Scope.CURRENT)) {
|
||||
dialog.appendTextArea(entry.key() + "=" + entry.value());
|
||||
}
|
||||
|
||||
dialog.appendTextArea("------------User environment---------------");
|
||||
for (EnvironmentVariableService.Entry entry
|
||||
: EnvironmentVariableService.list(EnvironmentVariableService.Scope.USER)) {
|
||||
dialog.appendTextArea(entry.key() + "=" + entry.value());
|
||||
}
|
||||
|
||||
dialog.appendTextArea("------------System environment---------------");
|
||||
for (EnvironmentVariableService.Entry entry
|
||||
: EnvironmentVariableService.list(EnvironmentVariableService.Scope.SYSTEM)) {
|
||||
dialog.appendTextArea(entry.key() + "=" + entry.value());
|
||||
}
|
||||
|
||||
dialog.appendTextArea("------------System.getProperties---------------");
|
||||
@@ -141,6 +200,17 @@ public class VariablesForm {
|
||||
trailing.add(new JLabel(" "));
|
||||
|
||||
getInstance().getTabbedPane1().putClientProperty(TABBED_PANE_TRAILING_COMPONENT, trailing);
|
||||
variablesForm.sysEnvVarTable.getSelectionModel().addListSelectionListener(e -> variablesForm.updateActionState());
|
||||
variablesForm.sysEnvVarTable.addMouseListener(new MouseAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent event) {
|
||||
if (event.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(event)) {
|
||||
variablesForm.editSelectedEnvironmentVariable();
|
||||
}
|
||||
}
|
||||
});
|
||||
variablesForm.tabbedPane1.addChangeListener(e -> variablesForm.updateActionState());
|
||||
variablesForm.updateActionState();
|
||||
|
||||
}
|
||||
|
||||
@@ -151,25 +221,27 @@ public class VariablesForm {
|
||||
|
||||
public static void initSysEnvVarTable() {
|
||||
String[] headerNames = {I18n.get("variables.col.key"), I18n.get("variables.col.value")};
|
||||
DefaultTableModel model = new DefaultTableModel(null, headerNames);
|
||||
DefaultTableModel model = readOnlyTableModel(headerNames);
|
||||
|
||||
Map<String, String> map = System.getenv();
|
||||
Object[] data;
|
||||
for (Map.Entry<String, String> envEntry : map.entrySet()) {
|
||||
data = new Object[2];
|
||||
data[0] = envEntry.getKey();
|
||||
data[1] = envEntry.getValue();
|
||||
model.addRow(data);
|
||||
EnvironmentVariableService.Scope scope = getInstance().selectedScope();
|
||||
try {
|
||||
List<EnvironmentVariableService.Entry> entries = EnvironmentVariableService.list(scope);
|
||||
for (EnvironmentVariableService.Entry entry : entries) {
|
||||
model.addRow(new Object[]{entry.key(), entry.value()});
|
||||
}
|
||||
} catch (Exception error) {
|
||||
logger.error("读取系统环境变量失败", error);
|
||||
}
|
||||
|
||||
JTable sysEnvVarTable = getInstance().getSysEnvVarTable();
|
||||
sysEnvVarTable.setModel(model);
|
||||
resizeColumns(sysEnvVarTable.getColumnModel());
|
||||
getInstance().updateActionState();
|
||||
}
|
||||
|
||||
public static void initJavaPropsTable() {
|
||||
String[] headerNames = {I18n.get("variables.col.key"), I18n.get("variables.col.value")};
|
||||
DefaultTableModel model = new DefaultTableModel(null, headerNames);
|
||||
DefaultTableModel model = readOnlyTableModel(headerNames);
|
||||
|
||||
Properties properties = System.getProperties();
|
||||
Object[] data;
|
||||
@@ -185,6 +257,152 @@ public class VariablesForm {
|
||||
resizeColumns(javaPropsTable.getColumnModel());
|
||||
}
|
||||
|
||||
private static DefaultTableModel readOnlyTableModel(String[] headers) {
|
||||
return new DefaultTableModel(null, headers) {
|
||||
@Override
|
||||
public boolean isCellEditable(int row, int column) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private EnvironmentVariableService.Scope selectedScope() {
|
||||
Object selected = scopeComboBox == null ? null : scopeComboBox.getSelectedItem();
|
||||
return selected instanceof EnvironmentVariableService.Scope scope
|
||||
? scope : EnvironmentVariableService.Scope.CURRENT;
|
||||
}
|
||||
|
||||
private void editSelectedEnvironmentVariable() {
|
||||
int row = sysEnvVarTable.getSelectedRow();
|
||||
if (row < 0 || tabbedPane1.getSelectedIndex() != 0) {
|
||||
return;
|
||||
}
|
||||
showEnvironmentEditor(new EnvironmentVariableService.Entry(
|
||||
String.valueOf(sysEnvVarTable.getValueAt(row, 0)),
|
||||
String.valueOf(sysEnvVarTable.getValueAt(row, 1))));
|
||||
}
|
||||
|
||||
private void showEnvironmentEditor(EnvironmentVariableService.Entry existing) {
|
||||
if (!EnvironmentVariableService.supportsDirectModification()) {
|
||||
JOptionPane.showMessageDialog(variablesPanel, I18n.get("msg.systemEnvUnsupported"));
|
||||
return;
|
||||
}
|
||||
JTextField keyField = new JTextField(existing == null ? "" : existing.key(), 34);
|
||||
keyField.setEditable(existing == null);
|
||||
JTextArea valueArea = new JTextArea(existing == null ? "" : existing.value(), 6, 42);
|
||||
valueArea.setLineWrap(true);
|
||||
valueArea.setWrapStyleWord(false);
|
||||
|
||||
JPanel editor = new JPanel(new BorderLayout(8, 8));
|
||||
JPanel keyPanel = new JPanel(new BorderLayout(8, 0));
|
||||
keyPanel.add(new JLabel(I18n.get("variables.col.key")), BorderLayout.WEST);
|
||||
keyPanel.add(keyField, BorderLayout.CENTER);
|
||||
editor.add(keyPanel, BorderLayout.NORTH);
|
||||
editor.add(new JScrollPane(valueArea), BorderLayout.CENTER);
|
||||
|
||||
EnvironmentVariableService.Scope selectedScope = selectedScope();
|
||||
JComboBox<EnvironmentVariableService.Scope> targetScope = null;
|
||||
if (selectedScope == EnvironmentVariableService.Scope.CURRENT) {
|
||||
targetScope = new JComboBox<>(new EnvironmentVariableService.Scope[]{
|
||||
EnvironmentVariableService.Scope.USER,
|
||||
EnvironmentVariableService.Scope.SYSTEM
|
||||
});
|
||||
targetScope.setRenderer(scopeComboBox.getRenderer());
|
||||
JPanel scopePanel = new JPanel(new BorderLayout(8, 0));
|
||||
scopePanel.add(new JLabel(I18n.get("variables.targetScope")), BorderLayout.WEST);
|
||||
scopePanel.add(targetScope, BorderLayout.CENTER);
|
||||
editor.add(scopePanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
String title = I18n.get(existing == null ? "variables.dialog.addTitle" : "variables.dialog.editTitle");
|
||||
int result = JOptionPane.showConfirmDialog(variablesPanel, editor, title,
|
||||
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
|
||||
if (result != JOptionPane.OK_OPTION) {
|
||||
return;
|
||||
}
|
||||
String key = keyField.getText().trim();
|
||||
String value = valueArea.getText();
|
||||
EnvironmentVariableService.Scope mutationScope = selectedScope == EnvironmentVariableService.Scope.CURRENT
|
||||
? (EnvironmentVariableService.Scope) targetScope.getSelectedItem()
|
||||
: selectedScope;
|
||||
runMutation(() -> {
|
||||
EnvironmentVariableService.set(mutationScope, key, value);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void deleteSelectedEnvironmentVariable() {
|
||||
int row = sysEnvVarTable.getSelectedRow();
|
||||
if (row < 0 || tabbedPane1.getSelectedIndex() != 0) {
|
||||
return;
|
||||
}
|
||||
String key = String.valueOf(sysEnvVarTable.getValueAt(row, 0));
|
||||
int result = JOptionPane.showConfirmDialog(variablesPanel,
|
||||
I18n.format("variables.confirmDelete", key),
|
||||
I18n.get("common.confirm"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
|
||||
if (result != JOptionPane.OK_OPTION) {
|
||||
return;
|
||||
}
|
||||
runMutation(() -> {
|
||||
EnvironmentVariableService.delete(selectedScope(), key);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void runMutation(Callable<Void> mutation) {
|
||||
setBusy(true);
|
||||
new SwingWorker<Void, Void>() {
|
||||
@Override
|
||||
protected Void doInBackground() throws Exception {
|
||||
return mutation.call();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void done() {
|
||||
try {
|
||||
get();
|
||||
initSysEnvVarTable();
|
||||
JOptionPane.showMessageDialog(variablesPanel, I18n.get("variables.saved"),
|
||||
I18n.get("common.confirm"), JOptionPane.INFORMATION_MESSAGE);
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException error) {
|
||||
Throwable cause = error.getCause() == null ? error : error.getCause();
|
||||
logger.error("修改系统环境变量失败", cause);
|
||||
JOptionPane.showMessageDialog(variablesPanel,
|
||||
I18n.format("variables.saveFailed", cause.getMessage()),
|
||||
I18n.get("msg.failedTitle"), JOptionPane.ERROR_MESSAGE);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}.execute();
|
||||
}
|
||||
|
||||
private void setBusy(boolean busy) {
|
||||
variablesPanel.setCursor(Cursor.getPredefinedCursor(busy ? Cursor.WAIT_CURSOR : Cursor.DEFAULT_CURSOR));
|
||||
scopeComboBox.setEnabled(!busy);
|
||||
refreshButton.setEnabled(!busy);
|
||||
addButton.setEnabled(!busy && tabbedPane1.getSelectedIndex() == 0);
|
||||
editButton.setEnabled(!busy && tabbedPane1.getSelectedIndex() == 0 && sysEnvVarTable.getSelectedRow() >= 0);
|
||||
deleteButton.setEnabled(!busy && tabbedPane1.getSelectedIndex() == 0
|
||||
&& selectedScope() != EnvironmentVariableService.Scope.CURRENT
|
||||
&& sysEnvVarTable.getSelectedRow() >= 0);
|
||||
}
|
||||
|
||||
private void updateActionState() {
|
||||
boolean environmentTab = tabbedPane1.getSelectedIndex() == 0;
|
||||
boolean selected = sysEnvVarTable.getSelectedRow() >= 0;
|
||||
boolean persistentScope = selectedScope() != EnvironmentVariableService.Scope.CURRENT;
|
||||
scopeComboBox.setVisible(environmentTab);
|
||||
addButton.setVisible(environmentTab);
|
||||
editButton.setVisible(environmentTab);
|
||||
deleteButton.setVisible(environmentTab);
|
||||
addButton.setEnabled(environmentTab);
|
||||
editButton.setEnabled(environmentTab && selected);
|
||||
deleteButton.setEnabled(environmentTab && persistentScope && selected);
|
||||
}
|
||||
|
||||
private static void resizeColumns(TableColumnModel tableColumnModel) {
|
||||
TableColumn column;
|
||||
int tW = App.mainFrame.getWidth() - 20;
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
package com.luoboduner.moo.tool.util;
|
||||
|
||||
import com.sun.jna.platform.win32.Advapi32Util;
|
||||
import com.sun.jna.platform.win32.WinReg;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Reads and modifies persistent operating-system environment variables.
|
||||
*/
|
||||
public final class EnvironmentVariableService {
|
||||
private static final Pattern VARIABLE_NAME = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
|
||||
private static final Pattern ASSIGNMENT = Pattern.compile("^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$");
|
||||
private static final String WINDOWS_USER_KEY = "Environment";
|
||||
private static final String WINDOWS_SYSTEM_KEY = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
|
||||
private static final String PROFILE_MARKER_START = "# >>> MooTool environment >>>";
|
||||
private static final String PROFILE_MARKER_END = "# <<< MooTool environment <<<";
|
||||
private static final Duration COMMAND_TIMEOUT = Duration.ofMinutes(2);
|
||||
|
||||
public enum Scope {
|
||||
CURRENT,
|
||||
USER,
|
||||
SYSTEM
|
||||
}
|
||||
|
||||
public record Entry(String key, String value) {
|
||||
}
|
||||
|
||||
private EnvironmentVariableService() {
|
||||
}
|
||||
|
||||
public static List<Entry> list(Scope scope) throws IOException {
|
||||
if (scope == Scope.CURRENT) {
|
||||
return System.getenv().entrySet().stream()
|
||||
.map(entry -> new Entry(entry.getKey(), entry.getValue()))
|
||||
.sorted(Comparator.comparing(Entry::key, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
}
|
||||
if (SystemUtil.isWindowsOs()) {
|
||||
return listWindows(scope);
|
||||
}
|
||||
return parseEnvironmentContent(readIfExists(environmentFile(scope)));
|
||||
}
|
||||
|
||||
public static void set(Scope scope, String key, String value) throws IOException {
|
||||
requirePersistentScope(scope);
|
||||
validate(key, value);
|
||||
if (SystemUtil.isWindowsOs()) {
|
||||
writeWindows(scope, key, value);
|
||||
return;
|
||||
}
|
||||
writeUnix(scope, key, value);
|
||||
}
|
||||
|
||||
public static void delete(Scope scope, String key) throws IOException {
|
||||
requirePersistentScope(scope);
|
||||
validateKey(key);
|
||||
if (SystemUtil.isWindowsOs()) {
|
||||
deleteWindows(scope, key);
|
||||
return;
|
||||
}
|
||||
writeUnix(scope, key, null);
|
||||
}
|
||||
|
||||
public static boolean supportsDirectModification() {
|
||||
return SystemUtil.isWindowsOs() || SystemUtil.isMacOs() || SystemUtil.isLinuxOs();
|
||||
}
|
||||
|
||||
private static List<Entry> listWindows(Scope scope) {
|
||||
WinReg.HKEY root = scope == Scope.USER ? WinReg.HKEY_CURRENT_USER : WinReg.HKEY_LOCAL_MACHINE;
|
||||
String path = scope == Scope.USER ? WINDOWS_USER_KEY : WINDOWS_SYSTEM_KEY;
|
||||
Map<String, Object> values = Advapi32Util.registryGetValues(root, path);
|
||||
return values.entrySet().stream()
|
||||
.map(entry -> new Entry(entry.getKey(), String.valueOf(entry.getValue())))
|
||||
.sorted(Comparator.comparing(Entry::key, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static void writeWindows(Scope scope, String key, String value) throws IOException {
|
||||
String target = scope == Scope.USER ? "User" : "Machine";
|
||||
String script = windowsMutationScript(target, key, value);
|
||||
if (scope == Scope.SYSTEM) {
|
||||
runElevatedPowerShell(script);
|
||||
} else {
|
||||
runPowerShell(script);
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteWindows(Scope scope, String key) throws IOException {
|
||||
String target = scope == Scope.USER ? "User" : "Machine";
|
||||
String script = windowsMutationScript(target, key, null);
|
||||
if (scope == Scope.SYSTEM) {
|
||||
runElevatedPowerShell(script);
|
||||
} else {
|
||||
runPowerShell(script);
|
||||
}
|
||||
}
|
||||
|
||||
private static String windowsMutationScript(String target, String key, String value) {
|
||||
String encodedKey = powershellQuote(key);
|
||||
String encodedValue = value == null ? "$null" : "'" + powershellQuote(value) + "'";
|
||||
return "[Environment]::SetEnvironmentVariable('" + encodedKey + "'," + encodedValue
|
||||
+ ",[EnvironmentVariableTarget]::" + target + ")";
|
||||
}
|
||||
|
||||
private static void runElevatedPowerShell(String script) throws IOException {
|
||||
String encoded = Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
|
||||
String outer = "$p=Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru "
|
||||
+ "-ArgumentList '-NoProfile','-EncodedCommand','" + encoded + "'; exit $p.ExitCode";
|
||||
runCommand(List.of("powershell.exe", "-NoProfile", "-Command", outer));
|
||||
}
|
||||
|
||||
private static void runPowerShell(String script) throws IOException {
|
||||
String encoded = Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
|
||||
runCommand(List.of("powershell.exe", "-NoProfile", "-EncodedCommand", encoded));
|
||||
}
|
||||
|
||||
private static String powershellQuote(String value) {
|
||||
return value.replace("'", "''");
|
||||
}
|
||||
|
||||
private static void writeUnix(Scope scope, String key, String value) throws IOException {
|
||||
Path destination = environmentFile(scope);
|
||||
boolean shellExport = scope == Scope.USER || SystemUtil.isMacOs();
|
||||
String current = readIfExists(destination);
|
||||
String updated = updateEnvironmentContent(current, key, value, shellExport);
|
||||
if (scope == Scope.USER) {
|
||||
Files.createDirectories(destination.getParent());
|
||||
Files.writeString(destination, updated, StandardCharsets.UTF_8);
|
||||
ensureUserProfileSources(destination);
|
||||
applyToCurrentMacSession(key, value);
|
||||
return;
|
||||
}
|
||||
writeSystemFile(destination, updated);
|
||||
}
|
||||
|
||||
private static Path environmentFile(Scope scope) {
|
||||
if (scope == Scope.USER) {
|
||||
return Path.of(System.getProperty("user.home"), ".MooTool", "environment");
|
||||
}
|
||||
return SystemUtil.isMacOs() ? Path.of("/etc/zshenv") : Path.of("/etc/environment");
|
||||
}
|
||||
|
||||
private static void ensureUserProfileSources(Path environmentFile) throws IOException {
|
||||
Path profile = Path.of(System.getProperty("user.home"), SystemUtil.isMacOs() ? ".zshenv" : ".profile");
|
||||
String current = readIfExists(profile);
|
||||
if (current.contains(PROFILE_MARKER_START)) {
|
||||
return;
|
||||
}
|
||||
String quotedPath = shellQuote(environmentFile.toAbsolutePath().toString());
|
||||
String source = ". " + quotedPath;
|
||||
String block = PROFILE_MARKER_START + System.lineSeparator()
|
||||
+ "[ -f " + quotedPath + " ] && " + source + System.lineSeparator()
|
||||
+ PROFILE_MARKER_END + System.lineSeparator();
|
||||
String separator = current.isEmpty() || current.endsWith("\n") ? "" : System.lineSeparator();
|
||||
Files.writeString(profile, current + separator + block, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static void applyToCurrentMacSession(String key, String value) {
|
||||
if (!SystemUtil.isMacOs()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
List<String> command = value == null
|
||||
? List.of("/bin/launchctl", "unsetenv", key)
|
||||
: List.of("/bin/launchctl", "setenv", key, value);
|
||||
runCommand(command);
|
||||
} catch (IOException ignored) {
|
||||
// The persistent shell configuration is already saved.
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeSystemFile(Path destination, String content) throws IOException {
|
||||
try {
|
||||
Files.writeString(destination, content, StandardCharsets.UTF_8);
|
||||
return;
|
||||
} catch (IOException directWriteError) {
|
||||
Path temporary = Files.createTempFile("mootool-environment-", ".tmp");
|
||||
try {
|
||||
Files.writeString(temporary, content, StandardCharsets.UTF_8);
|
||||
if (SystemUtil.isMacOs()) {
|
||||
String command = "/bin/cp " + shellQuote(temporary.toString()) + " "
|
||||
+ shellQuote(destination.toString()) + " && /bin/chmod 644 " + shellQuote(destination.toString());
|
||||
String appleScript = "do shell script \"" + appleScriptQuote(command) + "\" with administrator privileges";
|
||||
runCommand(List.of("/usr/bin/osascript", "-e", appleScript));
|
||||
} else if (SystemUtil.isLinuxOs()) {
|
||||
runCommand(List.of("pkexec", "/bin/sh", "-c",
|
||||
"/bin/cp \"$1\" \"$2\" && /bin/chmod 644 \"$2\"", "mootool", temporary.toString(), destination.toString()));
|
||||
} else {
|
||||
throw directWriteError;
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void runCommand(List<String> command) throws IOException {
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
boolean finished;
|
||||
try {
|
||||
finished = process.waitFor(COMMAND_TIMEOUT.toSeconds(), TimeUnit.SECONDS);
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Environment update was interrupted", error);
|
||||
}
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("Environment update timed out");
|
||||
}
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException(output.isEmpty() ? "Environment update was canceled or denied" : output);
|
||||
}
|
||||
}
|
||||
|
||||
static List<Entry> parseEnvironmentContent(String content) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (String line : content.split("\\R")) {
|
||||
Matcher matcher = ASSIGNMENT.matcher(line);
|
||||
if (!matcher.matches()) {
|
||||
continue;
|
||||
}
|
||||
values.put(matcher.group(1), unquote(matcher.group(2).trim()));
|
||||
}
|
||||
return values.entrySet().stream()
|
||||
.map(entry -> new Entry(entry.getKey(), entry.getValue()))
|
||||
.sorted(Comparator.comparing(Entry::key, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
}
|
||||
|
||||
static String updateEnvironmentContent(String content, String key, String value, boolean shellExport) {
|
||||
validateKey(key);
|
||||
if (value != null) {
|
||||
validate(key, value);
|
||||
}
|
||||
List<String> lines = new ArrayList<>(List.of(content.split("\\R", -1)));
|
||||
String replacement = value == null ? null : serialize(key, value, shellExport);
|
||||
boolean replaced = false;
|
||||
List<String> result = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
Matcher matcher = ASSIGNMENT.matcher(line);
|
||||
if (matcher.matches() && matcher.group(1).equals(key)) {
|
||||
if (!replaced && replacement != null) {
|
||||
result.add(replacement);
|
||||
replaced = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
result.add(line);
|
||||
}
|
||||
if (replacement != null && !replaced) {
|
||||
while (!result.isEmpty() && result.get(result.size() - 1).isEmpty()) {
|
||||
result.remove(result.size() - 1);
|
||||
}
|
||||
result.add(replacement);
|
||||
}
|
||||
while (!result.isEmpty() && result.get(result.size() - 1).isEmpty()) {
|
||||
result.remove(result.size() - 1);
|
||||
}
|
||||
return result.isEmpty() ? "" : String.join("\n", result) + "\n";
|
||||
}
|
||||
|
||||
private static String serialize(String key, String value, boolean shellExport) {
|
||||
if (shellExport) {
|
||||
return "export " + key + "='" + value.replace("'", "'\\''") + "'";
|
||||
}
|
||||
return key + "=\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
private static String unquote(String value) {
|
||||
if (value.length() >= 2 && value.startsWith("'") && value.endsWith("'")) {
|
||||
return value.substring(1, value.length() - 1).replace("'\\''", "'");
|
||||
}
|
||||
if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
|
||||
return value.substring(1, value.length() - 1).replace("\\\"", "\"").replace("\\\\", "\\");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String readIfExists(Path path) throws IOException {
|
||||
return Files.exists(path) ? Files.readString(path, StandardCharsets.UTF_8) : "";
|
||||
}
|
||||
|
||||
private static void validate(String key, String value) {
|
||||
validateKey(key);
|
||||
if (value == null || value.length() > 65_535 || value.indexOf('\0') >= 0
|
||||
|| value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) {
|
||||
throw new IllegalArgumentException("Invalid environment variable value");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateKey(String key) {
|
||||
if (key == null || !VARIABLE_NAME.matcher(key).matches()) {
|
||||
throw new IllegalArgumentException("Invalid environment variable name");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requirePersistentScope(Scope scope) {
|
||||
if (scope == Scope.CURRENT) {
|
||||
throw new IllegalArgumentException("Current process environment is read-only");
|
||||
}
|
||||
}
|
||||
|
||||
private static String shellQuote(String value) {
|
||||
return "'" + value.replace("'", "'\\''") + "'";
|
||||
}
|
||||
|
||||
private static String appleScriptQuote(String value) {
|
||||
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
}
|
||||
}
|
||||
@@ -732,6 +732,17 @@ variables.tab.sysEnv=System Environment Variables
|
||||
variables.tab.javaProps=Java Properties
|
||||
variables.col.key=Key
|
||||
variables.col.value=Value
|
||||
variables.scope.current=Current environment
|
||||
variables.scope.user=User variables
|
||||
variables.scope.system=System variables
|
||||
variables.targetScope=Save to
|
||||
variables.action.add=Add environment variable
|
||||
variables.action.edit=Edit environment variable
|
||||
variables.dialog.addTitle=Add Environment Variable
|
||||
variables.dialog.editTitle=Edit Environment Variable
|
||||
variables.confirmDelete=Delete environment variable "{0}"? The change applies to newly started processes.
|
||||
variables.saved=Environment variables updated. Newly started terminals and applications will use the new value.
|
||||
variables.saveFailed=Failed to update environment variables.\n\n{0}
|
||||
|
||||
# Hardware / System Info tab
|
||||
hardware.tab.system=System
|
||||
|
||||
@@ -707,6 +707,17 @@ variables.tab.sysEnv=システム環境変数
|
||||
variables.tab.javaProps=Java properties
|
||||
variables.col.key=Key
|
||||
variables.col.value=Value
|
||||
variables.scope.current=現在の環境
|
||||
variables.scope.user=ユーザー変数
|
||||
variables.scope.system=システム変数
|
||||
variables.targetScope=保存先
|
||||
variables.action.add=環境変数を追加
|
||||
variables.action.edit=環境変数を編集
|
||||
variables.dialog.addTitle=環境変数を追加
|
||||
variables.dialog.editTitle=環境変数を編集
|
||||
variables.confirmDelete=環境変数「{0}」を削除しますか?新しく起動するプロセスから反映されます。
|
||||
variables.saved=環境変数を更新しました。新しく起動するターミナルとアプリで新しい値が使用されます。
|
||||
variables.saveFailed=環境変数の更新に失敗しました。\n\n{0}
|
||||
|
||||
# Hardware / System Info tab
|
||||
hardware.tab.system=システム
|
||||
|
||||
@@ -732,6 +732,17 @@ variables.tab.sysEnv=系统环境变量
|
||||
variables.tab.javaProps=Java properties
|
||||
variables.col.key=Key
|
||||
variables.col.value=Value
|
||||
variables.scope.current=当前环境
|
||||
variables.scope.user=用户变量
|
||||
variables.scope.system=系统变量
|
||||
variables.targetScope=保存到
|
||||
variables.action.add=新增环境变量
|
||||
variables.action.edit=编辑环境变量
|
||||
variables.dialog.addTitle=新增环境变量
|
||||
variables.dialog.editTitle=编辑环境变量
|
||||
variables.confirmDelete=确认删除环境变量“{0}”?新进程将在删除后生效。
|
||||
variables.saved=环境变量已更新,新启动的终端和应用将使用新值。
|
||||
variables.saveFailed=修改环境变量失败!\n\n{0}
|
||||
|
||||
# Hardware / System Info tab
|
||||
hardware.tab.system=系统
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.luoboduner.moo.tool.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class EnvironmentVariableServiceTest {
|
||||
|
||||
@Test
|
||||
void parsesShellAndEnvironmentFileAssignments() {
|
||||
List<EnvironmentVariableService.Entry> entries = EnvironmentVariableService.parseEnvironmentContent("""
|
||||
# comment
|
||||
export JAVA_HOME='/opt/jdk 21'
|
||||
PATH="/usr/local/bin:$PATH"
|
||||
EMPTY=
|
||||
""");
|
||||
|
||||
assertEquals(List.of(
|
||||
new EnvironmentVariableService.Entry("EMPTY", ""),
|
||||
new EnvironmentVariableService.Entry("JAVA_HOME", "/opt/jdk 21"),
|
||||
new EnvironmentVariableService.Entry("PATH", "/usr/local/bin:$PATH")
|
||||
), entries);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesOnlyTheRequestedAssignmentAndPreservesComments() {
|
||||
String updated = EnvironmentVariableService.updateEnvironmentContent(
|
||||
"# managed elsewhere\nexport PATH='/old'\nOTHER=\"value\"\n",
|
||||
"PATH",
|
||||
"/new path",
|
||||
true
|
||||
);
|
||||
|
||||
assertEquals("# managed elsewhere\nexport PATH='/new path'\nOTHER=\"value\"\n", updated);
|
||||
assertEquals("# managed elsewhere\nOTHER=\"value\"\n",
|
||||
EnvironmentVariableService.updateEnvironmentContent(updated, "PATH", null, true));
|
||||
assertEquals("export QUOTED='it'\\''s safe'\n",
|
||||
EnvironmentVariableService.updateEnvironmentContent("", "QUOTED", "it's safe", true));
|
||||
assertEquals("it's safe", EnvironmentVariableService.parseEnvironmentContent(
|
||||
"export QUOTED='it'\\''s safe'\n").getFirst().value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsafeNamesAndMultilineValues() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EnvironmentVariableService.updateEnvironmentContent("", "BAD-NAME", "value", true));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EnvironmentVariableService.updateEnvironmentContent("", "SAFE_NAME", "one\ntwo", true));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> EnvironmentVariableService.set(EnvironmentVariableService.Scope.CURRENT, "SAFE_NAME", "value"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user