@mindbase/deploy 1.0.1 → 1.1.1

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.
package/bin/shared.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Command } from 'commander';
2
2
  import * as clack from '@clack/prompts';
3
- import { resolve } from 'path';
4
3
  import { runApp, runProject, showConfig } from '../src/app.js';
5
4
  import { runInit } from '../src/init/app.js';
6
5
  import { createServerCommand } from '../src/server/app.js';
@@ -26,12 +25,12 @@ export function createDeployProgram(): Command {
26
25
  });
27
26
 
28
27
  program
29
- .command('init')
30
- .description('交互式初始化项目部署配置')
31
- .action(async () => {
28
+ .command('init [path]')
29
+ .description('在 cwd(或指定目录)生成本地 deploy.config.json')
30
+ .action(async (path?: string) => {
32
31
  clack.intro('deploy init');
33
32
  try {
34
- await runInit(resolve('.'));
33
+ await runInit(path);
35
34
  } catch (err) {
36
35
  clack.log.error(`执行失败: ${err}`);
37
36
  process.exit(1);
@@ -39,13 +38,13 @@ export function createDeployProgram(): Command {
39
38
  });
40
39
 
41
40
  program
42
- .command('run <project>')
43
- .description('直接运行指定项目')
44
- .option('-s, --server <server>', '覆盖项目默认服务器')
45
- .action(async (project: string, options: { server?: string }) => {
41
+ .command('run [path]')
42
+ .description('部署单个项目(path 缺省为 cwd,可传目录或 deploy.config.json)')
43
+ .option('-s, --server <server>', '覆盖项目配置中的 server')
44
+ .action(async (path: string | undefined, options: { server?: string }) => {
46
45
  clack.intro('deploy run');
47
46
  try {
48
- await runProject(project, options.server);
47
+ await runProject(path, options.server);
49
48
  } catch (err) {
50
49
  clack.log.error(`执行失败: ${err}`);
51
50
  process.exit(1);
@@ -54,7 +53,7 @@ export function createDeployProgram(): Command {
54
53
 
55
54
  program
56
55
  .command('config')
57
- .description('查看配置')
56
+ .description('查看全局 servers 配置')
58
57
  .action(() => {
59
58
  showConfig();
60
59
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindbase/deploy",
3
- "version": "1.0.1",
3
+ "version": "1.1.1",
4
4
  "description": "MindBase 部署工具",
5
5
  "type": "module",
6
6
  "bin": {
package/src/app.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import * as clack from '@clack/prompts';
2
2
  import pc from 'picocolors';
3
+ import { relative } from 'path';
3
4
  import { noteBox } from '@mindbase/cli-ui';
4
- import { getConfig, getConfigPath } from './config/manager.js';
5
- import type { DeployConfig, ProjectConfig } from './config/schema.js';
5
+ import { getConfig, getConfigPath, discoverProjectConfigs, loadProjectConfig } from './config/manager.js';
6
+ import type { ProjectConfig } from './config/schema.js';
6
7
  import { connectSftp } from './ssh/client.js';
7
8
  import { runSteps } from './script/runner.js';
8
9
 
@@ -27,33 +28,47 @@ export function showConfig(): void {
27
28
  }
28
29
 
29
30
  /**
30
- * 直接运行指定项目
31
+ * 显示项目配置摘要并让用户确认部署
31
32
  */
32
- export async function runProject(projectId: string, serverOverride?: string): Promise<void> {
33
- const config = getConfig();
33
+ async function confirmProjectDeploy(project: ProjectConfig, serverId: string): Promise<boolean> {
34
+ const summary = [
35
+ `名称: ${project.name}`,
36
+ `服务器: ${serverId}`,
37
+ `本地目录: ${project.localDir}`,
38
+ `远端目录: ${project.remoteDir}`,
39
+ `步骤数: ${project.steps.length}`,
40
+ ].join('\n');
41
+ noteBox(summary, '即将部署');
42
+ return handleCancel<boolean>(
43
+ await clack.confirm({ message: '确认部署?', initialValue: true })
44
+ );
45
+ }
34
46
 
35
- const project = config.projects[projectId];
36
- if (!project) {
37
- clack.log.error(`项目 "${projectId}" 不存在`);
38
- const available = Object.keys(config.projects);
39
- if (available.length > 0) {
40
- clack.log.info(`可用项目: ${available.join(', ')}`);
41
- }
42
- process.exit(1);
43
- }
47
+ /**
48
+ * 直接运行指定项目(单项目模式)
49
+ */
50
+ export async function runProject(targetPath?: string, serverOverride?: string): Promise<void> {
51
+ const project = loadProjectConfig(targetPath);
52
+ const globalConfig = getConfig();
44
53
 
45
54
  const serverId = serverOverride || project.server;
46
- const serverConfig = config.servers[serverId];
55
+ const serverConfig = globalConfig.servers[serverId];
47
56
  if (!serverConfig) {
48
- clack.log.error(`服务器 "${serverId}" 不存在`);
57
+ clack.log.error(`服务器 "${serverId}" 不存在,请先运行 deploy server add`);
49
58
  process.exit(1);
50
59
  }
51
60
 
52
61
  clack.intro(`部署 ${pc.cyan(project.name)} → ${pc.cyan(serverId)}`);
53
62
 
63
+ if (!(await confirmProjectDeploy(project, serverId))) {
64
+ clack.log.info('已取消');
65
+ clack.outro('完成');
66
+ return;
67
+ }
68
+
54
69
  const spinner = clack.spinner();
55
70
  spinner.start('连接服务器...');
56
- const sftp = await connectSftp(projectId, serverConfig);
71
+ const sftp = await connectSftp(project.name, serverConfig);
57
72
  spinner.stop('已连接');
58
73
 
59
74
  try {
@@ -69,87 +84,99 @@ export async function runProject(projectId: string, serverOverride?: string): Pr
69
84
  }
70
85
 
71
86
  /**
72
- * 交互式主流程:选服务器多选项目依次部署
87
+ * 交互式主流程:扫描 cwd 下所有 deploy.config.json 多选按 server 分组部署
73
88
  */
74
89
  export async function runApp(): Promise<void> {
75
- const config = getConfig();
90
+ const cwd = process.cwd();
91
+ const discovered = discoverProjectConfigs(cwd);
92
+ const globalConfig = getConfig();
76
93
 
77
- // 检查配置
78
- const serverIds = Object.keys(config.servers);
79
- const projectIds = Object.keys(config.projects);
80
-
81
- if (serverIds.length === 0) {
82
- clack.log.error('没有已配置的服务器,请先运行 deploy server add');
94
+ if (discovered.length === 0) {
95
+ clack.log.error(`未在 ${cwd} 下找到任何 deploy.config.json,请先运行 deploy init`);
83
96
  return;
84
97
  }
85
- if (projectIds.length === 0) {
86
- clack.log.error('没有已配置的项目,请先运行 deploy init');
98
+
99
+ // 0 个服务器直接报错
100
+ if (Object.keys(globalConfig.servers).length === 0) {
101
+ clack.log.error('没有已配置的服务器,请先运行 deploy server add');
87
102
  return;
88
103
  }
89
104
 
90
105
  clack.intro('deploy');
91
106
 
92
- // 选择服务器
93
- const serverId = handleCancel<string>(
94
- await clack.select({
95
- message: '选择目标服务器',
96
- options: serverIds.map((id) => ({
97
- value: id,
98
- label: `${id} (${config.servers[id].host}:${config.servers[id].port})`,
99
- })),
100
- })
101
- );
107
+ // 选择项目
108
+ let selected: { path: string; config: ProjectConfig }[];
109
+
110
+ if (discovered.length === 1) {
111
+ const only = discovered[0];
112
+ clack.log.info(`仅发现一个项目: ${only.config.name}`);
113
+ const go = handleCancel<boolean>(
114
+ await clack.confirm({ message: `是否部署 ${only.config.name}?`, initialValue: true })
115
+ );
116
+ if (!go) {
117
+ clack.outro('已取消');
118
+ return;
119
+ }
120
+ selected = [only];
121
+ } else {
122
+ selected = handleCancel<typeof discovered>(
123
+ await clack.multiselect({
124
+ message: '选择要部署的项目(空格切换,a 全选)',
125
+ options: discovered.map((item) => ({
126
+ value: item,
127
+ label: `${item.config.name} (${relative(cwd, item.path) || item.path}) → ${pc.dim(item.config.server)}`,
128
+ })),
129
+ required: true,
130
+ })
131
+ );
132
+ }
102
133
 
103
- // 筛选该项目服务器下的项目(或显示全部)
104
- const filteredProjects = projectIds.filter(
105
- (id) => config.projects[id].server === serverId
106
- );
107
- const selectableProjects = filteredProjects.length > 0 ? filteredProjects : projectIds;
108
-
109
- // 多选项目
110
- const selectedProjects = handleCancel<string[]>(
111
- await clack.multiselect({
112
- message: '选择要部署的项目(空格切换,a 全选)',
113
- options: selectableProjects.map((id) => ({
114
- value: id,
115
- label: `${config.projects[id].name} (${id})`,
116
- })),
117
- required: true,
118
- })
119
- );
134
+ // 校验所有选中项目的 server 都存在
135
+ const missingServers = new Set<string>();
136
+ for (const item of selected) {
137
+ if (!globalConfig.servers[item.config.server]) {
138
+ missingServers.add(item.config.server);
139
+ }
140
+ }
141
+ if (missingServers.size > 0) {
142
+ clack.log.error(`以下服务器未配置: ${[...missingServers].join(', ')}`);
143
+ clack.outro('已中止');
144
+ return;
145
+ }
120
146
 
121
- // 连接服务器
122
- const spinner = clack.spinner();
123
- spinner.start(`连接 ${serverId}...`);
124
- const serverConfig = config.servers[serverId];
125
- const sftp = await connectSftp('deploy', serverConfig);
126
- spinner.stop('已连接');
147
+ // 按 server 分组
148
+ const groups = new Map<string, { path: string; config: ProjectConfig }[]>();
149
+ for (const item of selected) {
150
+ const arr = groups.get(item.config.server) ?? [];
151
+ arr.push(item);
152
+ groups.set(item.config.server, arr);
153
+ }
127
154
 
128
- try {
129
- // 依次部署选中的项目
130
- for (const projectId of selectedProjects) {
131
- const project = config.projects[projectId];
132
- // 运行时使用选中的服务器覆盖项目默认服务器
133
- const effectiveProject: ProjectConfig = {
134
- ...project,
135
- server: serverId,
136
- };
137
-
138
- clack.log.step(`开始部署 ${pc.cyan(project.name)}`);
139
-
140
- try {
141
- await runSteps(project.steps, effectiveProject, sftp);
142
- clack.log.success(`${project.name} 部署完成`);
143
- } catch (err) {
144
- clack.log.error(`${project.name} 部署失败: ${err}`);
145
- const continueDeploy = handleCancel<boolean>(
146
- await clack.confirm({ message: '是否继续部署下一个项目?' })
147
- );
148
- if (!continueDeploy) break;
155
+ // 依次连接每个 server,组内项目依次部署
156
+ for (const [serverId, items] of groups) {
157
+ const serverConfig = globalConfig.servers[serverId];
158
+ const spinner = clack.spinner();
159
+ spinner.start(`连接 ${serverId}...`);
160
+ const sftp = await connectSftp('deploy', serverConfig);
161
+ spinner.stop('已连接');
162
+
163
+ try {
164
+ for (const { config } of items) {
165
+ clack.log.step(`开始部署 ${pc.cyan(config.name)} → ${pc.cyan(serverId)}`);
166
+ try {
167
+ await runSteps(config.steps, config, sftp);
168
+ clack.log.success(`${config.name} 部署完成`);
169
+ } catch (err) {
170
+ clack.log.error(`${config.name} 部署失败: ${err}`);
171
+ const cont = handleCancel<boolean>(
172
+ await clack.confirm({ message: '是否继续部署下一个项目?' })
173
+ );
174
+ if (!cont) break;
175
+ }
149
176
  }
177
+ } finally {
178
+ await sftp.end();
150
179
  }
151
- } finally {
152
- await sftp.end();
153
180
  }
154
181
 
155
182
  clack.outro('全部完成');
@@ -1,15 +1,32 @@
1
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
2
- import { dirname, join } from 'path';
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';
2
+ import { dirname, join, resolve, isAbsolute } from 'path';
3
3
  import { homedir } from 'os';
4
- import type { DeployConfig } from './schema.js';
4
+ import type { GlobalConfig, ProjectConfig } from './schema.js';
5
5
 
6
- /** 默认配置 */
7
- const defaultConfig: DeployConfig = {
6
+ /** 项目级配置文件名 */
7
+ export const PROJECT_CONFIG_FILE = 'deploy.config.json';
8
+
9
+ /** 扫描时忽略的目录名 */
10
+ const SCAN_IGNORE_DIRS = new Set([
11
+ 'node_modules',
12
+ '.git',
13
+ 'dist',
14
+ 'build',
15
+ 'target',
16
+ '.next',
17
+ 'coverage',
18
+ '.cache',
19
+ ]);
20
+
21
+ /** 扫描深度上限 */
22
+ const SCAN_MAX_DEPTH = 5;
23
+
24
+ /** 默认全局配置 */
25
+ const defaultGlobalConfig: GlobalConfig = {
8
26
  servers: {},
9
- projects: {},
10
27
  };
11
28
 
12
- /** 配置文件路径 */
29
+ /** 全局配置目录与文件路径 */
13
30
  const CONFIG_DIR = join(homedir(), '.mindbase');
14
31
  const CONFIG_PATH = join(CONFIG_DIR, 'deploy.json');
15
32
 
@@ -23,34 +40,133 @@ function ensureConfigDir(): void {
23
40
  }
24
41
 
25
42
  /**
26
- * 读取部署配置
43
+ * 读取全局配置(servers)
27
44
  */
28
- export function getConfig(): DeployConfig {
45
+ export function getConfig(): GlobalConfig {
29
46
  if (!existsSync(CONFIG_PATH)) {
30
47
  ensureConfigDir();
31
- writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2), 'utf-8');
32
- return structuredClone(defaultConfig);
48
+ writeFileSync(CONFIG_PATH, JSON.stringify(defaultGlobalConfig, null, 2), 'utf-8');
49
+ return structuredClone(defaultGlobalConfig);
33
50
  }
34
51
 
35
52
  try {
36
53
  const content = readFileSync(CONFIG_PATH, 'utf-8');
37
- return JSON.parse(content);
54
+ const parsed = JSON.parse(content);
55
+ return { servers: parsed.servers ?? {} };
38
56
  } catch {
39
- return structuredClone(defaultConfig);
57
+ return structuredClone(defaultGlobalConfig);
40
58
  }
41
59
  }
42
60
 
43
61
  /**
44
- * 写入部署配置
62
+ * 写入全局配置
45
63
  */
46
- export function setConfig(config: DeployConfig): void {
64
+ export function setConfig(config: GlobalConfig): void {
47
65
  ensureConfigDir();
48
66
  writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8');
49
67
  }
50
68
 
51
69
  /**
52
- * 获取配置文件路径
70
+ * 获取全局配置文件路径
53
71
  */
54
72
  export function getConfigPath(): string {
55
73
  return CONFIG_PATH;
56
74
  }
75
+
76
+ /**
77
+ * 解析配置文件实际路径:目录 → 拼 deploy.config.json;文件 → 直接用
78
+ */
79
+ function resolveConfigFilePath(targetPath?: string): string {
80
+ const cwd = targetPath ?? process.cwd();
81
+ const abs = isAbsolute(cwd) ? cwd : resolve(process.cwd(), cwd);
82
+ const stat = existsSync(abs) ? statSync(abs) : null;
83
+ if (stat && stat.isFile()) return abs;
84
+ return join(abs, PROJECT_CONFIG_FILE);
85
+ }
86
+
87
+ /**
88
+ * 解析 localDir 为绝对路径(相对配置文件所在目录)
89
+ */
90
+ function resolveLocalDir(localDir: string, configFilePath: string): string {
91
+ if (isAbsolute(localDir)) return localDir;
92
+ return resolve(dirname(configFilePath), localDir);
93
+ }
94
+
95
+ /**
96
+ * 加载项目级配置
97
+ * @param targetPath 目录或文件路径,缺省为 cwd
98
+ */
99
+ export function loadProjectConfig(targetPath?: string): ProjectConfig {
100
+ const configFilePath = resolveConfigFilePath(targetPath);
101
+ if (!existsSync(configFilePath)) {
102
+ throw new Error(`项目配置文件不存在: ${configFilePath}`);
103
+ }
104
+
105
+ const raw = readFileSync(configFilePath, 'utf-8');
106
+ const parsed = JSON.parse(raw) as ProjectConfig;
107
+ parsed.localDir = resolveLocalDir(parsed.localDir ?? '.', configFilePath);
108
+ return parsed;
109
+ }
110
+
111
+ /**
112
+ * 写入项目级配置
113
+ * @param config 项目配置
114
+ * @param targetPath 目录或文件路径,缺省为 cwd
115
+ */
116
+ export function saveProjectConfig(config: ProjectConfig, targetPath?: string): void {
117
+ const configFilePath = resolveConfigFilePath(targetPath);
118
+ mkdirSync(dirname(configFilePath), { recursive: true });
119
+ writeFileSync(configFilePath, JSON.stringify(config, null, 2), 'utf-8');
120
+ }
121
+
122
+ /** 发现结果 */
123
+ export interface DiscoveredProject {
124
+ /** 配置文件绝对路径 */
125
+ path: string;
126
+ /** 已解析的 ProjectConfig */
127
+ config: ProjectConfig;
128
+ }
129
+
130
+ /**
131
+ * 扫描 rootPath 下所有 deploy.config.json
132
+ */
133
+ export function discoverProjectConfigs(rootPath?: string): DiscoveredProject[] {
134
+ const root = rootPath ?? process.cwd();
135
+ const results: DiscoveredProject[] = [];
136
+
137
+ function walk(dir: string, depth: number): void {
138
+ if (depth > SCAN_MAX_DEPTH) return;
139
+
140
+ let entries;
141
+ try {
142
+ entries = readdirSync(dir);
143
+ } catch {
144
+ return;
145
+ }
146
+
147
+ for (const entry of entries) {
148
+ if (SCAN_IGNORE_DIRS.has(entry)) continue;
149
+ const full = join(dir, entry);
150
+ let stat;
151
+ try {
152
+ stat = statSync(full);
153
+ } catch {
154
+ continue;
155
+ }
156
+
157
+ if (stat.isDirectory()) {
158
+ walk(full, depth + 1);
159
+ } else if (entry === PROJECT_CONFIG_FILE) {
160
+ try {
161
+ const config = loadProjectConfig(full);
162
+ results.push({ path: full, config });
163
+ } catch {
164
+ /* 跳过损坏的配置文件 */
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ walk(root, 0);
171
+ return results;
172
+ }
@@ -79,13 +79,13 @@ export interface PrivateKeyServerConfig {
79
79
  /** 服务器配置 */
80
80
  export type ServerConfig = PasswordServerConfig | PrivateKeyServerConfig;
81
81
 
82
- /** 项目配置 */
82
+ /** 项目配置(项目级 deploy.config.json) */
83
83
  export interface ProjectConfig {
84
84
  /** 项目显示名称 */
85
85
  name: string;
86
- /** 本地目录(绝对路径) */
86
+ /** 本地目录(绝对路径或相对配置文件的路径,加载时解析为绝对路径) */
87
87
  localDir: string;
88
- /** 默认目标服务器 ID */
88
+ /** 目标服务器 ID(引用全局 servers) */
89
89
  server: string;
90
90
  /** 远端目录 */
91
91
  remoteDir: string;
@@ -93,10 +93,8 @@ export interface ProjectConfig {
93
93
  steps: Step[];
94
94
  }
95
95
 
96
- /** 部署配置文件结构 */
97
- export interface DeployConfig {
96
+ /** 全局配置结构(~/.mindbase/deploy.json) */
97
+ export interface GlobalConfig {
98
98
  /** 服务器列表 */
99
99
  servers: Record<string, ServerConfig>;
100
- /** 项目列表 */
101
- projects: Record<string, ProjectConfig>;
102
100
  }
package/src/init/app.ts CHANGED
@@ -3,8 +3,8 @@ import pc from 'picocolors';
3
3
  import { resolve } from 'path';
4
4
  import { existsSync, readFileSync } from 'fs';
5
5
  import { noteBox } from '@mindbase/cli-ui';
6
- import { getConfig, setConfig } from '../config/manager.js';
7
- import type { Step, StepType, ProjectConfig, ServerConfig } from '../config/schema.js';
6
+ import { getConfig, saveProjectConfig } from '../config/manager.js';
7
+ import type { Step, StepType, ProjectConfig } from '../config/schema.js';
8
8
  import { connectSftp } from '../ssh/client.js';
9
9
 
10
10
  /** 取消处理 */
@@ -262,29 +262,21 @@ async function collectStep(): Promise<Step | null> {
262
262
 
263
263
  /**
264
264
  * 运行 deploy init 主流程
265
+ * @param targetPath 项目目录(缺省 cwd),生成的 deploy.config.json 写入此目录
265
266
  */
266
- export async function runInit(cwd: string): Promise<void> {
267
+ export async function runInit(targetPath?: string): Promise<void> {
267
268
  clack.intro('deploy init');
268
269
 
270
+ const cwd = resolve(targetPath ?? '.');
271
+
269
272
  const deployConfig = getConfig();
270
273
 
271
274
  // 1. 项目名称
272
275
  const defaultName = getDefaultProjectName(cwd);
273
- const projectId = handleCancel<string>(
274
- await clack.text({
275
- message: '项目 ID(用于标识)',
276
- initialValue: defaultName,
277
- })
278
- );
279
-
280
- if (deployConfig.projects[projectId]) {
281
- clack.log.warn(`项目 "${projectId}" 已存在,将覆盖配置`);
282
- }
283
-
284
276
  const name = handleCancel<string>(
285
277
  await clack.text({
286
278
  message: '项目显示名称',
287
- initialValue: projectId,
279
+ initialValue: defaultName,
288
280
  })
289
281
  );
290
282
 
@@ -307,11 +299,11 @@ export async function runInit(cwd: string): Promise<void> {
307
299
  })
308
300
  );
309
301
 
310
- // 4. 本地目录(绝对路径)
302
+ // 4. 本地目录(用相对路径 ./,便于跨设备/入库)
311
303
  const localDir = handleCancel<string>(
312
304
  await clack.text({
313
- message: '本地目录(绝对路径)',
314
- initialValue: cwd,
305
+ message: '本地目录(相对 deploy.config.json,默认 ./)',
306
+ initialValue: './',
315
307
  })
316
308
  );
317
309
 
@@ -391,7 +383,7 @@ export async function runInit(cwd: string): Promise<void> {
391
383
  // 7. 预览配置
392
384
  const projectConfig: ProjectConfig = {
393
385
  name,
394
- localDir: resolve(localDir),
386
+ localDir,
395
387
  server: serverId,
396
388
  remoteDir,
397
389
  steps,
@@ -404,9 +396,8 @@ export async function runInit(cwd: string): Promise<void> {
404
396
  );
405
397
 
406
398
  if (confirmSave) {
407
- deployConfig.projects[projectId] = projectConfig;
408
- setConfig(deployConfig);
409
- clack.log.success(`项目 "${projectId}" 配置已保存`);
399
+ saveProjectConfig(projectConfig, cwd);
400
+ clack.log.success(`配置已写入 ${resolve(cwd, 'deploy.config.json')}`);
410
401
  } else {
411
402
  clack.log.info('已取消保存');
412
403
  }