# DevPack API 设计文档 > 版本:v1.0.0-draft > 更新日期:2026-03-03 > 作者:DevPack Team --- ## 1. CLI 命令参考 ### 1.1 命令总览 ``` devpack [command] [subcommand] [flags] Available Commands: init 初始化 DevPack 配置 scan 扫描当前开发环境 capture 捕获环境并生成 Pack restore 从 Pack 还原开发环境 diff 对比两个环境的差异 export 导出 Pack 为文件 import 导入 Pack 文件 list 列出 Pack 和 Profile profile 管理配置文件 verify 验证 Pack 文件完整性 version 显示版本信息 help 帮助信息 Global Flags: -v, --verbose 详细输出 -q, --quiet 静默模式 --log-level 日志级别 (trace|debug|info|warn|error) --log-file 日志文件路径 --no-color 禁用彩色输出 --config 配置文件路径(默认 ~/.devpack/config.yaml) -h, --help 帮助信息 ``` --- ### 1.2 devpack init 初始化 DevPack,创建配置目录和默认配置文件。 ``` devpack init [flags] Flags: --profile 创建并使用指定名称的 Profile --template 使用预设模板 (minimal|standard|full) --force 覆盖已有配置 ``` **示例:** ```bash # 默认初始化 devpack init # 使用模板初始化 devpack init --template standard # 创建指定 Profile devpack init --profile golang-dev ``` **行为:** 1. 创建 `~/.devpack/` 目录 2. 生成 `~/.devpack/config.yaml` 默认配置 3. 创建 `~/.devpack/profiles/` 目录 4. 创建 `~/.devpack/packs/` 目录 5. 创建 `~/.devpack/logs/` 目录 **输出示例:** ``` ✓ Created ~/.devpack/config.yaml ✓ Created ~/.devpack/profiles/default.yaml ✓ DevPack initialized successfully! Run 'devpack scan' to scan your current environment. ``` --- ### 1.3 devpack scan 扫描当前系统的开发环境。 ``` devpack scan [flags] Flags: -c, --collectors 指定采集器(逗号分隔) --category 按分类扫描 (runtime|package|editor|shell|git|env) --profile 使用指定 Profile 的扫描配置 -o, --output 输出格式 (table|json|yaml) [默认: table] --save 保存扫描结果到文件 --detailed 显示详细信息 ``` **示例:** ```bash # 扫描所有 devpack scan # 只扫描运行时 devpack scan --category runtime # 扫描特定采集器 devpack scan -c go,node,vscode # JSON 格式输出 devpack scan -o json # 保存结果 devpack scan --save scan-result.json ``` **输出示例:** ``` 🔍 Scanning development environment... ╔══════════════╤════════════════════╤═══════════╤═══════════════════╗ ║ Category │ Name │ Version │ Details ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Runtime │ Go │ 1.22.1 │ GOPATH: ~/go ║ ║ Runtime │ Node.js │ 20.11.0 │ npm: 10.2.4 ║ ║ Runtime │ Python │ 3.12.2 │ pip: 24.0 ║ ║ Runtime │ Rust │ 1.76.0 │ rustup: 1.27.0 ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Package Mgr │ Scoop │ - │ 42 packages ║ ║ Package Mgr │ Winget │ - │ 15 packages ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Editor │ VS Code │ 1.87.0 │ 35 extensions ║ ║ Editor │ Neovim │ 0.9.5 │ 18 plugins ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Shell │ PowerShell │ 7.4.1 │ 5 modules ║ ║ Shell │ Windows Terminal │ 1.19 │ 3 profiles ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Git │ Git │ 2.43.0 │ 12 aliases ║ ╠══════════════╪════════════════════╪═══════════╪═══════════════════╣ ║ Environment │ Environment Vars │ - │ 8 dev-related ║ ╚══════════════╧════════════════════╧═══════════╧═══════════════════╝ Found 12 items across 6 categories. Estimated pack size: ~12 MB ``` --- ### 1.4 devpack capture 捕获当前环境并创建 Pack。 ``` devpack capture [flags] Flags: -n, --name Pack 名称(必需) -d, --description Pack 描述 -p, --profile 使用指定 Profile -c, --collectors 指定采集器(逗号分隔) --filter 过滤表达式 --all 捕获所有可用采集器 --encrypt 加密敏感数据 --password 加密密码(不建议命令行传入) --exclude 排除模式(逗号分隔) --tag 标签(逗号分隔) -y, --yes 跳过确认提示 ``` **示例:** ```bash # 使用默认 Profile 捕获 devpack capture --name "my-env-2026" # 捕获所有内容 devpack capture --name "full-env" --all # 使用指定 Profile devpack capture --name "golang-env" --profile golang-dev # 选择性捕获 devpack capture --name "vscode-only" -c vscode # 加密捕获 devpack capture --name "secure-env" --all --encrypt # 带过滤器 devpack capture --name "web-dev" \ -c go,node,vscode \ --filter "runtime:go,runtime:node,editor:vscode" ``` **输出示例:** ``` 📦 Capturing environment "my-env-2026"... Collecting: ✓ Go Runtime (1.22.1, 3 tools) [2.1 MB] ✓ Node.js Runtime (20.11.0, 12 global pkgs) [1.5 MB] ✓ VS Code (35 extensions, settings) [4.2 MB] ✓ PowerShell (profile, 5 modules) [0.3 MB] ✓ Scoop (42 packages) [0.1 MB] ✓ Git (config, 12 aliases) [0.01 MB] ✓ Environment Variables (8 variables) [0.001 MB] ⚠ SSH Keys skipped (use --encrypt) Pack created: my-env-2026 Items: 7 collectors, 115 items Size: 8.2 MB (compressed) Pack ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890 Run 'devpack export my-env-2026 -o my-env-2026.devpack' to export. ``` --- ### 1.5 devpack restore 从 Pack 还原开发环境。 ``` devpack restore [flags] Flags: --dry-run 预览更改(不实际执行) --conflict 冲突处理策略 (skip|overwrite|merge|prompt|newest) --no-rollback 不创建还原点 -c, --collectors 只还原指定采集器 --exclude 排除指定采集器 --password 解密密码 --parallel 并行还原数(默认: 4) -y, --yes 跳过确认提示 --force 强制还原(忽略平台不匹配) ``` **示例:** ```bash # 干运行预览 devpack restore my-env-2026 --dry-run # 正常还原 devpack restore my-env-2026 # 跳过冲突 devpack restore my-env-2026 --conflict skip # 只还原编辑器配置 devpack restore my-env-2026 -c vscode # 还原加密 Pack devpack restore secure-env --password ``` **干运行输出示例:** ``` 🔍 Dry Run — Restore Plan for "my-env-2026" Source: DESKTOP-ABC123 (Windows 11, amd64) Target: LAPTOP-XYZ789 (Windows 11, amd64) ✓ Compatible Plan: ┌────────────────────┬────────────┬──────────────────────────────┐ │ Item │ Action │ Details │ ├────────────────────┼────────────┼──────────────────────────────┤ │ Go 1.22.1 │ INSTALL │ Download from golang.org │ │ Node.js 20.11.0 │ SKIP │ Already installed (20.11.0) │ │ Python 3.12.2 │ UPGRADE │ Current: 3.11.7 → 3.12.2 │ │ VS Code Extensions │ INSTALL 12 │ 23 already present │ │ VS Code Settings │ MERGE │ Conflict in 3 settings │ │ PowerShell Profile │ OVERWRITE │ Backup: profile.bak │ │ Scoop Packages │ INSTALL 8 │ 34 already present │ │ Git Config │ MERGE │ Add 5 aliases │ │ Env Variables │ SET 3 │ GOPATH, GOROOT, NODE_HOME │ └────────────────────┴────────────┴──────────────────────────────┘ Install: 3 items | Upgrade: 1 | Merge: 2 | Skip: 1 | Overwrite: 1 ⚠ This is a dry run. No changes were made. Run without --dry-run to apply these changes. ``` --- ### 1.6 devpack diff 对比两个环境的差异。 ``` devpack diff [flags] Flags: --current 与当前环境对比 --with 与另一个 Pack 对比 -c, --collectors 只对比指定采集器 -o, --output 输出格式 (table|json|yaml) ``` **示例:** ```bash # 与当前环境对比 devpack diff my-env-2026 --current # 两个 Pack 对比 devpack diff env-v1 --with env-v2 ``` --- ### 1.7 devpack export / import 导出和导入 Pack 文件。 ``` # 导出 devpack export [flags] Flags: -o, --output 输出文件路径(默认: .devpack) # 导入 devpack import [flags] Flags: -n, --name 导入后的名称(默认使用 Pack 原名) --verify 导入前验证文件完整性 ``` --- ### 1.8 devpack list 列出本地的 Pack 和 Profile。 ``` devpack list [subcommand] [flags] Subcommands: packs 列出所有 Pack profiles 列出所有 Profile collectors 列出所有可用采集器 Flags: -o, --output 输出格式 (table|json|yaml) --detailed 显示详细信息 ``` --- ### 1.9 devpack profile 管理 Profile 配置文件。 ``` devpack profile [subcommand] [flags] Subcommands: create 创建新 Profile edit 编辑 Profile delete 删除 Profile show 显示 Profile 内容 list 列出所有 Profile use 设置默认 Profile ``` --- ### 1.10 devpack verify 验证 Pack 文件的完整性。 ``` devpack verify [flags] Flags: --checksum 验证校验和 --structure 验证目录结构 --deep 深度验证(检查所有采集器数据) ``` --- ## 2. 内部 API ### 2.1 Collector 接口 ```go package collector import ( "context" "time" ) // Collector 所有采集器的统一接口 type Collector interface { // 基本信息 Name() string DisplayName() string Description() string Category() Category // 可用性检查 IsAvailable(ctx context.Context) bool // 核心操作 Scan(ctx context.Context, opts ScanOptions) (*ScanResult, error) Capture(ctx context.Context, targetDir string, opts CaptureOptions) error Restore(ctx context.Context, sourceDir string, opts RestoreOptions) error Verify(ctx context.Context) (*VerifyResult, error) } // ScanOptions 扫描选项 type ScanOptions struct { Detailed bool // 是否返回详细信息 Filters map[string]string // 过滤条件 Timeout time.Duration // 超时时间 } // CaptureOptions 捕获选项 type CaptureOptions struct { IncludePatterns []string // 包含模式 ExcludePatterns []string // 排除模式 Encrypt bool // 是否加密 } // RestoreOptions 还原选项 type RestoreOptions struct { ConflictStrategy ConflictStrategy // 冲突策略 DryRun bool // 干运行 Force bool // 强制 } // ScanResult 扫描结果 type ScanResult struct { Collector string `json:"collector"` Category Category `json:"category"` Items []ScanItem `json:"items"` Timestamp time.Time `json:"timestamp"` Platform PlatformInfo `json:"platform"` Errors []string `json:"errors,omitempty"` } // ScanItem 扫描项 type ScanItem struct { Name string `json:"name"` Version string `json:"version,omitempty"` Path string `json:"path,omitempty"` Type string `json:"type,omitempty"` // binary, config, package Properties map[string]string `json:"properties,omitempty"` Size int64 `json:"size,omitempty"` Sensitive bool `json:"sensitive,omitempty"` // 是否包含敏感数据 Children []ScanItem `json:"children,omitempty"` } // VerifyResult 验证结果 type VerifyResult struct { Success bool `json:"success"` Items []VerifyItem `json:"items"` } type VerifyItem struct { Name string `json:"name"` Status string `json:"status"` // ok, missing, version_mismatch, error Message string `json:"message,omitempty"` } ``` ### 2.2 Pack Engine API ```go package pack import ( "context" "io" "github.com/user/devpack/pkg/manifest" ) // Packer 打包器 type Packer struct { // ... } // NewPacker 创建打包器 func NewPacker(opts PackerOptions) *Packer // PackerOptions 打包器选项 type PackerOptions struct { Name string Description string Author string Compression CompressionType // gzip, zstd, none Encryption bool Password string } // Pack 执行打包 func (p *Packer) Pack(ctx context.Context, sourceDir string, output io.Writer) (*manifest.Manifest, error) // Unpacker 解包器 type Unpacker struct { // ... } // NewUnpacker 创建解包器 func NewUnpacker() *Unpacker // Unpack 执行解包 func (u *Unpacker) Unpack(ctx context.Context, input io.Reader, targetDir string) (*manifest.Manifest, error) // Verify 验证 Pack 文件 func (u *Unpacker) Verify(ctx context.Context, input io.Reader) (*VerifyResult, error) ``` ### 2.3 Restore Engine API ```go package restore import ( "context" "github.com/user/devpack/internal/collector" "github.com/user/devpack/pkg/manifest" ) // Engine 还原引擎 type Engine struct { registry *collector.Registry platform platform.Platform // ... } // NewEngine 创建还原引擎 func NewEngine(registry *collector.Registry, platform platform.Platform) *Engine // Plan 生成还原计划 func (e *Engine) Plan(ctx context.Context, m *manifest.Manifest, opts PlanOptions) (*RestorePlan, error) // Execute 执行还原计划 func (e *Engine) Execute(ctx context.Context, plan *RestorePlan) (*RestoreReport, error) // Rollback 回滚还原 func (e *Engine) Rollback(ctx context.Context, restorePointID string) error // RestorePlan 还原计划 type RestorePlan struct { PackName string `json:"pack_name"` Items []RestorePlanItem `json:"items"` Conflicts []ConflictItem `json:"conflicts"` TotalSteps int `json:"total_steps"` } // RestorePlanItem 还原计划项 type RestorePlanItem struct { Collector string `json:"collector"` ItemName string `json:"item_name"` Action RestoreAction `json:"action"` // install, upgrade, merge, skip, overwrite Current string `json:"current,omitempty"` Target string `json:"target"` Details string `json:"details,omitempty"` Order int `json:"order"` // 执行顺序 } // RestoreAction 还原动作 type RestoreAction string const ( ActionInstall RestoreAction = "install" ActionUpgrade RestoreAction = "upgrade" ActionMerge RestoreAction = "merge" ActionSkip RestoreAction = "skip" ActionOverwrite RestoreAction = "overwrite" ) // RestoreReport 还原报告 type RestoreReport struct { Success int `json:"success"` Failed int `json:"failed"` Skipped int `json:"skipped"` Items []ReportItem `json:"items"` Duration time.Duration `json:"duration"` RestorePointID string `json:"restore_point_id,omitempty"` } ``` --- ## 3. Pack 文件格式规范 ### 3.1 文件结构 ``` .devpack # tar.gz 归档 │ ├── manifest.json # Pack 清单(必需) ├── checksum.sha256 # 校验和文件(必需) │ ├── collectors/ # 采集器数据目录 │ ├── / # 分类目录 │ │ └── / # 采集器目录 │ │ ├── metadata.json # 采集器元数据 │ │ └── data/ # 采集器数据 │ │ └── ... # 具体数据文件 │ └── ... │ └── encrypted/ # 加密数据目录(可选) └── / └── data.enc # 加密数据 ``` ### 3.2 manifest.json 完整规范 ```json { "version": "0.1.0", "format_ver": "1", "pack_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "name": "my-dev-env", "description": "My full development environment", "author": "developer@example.com", "created_at": "2026-03-03T10:30:00Z", "tags": ["golang", "fullstack"], "source": { "hostname": "DESKTOP-ABC123", "os": "windows", "os_version": "10.0.22631", "arch": "amd64", "username": "developer", "devpack_version": "0.1.0" }, "collectors": [ { "name": "go", "category": "runtime", "display_name": "Go Runtime", "item_count": 4, "data_path": "collectors/runtime/go", "data_size": 2148576, "checksum": "sha256:abc123..." }, { "name": "vscode", "category": "editor", "display_name": "Visual Studio Code", "item_count": 36, "data_path": "collectors/editor/vscode", "data_size": 4412928, "checksum": "sha256:def456..." } ], "encryption": { "algorithm": "AES-256-GCM", "kdf": "argon2id", "kdf_params": { "time": 1, "memory": 65536, "threads": 4 }, "encrypted_collectors": ["ssh"] }, "checksum": "sha256:789abc..." } ``` ### 3.3 metadata.json 规范 每个采集器目录下的元数据文件: ```json { "collector": "go", "category": "runtime", "captured_at": "2026-03-03T10:30:00Z", "platform": { "os": "windows", "arch": "amd64" }, "items": [ { "name": "go", "version": "1.22.1", "type": "binary", "install_method": "direct", "install_url": "https://go.dev/dl/go1.22.1.windows-amd64.msi", "properties": { "GOPATH": "C:\\Users\\dev\\go", "GOROOT": "C:\\Program Files\\Go", "GOPROXY": "https://goproxy.cn,direct" } }, { "name": "gopls", "version": "0.15.1", "type": "tool", "install_method": "go_install", "install_command": "go install golang.org/x/tools/gopls@v0.15.1" }, { "name": "golangci-lint", "version": "1.56.2", "type": "tool", "install_method": "go_install", "install_command": "go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.56.2" } ], "files": [ { "source": "data/go-env.json", "description": "Go environment variables" } ] } ``` --- ## 4. 配置文件规范 ### 4.1 全局配置 (~/.devpack/config.yaml) ```yaml # DevPack 全局配置 version: "1" # 存储设置 storage: packs_dir: "~/.devpack/packs" # Pack 存储目录 profiles_dir: "~/.devpack/profiles" # Profile 目录 logs_dir: "~/.devpack/logs" # 日志目录 temp_dir: "" # 临时目录(空则使用系统默认) # 默认行为 defaults: profile: "default" # 默认 Profile compression: "gzip" # 压缩方式 (gzip|zstd|none) conflict_strategy: "prompt" # 冲突策略 create_restore_point: true # 还原前创建还原点 parallel_restore: 4 # 并行还原数 # 日志设置 logging: level: "info" # 日志级别 format: "text" # 日志格式 (text|json) file: "~/.devpack/logs/devpack.log" # 日志文件 # 网络设置(用于下载安装器) network: timeout: 300 # 下载超时(秒) proxy: "" # HTTP 代理 retries: 3 # 重试次数 # UI 设置 ui: color: true # 彩色输出 progress_bar: true # 进度条 interactive: true # 交互式提示 # 安全设置 security: default_encrypt: false # 默认是否加密 scan_for_secrets: true # 扫描敏感数据并警告 exclude_patterns: # 全局排除模式 - "*_KEY" - "*_SECRET" - "*_TOKEN" - "*_PASSWORD" ``` ### 4.2 Profile 配置文件规范 ```yaml # Profile 配置文件 name: "default" description: "Default development environment profile" version: "1" collectors: # 运行时采集器配置 runtime: enabled: true include: [] # 空列表 = 全部,非空 = 只包含列出的 exclude: [] # 排除列表 options: {} # 采集器特定选项 # 包管理器采集器配置 package: enabled: true include: [] exclude: [] options: scoop: include_buckets: true exclude_packages: [] chocolatey: exclude_packages: [] # 编辑器采集器配置 editor: enabled: true include: ["vscode"] options: vscode: capture_extensions: true capture_settings: true capture_keybindings: true capture_snippets: true exclude_extensions: [] # Shell 采集器配置 shell: enabled: true include: [] options: {} # Git 采集器配置 git: enabled: true options: capture_config: true capture_aliases: true capture_hooks: false # 环境变量采集器配置 env: enabled: true options: include_patterns: [] exclude_patterns: - "*_KEY" - "*_SECRET" # SSH/GPG 采集器配置 ssh: enabled: false # 默认禁用 options: encrypt: true # 必须加密 # 字体采集器配置 font: enabled: false options: include_fonts: [] # 空 = 自动检测开发字体 # 还原选项 restore: conflict_strategy: "prompt" create_restore_point: true dry_run_first: false # 自定义钩子(高级) hooks: pre_capture: "" # 捕获前执行的命令 post_capture: "" # 捕获后执行的命令 pre_restore: "" # 还原前执行的命令 post_restore: "" # 还原后执行的命令 ``` --- ## 5. 退出码 | 退出码 | 含义 | |--------|------| | 0 | 成功 | | 1 | 一般性错误 | | 2 | 命令行参数错误 | | 3 | 配置错误 | | 10 | Pack 文件损坏或无效 | | 11 | 平台不兼容 | | 12 | 版本不兼容 | | 20 | 还原失败 | | 21 | 还原部分成功 | | 22 | 冲突(需要用户介入) | | 30 | 权限不足 | | 40 | 网络错误 | | 50 | 加密/解密错误 | --- ## 6. 环境变量 | 变量 | 说明 | 默认值 | |------|------|--------| | `DEVPACK_HOME` | DevPack 主目录 | `~/.devpack` | | `DEVPACK_LOG_LEVEL` | 日志级别 | `info` | | `DEVPACK_LOG_FILE` | 日志文件路径 | `~/.devpack/logs/devpack.log` | | `DEVPACK_CONFIG` | 配置文件路径 | `~/.devpack/config.yaml` | | `DEVPACK_NO_COLOR` | 禁用彩色输出 | `false` | | `DEVPACK_PROFILE` | 默认 Profile | `default` | | `DEVPACK_HTTP_PROXY` | HTTP 代理 | - |