Skip to content

refactor: 使用 Clap 重构命令行解析#260

Open
litwak913 wants to merge 7 commits into
MistEO:mainfrom
litwak913:clap
Open

refactor: 使用 Clap 重构命令行解析#260
litwak913 wants to merge 7 commits into
MistEO:mainfrom
litwak913:clap

Conversation

@litwak913

@litwak913 litwak913 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

使用 Clap 重构命令行解析,并将 AttachConsoleFreeConsole 替换为 winsafe 实现

Summary by Sourcery

重构命令行处理逻辑,使用集中式、基于 Clap 的解析器,并确保在应用启动的早期阶段就处理帮助输出。

新特性:

  • 引入通过 Clap 解析的 Cli 结构体,用于管理命令行选项,例如自动启动、实例选择以及运行后退出。

改进:

  • 用共享的 Cli 状态替代手动的参数检查,并由 Tauri 命令访问该状态。
  • 更新在 Windows 上附加控制台的逻辑,在打印 CLI 帮助时改用 winsafe 的辅助工具。
  • 调整屏幕关闭动作的消息处理,使用更新后的 winsafe 消息类型 API。

构建:

  • 添加 Clap 作为依赖并启用 derive 支持,同时提升 winsafe 的 Git 修订版本。
Original summary in English

Summary by Sourcery

Refactor command-line handling to use a centralized Clap-based parser and ensure help output is handled early in application startup.

New Features:

  • Introduce a Cli struct parsed via Clap to manage command-line options such as autostart, instance selection, and quit-after-run.

Enhancements:

  • Replace manual argument inspection with shared Cli state accessed by Tauri commands.
  • Update Windows console attachment logic to use winsafe helpers when printing CLI help.
  • Adjust screen-off action messaging to use the updated winsafe message type API.

Build:

  • Add Clap as a dependency with derive support and bump the winsafe git revision.

@litwak913 litwak913 changed the title feat: 使用 Clap 重构命令行解析 refactor: 使用 Clap 重构命令行解析 Jun 29, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - 我发现了 1 个问题,并且留下了一些总体反馈:

  • init_cli() 中调用 std::process::exit(0),意味着未来如果在非启动路径(例如 tauri 命令或后台任务)中使用这个辅助函数,可能会意外终止进程;建议将帮助信息处理限定在 main 中,或者改为返回一个结果值。
  • 使用 winsafe::AttachConsolewinsafe::FreeConsole 时,你现在总是调用 FreeConsole,却没有跟踪 attach 是否实际成功;如果之前的语义是有意为之,建议保留 attach 的状态,或者在释放前检查返回值。
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
-`init_cli()` 中调用 `std::process::exit(0)`,意味着未来如果在非启动路径(例如 tauri 命令或后台任务)中使用这个辅助函数,可能会意外终止进程;建议将帮助信息处理限定在 `main` 中,或者改为返回一个结果值。
- 使用 `winsafe::AttachConsole``winsafe::FreeConsole` 时,你现在总是调用 `FreeConsole`,却没有跟踪 attach 是否实际成功;如果之前的语义是有意为之,建议保留 attach 的状态,或者在释放前检查返回值。

## Individual Comments

