Skip to content

feat: main.py 支持 -h/--help 瞬时退出 - #4

Merged
MisonL merged 2 commits into
mainfrom
feat/cli-help-and-polish
Oct 14, 2026
Merged

MisonL merged 2 commits into
mainfrom
feat/cli-help-and-polish

Conversation

@MisonL

@MisonL MisonL commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

目的

TUI 真实体验检查(pty 驱动真实会话)发现的可用性缺口:run_cli 除 --smoke-test 外静默忽略一切命令行参数——新用户照惯例敲 --help 会直接进交互菜单(实测复现),只能 Ctrl+C 退出重来。

影响范围

  • main.py:run_cli 在初始化依赖之前拦截 -h/--help,打印用法(含 --smoke-test 与无参数行为说明)并退出 0。--help 必须瞬时返回,因此不做任何依赖初始化。
  • tests/test_main_entry.py:回归测试钉住「两个 flag 都打印用法且不进交互菜单/不触发自检」(红/绿验证:旧行为进菜单、新行为打印用法)。
  • CHANGELOG.md:新增 [Unreleased] / 新增 节。

验证命令

uv run pytest tests/test_main_entry.py -q   # 18 passed
uv run pytest -q                            # 4531 passed
uv run main.py --help                       # 打印用法,exit 0
# 8 项质量门全绿(ruff format/check、bandit、mypy、compileall、uv lock、git diff、smoke-test、verify_sites selftest)

配置影响

无。config.toml 的本机默认渠道修正(google→gpt-5-6-sol)是用户本机私有配置(git 忽略),不入库。

🤖 Generated with Claude Code

Sourcery 摘要

支持立即输出 CLI 帮助信息,让用户无需进入交互式菜单即可查看可用选项。

新功能:

  • 新增对 -h/--help 的即时处理:显示 CLI 用法并成功退出,不进入交互式应用。

错误修复:

  • 防止帮助参数被静默忽略并错误地启动交互式菜单。

文档:

  • 在未发布的变更日志中说明新增的帮助选项及其行为。

测试:

  • 添加回归测试,确保这两个帮助标志都会输出用法信息,且不会调用交互式菜单或冒烟测试。
Original summary in English

Summary by Sourcery

Support immediate CLI help output so users can discover available options without entering the interactive menu.

New Features:

  • Add immediate -h/--help handling to display CLI usage and exit successfully before entering the interactive application.

Bug Fixes:

  • Prevent help arguments from being silently ignored and incorrectly launching the interactive menu.

Documentation:

  • Document the new help options and behavior in the unreleased changelog.

Tests:

  • Add regression coverage ensuring both help flags print usage without invoking the interactive menu or smoke test.

MisonL and others added 2 commits October 14, 2026 22:00
旧实现除 --smoke-test 外静默忽略一切参数,新用户照惯例敲 --help
直接进交互菜单(实测复现),只能 Ctrl+C 退出重来。现在 -h/--help
在初始化依赖之前打印用法并退出(--help 必须瞬时返回)。
回归测试红/绿验证(旧行为进菜单、新行为打印用法)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 14, 2026

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bfe9ce90-f77b-4e10-a850-e4332e074375
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

审查者指南

本 PR 在 run_cli 初始化依赖前拦截 -h/--help,输出包含现有运行模式的用法说明并瞬时以 0 退出;同时通过回归测试确认不会进入交互菜单或触发自检,并更新变更日志。

CLI 帮助处理流程图

flowchart TD
    Start[run_cli] --> Parse[解析 argv]
    Parse --> Help{存在 -h 或 --help?}
    Help -->|是| Usage[打印版本与用法]
    Usage --> ExitHelp[返回 0]
    Help -->|否| Smoke{存在 --smoke-test?}
    Smoke -->|是| RunSmoke[run_smoke_test]
    Smoke -->|否| Interactive[进入交互式菜单]
Loading

文件级变更

变更 详情 文件
在依赖初始化和其他 CLI 分支之前处理帮助参数,输出简明用法并立即返回成功状态。
  • 同时识别 -h 和 --help。
  • 展示版本、用法、--smoke-test、帮助选项及无参数行为。
  • 确保帮助路径不进入交互菜单或触发自检。
main.py
增加帮助参数行为的回归覆盖,验证输出和提前退出语义。
  • 分别测试 -h 与 --help。
  • 断言返回码为 0、未调用交互入口和自检,并包含关键用法文本。
tests/test_main_entry.py
记录未发布版本中的帮助功能改动及用户体验修复。
  • 新增 [Unreleased] 下的功能条目。
CHANGELOG.md

提示与命令

