sz-rust-cli 1.4.0

SZ-Rust 命令行工具:项目脚手架、数据库迁移、调度器管理
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-2026 SZ-Rust Team
//
//! CLI 命令定义 — 基于 clap derive
//!
//! 对齐 PHP ThinkPHP 6 `think` 命令体系,借鉴 Laravel Artisan 风格。
//!
//! ## PHP 对齐
//!
//! PHP `think` 命令使用 Symfony Console 组件,通过 `configure()` 定义参数和选项。
//! Rust 端使用 clap derive 宏,通过结构体字段定义参数和选项。
//!
//! ## 命令对照表
//!
//! | PHP | Rust | 说明 |
//! |-----|------|------|
//! | `php think make:model User` | `sz-rust make:model User` | 生成 Model |
//! | `php think make:controller User` | `sz-rust make:controller User` | 生成 Controller |
//! | `php think make:migration CreateUsers` | `sz-rust make:migration create_users` | 生成迁移文件 |
//! | `php think make:seeder UserSeeder` | `sz-rust make:seeder user_seeder` | 生成填充文件 |
//! | `php think make:validate User` | `sz-rust make:validate User` | 生成验证器 |
//! | `php think make:event User` | `sz-rust make:event User` | 生成事件 |
//! | `php think make:listener UserListener` | `sz-rust make:listener UserListener` | 生成监听器 |
//! | `php think make:command Hello` | `sz-rust make:command Hello` | 生成命令 |
//! | `php think make:service UserService` | `sz-rust make:service UserService` | 生成服务 |
//! | `php think migrate` | `sz-rust migrate` | 执行迁移 |
//! | `php think migrate:rollback` | `sz-rust migrate --rollback` | 回滚迁移 |
//! | `php think migrate:status` | `sz-rust migrate:status` | 迁移状态 |
//! | `php think db:seed` | `sz-rust db:seed` | 数据填充 |
//! | `php think route:list` | `sz-rust route:list` | 路由列表 |
//! | `php think cache:clear` | `sz-rust cache:clear` | 清空缓存 |
//! | `php think optimize:route` | `sz-rust optimize:route` | 路由缓存 |
//! | `php think optimize:config` | `sz-rust optimize:config` | 配置缓存 |
//! | `php think optimize:schema` | `sz-rust optimize:schema` | 数据表字段缓存 |
//! | `php think route:clear` | `sz-rust route:clear` | 清除路由缓存 |

use clap::{Parser, Subcommand};

use crate::cmd;
use crate::error::CliError;

/// SZ-Rust 命令行工具
///
/// 替代 PHP `think` 命令,提供代码生成、数据库迁移、路由查看、缓存管理等功能。
#[derive(Parser, Debug)]
#[command(
    name = "sz-rust",
    bin_name = "sz-rust",
    version,
    about = "SZ-Rust 命令行工具 — 替代 PHP think 命令",
    long_about = "SZ-Rust CLI 对齐 PHP ThinkPHP 6 think 命令体系,提供 make:migration / make:model / make:controller / migrate / route:list / cache:clear 等命令。"
)]
pub struct Cli {
    /// 子命令
    #[command(subcommand)]
    pub command: Option<Command>,
}

/// 顶层命令枚举
///
/// 对齐 PHP `think` 的命令分组(make / migrate / route / cache)。
#[derive(Subcommand, Debug)]
pub enum Command {
    /// 代码生成命令组(make:migration / make:model / make:controller / make:guard / make:scaffold)
    #[command(name = "make")]
    Make {
        /// make 子命令
        #[command(subcommand)]
        make_command: cmd::make::MakeCommand,
    },

    /// 数据库迁移命令(migrate / migrate:status / migrate:rollback)
    #[command(name = "migrate")]
    Migrate {
        /// 迁移子命令参数
        #[command(flatten)]
        args: cmd::migrate::MigrateArgs,
    },

    /// 迁移状态查询(对齐 PHP `php think migrate:status`)
    #[command(name = "migrate:status")]
    MigrateStatus {
        /// 迁移目录(默认 `migrations`)
        #[arg(short = 'p', long, default_value = "migrations")]
        path: String,

        /// 数据库类型(默认 `postgres`,对齐 sz-orm `DbType`)
        #[arg(long, default_value = "postgres")]
        db_type: String,

        /// 打印每个迁移的 SQL 内容
        #[arg(long)]
        show_sql: bool,

        /// 数据库连接 URL(启用在线模式,查询真实状态)
        ///
        /// 省略时为离线模式,所有迁移状态显示为 `Pending*`。
        #[arg(long)]
        url: Option<String>,
    },

