sz_rust_cli/lib.rs
1//! SZ-Rust CLI — 命令行工具
2//!
3//! 替代 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//! | `console` | 自定义命令注册与分发(对齐 PHP `think\console\Console`) |
23//! | `cmd::make` | make:* 代码生成命令 |
24//! | `cmd::migrate` | migrate / migrate:status 迁移命令 |
25//! | `cmd::route` | route:list 路由列表命令 |
26//! | `cmd::cache` | cache:clear 缓存清理命令 |
27//! | `cmd::scheduler` | scheduler:* 调度器命令 |
28//! | `error` | CLI 错误类型 |
29//! | `stubs` | 代码生成模板(对齐 PHP make/stubs) |
30//!
31//! ## R5 硬约束
32//!
33//! - R5-48:`make:model` 生成 Model 骨架代码对齐 PHP `think\console\command\make\Model`
34//! - R5-49:`make:controller` 生成 Controller 骨架代码对齐 PHP `think\console\command\make\Controller`
35//! - R5-50:`migrate:status` 显示迁移进度对齐 PHP `think migrate:status`
36//! - R5-51:`cache:clear` 清空缓存对齐 PHP `think cache:clear`
37
38#![forbid(unsafe_code)]
39#![warn(missing_docs)]
40
41pub mod cli;
42pub mod cmd;
43pub mod console;
44pub mod error;
45pub mod stubs;
46
47pub use cli::{Cli, Command as CliCommand};
48pub use console::{Command, CommandSignature, Console};
49pub use error::CliError;
50
51/// 运行 CLI(入口函数)
52///
53/// 解析命令行参数并执行对应命令,返回退出码。
54///
55/// # 参数
56///
57/// - `args`:命令行参数(含程序名,如 `["sz-rust", "make", "model", "User"]`)
58///
59/// # 返回
60///
61/// - `Ok(0)`:成功
62/// - `Ok(code)`:命令指定的退出码
63/// - `Err(_)`:内部错误
64pub fn run<I, S>(args: I) -> Result<i32, CliError>
65where
66 I: IntoIterator<Item = S>,
67 S: Into<std::ffi::OsString> + Clone,
68{
69 use clap::Parser;
70 let cli = Cli::parse_from(args);
71 cli.execute()
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn test_run_no_args_returns_ok() {
80 // 仅程序名、无子命令:command=None,execute 返回 Ok(0)
81 let result = run(vec!["sz-rust"]);
82 assert!(result.is_ok());
83 assert_eq!(result.unwrap(), 0);
84 }
85
86 #[test]
87 fn test_run_version_flag() {
88 // --version 由 clap 处理后退出(clap 内部调用 exit,测试中会 panic)
89 // 因此这里只验证 --help 不影响 run 逻辑
90 let result = run(vec!["sz-rust", "cache:clear"]);
91 assert!(result.is_ok());
92 }
93}