Skip to main content

sz_rust_cli/
lib.rs

1//! SZ-Rust CLI — 命令行工具
2//!
3//! Phase 8 交付物,替代 PHP `think` 命令,借鉴 Laravel Artisan 风格。
4//!
5//! ## PHP 对齐
6//!
7//! 本包对齐 PHP ThinkPHP 6 `think` 命令体系:
8//!
9//! - `php think make:model` → `sz-rust make:model`
10//! - `php think make:controller` → `sz-rust make:controller`
11//! - `php think make:migration` → `sz-rust make:migration`(Phinx 风格)
12//! - `php think migrate` → `sz-rust migrate`
13//! - `php think migrate:status` → `sz-rust migrate:status`
14//! - `php think route:list` → `sz-rust route:list`
15//! - `php think cache:clear` → `sz-rust cache:clear`
16//!
17//! ## 模块结构
18//!
19//! | 模块 | 功能 |
20//! |------|------|
21//! | `cli` | clap 命令定义(Cli / Commands / Options) |
22//! | `cmd::make` | make:* 代码生成命令 |
23//! | `cmd::migrate` | migrate / migrate:status 迁移命令 |
24//! | `cmd::route` | route:list 路由列表命令 |
25//! | `cmd::cache` | cache:clear 缓存清理命令 |
26//! | `cmd::scheduler` | scheduler:* 调度器命令(Phase 8.11-8.14) |
27//! | `error` | CLI 错误类型 |
28//! | `stubs` | 代码生成模板(对齐 PHP make/stubs) |
29//!
30//! ## R5 硬约束
31//!
32//! - R5-48:`make:model` 生成 Model 骨架代码对齐 PHP `think\console\command\make\Model`
33//! - R5-49:`make:controller` 生成 Controller 骨架代码对齐 PHP `think\console\command\make\Controller`
34//! - R5-50:`migrate:status` 显示迁移进度对齐 PHP `think migrate:status`
35//! - R5-51:`cache:clear` 清空缓存对齐 PHP `think cache:clear`
36
37pub mod cli;
38pub mod cmd;
39pub mod error;
40pub mod stubs;
41
42pub use cli::{Cli, Command};
43pub use error::CliError;
44
45/// 运行 CLI(入口函数)
46///
47/// 解析命令行参数并执行对应命令,返回退出码。
48///
49/// # 参数
50///
51/// - `args`:命令行参数(含程序名,如 `["sz-rust", "make", "model", "User"]`)
52///
53/// # 返回
54///
55/// - `Ok(0)`:成功
56/// - `Ok(code)`:命令指定的退出码
57/// - `Err(_)`:内部错误
58pub fn run<I, S>(args: I) -> Result<i32, CliError>
59where
60    I: IntoIterator<Item = S>,
61    S: Into<std::ffi::OsString> + Clone,
62{
63    use clap::Parser;
64    let cli = Cli::parse_from(args);
65    cli.execute()
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn test_run_no_args_returns_ok() {
74        // 仅程序名、无子命令:command=None,execute 返回 Ok(0)
75        let result = run(vec!["sz-rust"]);
76        assert!(result.is_ok());
77        assert_eq!(result.unwrap(), 0);
78    }
79
80    #[test]
81    fn test_run_version_flag() {
82        // --version 由 clap 处理后退出(clap 内部调用 exit,测试中会 panic)
83        // 因此这里只验证 --help 不影响 run 逻辑
84        let result = run(vec!["sz-rust", "cache:clear"]);
85        assert!(result.is_ok());
86    }
87}