mirror of
https://gitcode.com/github-mirrors/react-native-update-cli.git
synced 2025-09-16 09:41:38 +08:00
cli modular refactor (#16)
* add logic to support SENTRY_PROPERTIES parameter * remove update.json and meta.json files in ppk * udpapte * refactor modles * update * add package-module file * update * update readme file * modifu cli.json file * fix command issues * improve version workflow logic * udpate * update * update * update * udpate * udpate * add example * update readme file * udpate version * change logic to use pushy command uniformly
This commit is contained in:
471
example/ENHANCED_WORKFLOWS.md
Normal file
471
example/ENHANCED_WORKFLOWS.md
Normal file
@@ -0,0 +1,471 @@
|
||||
# 核心模块增强工作流
|
||||
|
||||
这个文档详细介绍了为React Native Update CLI核心模块设计的增强工作流,包括`app-module`、`bundle-module`、`package-module`、`user-module`、`version-module`的高级工作流功能。
|
||||
|
||||
## 📋 目录
|
||||
|
||||
- [App模块工作流](#app模块工作流)
|
||||
- [Bundle模块工作流](#bundle模块工作流)
|
||||
- [Package模块工作流](#package模块工作流)
|
||||
- [User模块工作流](#user模块工作流)
|
||||
- [Version模块工作流](#version模块工作流)
|
||||
- [工作流使用示例](#工作流使用示例)
|
||||
- [最佳实践](#最佳实践)
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
```bash
|
||||
# 运行所有增强工作流演示
|
||||
npx ts-node example/scripts/enhanced-workflow-demo.ts
|
||||
|
||||
# 交互式执行特定工作流
|
||||
npx ts-node example/scripts/enhanced-workflow-demo.ts interactive [工作流名称] [参数...]
|
||||
|
||||
# 示例:应用初始化
|
||||
npx ts-node example/scripts/enhanced-workflow-demo.ts interactive app-initialization --name MyApp --platform ios
|
||||
|
||||
# 示例:智能打包
|
||||
npx ts-node example/scripts/enhanced-workflow-demo.ts interactive intelligent-bundle --platform android --optimize true
|
||||
|
||||
# 示例:版本发布
|
||||
npx ts-node example/scripts/enhanced-workflow-demo.ts interactive version-release-management --name v1.0.0 --platform ios --dryRun true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📱 App模块工作流
|
||||
|
||||
### 1. 应用初始化工作流 (`app-initialization`)
|
||||
|
||||
**用途**: 完整的应用创建和初始化流程
|
||||
|
||||
**功能特性**:
|
||||
- ✅ 参数验证和格式检查
|
||||
- ✅ 应用存在性检查和冲突处理
|
||||
- ✅ 应用创建和配置
|
||||
- ✅ 自动选择新创建的应用
|
||||
- ✅ 完整性验证和健康检查
|
||||
|
||||
**工作流步骤**:
|
||||
1. **参数验证**: 检查应用名称、平台、下载URL格式
|
||||
2. **存在性检查**: 验证应用是否已存在,支持强制覆盖
|
||||
3. **应用创建**: 执行应用创建操作
|
||||
4. **基本配置**: 设置更新策略、安全参数、版本控制
|
||||
5. **应用选择**: 自动选择新创建的应用
|
||||
6. **设置验证**: 验证应用配置的完整性和可用性
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('app-initialization', {
|
||||
args: [],
|
||||
options: {
|
||||
name: 'MyAwesomeApp', // 应用名称 (必需)
|
||||
platform: 'ios', // 平台 (必需)
|
||||
downloadUrl: 'https://...', // 下载URL (可选)
|
||||
force: false // 强制覆盖 (可选)
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 新项目应用创建
|
||||
- 多环境应用设置
|
||||
- 自动化部署脚本
|
||||
|
||||
### 2. 多平台应用管理工作流 (`multi-platform-app-management`)
|
||||
|
||||
**用途**: 跨平台应用统一管理和优化
|
||||
|
||||
**功能特性**:
|
||||
- 🔍 全平台应用扫描
|
||||
- 📊 应用状态分析和统计
|
||||
- ⚡ 自动优化建议和执行
|
||||
- 📈 应用健康度评估
|
||||
|
||||
**工作流步骤**:
|
||||
1. **平台扫描**: 扫描iOS、Android、Harmony平台的所有应用
|
||||
2. **状态分析**: 分析应用活跃度、版本分布、平台分布
|
||||
3. **问题识别**: 识别非活跃应用、配置问题
|
||||
4. **自动优化**: 执行应用配置优化和清理
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('multi-platform-app-management', {
|
||||
args: [],
|
||||
options: {
|
||||
includeInactive: true, // 包含非活跃应用
|
||||
autoOptimize: true // 自动优化配置
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 应用生态管理
|
||||
- 定期健康检查
|
||||
- 批量优化操作
|
||||
|
||||
---
|
||||
|
||||
## 📦 Bundle模块工作流
|
||||
|
||||
### 1. 智能打包工作流 (`intelligent-bundle`)
|
||||
|
||||
**用途**: 自动优化的多平台智能构建
|
||||
|
||||
**功能特性**:
|
||||
- 🖥️ 构建环境自动检测
|
||||
- 📂 项目结构智能分析
|
||||
- ⚙️ 自动优化配置
|
||||
- 🏗️ 多平台并行构建
|
||||
- 🔍 构建质量检查
|
||||
|
||||
**工作流步骤**:
|
||||
1. **环境检测**: 检查Node.js版本、内存、平台兼容性
|
||||
2. **项目分析**: 分析项目类型、依赖、预估大小
|
||||
3. **优化设置**: 根据项目特征自动配置优化选项
|
||||
4. **多平台构建**: 并行构建指定平台或所有平台
|
||||
5. **质量检查**: 检查构建质量、包大小、构建时间
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('intelligent-bundle', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'ios', // 目标平台 (可选,不指定则构建所有)
|
||||
dev: false, // 开发模式
|
||||
sourcemap: true, // 生成源码映射
|
||||
optimize: true // 启用自动优化
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 自动化CI/CD构建
|
||||
- 多平台发布准备
|
||||
- 性能优化构建
|
||||
|
||||
### 2. 增量构建工作流 (`incremental-build`)
|
||||
|
||||
**用途**: 高效的增量更新包生成
|
||||
|
||||
**功能特性**:
|
||||
- 🔍 自动基准版本检测
|
||||
- 🏗️ 当前版本构建
|
||||
- 📥 基准版本下载
|
||||
- 🔄 智能差异计算
|
||||
- ✅ 差异包验证
|
||||
|
||||
**工作流步骤**:
|
||||
1. **基准检测**: 自动检测或使用指定的基准版本
|
||||
2. **当前构建**: 构建当前版本的Bundle
|
||||
3. **基准下载**: 下载基准版本的Bundle文件
|
||||
4. **差异生成**: 计算并生成差异包
|
||||
5. **验证测试**: 验证差异包的完整性和可用性
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('incremental-build', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'android', // 目标平台 (必需)
|
||||
baseVersion: 'v1.0.0', // 基准版本 (可选,自动检测)
|
||||
skipValidation: false // 跳过验证
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 热更新包生成
|
||||
- 减少更新下载大小
|
||||
- 快速增量发布
|
||||
|
||||
---
|
||||
|
||||
## 📄 Package模块工作流
|
||||
|
||||
### 1. 批量包处理工作流 (`batch-package-processing`)
|
||||
|
||||
**用途**: 批量处理多个应用包文件
|
||||
|
||||
**功能特性**:
|
||||
- 🔍 智能文件扫描
|
||||
- 📊 包信息分析统计
|
||||
- 🔍 批量内容解析
|
||||
- 📤 自动上传处理
|
||||
- 📋 详细处理报告
|
||||
|
||||
**工作流步骤**:
|
||||
1. **文件扫描**: 扫描指定目录的包文件(IPA、APK、APP)
|
||||
2. **信息分析**: 分析包大小、平台分布、版本信息
|
||||
3. **内容解析**: 批量解析包的元信息、权限、资源
|
||||
4. **批量上传**: 自动上传解析成功的包文件
|
||||
5. **报告生成**: 生成详细的处理报告和统计信息
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('batch-package-processing', {
|
||||
args: [],
|
||||
options: {
|
||||
directory: './packages', // 包文件目录
|
||||
pattern: '*.{ipa,apk,app}', // 文件匹配模式
|
||||
skipUpload: false // 跳过上传步骤
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 批量包文件处理
|
||||
- 包文件质量检查
|
||||
- 自动化包管理
|
||||
|
||||
---
|
||||
|
||||
## 👤 User模块工作流
|
||||
|
||||
> User模块已经在现有代码中包含了完善的工作流:
|
||||
|
||||
### 1. 认证状态检查工作流 (`auth-check`)
|
||||
|
||||
**功能特性**:
|
||||
- 🔐 会话状态检查
|
||||
- ✅ 服务端验证
|
||||
- 👤 用户信息获取
|
||||
- 🔄 自动登录支持
|
||||
|
||||
### 2. 完整登录流程工作流 (`login-flow`)
|
||||
|
||||
**功能特性**:
|
||||
- 🔍 现有会话检查
|
||||
- 🔐 用户登录执行
|
||||
- ✅ 登录状态验证
|
||||
- 📋 流程状态汇总
|
||||
|
||||
---
|
||||
|
||||
## 🏷️ Version模块工作流
|
||||
|
||||
### 1. 版本发布管理工作流 (`version-release-management`)
|
||||
|
||||
**用途**: 完整的版本发布生命周期管理
|
||||
|
||||
**功能特性**:
|
||||
- 🔍 发布前全面检查
|
||||
- ✅ 版本信息验证
|
||||
- ⚙️ 发布参数配置
|
||||
- 🚀 发布执行和监控
|
||||
- 📊 发布后监控分析
|
||||
- 📋 完整发布报告
|
||||
|
||||
**工作流步骤**:
|
||||
1. **发布前检查**: 验证版本格式、平台支持、构建环境、依赖完整性
|
||||
2. **版本验证**: 检查版本冲突、规范性、发布类型
|
||||
3. **发布准备**: 生成发布说明、配置分发参数、设置回滚策略
|
||||
4. **执行发布**: 上传版本包、更新信息、配置分发、激活版本
|
||||
5. **发布监控**: 监控下载成功率、安装成功率、崩溃率等关键指标
|
||||
6. **发布总结**: 生成完整的发布报告和统计信息
|
||||
|
||||
**使用示例**:
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('version-release-management', {
|
||||
args: [],
|
||||
options: {
|
||||
name: 'v2.1.0', // 版本名称 (必需)
|
||||
description: 'Major update', // 版本描述
|
||||
platform: 'ios', // 目标平台 (必需)
|
||||
rollout: 50, // 发布覆盖率
|
||||
packageVersion: '2.1.0', // 包版本号
|
||||
dryRun: false, // 模拟发布
|
||||
force: false // 强制发布
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 正式版本发布
|
||||
- 灰度发布管理
|
||||
- 发布质量控制
|
||||
|
||||
---
|
||||
|
||||
## 🔗 工作流使用示例
|
||||
|
||||
### 1. 完整发布流程组合
|
||||
|
||||
```typescript
|
||||
// 完整的应用发布流程
|
||||
async function completeReleaseFlow() {
|
||||
// 1. 应用初始化
|
||||
await moduleManager.executeWorkflow('app-initialization', {
|
||||
args: [],
|
||||
options: {
|
||||
name: 'ProductionApp',
|
||||
platform: 'ios',
|
||||
force: true
|
||||
}
|
||||
});
|
||||
|
||||
// 2. 智能打包
|
||||
await moduleManager.executeWorkflow('intelligent-bundle', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'ios',
|
||||
dev: false,
|
||||
optimize: true
|
||||
}
|
||||
});
|
||||
|
||||
// 3. 版本发布
|
||||
await moduleManager.executeWorkflow('version-release-management', {
|
||||
args: [],
|
||||
options: {
|
||||
name: 'v1.0.0',
|
||||
platform: 'ios',
|
||||
rollout: 100
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 多平台批量构建
|
||||
|
||||
```typescript
|
||||
async function multiPlatformBuild() {
|
||||
const platforms = ['ios', 'android', 'harmony'];
|
||||
|
||||
for (const platform of platforms) {
|
||||
await moduleManager.executeWorkflow('intelligent-bundle', {
|
||||
args: [],
|
||||
options: {
|
||||
platform,
|
||||
dev: false,
|
||||
optimize: true
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 增量更新流程
|
||||
|
||||
```typescript
|
||||
async function incrementalUpdateFlow() {
|
||||
// 1. 生成增量包
|
||||
const buildResult = await moduleManager.executeWorkflow('incremental-build', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'android',
|
||||
baseVersion: 'v1.0.0'
|
||||
}
|
||||
});
|
||||
|
||||
// 2. 发布增量更新
|
||||
if (buildResult.success) {
|
||||
await moduleManager.executeWorkflow('version-release-management', {
|
||||
args: [],
|
||||
options: {
|
||||
name: 'v1.0.1',
|
||||
platform: 'android',
|
||||
rollout: 20 // 小范围发布
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 最佳实践
|
||||
|
||||
### 1. 工作流选择指南
|
||||
|
||||
| 场景 | 推荐工作流 | 配置建议 |
|
||||
|------|------------|----------|
|
||||
| 新应用创建 | `app-initialization` | 启用force参数避免冲突 |
|
||||
| 生产发布 | `intelligent-bundle` + `version-release-management` | 关闭dev模式,启用优化 |
|
||||
| 热更新 | `incremental-build` | 指定合适的基准版本 |
|
||||
| 批量管理 | `batch-package-processing` | 定期执行包文件清理 |
|
||||
| 灰度发布 | `version-release-management` | 设置合适的rollout比例 |
|
||||
|
||||
### 2. 错误处理策略
|
||||
|
||||
```typescript
|
||||
async function robustWorkflowExecution() {
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow('app-initialization', {
|
||||
args: [],
|
||||
options: { name: 'MyApp', platform: 'ios' }
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.error('工作流执行失败:', result.error);
|
||||
// 执行回滚或重试逻辑
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('工作流异常:', error);
|
||||
// 异常处理逻辑
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 工作流监控
|
||||
|
||||
```typescript
|
||||
// 工作流执行监控
|
||||
const workflowMonitor = {
|
||||
async executeWithMonitoring(workflowName: string, context: any) {
|
||||
const startTime = Date.now();
|
||||
console.log(`开始执行工作流: ${workflowName}`);
|
||||
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow(workflowName, context);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
console.log(`工作流执行完成: ${workflowName}, 耗时: ${duration}ms`);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime;
|
||||
console.error(`工作流执行失败: ${workflowName}, 耗时: ${duration}ms`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 4. 配置管理
|
||||
|
||||
```typescript
|
||||
// 工作流配置管理
|
||||
const workflowConfigs = {
|
||||
development: {
|
||||
'intelligent-bundle': { dev: true, optimize: false },
|
||||
'version-release-management': { dryRun: true, rollout: 10 }
|
||||
},
|
||||
production: {
|
||||
'intelligent-bundle': { dev: false, optimize: true },
|
||||
'version-release-management': { dryRun: false, rollout: 100 }
|
||||
}
|
||||
};
|
||||
|
||||
async function executeWithConfig(workflowName: string, environment: string) {
|
||||
const config = workflowConfigs[environment]?.[workflowName] || {};
|
||||
|
||||
return await moduleManager.executeWorkflow(workflowName, {
|
||||
args: [],
|
||||
options: config
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 总结
|
||||
|
||||
这些增强的核心工作流为React Native Update CLI提供了:
|
||||
|
||||
1. **完整的应用生命周期管理** - 从创建到发布的全流程覆盖
|
||||
2. **智能化构建和优化** - 自动环境检测和性能优化
|
||||
3. **高效的增量更新** - 减少更新包大小,提升用户体验
|
||||
4. **批量处理能力** - 提高大规模应用管理效率
|
||||
5. **规范化发布流程** - 确保发布质量和一致性
|
||||
|
||||
每个工作流都经过精心设计,包含详细的步骤、错误处理、进度反馈和结果验证,为开发者提供了强大而可靠的自动化工具。
|
376
example/README.md
Normal file
376
example/README.md
Normal file
@@ -0,0 +1,376 @@
|
||||
# Custom Modules and Workflows Examples
|
||||
|
||||
[中文文档](./README.zh-CN.md) | [Chinese Documentation](./README.zh-CN.md)
|
||||
|
||||
This directory contains complete examples of React Native Update CLI custom modules and workflows, demonstrating how to extend the CLI functionality.
|
||||
|
||||
## 📁 Directory Structure
|
||||
|
||||
```
|
||||
example/
|
||||
├── modules/ # Custom module examples
|
||||
│ ├── custom-deploy-module.ts # Custom deployment module
|
||||
│ └── analytics-module.ts # Analytics module
|
||||
├── workflows/ # Custom workflow examples
|
||||
│ └── custom-workflows.ts # Complex workflow collection
|
||||
├── scripts/ # Execution script examples
|
||||
│ ├── register-modules.ts # Module registration and execution
|
||||
│ ├── provider-api-example.ts # Provider API usage examples
|
||||
│ └── workflow-demo.ts # Workflow demonstration script
|
||||
└── README.md # This documentation
|
||||
```
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Run Module Registration and Execution Examples
|
||||
|
||||
```bash
|
||||
# Compile TypeScript (if needed)
|
||||
npm run build
|
||||
|
||||
# Run module examples
|
||||
npx ts-node example/scripts/register-modules.ts
|
||||
```
|
||||
|
||||
### 2. Run Provider API Examples
|
||||
|
||||
```bash
|
||||
npx ts-node example/scripts/provider-api-example.ts
|
||||
```
|
||||
|
||||
### 3. Run Workflow Demonstrations
|
||||
|
||||
```bash
|
||||
# Run all workflow demonstrations
|
||||
npx ts-node example/scripts/workflow-demo.ts
|
||||
|
||||
# Interactive execution of specific workflows
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive canary-deployment --version 1.0.0 --initialRollout 5
|
||||
|
||||
# Multi-environment deployment workflow
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive multi-env-deploy --version 1.0.0
|
||||
|
||||
# Rollback workflow
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive rollback-workflow --targetVersion 0.9.5
|
||||
```
|
||||
|
||||
## 📦 Custom Module Examples
|
||||
|
||||
### 1. Custom Deployment Module (`custom-deploy-module.ts`)
|
||||
|
||||
This module demonstrates how to create a complete deployment management module, including:
|
||||
|
||||
#### Commands:
|
||||
- `deploy-dev`: Deploy to development environment
|
||||
- `deploy-prod`: Deploy to production environment
|
||||
- `rollback`: Rollback to specified version
|
||||
|
||||
#### Workflows:
|
||||
- `full-deploy`: Complete deployment process (development → testing → production)
|
||||
- `hotfix-deploy`: Quick hotfix deployment process
|
||||
|
||||
#### Usage Example:
|
||||
```typescript
|
||||
import { moduleManager } from 'react-native-update-cli';
|
||||
import { customDeployModule } from './modules/custom-deploy-module';
|
||||
|
||||
// Register module
|
||||
moduleManager.registerModule(customDeployModule);
|
||||
|
||||
// Execute development deployment
|
||||
await moduleManager.executeCommand('deploy-dev', {
|
||||
args: [],
|
||||
options: { platform: 'ios', force: true }
|
||||
});
|
||||
|
||||
// Execute complete deployment workflow
|
||||
await moduleManager.executeWorkflow('full-deploy', {
|
||||
args: [],
|
||||
options: { version: '1.2.3' }
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Analytics Module (`analytics-module.ts`)
|
||||
|
||||
Demonstrates how to create analytics and statistics functionality:
|
||||
|
||||
#### Commands:
|
||||
- `track-deployment`: Record deployment statistics
|
||||
- `deployment-report`: Generate deployment reports
|
||||
|
||||
#### Workflows:
|
||||
- `deploy-with-analytics`: Deployment process with analytics
|
||||
|
||||
## 🔄 Custom Workflow Examples
|
||||
|
||||
### 1. Canary Deployment Workflow (`canary-deployment`)
|
||||
|
||||
Implements a complete canary deployment process:
|
||||
|
||||
- ✅ Prepare canary deployment environment
|
||||
- ✅ Initial small-scale deployment
|
||||
- ✅ Monitor key metrics
|
||||
- ✅ Automatically expand deployment based on metrics
|
||||
- ✅ Final validation
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('canary-deployment', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
initialRollout: 10, // 初始10%用户
|
||||
autoExpand: true // 自动扩大范围
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Multi-Environment Deployment Workflow (`multi-env-deploy`)
|
||||
|
||||
Implements a standard multi-environment deployment process:
|
||||
|
||||
- ✅ Deploy to development environment
|
||||
- ✅ Run integration tests
|
||||
- ✅ Deploy to staging environment
|
||||
- ✅ Run end-to-end tests
|
||||
- ✅ Deploy to production environment
|
||||
- ✅ Post-deployment validation
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('multi-env-deploy', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
skipProduction: false, // 不跳过生产部署
|
||||
forceProduction: false // 测试失败时不强制部署
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Rollback Workflow (`rollback-workflow`)
|
||||
|
||||
Safe application rollback process:
|
||||
|
||||
- ✅ Validate target version
|
||||
- ✅ Backup current state
|
||||
- ✅ Execute rollback operation
|
||||
- ✅ Verify rollback results
|
||||
- ✅ Notify relevant personnel
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('rollback-workflow', {
|
||||
args: [],
|
||||
options: {
|
||||
targetVersion: '2.0.5',
|
||||
skipVerification: false
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 🛠️ Provider API Usage Examples
|
||||
|
||||
Provider API provides programmatic interfaces suitable for integration in applications:
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```typescript
|
||||
import { moduleManager } from 'react-native-update-cli';
|
||||
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
// Bundle application
|
||||
const bundleResult = await provider.bundle({
|
||||
platform: 'ios',
|
||||
dev: false,
|
||||
sourcemap: true
|
||||
});
|
||||
|
||||
// Publish version
|
||||
const publishResult = await provider.publish({
|
||||
name: 'v1.0.0',
|
||||
description: 'Bug fixes',
|
||||
rollout: 100
|
||||
});
|
||||
|
||||
// Upload file
|
||||
const uploadResult = await provider.upload({
|
||||
filePath: 'app.ipa',
|
||||
platform: 'ios'
|
||||
});
|
||||
```
|
||||
|
||||
### Application Management
|
||||
|
||||
```typescript
|
||||
// Create application
|
||||
await provider.createApp('MyApp', 'ios');
|
||||
|
||||
// Get current application
|
||||
const { appId, platform } = await provider.getSelectedApp('ios');
|
||||
|
||||
// List versions
|
||||
const versions = await provider.listVersions(appId);
|
||||
|
||||
// Update version
|
||||
await provider.updateVersion(appId, versionId, {
|
||||
name: 'v1.1.0',
|
||||
description: 'New features'
|
||||
});
|
||||
```
|
||||
|
||||
### Automation Service Class
|
||||
|
||||
```typescript
|
||||
class DeploymentService {
|
||||
private provider = moduleManager.getProvider();
|
||||
|
||||
async buildAndPublish(platform: Platform, version: string) {
|
||||
// 1. Bundle
|
||||
const bundleResult = await this.provider.bundle({
|
||||
platform, dev: false, sourcemap: true
|
||||
});
|
||||
|
||||
// 2. Publish
|
||||
const publishResult = await this.provider.publish({
|
||||
name: version, rollout: 100
|
||||
});
|
||||
|
||||
return { bundleResult, publishResult };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 Advanced Features
|
||||
|
||||
### 1. Workflow Validation
|
||||
|
||||
```typescript
|
||||
const workflow: CustomWorkflow = {
|
||||
name: 'my-workflow',
|
||||
steps: [...],
|
||||
validate: (context) => {
|
||||
if (!context.options.version) {
|
||||
console.error('Version number must be specified');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Conditional Execution
|
||||
|
||||
```typescript
|
||||
const step: WorkflowStep = {
|
||||
name: 'conditional-step',
|
||||
execute: async (context) => { /* ... */ },
|
||||
condition: (context) => {
|
||||
return context.options.environment === 'production';
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 3. Error Handling
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const result = await moduleManager.executeCommand('deploy-prod', {
|
||||
args: [],
|
||||
options: {} // Missing required parameters
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Execution failed:', error.message);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Custom Workflow Registration
|
||||
|
||||
```typescript
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
provider.registerWorkflow({
|
||||
name: 'custom-workflow',
|
||||
description: 'Custom workflow',
|
||||
steps: [
|
||||
{
|
||||
name: 'step1',
|
||||
execute: async (context, previousResult) => {
|
||||
// Execution logic
|
||||
return { step1: 'completed' };
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// Execute workflow
|
||||
await provider.executeWorkflow('custom-workflow', {
|
||||
args: [],
|
||||
options: {}
|
||||
});
|
||||
```
|
||||
|
||||
## 📝 Best Practices
|
||||
|
||||
### 1. Module Design
|
||||
|
||||
- **Single Responsibility**: Each module focuses on specific functional domains
|
||||
- **Clear Naming**: Use descriptive command and option names
|
||||
- **Complete Documentation**: Provide descriptions for all commands and options
|
||||
- **Error Handling**: Provide clear error messages and recovery suggestions
|
||||
|
||||
### 2. Workflow Design
|
||||
|
||||
- **Atomic Operations**: Each step should be atomic and independently executable
|
||||
- **State Passing**: Properly use previousResult to pass state
|
||||
- **Error Recovery**: Consider cleanup and recovery mechanisms for failures
|
||||
- **Progress Feedback**: Provide clear progress information to users
|
||||
|
||||
### 3. Development Recommendations
|
||||
|
||||
- **Type Safety**: Make full use of the TypeScript type system
|
||||
- **Test Coverage**: Write tests for custom modules
|
||||
- **Documentation Maintenance**: Keep examples and documentation synchronized
|
||||
- **Version Management**: Set appropriate version numbers for modules
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. **模块注册失败**
|
||||
```typescript
|
||||
// 确保模块符合 CLIModule 接口
|
||||
const module: CLIModule = {
|
||||
name: 'my-module',
|
||||
version: '1.0.0',
|
||||
commands: [...],
|
||||
workflows: [...]
|
||||
};
|
||||
```
|
||||
|
||||
2. **Command Execution Failed**
|
||||
```typescript
|
||||
// Check command name and parameters
|
||||
await moduleManager.executeCommand('correct-command-name', {
|
||||
args: [],
|
||||
options: { requiredParam: 'value' }
|
||||
});
|
||||
```
|
||||
|
||||
3. **Workflow Validation Failed**
|
||||
```typescript
|
||||
// Ensure all required options are provided
|
||||
await moduleManager.executeWorkflow('workflow-name', {
|
||||
args: [],
|
||||
options: { version: '1.0.0' } // Required parameter
|
||||
});
|
||||
```
|
||||
|
||||
## 📖 Related Documentation
|
||||
|
||||
- [Main Project README](../README.md)
|
||||
- [Modular Architecture Documentation](../docs/architecture.md)
|
||||
- [API Reference Documentation](../docs/api-reference.md)
|
||||
- [Contributing Guide](../CONTRIBUTING.md)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Welcome to submit more examples and improvement suggestions! Please check the main project's contributing guide.
|
374
example/README.zh-CN.md
Normal file
374
example/README.zh-CN.md
Normal file
@@ -0,0 +1,374 @@
|
||||
# 自定义模块和工作流示例
|
||||
|
||||
这个目录包含了 React Native Update CLI 自定义模块和工作流的完整示例,演示如何扩展 CLI 的功能。
|
||||
|
||||
## 📁 目录结构
|
||||
|
||||
```
|
||||
example/
|
||||
├── modules/ # 自定义模块示例
|
||||
│ ├── custom-deploy-module.ts # 自定义部署模块
|
||||
│ └── analytics-module.ts # 分析统计模块
|
||||
├── workflows/ # 自定义工作流示例
|
||||
│ └── custom-workflows.ts # 复杂工作流集合
|
||||
├── scripts/ # 执行脚本示例
|
||||
│ ├── register-modules.ts # 模块注册和执行
|
||||
│ ├── provider-api-example.ts # Provider API 使用示例
|
||||
│ └── workflow-demo.ts # 工作流演示脚本
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 1. 运行模块注册和执行示例
|
||||
|
||||
```bash
|
||||
# 编译TypeScript (如果需要)
|
||||
npm run build
|
||||
|
||||
# 运行模块示例
|
||||
npx ts-node example/scripts/register-modules.ts
|
||||
```
|
||||
|
||||
### 2. 运行Provider API示例
|
||||
|
||||
```bash
|
||||
npx ts-node example/scripts/provider-api-example.ts
|
||||
```
|
||||
|
||||
### 3. 运行工作流演示
|
||||
|
||||
```bash
|
||||
# 运行所有工作流演示
|
||||
npx ts-node example/scripts/workflow-demo.ts
|
||||
|
||||
# 交互式执行特定工作流
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive canary-deployment --version 1.0.0 --initialRollout 5
|
||||
|
||||
# 多环境部署工作流
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive multi-env-deploy --version 1.0.0
|
||||
|
||||
# 回滚工作流
|
||||
npx ts-node example/scripts/workflow-demo.ts interactive rollback-workflow --targetVersion 0.9.5
|
||||
```
|
||||
|
||||
## 📦 自定义模块示例
|
||||
|
||||
### 1. 自定义部署模块 (`custom-deploy-module.ts`)
|
||||
|
||||
这个模块演示了如何创建一个完整的部署管理模块,包含:
|
||||
|
||||
#### 命令:
|
||||
- `deploy-dev`: 部署到开发环境
|
||||
- `deploy-prod`: 部署到生产环境
|
||||
- `rollback`: 回滚到指定版本
|
||||
|
||||
#### 工作流:
|
||||
- `full-deploy`: 完整部署流程(开发 → 测试 → 生产)
|
||||
- `hotfix-deploy`: 热修复快速部署流程
|
||||
|
||||
#### 使用示例:
|
||||
```typescript
|
||||
import { moduleManager } from 'react-native-update-cli';
|
||||
import { customDeployModule } from './modules/custom-deploy-module';
|
||||
|
||||
// 注册模块
|
||||
moduleManager.registerModule(customDeployModule);
|
||||
|
||||
// 执行开发部署
|
||||
await moduleManager.executeCommand('deploy-dev', {
|
||||
args: [],
|
||||
options: { platform: 'ios', force: true }
|
||||
});
|
||||
|
||||
// 执行完整部署工作流
|
||||
await moduleManager.executeWorkflow('full-deploy', {
|
||||
args: [],
|
||||
options: { version: '1.2.3' }
|
||||
});
|
||||
```
|
||||
|
||||
### 2. 分析统计模块 (`analytics-module.ts`)
|
||||
|
||||
演示如何创建分析和统计功能:
|
||||
|
||||
#### 命令:
|
||||
- `track-deployment`: 记录部署统计信息
|
||||
- `deployment-report`: 生成部署报告
|
||||
|
||||
#### 工作流:
|
||||
- `deploy-with-analytics`: 带统计的部署流程
|
||||
|
||||
## 🔄 自定义工作流示例
|
||||
|
||||
### 1. 灰度发布工作流 (`canary-deployment`)
|
||||
|
||||
实现完整的灰度发布流程:
|
||||
|
||||
- ✅ 准备灰度发布环境
|
||||
- ✅ 初始小范围部署
|
||||
- ✅ 监控关键指标
|
||||
- ✅ 基于指标自动扩大发布范围
|
||||
- ✅ 最终验证
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('canary-deployment', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
initialRollout: 10, // 初始10%用户
|
||||
autoExpand: true // 自动扩大范围
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 2. 多环境发布工作流 (`multi-env-deploy`)
|
||||
|
||||
实现标准的多环境发布流程:
|
||||
|
||||
- ✅ 部署到开发环境
|
||||
- ✅ 运行集成测试
|
||||
- ✅ 部署到预发布环境
|
||||
- ✅ 运行端到端测试
|
||||
- ✅ 部署到生产环境
|
||||
- ✅ 部署后验证
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('multi-env-deploy', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
skipProduction: false, // 不跳过生产部署
|
||||
forceProduction: false // 测试失败时不强制部署
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 3. 回滚工作流 (`rollback-workflow`)
|
||||
|
||||
安全的应用回滚流程:
|
||||
|
||||
- ✅ 验证目标版本
|
||||
- ✅ 备份当前状态
|
||||
- ✅ 执行回滚操作
|
||||
- ✅ 验证回滚结果
|
||||
- ✅ 通知相关人员
|
||||
|
||||
```typescript
|
||||
await moduleManager.executeWorkflow('rollback-workflow', {
|
||||
args: [],
|
||||
options: {
|
||||
targetVersion: '2.0.5',
|
||||
skipVerification: false
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 🛠️ Provider API 使用示例
|
||||
|
||||
Provider API 提供了编程式接口,适合在应用程序中集成:
|
||||
|
||||
### 基本使用
|
||||
|
||||
```typescript
|
||||
import { moduleManager } from 'react-native-update-cli';
|
||||
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
// 打包应用
|
||||
const bundleResult = await provider.bundle({
|
||||
platform: 'ios',
|
||||
dev: false,
|
||||
sourcemap: true
|
||||
});
|
||||
|
||||
// 发布版本
|
||||
const publishResult = await provider.publish({
|
||||
name: 'v1.0.0',
|
||||
description: 'Bug fixes',
|
||||
rollout: 100
|
||||
});
|
||||
|
||||
// 上传文件
|
||||
const uploadResult = await provider.upload({
|
||||
filePath: 'app.ipa',
|
||||
platform: 'ios'
|
||||
});
|
||||
```
|
||||
|
||||
### 应用管理
|
||||
|
||||
```typescript
|
||||
// 创建应用
|
||||
await provider.createApp('MyApp', 'ios');
|
||||
|
||||
// 获取当前应用
|
||||
const { appId, platform } = await provider.getSelectedApp('ios');
|
||||
|
||||
// 列出版本
|
||||
const versions = await provider.listVersions(appId);
|
||||
|
||||
// 更新版本
|
||||
await provider.updateVersion(appId, versionId, {
|
||||
name: 'v1.1.0',
|
||||
description: 'New features'
|
||||
});
|
||||
```
|
||||
|
||||
### 自动化服务类
|
||||
|
||||
```typescript
|
||||
class DeploymentService {
|
||||
private provider = moduleManager.getProvider();
|
||||
|
||||
async buildAndPublish(platform: Platform, version: string) {
|
||||
// 1. 打包
|
||||
const bundleResult = await this.provider.bundle({
|
||||
platform, dev: false, sourcemap: true
|
||||
});
|
||||
|
||||
// 2. 发布
|
||||
const publishResult = await this.provider.publish({
|
||||
name: version, rollout: 100
|
||||
});
|
||||
|
||||
return { bundleResult, publishResult };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 高级特性
|
||||
|
||||
### 1. 工作流验证
|
||||
|
||||
```typescript
|
||||
const workflow: CustomWorkflow = {
|
||||
name: 'my-workflow',
|
||||
steps: [...],
|
||||
validate: (context) => {
|
||||
if (!context.options.version) {
|
||||
console.error('必须指定版本号');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 2. 条件执行
|
||||
|
||||
```typescript
|
||||
const step: WorkflowStep = {
|
||||
name: 'conditional-step',
|
||||
execute: async (context) => { /* ... */ },
|
||||
condition: (context) => {
|
||||
return context.options.environment === 'production';
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 3. 错误处理
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const result = await moduleManager.executeCommand('deploy-prod', {
|
||||
args: [],
|
||||
options: {} // 缺少必需参数
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('执行失败:', error.message);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 自定义工作流注册
|
||||
|
||||
```typescript
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
provider.registerWorkflow({
|
||||
name: 'custom-workflow',
|
||||
description: '自定义工作流',
|
||||
steps: [
|
||||
{
|
||||
name: 'step1',
|
||||
execute: async (context, previousResult) => {
|
||||
// 执行逻辑
|
||||
return { step1: 'completed' };
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 执行工作流
|
||||
await provider.executeWorkflow('custom-workflow', {
|
||||
args: [],
|
||||
options: {}
|
||||
});
|
||||
```
|
||||
|
||||
## 📝 最佳实践
|
||||
|
||||
### 1. 模块设计
|
||||
|
||||
- **单一职责**: 每个模块专注于特定功能领域
|
||||
- **清晰命名**: 使用描述性的命令和选项名称
|
||||
- **完整文档**: 为所有命令和选项提供描述
|
||||
- **错误处理**: 提供清晰的错误信息和恢复建议
|
||||
|
||||
### 2. 工作流设计
|
||||
|
||||
- **原子操作**: 每个步骤应该是原子的,可独立执行
|
||||
- **状态传递**: 合理使用 previousResult 传递状态
|
||||
- **错误恢复**: 考虑失败时的清理和恢复机制
|
||||
- **进度反馈**: 提供清晰的进度信息给用户
|
||||
|
||||
### 3. 开发建议
|
||||
|
||||
- **类型安全**: 充分利用 TypeScript 类型系统
|
||||
- **测试覆盖**: 为自定义模块编写测试
|
||||
- **文档维护**: 保持示例和文档的同步更新
|
||||
- **版本管理**: 为模块设置合适的版本号
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. **模块注册失败**
|
||||
```typescript
|
||||
// 确保模块符合 CLIModule 接口
|
||||
const module: CLIModule = {
|
||||
name: 'my-module',
|
||||
version: '1.0.0',
|
||||
commands: [...],
|
||||
workflows: [...]
|
||||
};
|
||||
```
|
||||
|
||||
2. **命令执行失败**
|
||||
```typescript
|
||||
// 检查命令名称和参数
|
||||
await moduleManager.executeCommand('correct-command-name', {
|
||||
args: [],
|
||||
options: { requiredParam: 'value' }
|
||||
});
|
||||
```
|
||||
|
||||
3. **工作流验证失败**
|
||||
```typescript
|
||||
// 确保提供所有必需的选项
|
||||
await moduleManager.executeWorkflow('workflow-name', {
|
||||
args: [],
|
||||
options: { version: '1.0.0' } // 必需参数
|
||||
});
|
||||
```
|
||||
|
||||
## 📖 相关文档
|
||||
|
||||
- [主项目 README](../README.md)
|
||||
- [模块化架构文档](../docs/architecture.md)
|
||||
- [API 参考文档](../docs/api-reference.md)
|
||||
- [贡献指南](../CONTRIBUTING.md)
|
||||
|
||||
## 🤝 贡献
|
||||
|
||||
欢迎提交更多示例和改进建议!请查看主项目的贡献指南。
|
149
example/modules/analytics-module.ts
Normal file
149
example/modules/analytics-module.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import type {
|
||||
CLIModule,
|
||||
CLIProvider,
|
||||
CommandContext,
|
||||
CommandResult,
|
||||
} from '../../src/types';
|
||||
|
||||
/**
|
||||
* 分析统计模块示例
|
||||
* 演示一个简单的分析统计功能模块
|
||||
*/
|
||||
export const analyticsModule: CLIModule = {
|
||||
name: 'analytics',
|
||||
version: '1.0.0',
|
||||
commands: [
|
||||
{
|
||||
name: 'track-deployment',
|
||||
description: '记录部署统计信息',
|
||||
handler: async (context: CommandContext): Promise<CommandResult> => {
|
||||
console.log('📊 记录部署统计信息...');
|
||||
|
||||
const { platform, environment, version } = context.options;
|
||||
|
||||
const deploymentData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
platform: platform || 'unknown',
|
||||
environment: environment || 'unknown',
|
||||
version: version || 'unknown',
|
||||
success: true,
|
||||
duration: Math.floor(Math.random() * 1000) + 500, // 模拟部署时长
|
||||
};
|
||||
|
||||
console.log('✅ 部署统计已记录:');
|
||||
console.log(JSON.stringify(deploymentData, null, 2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: deploymentData,
|
||||
};
|
||||
},
|
||||
options: {
|
||||
platform: {
|
||||
hasValue: true,
|
||||
description: '平台',
|
||||
},
|
||||
environment: {
|
||||
hasValue: true,
|
||||
description: '环境',
|
||||
},
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '版本',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'deployment-report',
|
||||
description: '生成部署报告',
|
||||
handler: async (context: CommandContext): Promise<CommandResult> => {
|
||||
console.log('📈 生成部署报告...');
|
||||
|
||||
const { days = 7 } = context.options;
|
||||
|
||||
// 模拟生成报告数据
|
||||
const report = {
|
||||
period: `最近 ${days} 天`,
|
||||
totalDeployments: Math.floor(Math.random() * 50) + 10,
|
||||
successRate: 95.5,
|
||||
averageDuration: '2.3分钟',
|
||||
platformBreakdown: {
|
||||
ios: 45,
|
||||
android: 38,
|
||||
harmony: 12,
|
||||
},
|
||||
environmentBreakdown: {
|
||||
development: 60,
|
||||
staging: 25,
|
||||
production: 15,
|
||||
},
|
||||
};
|
||||
|
||||
console.log('📊 部署报告:');
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: report,
|
||||
};
|
||||
},
|
||||
options: {
|
||||
days: {
|
||||
hasValue: true,
|
||||
default: 7,
|
||||
description: '报告天数',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
workflows: [
|
||||
{
|
||||
name: 'deploy-with-analytics',
|
||||
description: '带统计的部署流程',
|
||||
steps: [
|
||||
{
|
||||
name: 'pre-deployment',
|
||||
description: '部署前准备',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('📋 部署前准备...');
|
||||
return { startTime: Date.now() };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deployment',
|
||||
description: '执行部署',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🚀 执行部署...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
return { ...previousResult, deploymentCompleted: true };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'record-analytics',
|
||||
description: '记录统计信息',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('📊 记录统计信息...');
|
||||
const duration = Date.now() - previousResult.startTime;
|
||||
const analytics = {
|
||||
duration,
|
||||
timestamp: new Date().toISOString(),
|
||||
success: true,
|
||||
};
|
||||
console.log(`✅ 部署完成,耗时 ${duration}ms`);
|
||||
return { ...previousResult, analytics };
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
init: (provider: CLIProvider) => {
|
||||
console.log('📊 分析统计模块已初始化');
|
||||
},
|
||||
|
||||
cleanup: () => {
|
||||
console.log('🧹 分析统计模块清理完成');
|
||||
},
|
||||
};
|
315
example/modules/custom-deploy-module.ts
Normal file
315
example/modules/custom-deploy-module.ts
Normal file
@@ -0,0 +1,315 @@
|
||||
import type {
|
||||
CLIModule,
|
||||
CLIProvider,
|
||||
CommandContext,
|
||||
CommandDefinition,
|
||||
CommandResult,
|
||||
CustomWorkflow,
|
||||
} from '../../src/types';
|
||||
|
||||
/**
|
||||
* 自定义部署模块示例
|
||||
* 演示如何创建一个包含多个命令和工作流的自定义模块
|
||||
*/
|
||||
export const customDeployModule: CLIModule = {
|
||||
name: 'custom-deploy',
|
||||
version: '1.0.0',
|
||||
|
||||
commands: [
|
||||
{
|
||||
name: 'deploy-dev',
|
||||
description: '部署到开发环境',
|
||||
handler: async (context: CommandContext): Promise<CommandResult> => {
|
||||
console.log('🚀 开始部署到开发环境...');
|
||||
|
||||
const { platform = 'ios', force = false } = context.options;
|
||||
|
||||
try {
|
||||
// 模拟部署逻辑
|
||||
console.log(`📱 平台: ${platform}`);
|
||||
console.log(`🔧 强制部署: ${force ? '是' : '否'}`);
|
||||
|
||||
// 模拟一些部署步骤
|
||||
console.log('1. 检查环境配置...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('2. 构建应用包...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
console.log('3. 上传到开发服务器...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('✅ 部署到开发环境完成!');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
environment: 'development',
|
||||
platform,
|
||||
deployTime: new Date().toISOString(),
|
||||
buildId: `dev-${Date.now()}`,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '部署失败',
|
||||
};
|
||||
}
|
||||
},
|
||||
options: {
|
||||
platform: {
|
||||
hasValue: true,
|
||||
default: 'ios',
|
||||
description: '目标平台 (ios/android/harmony)',
|
||||
},
|
||||
force: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '强制部署,跳过确认',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'deploy-prod',
|
||||
description: '部署到生产环境',
|
||||
handler: async (context: CommandContext): Promise<CommandResult> => {
|
||||
console.log('🔥 开始部署到生产环境...');
|
||||
|
||||
const { version, rollout = 100 } = context.options;
|
||||
|
||||
if (!version) {
|
||||
return {
|
||||
success: false,
|
||||
error: '生产部署必须指定版本号',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`📦 版本: ${version}`);
|
||||
console.log(`📊 发布比例: ${rollout}%`);
|
||||
|
||||
console.log('1. 安全检查...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('2. 生产构建...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log('3. 部署到生产环境...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
console.log('4. 健康检查...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
console.log('🎉 生产部署完成!');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
environment: 'production',
|
||||
version,
|
||||
rollout,
|
||||
deployTime: new Date().toISOString(),
|
||||
buildId: `prod-${Date.now()}`,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '生产部署失败',
|
||||
};
|
||||
}
|
||||
},
|
||||
options: {
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '版本号 (必需)',
|
||||
},
|
||||
rollout: {
|
||||
hasValue: true,
|
||||
default: 100,
|
||||
description: '发布比例 (0-100)',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'rollback',
|
||||
description: '回滚到指定版本',
|
||||
handler: async (context: CommandContext): Promise<CommandResult> => {
|
||||
console.log('🔄 开始回滚操作...');
|
||||
|
||||
const { version, immediate = false } = context.options;
|
||||
|
||||
if (!version) {
|
||||
return {
|
||||
success: false,
|
||||
error: '回滚操作必须指定目标版本',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`🎯 目标版本: ${version}`);
|
||||
console.log(`⚡ 立即回滚: ${immediate ? '是' : '否'}`);
|
||||
|
||||
console.log('1. 验证目标版本...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
console.log('2. 准备回滚...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('3. 执行回滚...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1200));
|
||||
|
||||
console.log('✅ 回滚完成!');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
targetVersion: version,
|
||||
rollbackTime: new Date().toISOString(),
|
||||
immediate,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '回滚失败',
|
||||
};
|
||||
}
|
||||
},
|
||||
options: {
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '目标版本号 (必需)',
|
||||
},
|
||||
immediate: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '立即回滚,不等待确认',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
workflows: [
|
||||
{
|
||||
name: 'full-deploy',
|
||||
description: '完整部署流程:开发 -> 测试 -> 生产',
|
||||
steps: [
|
||||
{
|
||||
name: 'deploy-to-dev',
|
||||
description: '部署到开发环境',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('🔧 步骤 1: 部署到开发环境');
|
||||
// 这里可以调用其他命令或执行自定义逻辑
|
||||
return { environment: 'dev', status: 'completed' };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'run-tests',
|
||||
description: '运行自动化测试',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🧪 步骤 2: 运行自动化测试');
|
||||
console.log(' - 单元测试...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
console.log(' - 集成测试...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
console.log(' - E2E测试...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
return { ...previousResult, tests: 'passed' };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deploy-to-prod',
|
||||
description: '部署到生产环境',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🚀 步骤 3: 部署到生产环境');
|
||||
if (previousResult.tests !== 'passed') {
|
||||
throw new Error('测试未通过,无法部署到生产环境');
|
||||
}
|
||||
return {
|
||||
...previousResult,
|
||||
environment: 'production',
|
||||
status: 'deployed',
|
||||
};
|
||||
},
|
||||
condition: (context: CommandContext) => {
|
||||
// 只有在非跳过生产部署的情况下才执行
|
||||
return !context.options.skipProd;
|
||||
},
|
||||
},
|
||||
],
|
||||
validate: (context: CommandContext) => {
|
||||
if (!context.options.version) {
|
||||
console.error('❌ 完整部署流程需要指定版本号');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
options: {
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '版本号 (必需)',
|
||||
},
|
||||
skipProd: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '跳过生产部署',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'hotfix-deploy',
|
||||
description: '热修复快速部署流程',
|
||||
steps: [
|
||||
{
|
||||
name: 'validate-hotfix',
|
||||
description: '验证热修复',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('🔍 验证热修复内容...');
|
||||
const { hotfixId } = context.options;
|
||||
if (!hotfixId) {
|
||||
throw new Error('缺少热修复ID');
|
||||
}
|
||||
return { hotfixId, validated: true };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'emergency-deploy',
|
||||
description: '紧急部署',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🚨 执行紧急部署...');
|
||||
console.log('⚡ 快速构建...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
console.log('🚀 立即发布...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
return {
|
||||
...previousResult,
|
||||
deployed: true,
|
||||
deployTime: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
options: {
|
||||
hotfixId: {
|
||||
hasValue: true,
|
||||
description: '热修复ID (必需)',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
init: (provider: CLIProvider) => {
|
||||
console.log('🎯 自定义部署模块已初始化');
|
||||
console.log(' 可用命令: deploy-dev, deploy-prod, rollback');
|
||||
console.log(' 可用工作流: full-deploy, hotfix-deploy');
|
||||
},
|
||||
|
||||
cleanup: () => {
|
||||
console.log('🧹 自定义部署模块清理完成');
|
||||
},
|
||||
};
|
41
example/package.json
Normal file
41
example/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "react-native-update-cli-examples",
|
||||
"version": "1.0.0",
|
||||
"description": "React Native Update CLI 自定义模块和工作流示例",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit --skipLibCheck",
|
||||
"register-modules": "ts-node scripts/register-modules.ts",
|
||||
"provider-demo": "ts-node scripts/provider-api-example.ts",
|
||||
"workflow-demo": "ts-node scripts/workflow-demo.ts",
|
||||
"workflow-interactive": "ts-node scripts/workflow-demo.ts interactive",
|
||||
"enhanced-workflow-demo": "ts-node scripts/enhanced-workflow-demo.ts",
|
||||
"enhanced-workflow-interactive": "ts-node scripts/enhanced-workflow-demo.ts interactive",
|
||||
"demo:all": "npm run register-modules && npm run provider-demo && npm run workflow-demo && npm run enhanced-workflow-demo",
|
||||
"demo:canary": "npm run workflow-interactive canary-deployment -- --version 1.0.0 --initialRollout 5",
|
||||
"demo:multi-env": "npm run workflow-interactive multi-env-deploy -- --version 1.0.0",
|
||||
"demo:rollback": "npm run workflow-interactive rollback-workflow -- --targetVersion 0.9.5",
|
||||
"demo:app-init": "npm run enhanced-workflow-interactive app-initialization -- --name MyApp --platform ios",
|
||||
"demo:smart-bundle": "npm run enhanced-workflow-interactive intelligent-bundle -- --platform android --optimize true",
|
||||
"demo:version-release": "npm run enhanced-workflow-interactive version-release-management -- --name v1.0.0 --platform ios --dryRun true"
|
||||
},
|
||||
"dependencies": {
|
||||
"react-native-update-cli": "file:../"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"ts-node": "^10.9.0",
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"keywords": [
|
||||
"react-native",
|
||||
"update",
|
||||
"cli",
|
||||
"module",
|
||||
"workflow",
|
||||
"example",
|
||||
"custom"
|
||||
],
|
||||
"author": "reactnativecn",
|
||||
"license": "BSD-3-Clause"
|
||||
}
|
552
example/scripts/enhanced-workflow-demo.ts
Normal file
552
example/scripts/enhanced-workflow-demo.ts
Normal file
@@ -0,0 +1,552 @@
|
||||
#!/usr/bin/env ts-node
|
||||
|
||||
import { moduleManager } from '../../src/module-manager';
|
||||
import { enhancedCoreWorkflows } from '../workflows/enhanced-core-workflows';
|
||||
|
||||
/**
|
||||
* 增强核心工作流演示脚本
|
||||
* 展示如何使用为核心模块设计的高级工作流
|
||||
*/
|
||||
|
||||
async function registerEnhancedWorkflows() {
|
||||
console.log('📦 注册增强核心工作流...\n');
|
||||
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
// 注册所有增强核心工作流
|
||||
enhancedCoreWorkflows.forEach((workflow) => {
|
||||
provider.registerWorkflow(workflow);
|
||||
console.log(`✅ 注册工作流: ${workflow.name}`);
|
||||
console.log(` 描述: ${workflow.description}`);
|
||||
console.log(` 步骤数: ${workflow.steps.length}`);
|
||||
console.log();
|
||||
});
|
||||
|
||||
console.log('📋 所有增强核心工作流注册完成\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示App模块工作流
|
||||
*/
|
||||
async function demonstrateAppWorkflows() {
|
||||
console.log('📱 演示App模块增强工作流\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
// 1. 应用初始化工作流
|
||||
console.log('🚀 应用初始化工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const initResult = await moduleManager.executeWorkflow(
|
||||
'app-initialization',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
name: 'MyAwesomeApp',
|
||||
platform: 'ios',
|
||||
downloadUrl: 'https://example.com/download',
|
||||
force: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 应用初始化结果:');
|
||||
console.log(
|
||||
`创建状态: ${initResult.data?.created ? '✅ 成功' : '❌ 失败'}`,
|
||||
);
|
||||
console.log(
|
||||
`配置状态: ${initResult.data?.configured ? '✅ 成功' : '❌ 失败'}`,
|
||||
);
|
||||
console.log(
|
||||
`验证状态: ${initResult.data?.verified ? '✅ 成功' : '❌ 失败'}`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 应用初始化工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '-'.repeat(40));
|
||||
|
||||
// 2. 多平台应用管理工作流
|
||||
console.log('\\n🌍 多平台应用管理工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const managementResult = await moduleManager.executeWorkflow(
|
||||
'multi-platform-app-management',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
includeInactive: true,
|
||||
autoOptimize: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 多平台管理结果:');
|
||||
if (managementResult.data?.analysis) {
|
||||
const analysis = managementResult.data.analysis;
|
||||
console.log(`总应用数: ${analysis.totalApps}`);
|
||||
console.log(`活跃应用: ${analysis.activeApps}`);
|
||||
console.log(`平台分布: ${JSON.stringify(analysis.platformDistribution)}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 多平台应用管理工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示Bundle模块工作流
|
||||
*/
|
||||
async function demonstrateBundleWorkflows() {
|
||||
console.log('📦 演示Bundle模块增强工作流\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
// 1. 智能打包工作流
|
||||
console.log('🧠 智能打包工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const bundleResult = await moduleManager.executeWorkflow(
|
||||
'intelligent-bundle',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'ios',
|
||||
dev: false,
|
||||
sourcemap: true,
|
||||
optimize: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 智能打包结果:');
|
||||
if (bundleResult.data?.buildResults) {
|
||||
const builds = bundleResult.data.buildResults;
|
||||
builds.forEach((build: any) => {
|
||||
console.log(
|
||||
`${build.platform}: ${build.success ? '✅ 成功' : '❌ 失败'} (${build.buildTime}s, ${build.bundleSize}MB)`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (bundleResult.data?.averageScore) {
|
||||
console.log(`平均质量评分: ${bundleResult.data.averageScore}%`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 智能打包工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '-'.repeat(40));
|
||||
|
||||
// 2. 增量构建工作流
|
||||
console.log('\\n🔄 增量构建工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const incrementalResult = await moduleManager.executeWorkflow(
|
||||
'incremental-build',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'android',
|
||||
baseVersion: 'v1.0.0',
|
||||
skipValidation: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 增量构建结果:');
|
||||
if (incrementalResult.data?.diffPackage) {
|
||||
const diff = incrementalResult.data.diffPackage;
|
||||
console.log(`基准版本: ${diff.fromVersion}`);
|
||||
console.log(`目标版本: ${diff.toVersion}`);
|
||||
console.log(`原始大小: ${diff.originalSize}MB`);
|
||||
console.log(`差异包大小: ${diff.diffSize}MB`);
|
||||
console.log(`压缩比: ${diff.compressionRatio}%`);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`验证状态: ${incrementalResult.data?.allValid ? '✅ 通过' : '❌ 失败'}`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 增量构建工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示Package模块工作流
|
||||
*/
|
||||
async function demonstratePackageWorkflows() {
|
||||
console.log('📄 演示Package模块增强工作流\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
// 批量包处理工作流
|
||||
console.log('📦 批量包处理工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const packageResult = await moduleManager.executeWorkflow(
|
||||
'batch-package-processing',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
directory: './packages',
|
||||
pattern: '*.{ipa,apk,app}',
|
||||
skipUpload: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 批量包处理结果:');
|
||||
if (packageResult.data?.report) {
|
||||
const report = packageResult.data.report;
|
||||
console.log(`总包数: ${report.summary.totalPackages}`);
|
||||
console.log(`解析成功: ${report.summary.parsedSuccessfully}`);
|
||||
console.log(`上传成功: ${report.summary.uploadedSuccessfully}`);
|
||||
console.log(`总大小: ${report.summary.totalSize.toFixed(1)}MB`);
|
||||
|
||||
if (report.failedOperations.length > 0) {
|
||||
console.log('\\n❌ 失败操作:');
|
||||
report.failedOperations.forEach((op: any) => {
|
||||
console.log(` ${op.operation}: ${op.file}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 批量包处理工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示Version模块工作流
|
||||
*/
|
||||
async function demonstrateVersionWorkflows() {
|
||||
console.log('🏷️ 演示Version模块增强工作流\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
// 版本发布管理工作流
|
||||
console.log('🚀 版本发布管理工作流演示');
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
try {
|
||||
const versionResult = await moduleManager.executeWorkflow(
|
||||
'version-release-management',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
name: 'v2.1.0',
|
||||
description: 'Major feature update with bug fixes',
|
||||
platform: 'ios',
|
||||
rollout: 50,
|
||||
dryRun: true, // 使用模拟发布
|
||||
force: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log('\\n📊 版本发布结果:');
|
||||
if (versionResult.data?.summary) {
|
||||
const summary = versionResult.data.summary;
|
||||
console.log(`版本: ${summary.version}`);
|
||||
console.log(`平台: ${summary.platform}`);
|
||||
console.log(`发布状态: ${summary.success ? '✅ 成功' : '❌ 失败'}`);
|
||||
console.log(
|
||||
`监控状态: ${summary.monitoringHealthy ? '✅ 正常' : '⚠️ 有警告'}`,
|
||||
);
|
||||
|
||||
if (summary.releaseId) {
|
||||
console.log(`发布ID: ${summary.releaseId}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (versionResult.data?.dryRun) {
|
||||
console.log('\\n🔍 这是一次模拟发布,未实际执行');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 版本发布管理工作流失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示工作流组合使用
|
||||
*/
|
||||
async function demonstrateWorkflowComposition() {
|
||||
console.log('🔗 演示工作流组合使用\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
console.log('📋 完整发布流程演示 (应用初始化 → 智能打包 → 版本发布)');
|
||||
console.log('-'.repeat(60));
|
||||
|
||||
try {
|
||||
// 1. 应用初始化
|
||||
console.log('\\n步骤 1: 应用初始化');
|
||||
const appResult = await moduleManager.executeWorkflow(
|
||||
'app-initialization',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
name: 'CompositeApp',
|
||||
platform: 'android',
|
||||
force: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!appResult.success) {
|
||||
throw new Error('应用初始化失败');
|
||||
}
|
||||
|
||||
// 2. 智能打包
|
||||
console.log('\\n步骤 2: 智能打包');
|
||||
const bundleResult = await moduleManager.executeWorkflow(
|
||||
'intelligent-bundle',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'android',
|
||||
dev: false,
|
||||
optimize: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!bundleResult.success) {
|
||||
throw new Error('智能打包失败');
|
||||
}
|
||||
|
||||
// 3. 版本发布
|
||||
console.log('\\n步骤 3: 版本发布');
|
||||
const releaseResult = await moduleManager.executeWorkflow(
|
||||
'version-release-management',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
name: 'v1.0.0',
|
||||
description: 'Initial release via composition workflow',
|
||||
platform: 'android',
|
||||
rollout: 10,
|
||||
dryRun: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!releaseResult.success) {
|
||||
throw new Error('版本发布失败');
|
||||
}
|
||||
|
||||
console.log('\\n🎉 完整发布流程执行成功!');
|
||||
console.log('📊 流程总结:');
|
||||
console.log(
|
||||
` ✅ 应用初始化: ${appResult.data?.created ? '成功' : '失败'}`,
|
||||
);
|
||||
console.log(
|
||||
` ✅ 智能打包: ${bundleResult.data?.allSuccess ? '成功' : '失败'}`,
|
||||
);
|
||||
console.log(
|
||||
` ✅ 版本发布: ${releaseResult.data?.summary?.success ? '成功' : '失败'}`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'❌ 工作流组合执行失败:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\\n' + '='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出所有增强工作流及其用途
|
||||
*/
|
||||
async function listEnhancedWorkflows() {
|
||||
console.log('📋 增强核心工作流列表\n');
|
||||
console.log('='.repeat(70));
|
||||
|
||||
const workflowCategories = {
|
||||
App模块工作流: [
|
||||
{
|
||||
name: 'app-initialization',
|
||||
description: '完整应用初始化流程 - 创建、配置、验证',
|
||||
useCase: '新应用创建和设置',
|
||||
},
|
||||
{
|
||||
name: 'multi-platform-app-management',
|
||||
description: '多平台应用统一管理工作流',
|
||||
useCase: '跨平台应用管理和优化',
|
||||
},
|
||||
],
|
||||
Bundle模块工作流: [
|
||||
{
|
||||
name: 'intelligent-bundle',
|
||||
description: '智能打包工作流 - 自动优化和多平台构建',
|
||||
useCase: '高效的自动化构建',
|
||||
},
|
||||
{
|
||||
name: 'incremental-build',
|
||||
description: '增量构建工作流 - 生成差异包',
|
||||
useCase: '减少更新包大小',
|
||||
},
|
||||
],
|
||||
Package模块工作流: [
|
||||
{
|
||||
name: 'batch-package-processing',
|
||||
description: '批量包处理工作流 - 上传、解析、验证',
|
||||
useCase: '批量处理应用包文件',
|
||||
},
|
||||
],
|
||||
Version模块工作流: [
|
||||
{
|
||||
name: 'version-release-management',
|
||||
description: '版本发布管理工作流 - 完整的版本发布生命周期',
|
||||
useCase: '规范化版本发布流程',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
Object.entries(workflowCategories).forEach(([category, workflows]) => {
|
||||
console.log(`\\n📂 ${category}:`);
|
||||
console.log('-'.repeat(50));
|
||||
|
||||
workflows.forEach((workflow, index) => {
|
||||
console.log(`${index + 1}. ${workflow.name}`);
|
||||
console.log(` 描述: ${workflow.description}`);
|
||||
console.log(` 用途: ${workflow.useCase}`);
|
||||
console.log();
|
||||
});
|
||||
});
|
||||
|
||||
console.log('='.repeat(70) + '\\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 主函数
|
||||
*/
|
||||
async function main() {
|
||||
console.log('🎯 增强核心工作流演示脚本\\n');
|
||||
|
||||
try {
|
||||
// 1. 注册增强工作流
|
||||
await registerEnhancedWorkflows();
|
||||
|
||||
// 2. 列出所有工作流
|
||||
await listEnhancedWorkflows();
|
||||
|
||||
// 3. 演示各模块工作流
|
||||
await demonstrateAppWorkflows();
|
||||
await demonstrateBundleWorkflows();
|
||||
await demonstratePackageWorkflows();
|
||||
await demonstrateVersionWorkflows();
|
||||
|
||||
// 4. 演示工作流组合
|
||||
await demonstrateWorkflowComposition();
|
||||
|
||||
console.log('🎉 所有增强核心工作流演示完成!');
|
||||
} catch (error) {
|
||||
console.error('❌ 演示过程中发生错误:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互式工作流执行
|
||||
*/
|
||||
async function interactiveEnhancedWorkflowExecution() {
|
||||
console.log('\\n🎮 交互式增强工作流执行\\n');
|
||||
|
||||
const workflowName = process.argv[3];
|
||||
|
||||
if (!workflowName) {
|
||||
console.log('使用方法:');
|
||||
console.log(' npm run enhanced-workflow-demo [工作流名称]');
|
||||
console.log('\\n可用的增强工作流:');
|
||||
console.log(' App模块:');
|
||||
console.log(' - app-initialization');
|
||||
console.log(' - multi-platform-app-management');
|
||||
console.log(' Bundle模块:');
|
||||
console.log(' - intelligent-bundle');
|
||||
console.log(' - incremental-build');
|
||||
console.log(' Package模块:');
|
||||
console.log(' - batch-package-processing');
|
||||
console.log(' Version模块:');
|
||||
console.log(' - version-release-management');
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析命令行参数
|
||||
const options: Record<string, any> = {};
|
||||
for (let i = 4; i < process.argv.length; i += 2) {
|
||||
const key = process.argv[i]?.replace(/^--/, '');
|
||||
const value = process.argv[i + 1];
|
||||
if (key && value) {
|
||||
// 尝试解析布尔值和数字
|
||||
if (value === 'true') options[key] = true;
|
||||
else if (value === 'false') options[key] = false;
|
||||
else if (/^\d+$/.test(value)) options[key] = Number.parseInt(value);
|
||||
else options[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`执行增强工作流: ${workflowName}`);
|
||||
console.log('参数:', options);
|
||||
console.log();
|
||||
|
||||
try {
|
||||
await registerEnhancedWorkflows();
|
||||
|
||||
const result = await moduleManager.executeWorkflow(workflowName, {
|
||||
args: [],
|
||||
options,
|
||||
});
|
||||
|
||||
console.log('\\n📊 工作流执行结果:');
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
console.error('❌ 工作流执行失败:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 执行脚本
|
||||
if (require.main === module) {
|
||||
if (process.argv.length > 2 && process.argv[2] === 'interactive') {
|
||||
interactiveEnhancedWorkflowExecution()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error('❌ 交互式执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error('❌ 演示脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
342
example/scripts/provider-api-example.ts
Normal file
342
example/scripts/provider-api-example.ts
Normal file
@@ -0,0 +1,342 @@
|
||||
#!/usr/bin/env ts-node
|
||||
|
||||
import { moduleManager } from '../../src/module-manager';
|
||||
import type { CLIProvider, Platform } from '../../src/types';
|
||||
|
||||
/**
|
||||
* Provider API 使用示例
|
||||
* 演示如何使用 CLIProvider 进行编程式操作
|
||||
*/
|
||||
|
||||
class DeploymentService {
|
||||
private provider: CLIProvider;
|
||||
|
||||
constructor() {
|
||||
this.provider = moduleManager.getProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动化构建和发布流程
|
||||
*/
|
||||
async buildAndPublish(platform: Platform, version: string) {
|
||||
console.log(
|
||||
`🚀 开始 ${platform} 平台的构建和发布流程 (版本: ${version})\n`,
|
||||
);
|
||||
|
||||
try {
|
||||
// 1. 打包应用
|
||||
console.log('📦 正在打包应用...');
|
||||
const bundleResult = await this.provider.bundle({
|
||||
platform,
|
||||
dev: false,
|
||||
sourcemap: true,
|
||||
bundleName: `app-${version}.bundle`,
|
||||
});
|
||||
|
||||
if (!bundleResult.success) {
|
||||
throw new Error(`打包失败: ${bundleResult.error}`);
|
||||
}
|
||||
console.log('✅ 打包完成');
|
||||
|
||||
// 2. 发布版本
|
||||
console.log('\n📡 正在发布版本...');
|
||||
const publishResult = await this.provider.publish({
|
||||
name: version,
|
||||
description: `自动发布版本 ${version}`,
|
||||
rollout: 100,
|
||||
});
|
||||
|
||||
if (!publishResult.success) {
|
||||
throw new Error(`发布失败: ${publishResult.error}`);
|
||||
}
|
||||
console.log('✅ 发布完成');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
bundleData: bundleResult.data,
|
||||
publishData: publishResult.data,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ 构建发布失败:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用管理示例
|
||||
*/
|
||||
async manageApp(platform: Platform) {
|
||||
console.log(`📱 管理 ${platform} 应用\n`);
|
||||
|
||||
try {
|
||||
// 获取当前选中的应用
|
||||
const { appId } = await this.provider.getSelectedApp(platform);
|
||||
console.log(`当前应用ID: ${appId}`);
|
||||
|
||||
// 列出应用版本
|
||||
const versionsResult = await this.provider.listVersions(appId);
|
||||
if (versionsResult.success && versionsResult.data) {
|
||||
console.log('📋 应用版本列表:');
|
||||
versionsResult.data.forEach((version: any, index: number) => {
|
||||
console.log(` ${index + 1}. ${version.name} (${version.id})`);
|
||||
});
|
||||
}
|
||||
|
||||
// 列出应用包
|
||||
const packagesResult = await (this.provider as any).listPackages(appId);
|
||||
if (packagesResult.success && packagesResult.data) {
|
||||
console.log('\n📦 应用包列表:');
|
||||
packagesResult.data.forEach((pkg: any, index: number) => {
|
||||
console.log(` ${index + 1}. ${pkg.name} (${pkg.id})`);
|
||||
});
|
||||
}
|
||||
|
||||
return { appId, platform };
|
||||
} catch (error) {
|
||||
console.error('❌ 应用管理失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量操作示例
|
||||
*/
|
||||
async batchOperations() {
|
||||
console.log('🔄 批量操作示例\n');
|
||||
|
||||
const platforms: Platform[] = ['ios', 'android'];
|
||||
const results = [];
|
||||
|
||||
for (const platform of platforms) {
|
||||
try {
|
||||
console.log(`--- 处理 ${platform} 平台 ---`);
|
||||
|
||||
// 获取平台信息
|
||||
const platformInfo = await this.provider.getPlatform(platform);
|
||||
console.log(`平台: ${platformInfo}`);
|
||||
|
||||
// 模拟打包操作
|
||||
const bundleResult = await this.provider.bundle({
|
||||
platform,
|
||||
dev: true,
|
||||
sourcemap: false,
|
||||
});
|
||||
|
||||
results.push({
|
||||
platform,
|
||||
success: bundleResult.success,
|
||||
data: bundleResult.data,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`${platform} 处理完成: ${bundleResult.success ? '✅' : '❌'}\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`${platform} 处理失败:`, error);
|
||||
results.push({
|
||||
platform,
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传示例
|
||||
*/
|
||||
async uploadExample() {
|
||||
console.log('📤 文件上传示例\n');
|
||||
|
||||
// 模拟上传文件路径
|
||||
const mockFilePaths = {
|
||||
ios: '/path/to/app.ipa',
|
||||
android: '/path/to/app.apk',
|
||||
};
|
||||
|
||||
try {
|
||||
for (const [platform, filePath] of Object.entries(mockFilePaths)) {
|
||||
console.log(`上传 ${platform} 文件: ${filePath}`);
|
||||
|
||||
// 注意:这里是模拟,实际使用时需要真实的文件路径
|
||||
const uploadResult = await this.provider.upload({
|
||||
platform: platform as Platform,
|
||||
filePath,
|
||||
appId: 'mock-app-id',
|
||||
});
|
||||
|
||||
console.log(
|
||||
`${platform} 上传结果:`,
|
||||
uploadResult.success ? '✅' : '❌',
|
||||
);
|
||||
if (!uploadResult.success) {
|
||||
console.log(`错误: ${uploadResult.error}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 上传过程中发生错误:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 高级工作流示例
|
||||
*/
|
||||
async function demonstrateAdvancedWorkflows() {
|
||||
console.log('\n🔧 高级工作流示例\n');
|
||||
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
// 注册自定义工作流
|
||||
provider.registerWorkflow({
|
||||
name: 'advanced-ci-cd',
|
||||
description: '高级CI/CD流程',
|
||||
steps: [
|
||||
{
|
||||
name: 'environment-check',
|
||||
description: '环境检查',
|
||||
execute: async (context) => {
|
||||
console.log('🔍 检查环境配置...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
return { environmentValid: true };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'quality-gate',
|
||||
description: '质量门禁',
|
||||
execute: async (context, previousResult) => {
|
||||
console.log('🛡️ 执行质量门禁检查...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
// 模拟质量检查
|
||||
const qualityScore = Math.random() * 100;
|
||||
const passed = qualityScore > 80;
|
||||
|
||||
console.log(
|
||||
`质量分数: ${qualityScore.toFixed(1)}/100 ${passed ? '✅' : '❌'}`,
|
||||
);
|
||||
|
||||
if (!passed) {
|
||||
throw new Error('质量门禁检查未通过');
|
||||
}
|
||||
|
||||
return { ...previousResult, qualityScore };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'multi-platform-build',
|
||||
description: '多平台构建',
|
||||
execute: async (context, previousResult) => {
|
||||
console.log('🏗️ 多平台并行构建...');
|
||||
|
||||
const platforms: Platform[] = ['ios', 'android'];
|
||||
const buildResults = [];
|
||||
|
||||
// 模拟并行构建
|
||||
for (const platform of platforms) {
|
||||
console.log(` 构建 ${platform}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
buildResults.push({ platform, success: true });
|
||||
}
|
||||
|
||||
return { ...previousResult, builds: buildResults };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deployment-notification',
|
||||
description: '部署通知',
|
||||
execute: async (context, previousResult) => {
|
||||
console.log('📢 发送部署通知...');
|
||||
|
||||
const notification = {
|
||||
message: '部署完成',
|
||||
platforms: previousResult.builds?.map((b: any) => b.platform) || [],
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
console.log('通知内容:', JSON.stringify(notification, null, 2));
|
||||
|
||||
return { ...previousResult, notification };
|
||||
},
|
||||
},
|
||||
],
|
||||
validate: (context) => {
|
||||
if (!context.options.environment) {
|
||||
console.error('❌ 必须指定环境参数');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
options: {
|
||||
environment: {
|
||||
hasValue: true,
|
||||
description: '部署环境 (必需)',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 执行高级工作流
|
||||
try {
|
||||
const result = await provider.executeWorkflow('advanced-ci-cd', {
|
||||
args: [],
|
||||
options: {
|
||||
environment: 'production',
|
||||
},
|
||||
});
|
||||
console.log('\n🎉 高级工作流执行完成:', result);
|
||||
} catch (error) {
|
||||
console.error('❌ 高级工作流执行失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 主函数
|
||||
*/
|
||||
async function main() {
|
||||
console.log('🎯 Provider API 使用示例\n');
|
||||
|
||||
const service = new DeploymentService();
|
||||
|
||||
try {
|
||||
// 1. 构建和发布示例
|
||||
await service.buildAndPublish('ios', '1.2.3');
|
||||
console.log('\n' + '='.repeat(50) + '\n');
|
||||
|
||||
// 2. 应用管理示例
|
||||
await service.manageApp('ios');
|
||||
console.log('\n' + '='.repeat(50) + '\n');
|
||||
|
||||
// 3. 批量操作示例
|
||||
const batchResults = await service.batchOperations();
|
||||
console.log('批量操作结果:', batchResults);
|
||||
console.log('\n' + '='.repeat(50) + '\n');
|
||||
|
||||
// 4. 文件上传示例
|
||||
await service.uploadExample();
|
||||
console.log('\n' + '='.repeat(50) + '\n');
|
||||
|
||||
// 5. 高级工作流示例
|
||||
await demonstrateAdvancedWorkflows();
|
||||
} catch (error) {
|
||||
console.error('❌ 示例执行失败:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 执行示例
|
||||
if (require.main === module) {
|
||||
main()
|
||||
.then(() => {
|
||||
console.log('\n✨ Provider API 示例执行完成');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('❌ 示例执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
155
example/scripts/register-modules.ts
Normal file
155
example/scripts/register-modules.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env ts-node
|
||||
|
||||
import { moduleManager } from '../../src/module-manager';
|
||||
import { analyticsModule } from '../modules/analytics-module';
|
||||
import { customDeployModule } from '../modules/custom-deploy-module';
|
||||
|
||||
/**
|
||||
* 模块注册和执行示例脚本
|
||||
* 演示如何注册自定义模块并执行命令和工作流
|
||||
*/
|
||||
|
||||
async function main() {
|
||||
console.log('🚀 开始模块注册和执行示例\n');
|
||||
|
||||
try {
|
||||
// 1. 注册自定义模块
|
||||
console.log('📦 注册自定义模块...');
|
||||
moduleManager.registerModule(customDeployModule);
|
||||
moduleManager.registerModule(analyticsModule);
|
||||
console.log('✅ 模块注册完成\n');
|
||||
|
||||
// 2. 列出所有可用的命令
|
||||
console.log('📋 可用命令列表:');
|
||||
const commands = moduleManager.listCommands();
|
||||
commands.forEach((cmd) => {
|
||||
console.log(` - ${cmd.name}: ${cmd.description || '无描述'}`);
|
||||
});
|
||||
console.log();
|
||||
|
||||
// 3. 列出所有可用的工作流
|
||||
console.log('🔄 可用工作流列表:');
|
||||
const workflows = moduleManager.listWorkflows();
|
||||
workflows.forEach((workflow) => {
|
||||
console.log(` - ${workflow.name}: ${workflow.description || '无描述'}`);
|
||||
});
|
||||
console.log();
|
||||
|
||||
// 4. 执行自定义命令示例
|
||||
console.log('🎯 执行命令示例:\n');
|
||||
|
||||
// 执行开发部署命令
|
||||
console.log('--- 执行 deploy-dev 命令 ---');
|
||||
const devDeployResult = await moduleManager.executeCommand('deploy-dev', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'ios',
|
||||
force: true,
|
||||
},
|
||||
});
|
||||
console.log('结果:', devDeployResult);
|
||||
console.log();
|
||||
|
||||
// 执行分析统计命令
|
||||
console.log('--- 执行 track-deployment 命令 ---');
|
||||
const trackResult = await moduleManager.executeCommand('track-deployment', {
|
||||
args: [],
|
||||
options: {
|
||||
platform: 'android',
|
||||
environment: 'production',
|
||||
version: '1.2.3',
|
||||
},
|
||||
});
|
||||
console.log('结果:', trackResult);
|
||||
console.log();
|
||||
|
||||
// 生成部署报告
|
||||
console.log('--- 执行 deployment-report 命令 ---');
|
||||
const reportResult = await moduleManager.executeCommand(
|
||||
'deployment-report',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
days: 30,
|
||||
},
|
||||
},
|
||||
);
|
||||
console.log('结果:', reportResult);
|
||||
console.log();
|
||||
|
||||
// 5. 执行工作流示例
|
||||
console.log('🔄 执行工作流示例:\n');
|
||||
|
||||
// 执行带统计的部署工作流
|
||||
console.log('--- 执行 deploy-with-analytics 工作流 ---');
|
||||
const analyticsWorkflowResult = await moduleManager.executeWorkflow(
|
||||
'deploy-with-analytics',
|
||||
{
|
||||
args: [],
|
||||
options: {},
|
||||
},
|
||||
);
|
||||
console.log('工作流结果:', analyticsWorkflowResult);
|
||||
console.log();
|
||||
|
||||
// 执行热修复工作流
|
||||
console.log('--- 执行 hotfix-deploy 工作流 ---');
|
||||
const hotfixWorkflowResult = await moduleManager.executeWorkflow(
|
||||
'hotfix-deploy',
|
||||
{
|
||||
args: [],
|
||||
options: {
|
||||
hotfixId: 'HF-2024-001',
|
||||
},
|
||||
},
|
||||
);
|
||||
console.log('工作流结果:', hotfixWorkflowResult);
|
||||
console.log();
|
||||
|
||||
console.log('🎉 所有示例执行完成!');
|
||||
} catch (error) {
|
||||
console.error('❌ 执行过程中发生错误:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 错误处理函数
|
||||
async function demonstrateErrorHandling() {
|
||||
console.log('\n🚨 错误处理示例:\n');
|
||||
|
||||
try {
|
||||
// 尝试执行不存在的命令
|
||||
console.log('--- 尝试执行不存在的命令 ---');
|
||||
await moduleManager.executeCommand('non-existent-command', {
|
||||
args: [],
|
||||
options: {},
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('捕获错误:', error instanceof Error ? error.message : error);
|
||||
}
|
||||
|
||||
try {
|
||||
// 尝试执行缺少必需参数的命令
|
||||
console.log('\n--- 尝试执行缺少必需参数的命令 ---');
|
||||
await moduleManager.executeCommand('deploy-prod', {
|
||||
args: [],
|
||||
options: {}, // 缺少必需的 version 参数
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('捕获错误:', error instanceof Error ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
// 主函数执行
|
||||
if (require.main === module) {
|
||||
main()
|
||||
.then(() => demonstrateErrorHandling())
|
||||
.then(() => {
|
||||
console.log('\n✨ 示例脚本执行完成');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('❌ 脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
290
example/scripts/workflow-demo.ts
Normal file
290
example/scripts/workflow-demo.ts
Normal file
@@ -0,0 +1,290 @@
|
||||
#!/usr/bin/env ts-node
|
||||
|
||||
import { moduleManager } from '../../src/module-manager';
|
||||
import { customWorkflows } from '../workflows/custom-workflows';
|
||||
|
||||
/**
|
||||
* 工作流演示脚本
|
||||
* 展示如何注册和执行复杂的工作流
|
||||
*/
|
||||
|
||||
async function registerCustomWorkflows() {
|
||||
console.log('📋 注册自定义工作流...\n');
|
||||
|
||||
const provider = moduleManager.getProvider();
|
||||
|
||||
// 注册所有自定义工作流
|
||||
customWorkflows.forEach((workflow) => {
|
||||
provider.registerWorkflow(workflow);
|
||||
console.log(`✅ 注册工作流: ${workflow.name} - ${workflow.description}`);
|
||||
});
|
||||
|
||||
console.log('\n📋 所有工作流注册完成\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示灰度发布工作流
|
||||
*/
|
||||
async function demonstrateCanaryDeployment() {
|
||||
console.log('🔥 演示灰度发布工作流\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow('canary-deployment', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
initialRollout: 10,
|
||||
autoExpand: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('\n📊 灰度发布工作流结果:');
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
console.error('❌ 灰度发布工作流执行失败:', error);
|
||||
}
|
||||
|
||||
console.log('\n' + '='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示多环境发布工作流
|
||||
*/
|
||||
async function demonstrateMultiEnvironmentDeploy() {
|
||||
console.log('🌍 演示多环境发布工作流\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow('multi-env-deploy', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.0',
|
||||
skipProduction: false,
|
||||
forceProduction: false,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('\n📊 多环境发布工作流结果:');
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
console.error('❌ 多环境发布工作流执行失败:', error);
|
||||
}
|
||||
|
||||
console.log('\n' + '='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示回滚工作流
|
||||
*/
|
||||
async function demonstrateRollbackWorkflow() {
|
||||
console.log('🔄 演示回滚工作流\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow('rollback-workflow', {
|
||||
args: [],
|
||||
options: {
|
||||
targetVersion: '2.0.5',
|
||||
skipVerification: false,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('\n📊 回滚工作流结果:');
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
console.error('❌ 回滚工作流执行失败:', error);
|
||||
}
|
||||
|
||||
console.log('\n' + '='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示工作流验证失败的情况
|
||||
*/
|
||||
async function demonstrateWorkflowValidation() {
|
||||
console.log('⚠️ 演示工作流验证\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
// 1. 演示缺少必需参数的情况
|
||||
console.log('--- 测试缺少必需参数 ---');
|
||||
try {
|
||||
await moduleManager.executeWorkflow('canary-deployment', {
|
||||
args: [],
|
||||
options: {}, // 缺少 version 参数
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(
|
||||
'✅ 正确捕获验证错误:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\n--- 测试回滚工作流验证 ---');
|
||||
try {
|
||||
await moduleManager.executeWorkflow('rollback-workflow', {
|
||||
args: [],
|
||||
options: {}, // 缺少 targetVersion 参数
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(
|
||||
'✅ 正确捕获验证错误:',
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\n' + '='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 演示工作流的条件执行
|
||||
*/
|
||||
async function demonstrateConditionalExecution() {
|
||||
console.log('🔀 演示条件执行\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
// 演示跳过生产部署
|
||||
console.log('--- 跳过生产环境部署 ---');
|
||||
try {
|
||||
const result = await moduleManager.executeWorkflow('multi-env-deploy', {
|
||||
args: [],
|
||||
options: {
|
||||
version: '2.1.1',
|
||||
skipProduction: true, // 跳过生产部署
|
||||
},
|
||||
});
|
||||
|
||||
console.log('📊 跳过生产部署的结果:');
|
||||
console.log(`包含生产部署步骤: ${result.data?.production ? '是' : '否'}`);
|
||||
} catch (error) {
|
||||
console.error('❌ 条件执行演示失败:', error);
|
||||
}
|
||||
|
||||
console.log('\n' + '='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出所有可用的工作流
|
||||
*/
|
||||
async function listAvailableWorkflows() {
|
||||
console.log('📋 可用工作流列表\n');
|
||||
console.log('='.repeat(60));
|
||||
|
||||
const workflows = moduleManager.listWorkflows();
|
||||
|
||||
workflows.forEach((workflow, index) => {
|
||||
console.log(`${index + 1}. ${workflow.name}`);
|
||||
console.log(` 描述: ${workflow.description || '无描述'}`);
|
||||
console.log(` 步骤数: ${workflow.steps.length}`);
|
||||
|
||||
if (workflow.options) {
|
||||
console.log(' 选项:');
|
||||
Object.entries(workflow.options).forEach(([key, option]) => {
|
||||
const opt = option as any;
|
||||
const required = opt.hasValue && !opt.default;
|
||||
console.log(
|
||||
` --${key}: ${opt.description || '无描述'} ${required ? '(必需)' : ''}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
console.log();
|
||||
});
|
||||
|
||||
console.log('='.repeat(60) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 主函数
|
||||
*/
|
||||
async function main() {
|
||||
console.log('🎯 工作流演示脚本\n');
|
||||
|
||||
try {
|
||||
// 1. 注册自定义工作流
|
||||
await registerCustomWorkflows();
|
||||
|
||||
// 2. 列出所有可用工作流
|
||||
await listAvailableWorkflows();
|
||||
|
||||
// 3. 演示各种工作流
|
||||
await demonstrateCanaryDeployment();
|
||||
await demonstrateMultiEnvironmentDeploy();
|
||||
await demonstrateRollbackWorkflow();
|
||||
|
||||
// 4. 演示验证和条件执行
|
||||
await demonstrateWorkflowValidation();
|
||||
await demonstrateConditionalExecution();
|
||||
|
||||
console.log('🎉 所有工作流演示完成!');
|
||||
} catch (error) {
|
||||
console.error('❌ 演示过程中发生错误:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互式工作流执行
|
||||
*/
|
||||
async function interactiveWorkflowExecution() {
|
||||
console.log('\n🎮 交互式工作流执行\n');
|
||||
|
||||
const workflowName = process.argv[3];
|
||||
|
||||
if (!workflowName) {
|
||||
console.log('使用方法:');
|
||||
console.log(' npm run workflow-demo [工作流名称]');
|
||||
console.log('\n可用的工作流:');
|
||||
console.log(' - canary-deployment');
|
||||
console.log(' - multi-env-deploy');
|
||||
console.log(' - rollback-workflow');
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析命令行参数
|
||||
const options: Record<string, any> = {};
|
||||
for (let i = 4; i < process.argv.length; i += 2) {
|
||||
const key = process.argv[i]?.replace(/^--/, '');
|
||||
const value = process.argv[i + 1];
|
||||
if (key && value) {
|
||||
options[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`执行工作流: ${workflowName}`);
|
||||
console.log('参数:', options);
|
||||
console.log();
|
||||
|
||||
try {
|
||||
await registerCustomWorkflows();
|
||||
|
||||
const result = await moduleManager.executeWorkflow(workflowName, {
|
||||
args: [],
|
||||
options,
|
||||
});
|
||||
|
||||
console.log('\n📊 工作流执行结果:');
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} catch (error) {
|
||||
console.error('❌ 工作流执行失败:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 执行脚本
|
||||
if (require.main === module) {
|
||||
if (process.argv.length > 2 && process.argv[2] === 'interactive') {
|
||||
interactiveWorkflowExecution()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error('❌ 交互式执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error('❌ 演示脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
23
example/tsconfig.json
Normal file
23
example/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"moduleResolution": "node",
|
||||
"strict": false,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"resolveJsonModule": true,
|
||||
"noEmit": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"ts-node": {
|
||||
"transpileOnly": true,
|
||||
"compilerOptions": {
|
||||
"module": "commonjs"
|
||||
}
|
||||
}
|
||||
}
|
582
example/workflows/custom-workflows.ts
Normal file
582
example/workflows/custom-workflows.ts
Normal file
@@ -0,0 +1,582 @@
|
||||
import type {
|
||||
CLIProvider,
|
||||
CommandContext,
|
||||
CustomWorkflow,
|
||||
} from '../../src/types';
|
||||
|
||||
/**
|
||||
* 自定义工作流集合
|
||||
* 演示各种复杂的工作流场景
|
||||
*/
|
||||
|
||||
/**
|
||||
* 灰度发布工作流
|
||||
*/
|
||||
export const canaryDeploymentWorkflow: CustomWorkflow = {
|
||||
name: 'canary-deployment',
|
||||
description: '灰度发布工作流 - 逐步增加用户覆盖率',
|
||||
steps: [
|
||||
{
|
||||
name: 'prepare-canary',
|
||||
description: '准备灰度发布',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('🔧 准备灰度发布环境...');
|
||||
|
||||
const { version, initialRollout = 5 } = context.options;
|
||||
|
||||
console.log(`📦 版本: ${version}`);
|
||||
console.log(`📊 初始覆盖率: ${initialRollout}%`);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
return {
|
||||
version,
|
||||
currentRollout: initialRollout,
|
||||
stage: 'prepared',
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'initial-deployment',
|
||||
description: '初始小范围部署',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🚀 执行初始小范围部署...');
|
||||
|
||||
const { currentRollout } = previousResult;
|
||||
|
||||
console.log(`部署到 ${currentRollout}% 用户...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
console.log('✅ 初始部署完成');
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
deploymentTime: new Date().toISOString(),
|
||||
stage: 'initial-deployed',
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'monitor-metrics',
|
||||
description: '监控关键指标',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('📊 监控关键指标...');
|
||||
|
||||
// 模拟监控数据
|
||||
const metrics = {
|
||||
crashRate: Math.random() * 0.01, // 0-1%
|
||||
responseTime: 150 + Math.random() * 100, // 150-250ms
|
||||
userSatisfaction: 85 + Math.random() * 10, // 85-95%
|
||||
errorRate: Math.random() * 0.005, // 0-0.5%
|
||||
};
|
||||
|
||||
console.log('📈 监控结果:');
|
||||
console.log(` 崩溃率: ${(metrics.crashRate * 100).toFixed(3)}%`);
|
||||
console.log(` 响应时间: ${metrics.responseTime.toFixed(1)}ms`);
|
||||
console.log(` 用户满意度: ${metrics.userSatisfaction.toFixed(1)}%`);
|
||||
console.log(` 错误率: ${(metrics.errorRate * 100).toFixed(3)}%`);
|
||||
|
||||
// 判断是否可以继续扩大范围
|
||||
const canProceed =
|
||||
metrics.crashRate < 0.005 &&
|
||||
metrics.errorRate < 0.003 &&
|
||||
metrics.userSatisfaction > 80;
|
||||
|
||||
console.log(`🔍 健康检查: ${canProceed ? '✅ 通过' : '❌ 未通过'}`);
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
metrics,
|
||||
canProceed,
|
||||
stage: 'monitored',
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'expand-rollout',
|
||||
description: '扩大发布范围',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
const { canProceed, currentRollout } = previousResult;
|
||||
|
||||
if (!canProceed) {
|
||||
console.log('⚠️ 指标不达标,停止扩大发布范围');
|
||||
return {
|
||||
...previousResult,
|
||||
stage: 'rollout-stopped',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('📈 扩大发布范围...');
|
||||
|
||||
const newRollout = Math.min(currentRollout * 2, 100);
|
||||
console.log(`覆盖率从 ${currentRollout}% 扩大到 ${newRollout}%`);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1200));
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
currentRollout: newRollout,
|
||||
stage: newRollout >= 100 ? 'fully-deployed' : 'expanded',
|
||||
};
|
||||
},
|
||||
condition: (context: CommandContext) => {
|
||||
// 只有在启用自动扩大的情况下才执行
|
||||
return context.options.autoExpand !== false;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'final-verification',
|
||||
description: '最终验证',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🔍 执行最终验证...');
|
||||
|
||||
const { stage, currentRollout } = previousResult;
|
||||
|
||||
if (stage === 'rollout-stopped') {
|
||||
console.log('❌ 灰度发布因指标不达标而停止');
|
||||
return {
|
||||
...previousResult,
|
||||
finalStatus: 'failed',
|
||||
reason: 'metrics-failed',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('✅ 灰度发布验证完成');
|
||||
console.log(`📊 最终覆盖率: ${currentRollout}%`);
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
finalStatus: 'success',
|
||||
completedAt: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
validate: (context: CommandContext) => {
|
||||
if (!context.options.version) {
|
||||
console.error('❌ 灰度发布必须指定版本号');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
options: {
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '发布版本号 (必需)',
|
||||
},
|
||||
initialRollout: {
|
||||
hasValue: true,
|
||||
default: 5,
|
||||
description: '初始覆盖率百分比',
|
||||
},
|
||||
autoExpand: {
|
||||
hasValue: false,
|
||||
default: true,
|
||||
description: '自动扩大发布范围',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 多环境发布工作流
|
||||
*/
|
||||
export const multiEnvironmentDeployWorkflow: CustomWorkflow = {
|
||||
name: 'multi-env-deploy',
|
||||
description: '多环境依次发布工作流',
|
||||
steps: [
|
||||
{
|
||||
name: 'deploy-to-dev',
|
||||
description: '部署到开发环境',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('🔧 部署到开发环境...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
const devResult = {
|
||||
environment: 'development',
|
||||
deployTime: new Date().toISOString(),
|
||||
success: true,
|
||||
};
|
||||
|
||||
console.log('✅ 开发环境部署完成');
|
||||
return { dev: devResult };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'run-integration-tests',
|
||||
description: '运行集成测试',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🧪 运行集成测试...');
|
||||
|
||||
const testSuites = ['API测试', '数据库测试', '第三方服务测试'];
|
||||
const results = [];
|
||||
|
||||
for (const suite of testSuites) {
|
||||
console.log(` 运行 ${suite}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
const passed = Math.random() > 0.1; // 90% 通过率
|
||||
results.push({ suite, passed });
|
||||
console.log(` ${passed ? '✅' : '❌'} ${suite}`);
|
||||
}
|
||||
|
||||
const allPassed = results.every((r) => r.passed);
|
||||
console.log(
|
||||
`🧪 集成测试结果: ${allPassed ? '✅ 全部通过' : '❌ 有失败项'}`,
|
||||
);
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
integrationTests: { results, allPassed },
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deploy-to-staging',
|
||||
description: '部署到预发布环境',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
const { integrationTests } = previousResult;
|
||||
|
||||
if (!integrationTests.allPassed) {
|
||||
throw new Error('集成测试未通过,无法部署到预发布环境');
|
||||
}
|
||||
|
||||
console.log('🎭 部署到预发布环境...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
const stagingResult = {
|
||||
environment: 'staging',
|
||||
deployTime: new Date().toISOString(),
|
||||
success: true,
|
||||
};
|
||||
|
||||
console.log('✅ 预发布环境部署完成');
|
||||
return {
|
||||
...previousResult,
|
||||
staging: stagingResult,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'run-e2e-tests',
|
||||
description: '运行端到端测试',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🎯 运行端到端测试...');
|
||||
|
||||
const e2eTests = [
|
||||
'用户登录流程',
|
||||
'核心业务流程',
|
||||
'支付流程',
|
||||
'数据同步',
|
||||
];
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const test of e2eTests) {
|
||||
console.log(` 测试 ${test}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
const passed = Math.random() > 0.05; // 95% 通过率
|
||||
results.push({ test, passed });
|
||||
console.log(` ${passed ? '✅' : '❌'} ${test}`);
|
||||
}
|
||||
|
||||
const allPassed = results.every((r) => r.passed);
|
||||
console.log(
|
||||
`🎯 E2E测试结果: ${allPassed ? '✅ 全部通过' : '❌ 有失败项'}`,
|
||||
);
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
e2eTests: { results, allPassed },
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'deploy-to-production',
|
||||
description: '部署到生产环境',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
const { e2eTests } = previousResult;
|
||||
|
||||
if (!e2eTests.allPassed) {
|
||||
console.log('⚠️ E2E测试未全部通过,需要手动确认是否继续部署');
|
||||
|
||||
if (!context.options.forceProduction) {
|
||||
throw new Error('E2E测试未通过,使用 --force-production 强制部署');
|
||||
}
|
||||
}
|
||||
|
||||
console.log('🚀 部署到生产环境...');
|
||||
|
||||
// 生产部署需要更长时间
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
const productionResult = {
|
||||
environment: 'production',
|
||||
deployTime: new Date().toISOString(),
|
||||
success: true,
|
||||
version: context.options.version,
|
||||
};
|
||||
|
||||
console.log('🎉 生产环境部署完成');
|
||||
return {
|
||||
...previousResult,
|
||||
production: productionResult,
|
||||
};
|
||||
},
|
||||
condition: (context: CommandContext) => {
|
||||
// 只有在非跳过生产部署的情况下才执行
|
||||
return !context.options.skipProduction;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'post-deployment-verification',
|
||||
description: '部署后验证',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🔍 执行部署后验证...');
|
||||
|
||||
const verifications = [
|
||||
'健康检查',
|
||||
'关键接口测试',
|
||||
'监控数据验证',
|
||||
'用户访问验证',
|
||||
];
|
||||
|
||||
for (const verification of verifications) {
|
||||
console.log(` ${verification}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
console.log(` ✅ ${verification} 通过`);
|
||||
}
|
||||
|
||||
console.log('✅ 部署后验证完成');
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
postDeploymentVerification: {
|
||||
completed: true,
|
||||
verifiedAt: new Date().toISOString(),
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
validate: (context: CommandContext) => {
|
||||
if (!context.options.version) {
|
||||
console.error('❌ 多环境部署必须指定版本号');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
options: {
|
||||
version: {
|
||||
hasValue: true,
|
||||
description: '发布版本号 (必需)',
|
||||
},
|
||||
skipProduction: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '跳过生产环境部署',
|
||||
},
|
||||
forceProduction: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '强制部署到生产环境(即使测试未全部通过)',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 回滚工作流
|
||||
*/
|
||||
export const rollbackWorkflow: CustomWorkflow = {
|
||||
name: 'rollback-workflow',
|
||||
description: '应用回滚工作流',
|
||||
steps: [
|
||||
{
|
||||
name: 'validate-target-version',
|
||||
description: '验证目标版本',
|
||||
execute: async (context: CommandContext) => {
|
||||
console.log('🔍 验证目标回滚版本...');
|
||||
|
||||
const { targetVersion } = context.options;
|
||||
|
||||
if (!targetVersion) {
|
||||
throw new Error('必须指定目标回滚版本');
|
||||
}
|
||||
|
||||
// 模拟版本验证
|
||||
console.log(`验证版本 ${targetVersion} 是否存在...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
|
||||
const versionExists = true; // 模拟版本存在
|
||||
|
||||
if (!versionExists) {
|
||||
throw new Error(`版本 ${targetVersion} 不存在`);
|
||||
}
|
||||
|
||||
console.log(`✅ 版本 ${targetVersion} 验证通过`);
|
||||
|
||||
return {
|
||||
targetVersion,
|
||||
validated: true,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'backup-current-state',
|
||||
description: '备份当前状态',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('💾 备份当前应用状态...');
|
||||
|
||||
const backup = {
|
||||
backupId: `backup-${Date.now()}`,
|
||||
timestamp: new Date().toISOString(),
|
||||
currentVersion: 'current-version', // 在实际应用中获取当前版本
|
||||
configSnapshot: 'config-data', // 在实际应用中获取配置快照
|
||||
};
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
console.log(`✅ 状态备份完成,备份ID: ${backup.backupId}`);
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
backup,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'execute-rollback',
|
||||
description: '执行回滚',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🔄 执行回滚操作...');
|
||||
|
||||
const { targetVersion } = previousResult;
|
||||
|
||||
console.log(`回滚到版本: ${targetVersion}`);
|
||||
|
||||
// 模拟回滚过程
|
||||
const rollbackSteps = [
|
||||
'停止当前服务',
|
||||
'切换到目标版本',
|
||||
'更新配置',
|
||||
'重启服务',
|
||||
];
|
||||
|
||||
for (const step of rollbackSteps) {
|
||||
console.log(` ${step}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
console.log(` ✅ ${step} 完成`);
|
||||
}
|
||||
|
||||
console.log('🎉 回滚执行完成');
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
rollbackCompleted: true,
|
||||
rollbackTime: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'verify-rollback',
|
||||
description: '验证回滚结果',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('🔍 验证回滚结果...');
|
||||
|
||||
const verificationChecks = [
|
||||
'服务可用性检查',
|
||||
'功能完整性检查',
|
||||
'性能基线检查',
|
||||
'数据一致性检查',
|
||||
];
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const check of verificationChecks) {
|
||||
console.log(` ${check}...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
|
||||
const passed = Math.random() > 0.05; // 95% 通过率
|
||||
results.push({ check, passed });
|
||||
console.log(` ${passed ? '✅' : '❌'} ${check}`);
|
||||
}
|
||||
|
||||
const allPassed = results.every((r) => r.passed);
|
||||
|
||||
if (!allPassed) {
|
||||
console.log('⚠️ 部分验证未通过,可能需要进一步检查');
|
||||
} else {
|
||||
console.log('✅ 回滚验证全部通过');
|
||||
}
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
verification: { results, allPassed },
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'notify-stakeholders',
|
||||
description: '通知相关人员',
|
||||
execute: async (context: CommandContext, previousResult: any) => {
|
||||
console.log('📧 通知相关人员...');
|
||||
|
||||
const { targetVersion, verification } = previousResult;
|
||||
|
||||
const notification = {
|
||||
type: 'rollback-completed',
|
||||
targetVersion,
|
||||
success: verification.allPassed,
|
||||
timestamp: new Date().toISOString(),
|
||||
notifiedStakeholders: [
|
||||
'开发团队',
|
||||
'运维团队',
|
||||
'产品团队',
|
||||
'测试团队',
|
||||
],
|
||||
};
|
||||
|
||||
console.log('📬 发送通知给:');
|
||||
notification.notifiedStakeholders.forEach((stakeholder) => {
|
||||
console.log(` - ${stakeholder}`);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
console.log('✅ 通知发送完成');
|
||||
|
||||
return {
|
||||
...previousResult,
|
||||
notification,
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
validate: (context: CommandContext) => {
|
||||
if (!context.options.targetVersion) {
|
||||
console.error('❌ 回滚操作必须指定目标版本');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
options: {
|
||||
targetVersion: {
|
||||
hasValue: true,
|
||||
description: '目标回滚版本 (必需)',
|
||||
},
|
||||
skipVerification: {
|
||||
hasValue: false,
|
||||
default: false,
|
||||
description: '跳过回滚后验证',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 导出所有工作流
|
||||
*/
|
||||
export const customWorkflows = [
|
||||
canaryDeploymentWorkflow,
|
||||
multiEnvironmentDeployWorkflow,
|
||||
rollbackWorkflow,
|
||||
];
|
1552
example/workflows/enhanced-core-workflows.ts
Normal file
1552
example/workflows/enhanced-core-workflows.ts
Normal file
File diff suppressed because it is too large
Load Diff
1863
example/yarn.lock
Normal file
1863
example/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user