    /// 路由列表(对齐 PHP `php think route:list`)
    #[command(name = "route:list")]
    RouteList {
        /// 输出格式(table / json)
        #[arg(short = 'f', long, default_value = "table")]
        format: String,
    },

    /// 清空缓存(对齐 PHP `php think cache:clear`)
    #[command(name = "cache:clear")]
    CacheClear {
        /// 指定缓存存储名(默认清空所有)
        #[arg(short = 's', long)]
        store: Option<String>,
    },

    /// 数据填充(对齐 PHP `php think db:seed`)
    ///
    /// 从 `seeds/` 目录加载 `.sql` 文件并执行。提供 `--url` 时连接数据库真实执行,
    /// 否则为离线模式(仅打印待执行内容)。
    #[command(name = "db:seed")]
    Seed {
        /// 填充目录(默认 `seeds`)
        #[arg(short = 'p', long, default_value = "seeds")]
        path: String,

        /// 数据库类型(默认 `postgres`,对齐 sz-orm `DbType`)
        #[arg(long, default_value = "postgres")]
        db_type: String,

        /// 打印每个填充文件的 SQL 内容
        #[arg(long)]
        show_sql: bool,

        /// 数据库连接 URL(启用在线模式)
        ///
        /// 省略时为离线模式,仅打印待执行的 SQL。
        #[arg(long)]
        url: Option<String>,

        /// 指定填充器文件名(不含扩展名,如 `001_users_seed`)
        ///
        /// 省略时执行目录下所有 `.sql` 文件。
        #[arg(short = 'c', long)]
        class: Option<String>,
    },

    /// 调度器命令组(scheduler:list / scheduler:run / scheduler:start)
    #[command(name = "scheduler")]
    Scheduler {
        /// scheduler 子命令
        #[command(subcommand)]
        scheduler_command: cmd::scheduler::SchedulerCommand,
    },

    /// 生成路由缓存(对齐 PHP `php think optimize:route`)
    ///
    /// 收集路由元数据,序列化为 JSON 写入 `runtime/cache/route_cache.json`。
    #[command(name = "optimize:route")]
    OptimizeRoute,

    /// 生成配置缓存(对齐 PHP `php think optimize:config`)
    ///
    /// 扫描 `config/` 目录,合并所有配置,序列化为 JSON 写入 `runtime/cache/config_cache.json`。
    #[command(name = "optimize:config")]
    OptimizeConfig,

    /// 生成数据表字段缓存(对齐 PHP `php think optimize:schema`)
    ///
    /// 读取 `config/database.yml` 数据库连接配置,生成 schema 缓存索引文件
    /// (`runtime/schema_cache.json` + `runtime/schema_cache.php`)。
    /// 业务方运行时通过 `SchemaCache::remember_schema()` 填充具体字段信息。
    #[command(name = "optimize:schema")]
    OptimizeSchema,

    /// 清除路由缓存(对齐 PHP `php think route:clear`)
    ///
    /// 删除 `runtime/cache/route_cache.json` 文件。
    #[command(name = "route:clear")]
    RouteClear,

    /// 插件市场命令组(plugin search/install/publish/uninstall/update/list/login)
    #[command(name = "plugin")]
    Plugin {
        /// plugin 子命令
        #[command(subcommand)]
        plugin_command: cmd::plugin::PluginCommand,
    },

    /// Admin 后台管理插件命令组(admin migrate/list-routes/list-capabilities/init)
    #[command(name = "admin")]
    Admin {
        /// admin 子命令
        #[command(subcommand)]
        admin_command: cmd::admin::AdminCommand,
    },