与 Sourcery 交互

  • 触发新的审查: 在拉取请求中评论 @sourcery-ai review。
  • 继续讨论: 直接回复 Sourcery 的审查评论。
  • 根据审查评论创建 GitHub Issue: 回复审查评论,请 Sourcery 根据该评论创建 Issue。你也可以在审查评论中回复 @sourcery-ai issue 来创建 Issue。
  • 生成拉取请求标题: 在拉取请求标题中的任意位置写入 @sourcery-ai,即可随时生成标题。你也可以在拉取请求中评论 @sourcery-ai title,随时重新生成标题。
  • 生成拉取请求摘要: 在拉取请求正文中你希望生成摘要的位置写入 @sourcery-ai summary,即可随时生成 PR 摘要。你也可以在拉取请求中评论 @sourcery-ai summary,随时重新生成摘要。
  • 生成审查者指南: 在拉取请求中评论 @sourcery-ai guide,即可随时重新生成审查者指南。
  • 解决所有 Sourcery 评论: 在拉取请求中评论 @sourcery-ai resolve,即可解决所有 Sourcery 评论。如果你已处理完所有评论且不想再看到它们,这个命令会很有用。
  • 忽略所有 Sourcery 审查: 在拉取请求中评论 @sourcery-ai dismiss,即可忽略所有现有的 Sourcery 审查。如果你想从头开始进行新的审查,这个命令尤其有用——别忘了评论 @sourcery-ai review 来触发新的审查!

自定义使用体验

访问你的控制面板,即可:

  • 启用或停用审查功能,例如 Sourcery 生成的拉取请求摘要、审查者指南等。
  • 更改审查语言。
  • 添加、移除或编辑自定义审查说明。
  • 调整其他审查设置。

获取帮助

Original review guide in English

Reviewer's Guide

本 PR 在 run_cli 初始化依赖前拦截 -h/--help,输出包含现有运行模式的用法说明并瞬时以 0 退出;同时通过回归测试确认不会进入交互菜单或触发自检,并更新变更日志。

Flow diagram for CLI help handling

flowchart TD
    Start[run_cli] --> Parse[解析 argv]
    Parse --> Help{存在 -h 或 --help?}
    Help -->|是| Usage[打印版本与用法]
    Usage --> ExitHelp[返回 0]
    Help -->|否| Smoke{存在 --smoke-test?}
    Smoke -->|是| RunSmoke[run_smoke_test]
    Smoke -->|否| Interactive[进入交互式菜单]
Loading

File-Level Changes

Change Details Files
在依赖初始化和其他 CLI 分支之前处理帮助参数,输出简明用法并立即返回成功状态。
  • 同时识别 -h 和 --help。
  • 展示版本、用法、--smoke-test、帮助选项及无参数行为。
  • 确保帮助路径不进入交互菜单或触发自检。
main.py
增加帮助参数行为的回归覆盖,验证输出和提前退出语义。
  • 分别测试 -h 与 --help。
  • 断言返回码为 0、未调用交互入口和自检,并包含关键用法文本。
tests/test_main_entry.py
记录未发布版本中的帮助功能改动及用户体验修复。
  • 新增 [Unreleased] 下的功能条目。
CHANGELOG.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

嗨——我发现了 4 个问题

给 AI Agent 的提示
请处理本次代码审查中的评论:

## 单独评论

### 评论 1
<location path="main.py" line_range="383" />
<code_context>
+        console.print("  --smoke-test   非交互式启动自检(构建验证用)")
+        console.print("  -h, --help     显示本帮助并退出")
+        console.print("  无参数          进入交互式菜单(向量化 / 召回测试 / 聊天)")
+        return 0
     try:
         if "--smoke-test" in args:
</code_context>
<issue_to_address>
**帮助命令会删除缓存文件**

当配置的缓存目录中含有文件,或有其他进程正在使用该目录时,退出时已注册的 `cleanup_temp_files` 回调会对配置的缓存目录调用 `shutil.rmtree`,删除其中的文件并干扰使用这些文件的进程。

对于帮助命令,跳过或注销清理回调,确保显示帮助后退出时绝不会删除配置的缓存目录。
</issue_to_address>