### Comment 1
<location path="src-tauri/src/commands/system.rs" line_range="52" />
<code_context>
+
+pub fn init_cli() -> &'static Cli {
+    CLI.get_or_init(|| {
+        let cli = Cli::parse();
+        if cli.help {
+            #[cfg(windows)]
</code_context>
<issue_to_address>
**suggestion:** 使用 `Cli::parse()` 相比之前的手动解析方式,可能会改变对未知/无效参数的处理行为。

之前的临时解析基本上会忽略未知参数,而 `Cli::parse()` 现在会将未知或格式错误的参数视为错误并以非零状态退出。在 Tauri/GUI 应用中,如果启动器或操作系统集成注入了额外参数,这可能导致启动失败。如果你不希望这种更严格的行为,可以考虑配置 clap 以容忍未知参数(例如使用尾随可变参数的 "rest"),或者使用 `Cli::try_parse()` 并显式处理解析错误。

Suggested implementation:

```rust
pub fn init_cli() -> &'static Cli {
    CLI.get_or_init(|| {
        match Cli::try_parse() {
            Ok(cli) => cli,
            Err(err) => {
                // Preserve GUI startup even if unknown or malformed CLI args are present.
                // We log the error and fall back to a "no‑flags" default CLI config.
                warn!("Failed to parse CLI arguments (falling back to defaults): {err}");
                Cli::parse_from(["app"])
            }
        }
    })

```

1. 确保 `use log::warn;` 出现在 `src-tauri/src/commands/system.rs` 顶部(在任何函数之外)。如果它目前在函数内部,或者由于之前的修改出现在了不合适的位置,请将它移动到与其他 `use` 语句一起的导入部分。
2. 如果你的 `Cli` 类型在使用 `parse_from` 时需要特定的程序名,请将 `"app"` 替换为适合你的二进制程序的名称(例如 `"my-tauri-app"`)。
</issue_to_address>

Sourcery 对开源项目免费——如果你觉得我们的评审有帮助,欢迎分享 ✨
帮我变得更有用!请在每条评论上点 👍 或 👎,我会根据你的反馈改进后续评审。
Original comment in English

Hey - I've found 1 issue, and left some high level feedback:

  • Calling std::process::exit(0) inside init_cli() means any future use of this helper from non-startup paths (e.g. tauri commands or background tasks) could unexpectedly terminate the process; consider scoping help handling to main or returning a result instead.
  • When using winsafe::AttachConsole and winsafe::FreeConsole, you now always call FreeConsole without tracking whether attach actually succeeded; if the previous semantics were intentional, consider preserving the attach state or checking the return value before detaching.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Calling `std::process::exit(0)` inside `init_cli()` means any future use of this helper from non-startup paths (e.g. tauri commands or background tasks) could unexpectedly terminate the process; consider scoping help handling to `main` or returning a result instead.
- When using `winsafe::AttachConsole` and `winsafe::FreeConsole`, you now always call `FreeConsole` without tracking whether attach actually succeeded; if the previous semantics were intentional, consider preserving the attach state or checking the return value before detaching.

## Individual Comments

### Comment 1
<location path="src-tauri/src/commands/system.rs" line_range="52" />
<code_context>
+
+pub fn init_cli() -> &'static Cli {
+    CLI.get_or_init(|| {
+        let cli = Cli::parse();
+        if cli.help {
+            #[cfg(windows)]
</code_context>
<issue_to_address>
**suggestion:** Using `Cli::parse()` may change behavior for unknown/invalid flags compared to the previous manual parsing.

The previous ad‑hoc parsing effectively ignored unknown flags, while `Cli::parse()` will now treat unknown or malformed arguments as errors and exit non‑zero. In a Tauri/GUI app this may cause startup failures when extra arguments are injected by launchers or OS integrations. If you don’t want this stricter behavior, consider configuring clap to tolerate unknown arguments (e.g., a trailing var‑arg "rest"), or use `Cli::try_parse()` and handle parse errors explicitly.

Suggested implementation:

```rust
pub fn init_cli() -> &'static Cli {
    CLI.get_or_init(|| {
        match Cli::try_parse() {
            Ok(cli) => cli,
            Err(err) => {
                // Preserve GUI startup even if unknown or malformed CLI args are present.
                // We log the error and fall back to a "no‑flags" default CLI config.
                warn!("Failed to parse CLI arguments (falling back to defaults): {err}");
                Cli::parse_from(["app"])
            }
        }
    })

```

1. Ensure `use log::warn;` is present at the top of `src-tauri/src/commands/system.rs` (outside of any function). If it is currently inside a function or in an invalid position due to previous edits, move it to the import section with the other `use` statements.
2. If your `Cli` type requires a specific program name for `parse_from`, replace `"app"` with whatever is appropriate for your binary (e.g., `"my-tauri-app"`).
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src-tauri/src/commands/system.rs
@isHarryh

Copy link
Copy Markdown
Contributor

命令帮助文本的国际化是否考虑一下?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants