Files
dsh-server-manager/lib/config.js
T
2026-11-18 01:10:51 +08:00

81 lines
2.5 KiB
JavaScript

import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
export const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
export const CONFIG_PATH = join(DSH_HOME, 'server-manager.json')
const SEED = {
default: 'gitea',
servers: [
{
id: 'gitea',
label: 'Gitea 服务器',
host: '110.42.217.133',
port: 22,
user: 'root',
key: join(homedir(), '.ssh/gitea_deploy_ed25519')
}
]
}
export function loadConfig() {
try {
const raw = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))
const servers = Array.isArray(raw?.servers) ? raw.servers.filter((s) => s && s.host && s.user) : []
return {
default: typeof raw?.default === 'string' ? raw.default : (servers[0]?.id ?? null),
servers: servers.map((s) => ({
id: String(s.id || s.host),
label: String(s.label || s.id || s.host),
host: String(s.host),
port: Number(s.port) || 22,
user: String(s.user),
key: s.key ? String(s.key) : null
}))
}
} catch (error) {
if (error?.code !== 'ENOENT') return { default: null, servers: [], broken: String(error?.message || error) }
return { default: null, servers: [] }
}
}
export function saveConfig(cfg) {
mkdirSync(DSH_HOME, { recursive: true, mode: 0o700 })
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 })
try { chmodSync(CONFIG_PATH, 0o600) } catch {}
}
/** 第一次使用时写入示例配置,之后不再碰用户文件。 */
export function ensureSeed() {
if (existsSync(CONFIG_PATH)) return loadConfig()
saveConfig(SEED)
return loadConfig()
}
export function resolveServer(cfg, wanted) {
const list = cfg.servers || []
if (!list.length) {
return {
error:
'还没有配置服务器。编辑 `~/.dsh/server-manager.json`,在 servers 里加一条:\n' +
'{ "id": "mine", "label": "我的服务器", "host": "1.2.3.4", "port": 22, "user": "root", "key": "~/.ssh/id_ed25519" }'
}
}
const id = (wanted || cfg.default || '').trim()
const hit = list.find((s) => s.id === id || s.label === id || s.host === id)
if (hit) return { server: hit }
return {
error: `没有找到服务器「${id || '(空)'}」。可用的有:${list.map((s) => s.id).join('、')}`
}
}
export function describeServer(s) {
return `${s.label} · ${s.user}@${s.host}:${s.port}`
}
export function expandHome(p) {
if (!p) return p
return p.startsWith('~') ? join(homedir(), p.slice(1)) : p
}