    /// 启动 HTTP 服务(对齐 PHP php think run)
    #[command(name = "serve")]
    Serve {
        /// 启用 admin 插件(加载 /api/admin/* 路由 + Capability 注册)
        #[arg(long)]
        with_admin: bool,

        /// 启用 tenant_middleware(从 X-Tenant-Id Header 提取租户 ID)
        #[arg(long)]
        with_tenant: bool,

        /// 启用 data_scope_middleware(注入数据权限上下文)
        #[arg(long)]
        with_data_scope: bool,

        /// 监听地址(默认 0.0.0.0:8080)
        #[arg(long, default_value = "0.0.0.0:8080")]
        addr: String,

        /// 启用配置热重载(监听 config/ 目录文件变更)
        #[arg(long)]
        watch_config: bool,

        /// worker 线程数(默认 CPU 核心数,上限 1024)
        #[arg(long)]
        workers: Option<u16>,

        /// 优雅关闭超时秒数(默认 30,上限 300)
        #[arg(long)]
        grace_timeout: Option<u16>,

        /// TLS 证书文件路径
        #[arg(long)]
        tls_cert: Option<std::path::PathBuf>,

        /// TLS 私钥文件路径
        #[arg(long)]
        tls_key: Option<std::path::PathBuf>,

        /// 启用访问日志中间件
        #[arg(long)]
        access_log: bool,

        /// 启用健康检查端点(默认启用)
        #[arg(long, default_value_t = true)]
        health: bool,

        /// 禁用健康检查端点
        #[arg(long, conflicts_with = "health")]
        no_health: bool,
    },

    /// 触发运行中的 serve 进程重载配置(Windows 替代 SIGUSR1/SIGHUP)
    ///
    /// Unix 平台建议使用 `kill -USR1 <pid>` 或 `kill -HUP <pid>`。
    /// 首版仅输出提示信息,完整实现需后续版本支持。
    #[command(name = "serve:reload")]
    ServeReload,

    /// 触发运行中的 serve 进程切换日志级别(Windows 替代 SIGUSR2)
    ///
    /// Unix 平台建议使用 `kill -USR2 <pid>`。
    /// 首版仅输出提示信息,完整实现需后续版本支持。
    #[command(name = "serve:log-level")]
    ServeLogLevel,
}