### 评论 2
<location path="main.py" line_range="374" />
<code_context>
     import 期的失败由 ``get_settings`` 的边界负责(此处尚未执行)。
     """
     args = list(sys.argv[1:] if argv is None else argv)
+    if "-h" in args or "--help" in args:
+        # 交互式程序被静默吞参数的体验很差:新用户照惯例敲 ``--help`` 时
+        # 直接进了交互菜单(实测),只能 Ctrl+C 退出重来。给出简明用法
</code_context>
<issue_to_address>
**设置无效时帮助命令会失败**

当配置格式错误或未通过设置验证时,在 `run_cli` 执行到帮助分支之前,`main.py` 就会导入 `src.utils.cleanup`;该模块级 logger 会调用 `get_settings()`,并在导入期间引发异常,因此 `--help` 不会显示用法,而是报错退出。

将 `src.utils.cleanup` 的导入以及依赖设置的 logger 初始化延后,直到处理完帮助分支之后再执行。
</issue_to_address>

### 评论 3
<location path="main.py" line_range="379" />
<code_context>
+        # 直接进了交互菜单(实测),只能 Ctrl+C 退出重来。给出简明用法
+        # 后退出,不初始化依赖(``--help`` 必须瞬时返回)。
+        console.print(markup_text("PyRAG-Kit {}", VERSION))
+        console.print("用法: python main.py [选项]")
+        console.print("  --smoke-test   非交互式启动自检(构建验证用)")
+        console.print("  -h, --help     显示本帮助并退出")
</code_context>
<issue_to_address>
**打包后的帮助显示了无法使用的命令**

在冻结版本中请求帮助时,用法行会指示用户运行 `python main.py`,但发布包中包含的是 `PyRAG-Kit` 可执行文件,而不是独立的 `main.py`,因此用户无法按照说明运行选项。

冻结版本的用法行应显示 `PyRAG-Kit` 可执行文件。
</issue_to_address>

### 评论 4
<location path="tests/test_main_entry.py" line_range="347" />
<code_context>
+    """
+    called = {"main": 0, "smoke": 0}
+
+    monkeypatch.setattr(main, "main", lambda: called.__setitem__("main", 1))
+    monkeypatch.setattr(main, "run_smoke_test", lambda: called.__setitem__("smoke", 1))
+
</code_context>
<issue_to_address>
**帮助命令初始化依赖的问题未被测试发现**

如果回归导致在帮助分支之前调用 `initialize_dependencies()`,`test_run_cli_help_exits_before_interactive_menu` 在第 347–348 行只替换了 `main` 和 `run_smoke_test`;如果 `run_cli` 在处理帮助之前调用 `initialize_dependencies()`,第 354–359 行仍会在打印预期文本并返回 0 后通过。因此,该测试无法发现帮助命令不再于初始化依赖之前返回的问题。

替换 `initialize_dependencies`,并断言对于任一帮助标志都未调用它。
</issue_to_address>

Sourcery 评估

等待批准。 请先处理 4 个问题。

阻塞性问题:main.py:383、main.py:374、main.py:379、tests/test_main_entry.py:347


Sourcery 对开源项目免费——如果您喜欢我们的审查,欢迎分享 ✨
Original comment in English

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="main.py" line_range="383" />
<code_context>
+        console.print("  --smoke-test   非交互式启动自检(构建验证用)")
+        console.print("  -h, --help     显示本帮助并退出")
+        console.print("  无参数          进入交互式菜单(向量化 / 召回测试 / 聊天)")
+        return 0
     try:
         if "--smoke-test" in args:
</code_context>
<issue_to_address>
**Help deletes cached files**

When the configured cache directory contains files, or another process is using it, on exit, the registered `cleanup_temp_files` callback calls `shutil.rmtree` on the configured cache directory, deleting its files and disrupting any process using them.

Skip or unregister the cleanup callback for help invocations so exiting after help never removes the configured cache.
</issue_to_address>

### Comment 2
<location path="main.py" line_range="374" />
<code_context>
     import 期的失败由 ``get_settings`` 的边界负责(此处尚未执行)。
     """
     args = list(sys.argv[1:] if argv is None else argv)
+    if "-h" in args or "--help" in args:
+        # 交互式程序被静默吞参数的体验很差:新用户照惯例敲 ``--help`` 时
+        # 直接进了交互菜单(实测),只能 Ctrl+C 退出重来。给出简明用法
</code_context>
<issue_to_address>
**Help fails on invalid settings**

When configuration is malformed or fails settings validation, `main.py` imports `src.utils.cleanup` before `run_cli` reaches the help branch; its module-level logger calls `get_settings()`, which raises during import, so `--help` prints no usage and exits with an error.

Defer importing `src.utils.cleanup` and initializing its settings-dependent logger until after the help branch is handled.
</issue_to_address>

### Comment 3
<location path="main.py" line_range="379" />
<code_context>
+        # 直接进了交互菜单(实测),只能 Ctrl+C 退出重来。给出简明用法
+        # 后退出,不初始化依赖(``--help`` 必须瞬时返回)。
+        console.print(markup_text("PyRAG-Kit {}", VERSION))
+        console.print("用法: python main.py [选项]")
+        console.print("  --smoke-test   非交互式启动自检(构建验证用)")
+        console.print("  -h, --help     显示本帮助并退出")
</code_context>
<issue_to_address>
**Packaged help shows unusable command**

When help is requested from a frozen release, the usage line says to run `python main.py`, but the release package contains a `PyRAG-Kit` executable rather than a standalone `main.py`, so users cannot follow the instructions to run an option.

Show the `PyRAG-Kit` executable in the usage line for frozen releases.
</issue_to_address>

### Comment 4
<location path="tests/test_main_entry.py" line_range="347" />
<code_context>
+    """
+    called = {"main": 0, "smoke": 0}
+
+    monkeypatch.setattr(main, "main", lambda: called.__setitem__("main", 1))
+    monkeypatch.setattr(main, "run_smoke_test", lambda: called.__setitem__("smoke", 1))
+
</code_context>
<issue_to_address>
**Help initializes dependencies unnoticed**