impl Cli {
    /// 执行命令
    ///
    /// 根据 `command` 字段分发到对应的命令处理器。
    ///
    /// # 返回
    ///
    /// - `Ok(0)`:成功
    /// - `Ok(code)`:命令指定的退出码(非 0 表示部分失败)
    /// - `Err(_)`:内部错误
    pub async fn execute(&self) -> Result<i32, CliError> {
        match &self.command {
            None => {
                // 无子命令,打印帮助
                println!("SZ-Rust CLI — 使用 --help 查看可用命令");
                Ok(0)
            }
            Some(Command::Make { make_command }) => {
                cmd::make::execute(make_command).await.map(|_| 0)
            }
            Some(Command::Migrate { args }) => cmd::migrate::execute_migrate(args).await.map(|_| 0),
            Some(Command::MigrateStatus {
                path,
                db_type,
                show_sql,
                url,
            }) => cmd::migrate::execute_status_full(path, db_type, *show_sql, url.as_deref())
                .await
                .map(|_| 0),
            Some(Command::RouteList { format }) => {
                cmd::route::execute_route_list(format).map(|_| 0)
            }
            Some(Command::CacheClear { store }) => {
                cmd::cache::execute_cache_clear(store.as_deref()).map(|_| 0)
            }
            Some(Command::Seed {
                path,
                db_type,
                show_sql,
                url,
                class,
            }) => {
                let args = cmd::seed::SeedArgs {
                    path: path.clone(),
                    db_type: db_type.clone(),
                    show_sql: *show_sql,
                    url: url.clone(),
                    class: class.clone(),
                };
                cmd::seed::execute_seed(&args).map(|_| 0)
            }
            Some(Command::Scheduler { scheduler_command }) => {
                cmd::scheduler::execute(scheduler_command).map(|_| 0)
            }
            Some(Command::OptimizeRoute) => {
                cmd::optimize::execute_optimize_route().await.map(|_| 0)
            }
            Some(Command::OptimizeConfig) => {
                cmd::optimize::execute_optimize_config().await.map(|_| 0)
            }
            Some(Command::OptimizeSchema) => {
                cmd::optimize::execute_optimize_schema().await.map(|_| 0)
            }
            Some(Command::RouteClear) => cmd::optimize::execute_route_clear().await.map(|_| 0),
            Some(Command::Plugin { plugin_command }) => cmd::plugin::execute(plugin_command).await,
            Some(Command::Admin { admin_command }) => cmd::admin::execute(admin_command).await,
            Some(Command::Serve {
                with_admin,
                with_tenant,
                with_data_scope,
                addr,
                watch_config,
                workers,
                grace_timeout,
                tls_cert,
                tls_key,
                access_log,
                health,
                no_health,
            }) => {
                let args = cmd::serve::ServeArgs {
                    with_admin: *with_admin,
                    with_tenant: *with_tenant,
                    with_data_scope: *with_data_scope,
                    addr: addr.clone(),
                    watch_config: *watch_config,
                    workers: *workers,
                    grace_timeout: *grace_timeout,
                    tls_cert: tls_cert.clone(),
                    tls_key: tls_key.clone(),
                    access_log: *access_log,
                    health: *health && !*no_health,
                };
                tokio::task::spawn_blocking(move || cmd::serve::execute(args))
                    .await
                    .map_err(|e| CliError::Generic(format!("serve 任务执行失败: {e}")))?
            }
            Some(Command::ServeReload) => {
                println!("Windows 信号替代方案暂未实现,请使用 --watch-config 或重启服务");
                Ok(0)
            }
            Some(Command::ServeLogLevel) => {
                println!("Windows 信号替代方案暂未实现,请使用 --watch-config 或重启服务");
                Ok(0)
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::await_holding_lock)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn test_parse_make_model() {
        let cli = Cli::parse_from(["sz-rust", "make", "model", "User"]);
        match cli.command {
            Some(Command::Make { make_command }) => {
                assert!(matches!(make_command, cmd::make::MakeCommand::Model { .. }));
            }
            _ => panic!("expected Make command"),
        }
    }

    #[test]
    fn test_parse_make_controller() {
        let cli = Cli::parse_from(["sz-rust", "make", "controller", "User"]);
        match cli.command {
            Some(Command::Make { make_command }) => {
                assert!(matches!(
                    make_command,
                    cmd::make::MakeCommand::Controller { .. }
                ));
            }
            _ => panic!("expected Make command"),
        }
    }

    #[test]
    fn test_parse_make_migration() {
        let cli = Cli::parse_from(["sz-rust", "make", "migration", "create_users"]);
        match cli.command {
            Some(Command::Make { make_command }) => {
                assert!(matches!(
                    make_command,
                    cmd::make::MakeCommand::Migration { .. }
                ));
            }
            _ => panic!("expected Make command"),
        }
    }

    #[test]
    fn test_parse_optimize_schema() {
        let cli = Cli::parse_from(["sz-rust", "optimize:schema"]);
        assert!(matches!(cli.command, Some(Command::OptimizeSchema)));
    }

    #[test]
    fn test_parse_make_validate() {
        let cli = Cli::parse_from(["sz-rust", "make", "validate", "User"]);
        match cli.command {
            Some(Command::Make { make_command }) => {
                assert!(matches!(
                    make_command,
                    cmd::make::MakeCommand::Validate { .. }
                ));
            }
            _ => panic!("expected Make command"),
        }
    }

    #[test]
    fn test_parse_make_seeder() {
        let cli = Cli::parse_from(["sz-rust", "make", "seeder", "001_users"]);
        match cli.command {
            Some(Command::Make { make_command }) => {
                assert!(matches!(
                    make_command,
                    cmd::make::MakeCommand::Seeder { .. }
                ));
            }
            _ => panic!("expected Make command"),
        }
    }

    #[test]
    fn test_parse_migrate() {
        let cli = Cli::parse_from(["sz-rust", "migrate"]);
        assert!(matches!(cli.command, Some(Command::Migrate { .. })));
    }

    #[test]
    fn test_parse_migrate_status() {
        let cli = Cli::parse_from(["sz-rust", "migrate:status"]);
        assert!(matches!(cli.command, Some(Command::MigrateStatus { .. })));
    }

    #[test]
    fn test_parse_route_list() {
        let cli = Cli::parse_from(["sz-rust", "route:list"]);
        assert!(matches!(cli.command, Some(Command::RouteList { .. })));
    }

    #[test]
    fn test_parse_cache_clear() {
        let cli = Cli::parse_from(["sz-rust", "cache:clear"]);
        assert!(matches!(cli.command, Some(Command::CacheClear { .. })));
    }

    #[test]
    fn test_parse_cache_clear_with_store() {
        let cli = Cli::parse_from(["sz-rust", "cache:clear", "--store", "redis"]);
        match cli.command {
            Some(Command::CacheClear { store }) => {
                assert_eq!(store.as_deref(), Some("redis"));
            }
            _ => panic!("expected CacheClear command"),
        }
    }

    #[test]
    fn test_parse_scheduler() {
        let cli = Cli::parse_from(["sz-rust", "scheduler", "list"]);
        assert!(matches!(cli.command, Some(Command::Scheduler { .. })));
    }

    #[test]
    fn test_parse_db_seed() {
        let cli = Cli::parse_from(["sz-rust", "db:seed"]);
        assert!(matches!(cli.command, Some(Command::Seed { .. })));
    }

    #[test]
    fn test_parse_db_seed_with_options() {
        let cli = Cli::parse_from([
            "sz-rust",
            "db:seed",
            "--path",
            "custom_seeds",
            "--db-type",
            "mysql",
            "--show-sql",
            "--url",
            "mysql://user:pass@host:3306/db",
            "--class",
            "001_users",
        ]);
        match cli.command {
            Some(Command::Seed {
                path,
                db_type,
                show_sql,
                url,
                class,
            }) => {
                assert_eq!(path, "custom_seeds");
                assert_eq!(db_type, "mysql");
                assert!(show_sql);
                assert_eq!(url.as_deref(), Some("mysql://user:pass@host:3306/db"));
                assert_eq!(class.as_deref(), Some("001_users"));
            }
            _ => panic!("expected Seed command"),
        }
    }

    #[tokio::test]
    async fn test_execute_no_command_returns_ok() {
        let cli = Cli { command: None };
        let result = cli.execute().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_execute_make_model() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::Make {
                make_command: cmd::make::MakeCommand::Model {
                    name: "User".to_string(),
                },
            }),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
        assert!(temp.path().join("app/model/User.rs").exists());
    }

    #[tokio::test]
    async fn test_execute_migrate_offline() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::Migrate {
                args: cmd::migrate::MigrateArgs {
                    rollback: false,
                    path: temp.path().to_string_lossy().to_string(),
                    db_type: "postgres".to_string(),
                    show_sql: false,
                    url: None,
                },
            }),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_migrate_status_offline() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::MigrateStatus {
                path: temp.path().to_string_lossy().to_string(),
                db_type: "postgres".to_string(),
                show_sql: false,
                url: None,
            }),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_route_list() {
        let cli = Cli {
            command: Some(Command::RouteList {
                format: "table".to_string(),
            }),
        };
        let result = cli.execute().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_cache_clear() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::CacheClear { store: None }),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_seed_offline() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::Seed {
                path: temp.path().to_string_lossy().to_string(),
                db_type: "postgres".to_string(),
                show_sql: false,
                url: None,
                class: None,
            }),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_scheduler_list() {
        let cli = Cli {
            command: Some(Command::Scheduler {
                scheduler_command: cmd::scheduler::SchedulerCommand::List {
                    config: std::path::PathBuf::from("/nonexistent/scheduler.toml"),
                },
            }),
        };
        let result = cli.execute().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_optimize_route() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::OptimizeRoute),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_optimize_config() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        // execute_optimize_config 需要 config 目录存在
        std::fs::create_dir_all(temp.path().join("config")).unwrap();

        let cli = Cli {
            command: Some(Command::OptimizeConfig),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_optimize_schema() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::OptimizeSchema),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_route_clear() {
        let _lock = crate::cmd::test_support::acquire_global_lock();
        let temp = tempfile::tempdir().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        let cli = Cli {
            command: Some(Command::RouteClear),
        };
        let result = cli.execute().await;
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_plugin_login_without_token() {
        let cli = Cli {
            command: Some(Command::Plugin {
                plugin_command: cmd::plugin::PluginCommand::Login(cmd::plugin::LoginArgs {
                    token: None,
                    url: None,
                }),
            }),
        };
        let result = cli.execute().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 1);
    }

    #[tokio::test]

    async fn test_execute_serve_reload() {
        let cli = Cli {
            command: Some(Command::ServeReload),
        };
        let result = cli.execute().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_execute_serve_log_level() {
        let cli = Cli {
            command: Some(Command::ServeLogLevel),
        };
        let result = cli.execute().await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_execute_admin_via_parse_list_routes() {
        let cli = Cli::parse_from(["sz-rust", "admin", "list-routes"]);
        let result = cli.execute().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_admin_via_parse_list_capabilities() {
        let cli = Cli::parse_from(["sz-rust", "admin", "list-capabilities"]);
        let result = cli.execute().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_admin_via_parse_migrate_offline() {
        let cli = Cli::parse_from(["sz-rust", "admin", "migrate", "--show-sql"]);
        let result = cli.execute().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_execute_admin_via_parse_init_offline() {
        let cli = Cli::parse_from(["sz-rust", "admin", "init"]);
        let result = cli.execute().await;
        assert!(result.is_ok());
    }
}