When a regression calls `initialize_dependencies()` before the help branch, `test_run_cli_help_exits_before_interactive_menu` stubs only `main` and `run_smoke_test` at line 347-348; if `run_cli` calls `initialize_dependencies()` before handling help, lines 354-359 still pass after it prints the expected text and returns 0. The test therefore misses help no longer returning before dependency initialization.

Stub `initialize_dependencies` and assert it was not called for either help flag.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: main.py:383, main.py:374, main.py:379, tests/test_main_entry.py:347


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread main.py
Comment thread main.py
Comment thread main.py
Comment thread tests/test_main_entry.py
MisonL added a commit that referenced this pull request Oct 14, 2026
PR #4/#5 bot 复核的 9 条发现逐条探针核实,8 条属实修复、1 条记录不修:

--help(PR #4):
- 注销 atexit 退出清理钩子——import src.utils.cleanup 的模块级注册
  在分支之前生效,不注销则 --help 退出把上次会话的缓存目录整个
  rmtree(实测复现);--help 是只读查询,不应有副作用
- 坏配置下 --help 不再裸 traceback:log_manager.get_module_logger
  在 import 期调 get_settings(),配置语法错误让 --help 连用法都
  打不出(实测复现);日志级别降级为默认值,主流程仍按原契约报错
- 用法行按 sys.frozen 区分:打包产物是 PyRAG-Kit 可执行文件,
  python main.py 指引在冻结态不可用
- 回归测试补断言:help 分支不初始化依赖、注销退出清理

主题适配(PR #5):
- COLORFGBG 三段式取第二段作 bg——取末段把 mode=0 的亮色终端
  误判成暗色(实测 0;15;0 判 False);测试原断言与缺陷同向,
  已随修正翻转
- 判据放弃 str.isdigit(接受 '²' 而 int() 崩,实测 ValueError
  穿透到菜单构建),只认 ASCII 数字
- 召回测试提示符纳入主题:run_retrieval_test_async 的独立
  PromptSession 与固定 <deepskyblue> 未适配(实测 38;5;39 白底
  低对比),改主题样式 + <prompt> class
- 4 处嵌套 questionary.select(method/fusion/LLM/Rerank)补
  主题样式——只有 3 处外层菜单适配了,子菜单 pointer 仍用
  questionary 内置样式
- 记录不修:COLORFGBG bg=7(ANSI 浅灰)在个别终端映射为白——
  rxvt 惯例本就把 0-7 归暗色系,为罕见映射改判据会误伤主流

测试替身随新增 style= 参数适配;display_utils 豁免表与 green38
夹具随行号漂移重基线(原文逐条核对)。全量 4547 passed,
8 项质量门全绿。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@MisonL

MisonL commented Oct 14, 2026

Copy link
Copy Markdown
Owner Author

Sourcery 的 4 条发现已逐条探针核实,4 条均属实,修复在 #5(同一提交链):

  1. --help 删除缓存文件(属实):实测 --help 退出把 .cache/ 整个删了。修复:--help 分支注销 atexit 退出清理钩子——--help 是只读查询,不应有副作用。回归测试钉住 unregister 调用。
  2. 坏配置下 --help 失败(属实):实测 config.toml 加一行语法错误后 --help 以裸 traceback 收场(import src.utils.cleanup 的模块级 get_module_logger → get_settings() 在 import 期抛)。修复:get_module_logger 对配置失败降级为默认日志级别并告警;主流程稍后的 get_settings() 仍按原契约抛脱敏配置错误。
  3. 打包后用法行不可用(属实):用法行按 sys.frozen 区分——冻结态显示 PyRAG-Kit [选项],开发态显示 python main.py。
  4. 测试未覆盖依赖初始化(属实):测试补 initialize_dependencies 与 atexit.unregister 断言。

@MisonL
MisonL merged commit ea58250 into main Oct 14, 2026
4 checks passed
@MisonL
MisonL deleted the feat/cli-help-and-polish branch October 14, 2026 16:22
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.

1 participant