Compare commits
17 Commits
v0.3.1
...
e6b8b344aa
| Author | SHA1 | Date | |
|---|---|---|---|
|
e6b8b344aa
|
|||
| a0ea03fd90 | |||
| 3c2b96a4d1 | |||
| 16ffc94a06 | |||
| 9f177f7a1f | |||
| 18728a4a2e | |||
| f534ccc698 | |||
| 29c6ff3935 | |||
| bba15501c6 | |||
|
cc80604710
|
|||
|
35fe6e09b7
|
|||
|
349ff56299
|
|||
|
206bde0786
|
|||
|
995d263a48
|
|||
|
19aff8a6c1
|
|||
|
b6bc091502
|
|||
|
14ebb6857a
|
8
.gitignore
vendored
8
.gitignore
vendored
@@ -6,6 +6,7 @@ Cargo.lock
|
|||||||
|
|
||||||
# IDE
|
# IDE
|
||||||
.idea/
|
.idea/
|
||||||
|
.trae/
|
||||||
.vscode/
|
.vscode/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
@@ -22,4 +23,9 @@ test_output/
|
|||||||
# Config (for development)
|
# Config (for development)
|
||||||
config.toml
|
config.toml
|
||||||
.claude/
|
.claude/
|
||||||
CLAUDE.md
|
.qoder/
|
||||||
|
CLAUDE.md
|
||||||
|
**/agents/
|
||||||
|
adr/
|
||||||
|
.scratch/
|
||||||
|
CONTEXT.md
|
||||||
81
AGENTS.md
Normal file
81
AGENTS.md
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
|
||||||
|
|
||||||
|
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
|
||||||
|
|
||||||
|
**Important:** Use Chinese for information responses and thinking; use English for searching and querying.
|
||||||
|
|
||||||
|
## 1. Think Before Coding
|
||||||
|
|
||||||
|
**Don't assume. Don't hide confusion. Surface tradeoffs.**
|
||||||
|
|
||||||
|
Before implementing:
|
||||||
|
- State your assumptions explicitly. If uncertain, ask.
|
||||||
|
- If multiple interpretations exist, present them - don't pick silently.
|
||||||
|
- If a simpler approach exists, say so. Push back when warranted.
|
||||||
|
- If something is unclear, stop. Name what's confusing. Ask.
|
||||||
|
|
||||||
|
## 2. Simplicity First
|
||||||
|
|
||||||
|
**Minimum code that solves the problem. Nothing speculative.**
|
||||||
|
|
||||||
|
- No features beyond what was asked.
|
||||||
|
- No abstractions for single-use code.
|
||||||
|
- No "flexibility" or "configurability" that wasn't requested.
|
||||||
|
- No error handling for impossible scenarios.
|
||||||
|
- If you write 200 lines and it could be 50, rewrite it.
|
||||||
|
|
||||||
|
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
|
||||||
|
|
||||||
|
## 3. Surgical Changes
|
||||||
|
|
||||||
|
**Touch only what you must. Clean up only your own mess.**
|
||||||
|
|
||||||
|
When editing existing code:
|
||||||
|
- Don't "improve" adjacent code, comments, or formatting.
|
||||||
|
- Don't refactor things that aren't broken.
|
||||||
|
- Match existing style, even if you'd do it differently.
|
||||||
|
- If you notice unrelated dead code, mention it - don't delete it.
|
||||||
|
|
||||||
|
When your changes create orphans:
|
||||||
|
- Remove imports/variables/functions that YOUR changes made unused.
|
||||||
|
- Don't remove pre-existing dead code unless asked.
|
||||||
|
|
||||||
|
The test: Every changed line should trace directly to the user's request.
|
||||||
|
|
||||||
|
## 4. Goal-Driven Execution
|
||||||
|
|
||||||
|
**Define success criteria. Loop until verified.**
|
||||||
|
|
||||||
|
Transform tasks into verifiable goals:
|
||||||
|
- "Add validation" → "Write tests for invalid inputs, then make them pass"
|
||||||
|
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
|
||||||
|
- "Refactor X" → "Ensure tests pass before and after"
|
||||||
|
|
||||||
|
For multi-step tasks, state a brief plan:
|
||||||
|
```
|
||||||
|
1. [Step] → verify: [check]
|
||||||
|
2. [Step] → verify: [check]
|
||||||
|
3. [Step] → verify: [check]
|
||||||
|
```
|
||||||
|
|
||||||
|
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
|
||||||
|
|
||||||
|
## Agent skills
|
||||||
|
|
||||||
|
### Issue tracker
|
||||||
|
|
||||||
|
Issues and specs live as local markdown files under `.scratch/`. See `docs/agents/issue-tracker.md`.
|
||||||
|
|
||||||
|
### Triage labels
|
||||||
|
|
||||||
|
The five canonical triage roles use their default label strings. See `docs/agents/triage-labels.md`.
|
||||||
|
|
||||||
|
### Domain docs
|
||||||
|
|
||||||
|
Single-context repo with `CONTEXT.md` and `docs/adr/` at the root. See `docs/agents/domain.md`.
|
||||||
66
CHANGELOG.md
66
CHANGELOG.md
@@ -9,6 +9,72 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
暂无。
|
暂无。
|
||||||
|
|
||||||
|
## [0.6.1] - 2026-08-18
|
||||||
|
|
||||||
|
### 🔧 其他变更
|
||||||
|
- 依赖瘦身:移除未使用的直接依赖 `config`、`handlebars`、`shell-words`、`walkdir`、`console`、`lazy_static`、`atty`,crate 总数由 341 降至 296,release 二进制体积由 7.38 MB 降至 7.00 MB(-5.2%)
|
||||||
|
- `lazy_static!` 宏替换为标准库 `LazyLock`;`atty` 替换为标准库 `std::io::IsTerminal`
|
||||||
|
- `tokio` 特性由 `full` 精简为 `macros` + `rt-multi-thread`
|
||||||
|
- `regex` 关闭默认 unicode 特性(保留 `std` + `perf`),行为变化:`\s`/`\d`/`\w` 字符类仅匹配 ASCII,对提交信息、版本号、邮箱、GPG Key ID 校验无实质影响
|
||||||
|
|
||||||
|
## [0.6.0] - 2026-08-17
|
||||||
|
|
||||||
|
### ✨ 新功能
|
||||||
|
- LLM 层整体迁移至 rig-core 0.41:六家 provider(Ollama / OpenAI / Anthropic / Kimi / DeepSeek / OpenRouter)统一由 rig 原生客户端驱动,删除约 2100 行手写 HTTP/SSE/重试代码
|
||||||
|
- 新 LLM 门面(`src/llm/rig/`):provider 枚举 + 单一生成入口 + 凭据校验(rig VerifyClient)+ 错误映射层;提示词与提交解析拆分至独立模块
|
||||||
|
- Anthropic 支持自定义 `base_url`(此前被静默忽略,本次修复)
|
||||||
|
- 新增基于 rig mock 后端的 LLM 层离线测试(请求形状、流式事件、错误映射),并附 6 家 provider 的 `#[ignore]` 实网冒烟用例
|
||||||
|
|
||||||
|
### 🐞 错误修复
|
||||||
|
- 各 provider 超时统一由 `llm.timeout` 配置控制(此前默认超时 60/120/300 秒不一致)
|
||||||
|
- 消除 Ollama 客户端构造时的 panic(`expect` 式构造)
|
||||||
|
|
||||||
|
### 🔧 其他变更(行为变化)
|
||||||
|
- Ollama 请求端点由 `/api/generate` 改为 `/api/chat`(功能等价;自定义 Ollama 代理需兼容 chat 端点)
|
||||||
|
- 非流式请求不再做应用层重试(此前按错误文案字符串匹配重试 3 次);流式请求由 rig 的 SSE 机制自动重连
|
||||||
|
- 可用性校验端点变化:DeepSeek 改为 `/user/balance`、OpenRouter 改为 `/key`、Anthropic 改为 `/v1/models`(对外表现为 `LLM provider 'xxx' is not available` 语义不变)
|
||||||
|
- 依赖瘦身:移除 `reqwest`(0.12) 与 `async-trait` 直接依赖,不引入 rig agent/fastembed/lancedb 等组件
|
||||||
|
|
||||||
|
## [0.5.0] - 2026-07-24
|
||||||
|
|
||||||
|
### ✨ 新功能
|
||||||
|
- `commit` 命令新增 `.gitignore` 文件过滤:自动暂存与 `--all` 模式下自动跳过被 `.gitignore` 规则匹配的文件,并清理索引中已被忽略的已跟踪文件,暂存完成后列出被移除的文件
|
||||||
|
- `tag` 命令新增 `-A, --auto` 模式:优先从 `Cargo.toml`/`pyproject.toml` 读取项目版本,回退到基于 commit 的语义化升级分析(与 `--bump` 互斥)
|
||||||
|
- `changelog` 命令在未指定 `--from` 时,自动检测现有 changelog 中最高版本对应的 tag 作为起始点
|
||||||
|
- 新增 `parse_changelog_versions()`,按 semver 降序提取 changelog 中已有的版本
|
||||||
|
- 新增 `sort_tags_by_semver()`,取代纯时间排序,按语义版本正确排序标签
|
||||||
|
|
||||||
|
### 🐞 错误修复
|
||||||
|
- 修复 `get_tags()` 对 annotated tag 的解析:改用 `find_object`+`peel_to_commit` 正确取得标签指向的 commit
|
||||||
|
- 修复 `changelog` 写入时 `insert_changelog_entry` 覆盖已有章节的问题,现保留现有内容并按版本插入新条目
|
||||||
|
|
||||||
|
### 📚 文档
|
||||||
|
- 同步更新 README(中/英文):补充 `--think`、`tag --auto` 选项说明,移除已废弃的 `--prepend` 参数,修正 `set-llm` 的 `--base-url` 选项名
|
||||||
|
|
||||||
|
### 🔧 其他变更
|
||||||
|
- 新增 `TagInfo::version_name()` 与 `GitRepo::find_tag_by_version()` 辅助方法
|
||||||
|
- 新增 `tests/gitignore_tests.rs`,包含 7 个测试覆盖 `.gitignore` 过滤逻辑
|
||||||
|
|
||||||
|
## [0.4.0] - 2026-07-16
|
||||||
|
|
||||||
|
### ✨ 新功能
|
||||||
|
- 新增 `quicommit credential get|store|erase` 子命令,实现标准 Git credential helper 协议([gitcredentials](https://git-scm.com/docs/gitcredentials)),可与原生 `git` 命令无缝集成
|
||||||
|
- 新增 `host_to_service()` 主机名映射,将 github.com、gitlab.com、bitbucket.org 等常见托管平台映射为规范化服务名
|
||||||
|
- 新增 `get_pat_for_host()` 公共 API,支持从已保存的凭据中提取 PAT 用于登录验证
|
||||||
|
- 凭据存储复用现有基于系统密钥环的 PAT 与用户绑定逻辑,按 profile 维度管理
|
||||||
|
|
||||||
|
### 🐞 错误修复
|
||||||
|
- 移除 `keyring.rs` 中的调试 `eprintln!` 输出,避免污染 credential helper 的 stderr
|
||||||
|
|
||||||
|
### 📚 文档
|
||||||
|
- README(中/英文)新增 credential 命令使用说明
|
||||||
|
|
||||||
|
### 🔧 其他变更
|
||||||
|
- 新增 `src/lib.rs` 库目标,支持从 `tests/` 目录导入内部模块进行测试
|
||||||
|
- `src/main.rs` 重构为使用 `quicommit::` 库导入
|
||||||
|
- credential 命令及其子命令均使用 `#[command(hide = true)]` 隐藏,不在 `--help` 中显示
|
||||||
|
- 新增 `tests/credential_tests.rs`,包含 52 个测试用例覆盖协议解析、帮助可见性、完整存取周期及边界场景
|
||||||
|
|
||||||
## [0.3.1] - 2026-06-01
|
## [0.3.1] - 2026-06-01
|
||||||
|
|
||||||
### ✨ 新功能
|
### ✨ 新功能
|
||||||
|
|||||||
25
Cargo.toml
25
Cargo.toml
@@ -1,9 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "quicommit"
|
name = "quicommit"
|
||||||
version = "0.3.1"
|
version = "0.6.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
authors = ["Sidney Zhang <zly@lyzhang.me>"]
|
authors = ["Sidney Zhang <zly@lyzhang.me>"]
|
||||||
description = "A powerful Git assistant tool with AI-powered commit/tag/changelog generation(alpha version)"
|
description = "A powerful Git assistant tool with AI-powered commit/tag/changelog generation"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
repository = "https://git.lyz.one/SidneyZhang/QuiCommit"
|
repository = "https://git.lyz.one/SidneyZhang/QuiCommit"
|
||||||
keywords = ["git", "commit", "ai", "cli", "automation"]
|
keywords = ["git", "commit", "ai", "cli", "automation"]
|
||||||
@@ -19,11 +19,9 @@ path = "src/main.rs"
|
|||||||
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
|
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
|
||||||
clap_complete = "4.5"
|
clap_complete = "4.5"
|
||||||
dialoguer = "0.11"
|
dialoguer = "0.11"
|
||||||
console = "0.15"
|
|
||||||
indicatif = "0.17"
|
indicatif = "0.17"
|
||||||
|
|
||||||
# Configuration management
|
# Configuration management
|
||||||
config = "0.14"
|
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
dirs = "5.0"
|
dirs = "5.0"
|
||||||
@@ -32,9 +30,7 @@ dirs = "5.0"
|
|||||||
git2 = "0.20.3"
|
git2 = "0.20.3"
|
||||||
which = "6.0"
|
which = "6.0"
|
||||||
|
|
||||||
# HTTP client for LLM APIs
|
tokio = { version = "1.35", features = ["macros", "rt-multi-thread"] }
|
||||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "stream"], default-features = false }
|
|
||||||
tokio = { version = "1.35", features = ["full"] }
|
|
||||||
|
|
||||||
# Error handling
|
# Error handling
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
@@ -46,20 +42,16 @@ tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
|||||||
|
|
||||||
# Utilities
|
# Utilities
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
regex = "1.10"
|
regex = { version = "1.10", default-features = false, features = ["std", "perf"] }
|
||||||
lazy_static = "1.4"
|
roxmltree = "0.20"
|
||||||
colored = "2.1"
|
colored = "2.1"
|
||||||
handlebars = "5.1"
|
|
||||||
semver = "1.0"
|
semver = "1.0"
|
||||||
walkdir = "2.4"
|
|
||||||
tempfile = "3.9"
|
tempfile = "3.9"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
textwrap = "0.16"
|
textwrap = "0.16"
|
||||||
async-trait = "0.1"
|
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
atty = "0.2"
|
|
||||||
|
|
||||||
# Encryption for sensitive data (SSH keys, GPG, etc.)
|
# Encryption for sensitive data (SSH keys, GPG, etc.)
|
||||||
aes-gcm = "0.10"
|
aes-gcm = "0.10"
|
||||||
@@ -73,8 +65,8 @@ keyring = { version = "3.6.3", features = ["apple-native", "windows-native", "sy
|
|||||||
# Interactive editor
|
# Interactive editor
|
||||||
edit = "0.1"
|
edit = "0.1"
|
||||||
|
|
||||||
# Shell completion generation
|
# LLM integration (rig-core only: HTTP backend + rustls; no agent/derive)
|
||||||
shell-words = "1.1"
|
rig-core = { version = "0.41", default-features = false, features = ["reqwest", "rustls"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
assert_cmd = "2.0"
|
assert_cmd = "2.0"
|
||||||
@@ -82,6 +74,9 @@ predicates = "3.1"
|
|||||||
tempfile = "3.9"
|
tempfile = "3.9"
|
||||||
mockall = "0.12"
|
mockall = "0.12"
|
||||||
wiremock = "0.6"
|
wiremock = "0.6"
|
||||||
|
# rig mock HTTP backends for LLM layer tests
|
||||||
|
rig-core = { version = "0.41", default-features = false, features = ["test-utils"] }
|
||||||
|
http = "1"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = "s"
|
opt-level = "s"
|
||||||
|
|||||||
20
RAODMAP.md
20
RAODMAP.md
@@ -29,23 +29,17 @@
|
|||||||
|
|
||||||
将 Git 凭证管理集成到 QuiCommit 中,统一管理 HTTPS 仓库的身份认证。
|
将 Git 凭证管理集成到 QuiCommit 中,统一管理 HTTPS 仓库的身份认证。
|
||||||
|
|
||||||
- [ ] **Git Credential Helper 集成**
|
- [x] **Git Credential Helper 集成**
|
||||||
- 实现 `git credential-store` / `git-credential-libsecret` 等标准的 credential helper 协议
|
- 实现 `git credential-store` / `git-credential-libsecret` 等标准的 credential helper 协议
|
||||||
- 支持 `quicommit credential get|store|erase` 子命令
|
- 支持 `quicommit credential get|store|erase` 子命令
|
||||||
- 与系统密钥环无缝对接,复用已有的 `KeyringManager`
|
- 与系统密钥环无缝对接,复用已有的 `KeyringManager`
|
||||||
|
|
||||||
- [ ] **凭证管理 CLI**
|
- [x] **跨平台支持**
|
||||||
- `quicommit credential list` — 列出所有已存储的凭证
|
|
||||||
- `quicommit credential add` — 手动添加凭证(用户名 + 密码/Token)
|
|
||||||
- `quicommit credential remove` — 删除指定凭证
|
|
||||||
- `quicommit credential status` — 查看凭证管理状态
|
|
||||||
|
|
||||||
- [ ] **跨平台支持**
|
|
||||||
- Windows:集成 Windows Credential Manager
|
- Windows:集成 Windows Credential Manager
|
||||||
- macOS:集成 Keychain
|
- macOS:集成 Keychain
|
||||||
- Linux:通过 Secret Service / D-Bus 对接 GNOME Keyring / KWallet
|
- Linux:通过 Secret Service / D-Bus 对接 GNOME Keyring / KWallet
|
||||||
|
|
||||||
- [ ] **安全增强**
|
- [x] **安全增强**
|
||||||
- 支持 PAT(Personal Access Token)按 scope / 有效期管理
|
- 支持 PAT(Personal Access Token)按 scope / 有效期管理
|
||||||
- 支持凭证过期检查和自动提醒
|
- 支持凭证过期检查和自动提醒
|
||||||
|
|
||||||
@@ -88,10 +82,10 @@
|
|||||||
|
|
||||||
提升 AI 生成提交信息、标签说明和变更日志时的用户体验。
|
提升 AI 生成提交信息、标签说明和变更日志时的用户体验。
|
||||||
|
|
||||||
- [x] **流式输出与实时反馈**
|
- [ ] **流式输出与实时反馈**
|
||||||
- 支持 SSE(Server-Sent Events)流式生成
|
- [x] 支持 SSE(Server-Sent Events)流式生成
|
||||||
- 终端打字机效果实时显示生成内容
|
- [ ]终端打字机效果实时显示生成内容
|
||||||
- 流式生成过程中支持 `Ctrl+C` 中断
|
- [ ]流式生成过程中支持 `Ctrl+C` 中断
|
||||||
|
|
||||||
- [ ] **生成质量提升**
|
- [ ] **生成质量提升**
|
||||||
- 基于 commitlint 规则的后校验与自动修正
|
- 基于 commitlint 规则的后校验与自动修正
|
||||||
|
|||||||
148
README.md
148
README.md
@@ -18,7 +18,7 @@ A powerful AI-powered Git assistant for generating conventional commits, tags, a
|
|||||||
- **AI-Powered Generation**: Generate commits, tags, and changelogs using LLM APIs (Ollama, OpenAI, Anthropic, Kimi, DeepSeek, OpenRouter) or local models
|
- **AI-Powered Generation**: Generate commits, tags, and changelogs using LLM APIs (Ollama, OpenAI, Anthropic, Kimi, DeepSeek, OpenRouter) or local models
|
||||||
- **Conventional Commits**: Full support for Conventional Commits and commitlint formats
|
- **Conventional Commits**: Full support for Conventional Commits and commitlint formats
|
||||||
- **Profile Management**: Manage multiple Git identities with SSH keys and GPG signing support
|
- **Profile Management**: Manage multiple Git identities with SSH keys and GPG signing support
|
||||||
- **Smart Tagging**: Semantic version bumping with AI-generated release notes
|
- **Smart Tagging**: Semantic version bumping with AI-generated release notes; auto-detects version from 16+ project config files (Cargo.toml, package.json, pom.xml, pubspec.yaml, etc.)
|
||||||
- **Changelog Generation**: Automatic changelog generation in Keep a Changelog format
|
- **Changelog Generation**: Automatic changelog generation in Keep a Changelog format
|
||||||
- **Security**: Use system keyring to store API keys securely
|
- **Security**: Use system keyring to store API keys securely
|
||||||
- **Interactive UI**: Beautiful CLI with previews and confirmations
|
- **Interactive UI**: Beautiful CLI with previews and confirmations
|
||||||
@@ -63,7 +63,7 @@ quicommit commit
|
|||||||
# Manual commit
|
# Manual commit
|
||||||
quicommit commit --manual -t feat -m "add new feature"
|
quicommit commit --manual -t feat -m "add new feature"
|
||||||
|
|
||||||
# Stage all and commit
|
# Stage all and commit (skips .gitignore-matched files automatically)
|
||||||
quicommit commit -a
|
quicommit commit -a
|
||||||
|
|
||||||
# Skip confirmation
|
# Skip confirmation
|
||||||
@@ -72,16 +72,25 @@ quicommit commit --yes
|
|||||||
# Use date-based commit message
|
# Use date-based commit message
|
||||||
quicommit commit --date
|
quicommit commit --date
|
||||||
|
|
||||||
|
# Enable LLM thinking/reasoning mode for this commit
|
||||||
|
quicommit commit --think
|
||||||
|
|
||||||
# Push after committing
|
# Push after committing
|
||||||
quicommit commit --push
|
quicommit commit --push
|
||||||
```
|
```
|
||||||
|
|
||||||
|
When staging changes (auto-stage or `--all`), files matched by `.gitignore` rules are skipped and any ignored files already in the index are removed; the skipped list is printed for review.
|
||||||
|
|
||||||
### Create Tag
|
### Create Tag
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Auto-detect version bump
|
# Auto-detect version bump
|
||||||
quicommit tag
|
quicommit tag
|
||||||
|
|
||||||
|
# Auto-detect version from project config files (Cargo.toml, package.json, pom.xml, etc.),
|
||||||
|
# fall back to commit analysis
|
||||||
|
quicommit tag --auto
|
||||||
|
|
||||||
# Specify bump type
|
# Specify bump type
|
||||||
quicommit tag --bump minor
|
quicommit tag --bump minor
|
||||||
|
|
||||||
@@ -98,11 +107,14 @@ quicommit tag --push
|
|||||||
### Generate Changelog
|
### Generate Changelog
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Generate for unreleased changes
|
# Generate for unreleased changes (auto-detects --from from the highest version in the existing changelog)
|
||||||
quicommit changelog
|
quicommit changelog
|
||||||
|
|
||||||
# Generate for specific version
|
# Generate for specific version
|
||||||
quicommit changelog -v 1.0.0
|
quicommit changelog --version 1.0.0
|
||||||
|
|
||||||
|
# Generate from a specific tag
|
||||||
|
quicommit changelog --from v0.9.0
|
||||||
|
|
||||||
# AI-generate changelog
|
# AI-generate changelog
|
||||||
quicommit changelog --generate
|
quicommit changelog --generate
|
||||||
@@ -160,12 +172,69 @@ quicommit profile stats
|
|||||||
quicommit profile token
|
quicommit profile token
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Git Credential Helper
|
||||||
|
|
||||||
|
QuiCommit can act as a Git credential helper to securely store and retrieve
|
||||||
|
Personal Access Tokens (PATs) via the system keyring. The `credential` command
|
||||||
|
is hidden from `--help` because it is invoked automatically by Git, not by end
|
||||||
|
users.
|
||||||
|
|
||||||
|
#### Setup
|
||||||
|
|
||||||
|
Register QuiCommit as a credential helper for Git:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Use the default QuiCommit config
|
||||||
|
git config --global credential.helper quicommit
|
||||||
|
|
||||||
|
# Or specify a custom config file
|
||||||
|
git config --global credential.helper "quicommit --config /path/to/config.toml"
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also limit the helper to a specific host:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config --global credential.https://github.com.helper quicommit
|
||||||
|
```
|
||||||
|
|
||||||
|
#### How It Works
|
||||||
|
|
||||||
|
When Git needs credentials (e.g. pushing to a remote), it calls the helper
|
||||||
|
following the [gitcredentials protocol](https://git-scm.com/docs/gitcredentials):
|
||||||
|
|
||||||
|
1. **`get`** — Git asks QuiCommit for a stored PAT matching the requested host.
|
||||||
|
QuiCommit searches all configured profiles in the keyring and returns the
|
||||||
|
PAT (plus username) if found.
|
||||||
|
2. **`store`** — After a successful authentication (e.g. you entered a PAT in
|
||||||
|
the Git prompt), Git asks QuiCommit to save it. The PAT is stored in the
|
||||||
|
system keyring, bound to the matching profile.
|
||||||
|
3. **`erase`** — Git asks QuiCommit to delete a stored PAT for the given host.
|
||||||
|
|
||||||
|
Host names are mapped to canonical service names (`github.com` → `github`,
|
||||||
|
`gitlab.com` → `gitlab`, `bitbucket.org` → `bitbucket`, etc.). Unknown hosts
|
||||||
|
are used as-is.
|
||||||
|
|
||||||
|
#### Removing Stored Credentials
|
||||||
|
|
||||||
|
To remove a stored PAT, you can either use Git's built-in mechanism:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
echo "protocol=https
|
||||||
|
host=github.com" | git credential reject
|
||||||
|
```
|
||||||
|
|
||||||
|
Or remove it via the profile token management command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
quicommit profile token
|
||||||
|
```
|
||||||
|
|
||||||
### Configure LLM
|
### Configure LLM
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Configure Ollama (local)
|
# Configure Ollama (local)
|
||||||
quicommit config set-llm ollama
|
quicommit config set-llm ollama
|
||||||
quicommit config set-llm ollama --url http://localhost:11434 --model llama2
|
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
|
||||||
|
|
||||||
# Configure OpenAI
|
# Configure OpenAI
|
||||||
quicommit config set-llm openai
|
quicommit config set-llm openai
|
||||||
@@ -239,6 +308,7 @@ quicommit config reset --force
|
|||||||
| `quicommit changelog` | `cl` | Generate changelog |
|
| `quicommit changelog` | `cl` | Generate changelog |
|
||||||
| `quicommit profile` | `p` | Manage Git profiles |
|
| `quicommit profile` | `p` | Manage Git profiles |
|
||||||
| `quicommit config` | `cfg` | Manage settings |
|
| `quicommit config` | `cfg` | Manage settings |
|
||||||
|
| `quicommit credential` | — | Git credential helper (hidden, invoked by Git) |
|
||||||
|
|
||||||
### Commit Options
|
### Commit Options
|
||||||
|
|
||||||
@@ -251,13 +321,14 @@ quicommit config reset --force
|
|||||||
| `-b, --breaking` | Mark as breaking change |
|
| `-b, --breaking` | Mark as breaking change |
|
||||||
| `-d, --date` | Use date-based commit message |
|
| `-d, --date` | Use date-based commit message |
|
||||||
| `--manual` | Manual input, skip AI |
|
| `--manual` | Manual input, skip AI |
|
||||||
| `-a, --all` | Stage all changes |
|
| `-a, --all` | Stage all changes (skips `.gitignore`-matched files) |
|
||||||
| `-S, --sign` | GPG sign commit |
|
| `-S, --sign` | GPG sign commit |
|
||||||
| `--amend` | Amend previous commit |
|
| `--amend` | Amend previous commit |
|
||||||
| `--dry-run` | Show without committing |
|
| `--dry-run` | Show without committing |
|
||||||
| `--conventional` | Use Conventional Commits format |
|
| `--conventional` | Use Conventional Commits format |
|
||||||
| `--commitlint` | Use commitlint format |
|
| `--commitlint` | Use commitlint format |
|
||||||
| `--no-verify` | Skip commit message verification |
|
| `--no-verify` | Skip commit message verification |
|
||||||
|
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
|
||||||
| `-y, --yes` | Skip confirmation |
|
| `-y, --yes` | Skip confirmation |
|
||||||
| `--push` | Push after committing |
|
| `--push` | Push after committing |
|
||||||
| `--remote` | Specify remote repository (default: origin) |
|
| `--remote` | Specify remote repository (default: origin) |
|
||||||
@@ -268,6 +339,7 @@ quicommit config reset --force
|
|||||||
|--------|-------------|
|
|--------|-------------|
|
||||||
| `-n, --name` | Tag name |
|
| `-n, --name` | Tag name |
|
||||||
| `-b, --bump` | Version bump (major/minor/patch) |
|
| `-b, --bump` | Version bump (major/minor/patch) |
|
||||||
|
| `-A, --auto` | Auto-detect version from project config files (Cargo.toml, package.json, pom.xml, etc.), fall back to commit analysis (conflicts with `--bump`) |
|
||||||
| `-m, --message` | Tag message |
|
| `-m, --message` | Tag message |
|
||||||
| `-g, --generate` | AI-generate message |
|
| `-g, --generate` | AI-generate message |
|
||||||
| `-S, --sign` | GPG sign tag |
|
| `-S, --sign` | GPG sign tag |
|
||||||
@@ -276,6 +348,7 @@ quicommit config reset --force
|
|||||||
| `-p, --push` | Push to remote |
|
| `-p, --push` | Push to remote |
|
||||||
| `-r, --remote` | Specify remote repository (default: origin) |
|
| `-r, --remote` | Specify remote repository (default: origin) |
|
||||||
| `--dry-run` | Dry run |
|
| `--dry-run` | Dry run |
|
||||||
|
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
|
||||||
| `-y, --yes` | Skip confirmation |
|
| `-y, --yes` | Skip confirmation |
|
||||||
|
|
||||||
### Changelog Options
|
### Changelog Options
|
||||||
@@ -283,16 +356,16 @@ quicommit config reset --force
|
|||||||
| Option | Description |
|
| Option | Description |
|
||||||
|--------|-------------|
|
|--------|-------------|
|
||||||
| `-o, --output` | Output file path |
|
| `-o, --output` | Output file path |
|
||||||
| `-v, --version` | Generate for specific version |
|
| `--version` | Generate for specific version |
|
||||||
| `-f, --from` | Generate from specific tag |
|
| `-f, --from` | Generate from specific tag (auto-detected from existing changelog if omitted) |
|
||||||
| `-t, --to` | Generate to specific ref (default: HEAD) |
|
| `-t, --to` | Generate to specific ref (default: HEAD) |
|
||||||
| `-i, --init` | Initialize new changelog file |
|
| `-i, --init` | Initialize new changelog file |
|
||||||
| `-g, --generate` | AI-generate changelog |
|
| `-g, --generate` | AI-generate changelog |
|
||||||
| `--prepend` | Prepend to existing changelog |
|
|
||||||
| `--include-hashes` | Include commit hashes |
|
| `--include-hashes` | Include commit hashes |
|
||||||
| `--include-authors` | Include authors |
|
| `--include-authors` | Include authors |
|
||||||
| `--format` | Format (keep-a-changelog, github-releases) |
|
| `--format` | Format (keep-a-changelog, github-releases) |
|
||||||
| `--dry-run` | Dry run (output to stdout) |
|
| `--dry-run` | Dry run (output to stdout) |
|
||||||
|
| `--think` | Enable LLM thinking/reasoning mode (overrides config) |
|
||||||
| `-y, --yes` | Skip confirmation |
|
| `-y, --yes` | Skip confirmation |
|
||||||
|
|
||||||
## Configuration File
|
## Configuration File
|
||||||
@@ -332,58 +405,25 @@ use_agent = true
|
|||||||
|
|
||||||
[llm]
|
[llm]
|
||||||
provider = "ollama"
|
provider = "ollama"
|
||||||
|
model = "llama2"
|
||||||
|
# base_url = "http://localhost:11434"
|
||||||
max_tokens = 500
|
max_tokens = 500
|
||||||
temperature = 0.7
|
temperature = 0.7
|
||||||
timeout = 30
|
timeout = 30
|
||||||
|
api_key_storage = "keyring"
|
||||||
[llm.ollama]
|
thinking_enabled = false
|
||||||
url = "http://localhost:11434"
|
|
||||||
model = "llama2"
|
|
||||||
|
|
||||||
[llm.openai]
|
|
||||||
model = "gpt-4"
|
|
||||||
base_url = "https://api.openai.com/v1"
|
|
||||||
|
|
||||||
[llm.anthropic]
|
|
||||||
model = "claude-3-sonnet-20240229"
|
|
||||||
|
|
||||||
[llm.kimi]
|
|
||||||
model = "moonshot-v1-8k"
|
|
||||||
|
|
||||||
[llm.deepseek]
|
|
||||||
model = "deepseek-chat"
|
|
||||||
|
|
||||||
[llm.openrouter]
|
|
||||||
model = "openai/gpt-4"
|
|
||||||
|
|
||||||
[commit]
|
[commit]
|
||||||
format = "conventional"
|
format = "conventional"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
allow_empty = false
|
|
||||||
gpg_sign = false
|
|
||||||
max_subject_length = 100
|
|
||||||
require_scope = false
|
|
||||||
require_body = false
|
|
||||||
body_required_types = ["feat", "fix"]
|
|
||||||
|
|
||||||
[tag]
|
[tag]
|
||||||
version_prefix = "v"
|
version_prefix = "v"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
gpg_sign = false
|
|
||||||
include_changelog = true
|
|
||||||
|
|
||||||
[changelog]
|
[changelog]
|
||||||
path = "CHANGELOG.md"
|
path = "CHANGELOG.md"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
format = "keep-a-changelog"
|
|
||||||
include_hashes = false
|
|
||||||
include_authors = false
|
|
||||||
group_by_type = true
|
|
||||||
|
|
||||||
[theme]
|
|
||||||
colors = true
|
|
||||||
icons = true
|
|
||||||
date_format = "%Y-%m-%d"
|
|
||||||
|
|
||||||
[repo_profiles]
|
[repo_profiles]
|
||||||
"/path/to/work/project" = "work"
|
"/path/to/work/project" = "work"
|
||||||
@@ -402,9 +442,6 @@ date_format = "%Y-%m-%d"
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# View current configuration
|
# View current configuration
|
||||||
quicommit config list
|
|
||||||
|
|
||||||
# Show configuration details
|
|
||||||
quicommit config show
|
quicommit config show
|
||||||
|
|
||||||
# Edit configuration file
|
# Edit configuration file
|
||||||
@@ -505,13 +542,12 @@ src/
|
|||||||
│ ├── commit.rs
|
│ ├── commit.rs
|
||||||
│ ├── tag.rs
|
│ ├── tag.rs
|
||||||
│ └── changelog.rs
|
│ └── changelog.rs
|
||||||
├── llm/ # LLM provider implementations
|
├── llm/ # LLM integration (rig-core based)
|
||||||
│ ├── ollama.rs
|
│ ├── mod.rs
|
||||||
│ ├── openai.rs
|
│ ├── prompts.rs
|
||||||
│ ├── anthropic.rs
|
│ ├── parsing.rs
|
||||||
│ ├── kimi.rs
|
│ ├── thinking.rs
|
||||||
│ ├── deepseek.rs
|
│ └── rig/ # rig provider facade
|
||||||
│ └── openrouter.rs
|
|
||||||
├── i18n/ # Internationalization support
|
├── i18n/ # Internationalization support
|
||||||
│ ├── messages.rs
|
│ ├── messages.rs
|
||||||
│ └── translator.rs
|
│ └── translator.rs
|
||||||
|
|||||||
@@ -46,61 +46,35 @@ use_agent = true
|
|||||||
|
|
||||||
# LLM Configuration
|
# LLM Configuration
|
||||||
[llm]
|
[llm]
|
||||||
# Provider: ollama, openai, or anthropic
|
# Provider: ollama, openai, anthropic, kimi, deepseek, openrouter
|
||||||
provider = "ollama"
|
provider = "ollama"
|
||||||
|
# Model name (provider-appropriate)
|
||||||
|
model = "llama2"
|
||||||
|
# API base URL (optional, provider default will be used if not set)
|
||||||
|
# base_url = "http://localhost:11434"
|
||||||
max_tokens = 500
|
max_tokens = 500
|
||||||
temperature = 0.7
|
temperature = 0.7
|
||||||
timeout = 30
|
timeout = 30
|
||||||
|
# API key storage: keyring, config, environment
|
||||||
# Ollama settings (local LLM)
|
api_key_storage = "keyring"
|
||||||
[llm.ollama]
|
# Enable thinking/reasoning mode (deepseek, kimi, anthropic)
|
||||||
url = "http://localhost:11434"
|
thinking_enabled = false
|
||||||
model = "llama2"
|
|
||||||
|
|
||||||
# OpenAI settings
|
|
||||||
[llm.openai]
|
|
||||||
# api_key = "sk-..." # Set via: quicommit config set-openai-key
|
|
||||||
model = "gpt-4"
|
|
||||||
base_url = "https://api.openai.com/v1"
|
|
||||||
|
|
||||||
# Anthropic settings
|
|
||||||
[llm.anthropic]
|
|
||||||
# api_key = "sk-ant-..." # Set via: quicommit config set-anthropic-key
|
|
||||||
model = "claude-3-sonnet-20240229"
|
|
||||||
|
|
||||||
# Commit settings
|
# Commit settings
|
||||||
[commit]
|
[commit]
|
||||||
# Format: conventional or commitlint
|
# Format: conventional or commitlint
|
||||||
format = "conventional"
|
format = "conventional"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
allow_empty = false
|
|
||||||
gpg_sign = false
|
|
||||||
max_subject_length = 100
|
|
||||||
require_scope = false
|
|
||||||
require_body = false
|
|
||||||
body_required_types = ["feat", "fix"]
|
|
||||||
|
|
||||||
# Tag settings
|
# Tag settings
|
||||||
[tag]
|
[tag]
|
||||||
version_prefix = "v"
|
version_prefix = "v"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
gpg_sign = false
|
|
||||||
include_changelog = true
|
|
||||||
|
|
||||||
# Changelog settings
|
# Changelog settings
|
||||||
[changelog]
|
[changelog]
|
||||||
path = "CHANGELOG.md"
|
path = "CHANGELOG.md"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
format = "keep-a-changelog" # or "github-releases"
|
|
||||||
include_hashes = false
|
|
||||||
include_authors = false
|
|
||||||
group_by_type = true
|
|
||||||
|
|
||||||
# Theme settings
|
|
||||||
[theme]
|
|
||||||
colors = true
|
|
||||||
icons = true
|
|
||||||
date_format = "%Y-%m-%d"
|
|
||||||
|
|
||||||
# Repository-specific profile mappings
|
# Repository-specific profile mappings
|
||||||
# [repo_profiles]
|
# [repo_profiles]
|
||||||
|
|||||||
143
readme_zh.md
143
readme_zh.md
@@ -17,7 +17,7 @@
|
|||||||
- **AI智能生成**:使用LLM API(Ollama本地、OpenAI、Anthropic Claude、Kimi、DeepSeek、OpenRouter)生成提交信息、标签和变更日志
|
- **AI智能生成**:使用LLM API(Ollama本地、OpenAI、Anthropic Claude、Kimi、DeepSeek、OpenRouter)生成提交信息、标签和变更日志
|
||||||
- **规范化提交**:支持Conventional Commits和commitlint格式规范
|
- **规范化提交**:支持Conventional Commits和commitlint格式规范
|
||||||
- **多配置管理**:为不同场景管理多个Git身份,支持SSH密钥和GPG签名配置
|
- **多配置管理**:为不同场景管理多个Git身份,支持SSH密钥和GPG签名配置
|
||||||
- **智能标签管理**:基于语义版本自动检测升级,AI生成标签信息
|
- **智能标签管理**:基于语义版本自动检测升级,AI生成标签信息;支持从 16+ 种项目配置文件(Cargo.toml、package.json、pom.xml、pubspec.yaml 等)自动读取版本
|
||||||
- **变更日志生成**:自动生成Keep a Changelog格式的变更日志
|
- **变更日志生成**:自动生成Keep a Changelog格式的变更日志
|
||||||
- **安全保护**:使用系统密钥环进行安全存储
|
- **安全保护**:使用系统密钥环进行安全存储
|
||||||
- **交互式界面**:美观的CLI界面,支持预览和确认
|
- **交互式界面**:美观的CLI界面,支持预览和确认
|
||||||
@@ -62,7 +62,7 @@ quicommit commit
|
|||||||
# 手动提交
|
# 手动提交
|
||||||
quicommit commit --manual -t feat -m "添加新功能"
|
quicommit commit --manual -t feat -m "添加新功能"
|
||||||
|
|
||||||
# 暂存所有文件并提交
|
# 暂存所有文件并提交(自动跳过 .gitignore 匹配的文件)
|
||||||
quicommit commit -a
|
quicommit commit -a
|
||||||
|
|
||||||
# 跳过确认直接提交
|
# 跳过确认直接提交
|
||||||
@@ -71,16 +71,25 @@ quicommit commit --yes
|
|||||||
# 使用日期格式的提交信息
|
# 使用日期格式的提交信息
|
||||||
quicommit commit --date
|
quicommit commit --date
|
||||||
|
|
||||||
|
# 为本次提交启用 LLM 思考/推理模式
|
||||||
|
quicommit commit --think
|
||||||
|
|
||||||
# 提交后推送到远程
|
# 提交后推送到远程
|
||||||
quicommit commit --push
|
quicommit commit --push
|
||||||
```
|
```
|
||||||
|
|
||||||
|
在暂存更改时(自动暂存或 `--all` 模式),会自动跳过匹配 `.gitignore` 规则的文件,并清理索引中已被忽略的已跟踪文件,最后打印出被跳过的文件列表。
|
||||||
|
|
||||||
### 创建标签
|
### 创建标签
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 自动检测版本升级
|
# 自动检测版本升级
|
||||||
quicommit tag
|
quicommit tag
|
||||||
|
|
||||||
|
# 从项目配置文件(Cargo.toml、package.json、pom.xml 等)自动检测版本,
|
||||||
|
# 回退到基于 commit 的分析
|
||||||
|
quicommit tag --auto
|
||||||
|
|
||||||
# 指定版本升级类型
|
# 指定版本升级类型
|
||||||
quicommit tag --bump minor
|
quicommit tag --bump minor
|
||||||
|
|
||||||
@@ -97,11 +106,14 @@ quicommit tag --push
|
|||||||
### 生成变更日志
|
### 生成变更日志
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 生成未发布变更的变更日志
|
# 生成未发布变更的变更日志(未指定 --from 时自动从现有 changelog 的最高版本检测)
|
||||||
quicommit changelog
|
quicommit changelog
|
||||||
|
|
||||||
# 为特定版本生成
|
# 为特定版本生成
|
||||||
quicommit changelog -v 1.0.0
|
quicommit changelog --version 1.0.0
|
||||||
|
|
||||||
|
# 从指定标签生成
|
||||||
|
quicommit changelog --from v0.9.0
|
||||||
|
|
||||||
# AI生成变更日志
|
# AI生成变更日志
|
||||||
quicommit changelog --generate
|
quicommit changelog --generate
|
||||||
@@ -159,12 +171,64 @@ quicommit profile stats
|
|||||||
quicommit profile token
|
quicommit profile token
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Git 凭据助手(Credential Helper)
|
||||||
|
|
||||||
|
QuiCommit 可以作为 Git 凭据助手,通过系统密钥环安全地存储和读取个人访问令牌(PAT)。
|
||||||
|
`credential` 命令在 `--help` 中是隐藏的,因为它由 Git 自动调用,无需用户手动执行。
|
||||||
|
|
||||||
|
#### 配置方法
|
||||||
|
|
||||||
|
将 QuiCommit 注册为 Git 凭据助手:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用默认的 QuiCommit 配置
|
||||||
|
git config --global credential.helper quicommit
|
||||||
|
|
||||||
|
# 或指定自定义配置文件路径
|
||||||
|
git config --global credential.helper "quicommit --config /path/to/config.toml"
|
||||||
|
```
|
||||||
|
|
||||||
|
也可以仅对特定主机启用:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config --global credential.https://github.com.helper quicommit
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 工作原理
|
||||||
|
|
||||||
|
当 Git 需要凭据(例如推送到远程仓库)时,会按照
|
||||||
|
[gitcredentials 协议](https://git-scm.com/docs/gitcredentials) 调用助手:
|
||||||
|
|
||||||
|
1. **`get`** — Git 向 QuiCommit 请求与目标主机匹配的已存储 PAT。
|
||||||
|
QuiCommit 在所有已配置的 profile 中搜索密钥环,找到则返回 PAT(及用户名)。
|
||||||
|
2. **`store`** — 认证成功后(例如你在 Git 提示中输入了 PAT),Git 要求
|
||||||
|
QuiCommit 保存该凭据。PAT 将存入系统密钥环,并与匹配的 profile 绑定。
|
||||||
|
3. **`erase`** — Git 要求 QuiCommit 删除指定主机的已存储 PAT。
|
||||||
|
|
||||||
|
主机名会被映射为规范化的服务名(`github.com` → `github`、`gitlab.com` →
|
||||||
|
`gitlab`、`bitbucket.org` → `bitbucket` 等),未知主机则原样使用。
|
||||||
|
|
||||||
|
#### 删除已存储的凭据
|
||||||
|
|
||||||
|
可以通过 Git 内置机制删除已存储的 PAT:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
echo "protocol=https
|
||||||
|
host=github.com" | git credential reject
|
||||||
|
```
|
||||||
|
|
||||||
|
也可以通过 profile 令牌管理命令删除:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
quicommit profile token
|
||||||
|
```
|
||||||
|
|
||||||
### LLM配置
|
### LLM配置
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 配置Ollama(本地)
|
# 配置Ollama(本地)
|
||||||
quicommit config set-llm ollama
|
quicommit config set-llm ollama
|
||||||
quicommit config set-llm ollama --url http://localhost:11434 --model llama2
|
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
|
||||||
|
|
||||||
# 配置OpenAI
|
# 配置OpenAI
|
||||||
quicommit config set-llm openai
|
quicommit config set-llm openai
|
||||||
@@ -238,6 +302,7 @@ quicommit config reset --force
|
|||||||
| `quicommit changelog` | `cl` | 生成变更日志 |
|
| `quicommit changelog` | `cl` | 生成变更日志 |
|
||||||
| `quicommit profile` | `p` | 管理Git配置 |
|
| `quicommit profile` | `p` | 管理Git配置 |
|
||||||
| `quicommit config` | `cfg` | 管理应用配置 |
|
| `quicommit config` | `cfg` | 管理应用配置 |
|
||||||
|
| `quicommit credential` | — | Git凭据助手(隐藏,由Git调用) |
|
||||||
|
|
||||||
### commit命令选项
|
### commit命令选项
|
||||||
|
|
||||||
@@ -250,13 +315,14 @@ quicommit config reset --force
|
|||||||
| `-b, --breaking` | 标记为破坏性变更 |
|
| `-b, --breaking` | 标记为破坏性变更 |
|
||||||
| `-d, --date` | 使用日期格式的提交信息 |
|
| `-d, --date` | 使用日期格式的提交信息 |
|
||||||
| `--manual` | 手动输入,跳过AI生成 |
|
| `--manual` | 手动输入,跳过AI生成 |
|
||||||
| `-a, --all` | 暂存所有更改 |
|
| `-a, --all` | 暂存所有更改(自动跳过 `.gitignore` 匹配的文件) |
|
||||||
| `-S, --sign` | GPG签名提交 |
|
| `-S, --sign` | GPG签名提交 |
|
||||||
| `--amend` | 修改上一次提交 |
|
| `--amend` | 修改上一次提交 |
|
||||||
| `--dry-run` | 试运行,不实际提交 |
|
| `--dry-run` | 试运行,不实际提交 |
|
||||||
| `--conventional` | 使用Conventional Commits格式 |
|
| `--conventional` | 使用Conventional Commits格式 |
|
||||||
| `--commitlint` | 使用commitlint格式 |
|
| `--commitlint` | 使用commitlint格式 |
|
||||||
| `--no-verify` | 不验证提交信息 |
|
| `--no-verify` | 不验证提交信息 |
|
||||||
|
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
|
||||||
| `-y, --yes` | 跳过确认提示 |
|
| `-y, --yes` | 跳过确认提示 |
|
||||||
| `--push` | 提交后推送到远程 |
|
| `--push` | 提交后推送到远程 |
|
||||||
| `--remote` | 指定远程仓库(默认:origin) |
|
| `--remote` | 指定远程仓库(默认:origin) |
|
||||||
@@ -267,6 +333,7 @@ quicommit config reset --force
|
|||||||
|------|------|
|
|------|------|
|
||||||
| `-n, --name` | 标签名称 |
|
| `-n, --name` | 标签名称 |
|
||||||
| `-b, --bump` | 版本升级类型(major/minor/patch) |
|
| `-b, --bump` | 版本升级类型(major/minor/patch) |
|
||||||
|
| `-A, --auto` | 从项目配置文件(Cargo.toml、package.json、pom.xml 等 16+ 种)自动检测版本,回退到基于 commit 的分析(与 `--bump` 互斥) |
|
||||||
| `-m, --message` | 标签信息 |
|
| `-m, --message` | 标签信息 |
|
||||||
| `-g, --generate` | AI生成标签信息 |
|
| `-g, --generate` | AI生成标签信息 |
|
||||||
| `-S, --sign` | GPG签名标签 |
|
| `-S, --sign` | GPG签名标签 |
|
||||||
@@ -275,6 +342,7 @@ quicommit config reset --force
|
|||||||
| `-p, --push` | 推送到远程 |
|
| `-p, --push` | 推送到远程 |
|
||||||
| `-r, --remote` | 指定远程仓库(默认:origin) |
|
| `-r, --remote` | 指定远程仓库(默认:origin) |
|
||||||
| `--dry-run` | 试运行 |
|
| `--dry-run` | 试运行 |
|
||||||
|
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
|
||||||
| `-y, --yes` | 跳过确认提示 |
|
| `-y, --yes` | 跳过确认提示 |
|
||||||
|
|
||||||
### changelog命令选项
|
### changelog命令选项
|
||||||
@@ -282,16 +350,16 @@ quicommit config reset --force
|
|||||||
| 选项 | 说明 |
|
| 选项 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `-o, --output` | 输出文件路径 |
|
| `-o, --output` | 输出文件路径 |
|
||||||
| `-v, --version` | 为特定版本生成 |
|
| `--version` | 为特定版本生成 |
|
||||||
| `-f, --from` | 从指定标签生成 |
|
| `-f, --from` | 从指定标签生成(未指定时自动从现有 changelog 的最高版本检测) |
|
||||||
| `-t, --to` | 生成到指定引用(默认:HEAD) |
|
| `-t, --to` | 生成到指定引用(默认:HEAD) |
|
||||||
| `-i, --init` | 初始化新的变更日志文件 |
|
| `-i, --init` | 初始化新的变更日志文件 |
|
||||||
| `-g, --generate` | AI生成变更日志 |
|
| `-g, --generate` | AI生成变更日志 |
|
||||||
| `--prepend` | 添加到现有变更日志开头 |
|
|
||||||
| `--include-hashes` | 包含提交哈希 |
|
| `--include-hashes` | 包含提交哈希 |
|
||||||
| `--include-authors` | 包含作者信息 |
|
| `--include-authors` | 包含作者信息 |
|
||||||
| `--format` | 格式(keep-a-changelog、github-releases) |
|
| `--format` | 格式(keep-a-changelog、github-releases) |
|
||||||
| `--dry-run` | 试运行(输出到stdout) |
|
| `--dry-run` | 试运行(输出到stdout) |
|
||||||
|
| `--think` | 启用 LLM 思考/推理模式(覆盖配置) |
|
||||||
| `-y, --yes` | 跳过确认提示 |
|
| `-y, --yes` | 跳过确认提示 |
|
||||||
|
|
||||||
## 配置文件
|
## 配置文件
|
||||||
@@ -331,58 +399,25 @@ use_agent = true
|
|||||||
|
|
||||||
[llm]
|
[llm]
|
||||||
provider = "ollama"
|
provider = "ollama"
|
||||||
|
model = "llama2"
|
||||||
|
# base_url = "http://localhost:11434"
|
||||||
max_tokens = 500
|
max_tokens = 500
|
||||||
temperature = 0.7
|
temperature = 0.7
|
||||||
timeout = 30
|
timeout = 30
|
||||||
|
api_key_storage = "keyring"
|
||||||
[llm.ollama]
|
thinking_enabled = false
|
||||||
url = "http://localhost:11434"
|
|
||||||
model = "llama2"
|
|
||||||
|
|
||||||
[llm.openai]
|
|
||||||
model = "gpt-4"
|
|
||||||
base_url = "https://api.openai.com/v1"
|
|
||||||
|
|
||||||
[llm.anthropic]
|
|
||||||
model = "claude-3-sonnet-20240229"
|
|
||||||
|
|
||||||
[llm.kimi]
|
|
||||||
model = "moonshot-v1-8k"
|
|
||||||
|
|
||||||
[llm.deepseek]
|
|
||||||
model = "deepseek-chat"
|
|
||||||
|
|
||||||
[llm.openrouter]
|
|
||||||
model = "openai/gpt-4"
|
|
||||||
|
|
||||||
[commit]
|
[commit]
|
||||||
format = "conventional"
|
format = "conventional"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
allow_empty = false
|
|
||||||
gpg_sign = false
|
|
||||||
max_subject_length = 100
|
|
||||||
require_scope = false
|
|
||||||
require_body = false
|
|
||||||
body_required_types = ["feat", "fix"]
|
|
||||||
|
|
||||||
[tag]
|
[tag]
|
||||||
version_prefix = "v"
|
version_prefix = "v"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
gpg_sign = false
|
|
||||||
include_changelog = true
|
|
||||||
|
|
||||||
[changelog]
|
[changelog]
|
||||||
path = "CHANGELOG.md"
|
path = "CHANGELOG.md"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
format = "keep-a-changelog"
|
|
||||||
include_hashes = false
|
|
||||||
include_authors = false
|
|
||||||
group_by_type = true
|
|
||||||
|
|
||||||
[theme]
|
|
||||||
colors = true
|
|
||||||
icons = true
|
|
||||||
date_format = "%Y-%m-%d"
|
|
||||||
|
|
||||||
[repo_profiles]
|
[repo_profiles]
|
||||||
"/path/to/work/project" = "work"
|
"/path/to/work/project" = "work"
|
||||||
@@ -401,9 +436,6 @@ date_format = "%Y-%m-%d"
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看当前配置
|
# 查看当前配置
|
||||||
quicommit config list
|
|
||||||
|
|
||||||
# 显示配置详情
|
|
||||||
quicommit config show
|
quicommit config show
|
||||||
|
|
||||||
# 编辑配置文件
|
# 编辑配置文件
|
||||||
@@ -504,13 +536,12 @@ src/
|
|||||||
│ ├── commit.rs
|
│ ├── commit.rs
|
||||||
│ ├── tag.rs
|
│ ├── tag.rs
|
||||||
│ └── changelog.rs
|
│ └── changelog.rs
|
||||||
├── llm/ # LLM提供商实现
|
├── llm/ # LLM 集成(基于 rig-core)
|
||||||
│ ├── ollama.rs
|
│ ├── mod.rs
|
||||||
│ ├── openai.rs
|
│ ├── prompts.rs
|
||||||
│ ├── anthropic.rs
|
│ ├── parsing.rs
|
||||||
│ ├── kimi.rs
|
│ ├── thinking.rs
|
||||||
│ ├── deepseek.rs
|
│ └── rig/ # rig provider 门面
|
||||||
│ └── openrouter.rs
|
|
||||||
├── i18n/ # 国际化支持
|
├── i18n/ # 国际化支持
|
||||||
│ ├── messages.rs
|
│ ├── messages.rs
|
||||||
│ └── translator.rs
|
│ └── translator.rs
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
use crate::config::{Language, manager::ConfigManager};
|
use crate::config::{Language, manager::ConfigManager};
|
||||||
use crate::generator::ContentGenerator;
|
use crate::generator::ContentGenerator;
|
||||||
|
use crate::git::GitRepo;
|
||||||
use crate::git::find_repo;
|
use crate::git::find_repo;
|
||||||
use crate::git::{CommitInfo, changelog::*};
|
use crate::git::{CommitInfo, changelog::*};
|
||||||
use crate::i18n::{Messages, translate_changelog_category};
|
use crate::i18n::{Messages, translate_changelog_category};
|
||||||
@@ -120,7 +121,10 @@ impl ChangelogCommand {
|
|||||||
|
|
||||||
// Get commits
|
// Get commits
|
||||||
println!("{}", messages.fetching_commits());
|
println!("{}", messages.fetching_commits());
|
||||||
let commits = generate_from_history(&repo, self.from.as_deref(), Some(&self.to))?;
|
|
||||||
|
// Determine from_tag: use explicit --from, or auto-detect from changelog
|
||||||
|
let from_tag = self.resolve_from_tag(&repo, &output_path, &messages);
|
||||||
|
let commits = generate_from_history(&repo, from_tag.as_deref(), Some(&self.to))?;
|
||||||
|
|
||||||
if commits.is_empty() {
|
if commits.is_empty() {
|
||||||
bail!("{}", messages.no_commits_found());
|
bail!("{}", messages.no_commits_found());
|
||||||
@@ -167,33 +171,13 @@ impl ChangelogCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write to file (always prepend to preserve history)
|
// Write to file (always prepend new entry before existing versions)
|
||||||
if output_path.exists() {
|
if output_path.exists() {
|
||||||
let existing = std::fs::read_to_string(&output_path)?;
|
let existing = std::fs::read_to_string(&output_path)?;
|
||||||
let new_content = if existing.is_empty() {
|
let new_content = if existing.is_empty() {
|
||||||
format!("{}{}", CHANGELOG_HEADER, changelog)
|
format!("{}{}", CHANGELOG_HEADER, changelog)
|
||||||
} else if existing.starts_with(CHANGELOG_HEADER) {
|
|
||||||
format!("{}{}", CHANGELOG_HEADER, changelog)
|
|
||||||
} else if existing.starts_with("# Changelog") {
|
|
||||||
let lines: Vec<&str> = existing.lines().collect();
|
|
||||||
let mut header_end = 0;
|
|
||||||
|
|
||||||
for (i, line) in lines.iter().enumerate() {
|
|
||||||
if i == 0 && line.starts_with('#') {
|
|
||||||
header_end = i + 1;
|
|
||||||
} else if line.trim().is_empty() {
|
|
||||||
header_end = i + 1;
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let header = lines[..header_end].join("\n");
|
|
||||||
let rest = lines[header_end..].join("\n");
|
|
||||||
|
|
||||||
format!("{}\n{}\n{}", header, changelog, rest)
|
|
||||||
} else {
|
} else {
|
||||||
format!("{}{}", CHANGELOG_HEADER, changelog)
|
insert_changelog_entry(&existing, &changelog)
|
||||||
};
|
};
|
||||||
std::fs::write(&output_path, new_content)?;
|
std::fs::write(&output_path, new_content)?;
|
||||||
} else {
|
} else {
|
||||||
@@ -206,6 +190,28 @@ impl ChangelogCommand {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn resolve_from_tag(
|
||||||
|
&self,
|
||||||
|
repo: &GitRepo,
|
||||||
|
output_path: &PathBuf,
|
||||||
|
messages: &Messages,
|
||||||
|
) -> Option<String> {
|
||||||
|
// Explicit --from always wins
|
||||||
|
if self.from.is_some() {
|
||||||
|
return self.from.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-detect: find highest version already in changelog
|
||||||
|
let existing = std::fs::read_to_string(output_path).ok()?;
|
||||||
|
let versions = parse_changelog_versions(&existing);
|
||||||
|
let highest = versions.first()?;
|
||||||
|
|
||||||
|
// Match highest version to a git tag
|
||||||
|
let tag = repo.find_tag_by_version(highest)?;
|
||||||
|
println!(" {}: {}", messages.version(), tag.name);
|
||||||
|
Some(tag.name)
|
||||||
|
}
|
||||||
|
|
||||||
async fn generate_with_ai(
|
async fn generate_with_ai(
|
||||||
&self,
|
&self,
|
||||||
version: &str,
|
version: &str,
|
||||||
@@ -217,7 +223,7 @@ impl ChangelogCommand {
|
|||||||
|
|
||||||
println!("{}", messages.ai_generating_changelog());
|
println!("{}", messages.ai_generating_changelog());
|
||||||
|
|
||||||
let generator = ContentGenerator::new_with_think(&manager, self.think).await?;
|
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
|
||||||
generator
|
generator
|
||||||
.generate_changelog_entry(version, commits, language)
|
.generate_changelog_entry(version, commits, language)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -121,8 +121,17 @@ impl CommitCommand {
|
|||||||
// Auto-add if no files are staged and there are unstaged/untracked changes
|
// Auto-add if no files are staged and there are unstaged/untracked changes
|
||||||
if status.staged == 0 && (status.unstaged > 0 || status.untracked > 0) && !self.all {
|
if status.staged == 0 && (status.unstaged > 0 || status.untracked > 0) && !self.all {
|
||||||
println!("{}", messages.auto_stage_changes().yellow());
|
println!("{}", messages.auto_stage_changes().yellow());
|
||||||
repo.stage_all()?;
|
let removed = repo.stage_all()?;
|
||||||
println!("{}", messages.staged_all().green());
|
println!("{}", messages.staged_all().green());
|
||||||
|
if !removed.is_empty() {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
format!("Removed {} ignored files from staging:", removed.len()).yellow()
|
||||||
|
);
|
||||||
|
for file in &removed {
|
||||||
|
println!(" • {}", file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Re-check status after staging to ensure changes are detected
|
// Re-check status after staging to ensure changes are detected
|
||||||
let new_status = repo.status_summary()?;
|
let new_status = repo.status_summary()?;
|
||||||
@@ -133,8 +142,17 @@ impl CommitCommand {
|
|||||||
|
|
||||||
// Stage all if requested
|
// Stage all if requested
|
||||||
if self.all {
|
if self.all {
|
||||||
repo.stage_all()?;
|
let removed = repo.stage_all()?;
|
||||||
println!("{}", messages.staged_all().green());
|
println!("{}", messages.staged_all().green());
|
||||||
|
if !removed.is_empty() {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
format!("Removed {} ignored files from staging:", removed.len()).yellow()
|
||||||
|
);
|
||||||
|
for file in &removed {
|
||||||
|
println!(" • {}", file);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate or build commit message
|
// Generate or build commit message
|
||||||
@@ -280,7 +298,11 @@ impl CommitCommand {
|
|||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let manager = ConfigManager::new()?;
|
let manager = ConfigManager::new()?;
|
||||||
|
|
||||||
let generator = ContentGenerator::new_with_think(&manager, self.think)
|
let template = manager
|
||||||
|
.default_profile()
|
||||||
|
.and_then(|p| p.commit_template().map(|t| t.to_string()));
|
||||||
|
|
||||||
|
let generator = ContentGenerator::new_with_think(&manager, self.think, template)
|
||||||
.await
|
.await
|
||||||
.context("Failed to initialize LLM. Use --manual for manual commit.")?;
|
.context("Failed to initialize LLM. Use --manual for manual commit.")?;
|
||||||
|
|
||||||
|
|||||||
@@ -37,9 +37,6 @@ enum ConfigSubcommand {
|
|||||||
/// Show current configuration
|
/// Show current configuration
|
||||||
Show,
|
Show,
|
||||||
|
|
||||||
/// List all configuration information (with masked API keys)
|
|
||||||
List,
|
|
||||||
|
|
||||||
/// Edit configuration file
|
/// Edit configuration file
|
||||||
Edit,
|
Edit,
|
||||||
|
|
||||||
@@ -167,7 +164,6 @@ impl ConfigCommand {
|
|||||||
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
|
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
|
||||||
match &self.command {
|
match &self.command {
|
||||||
Some(ConfigSubcommand::Show) => self.show_config(&config_path).await,
|
Some(ConfigSubcommand::Show) => self.show_config(&config_path).await,
|
||||||
Some(ConfigSubcommand::List) => self.list_config(&config_path).await,
|
|
||||||
Some(ConfigSubcommand::Edit) => self.edit_config(&config_path).await,
|
Some(ConfigSubcommand::Edit) => self.edit_config(&config_path).await,
|
||||||
Some(ConfigSubcommand::Set { key, value }) => {
|
Some(ConfigSubcommand::Set { key, value }) => {
|
||||||
self.set_value(key, value, &config_path).await
|
self.set_value(key, value, &config_path).await
|
||||||
@@ -311,15 +307,6 @@ impl ConfigCommand {
|
|||||||
"no".red()
|
"no".red()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
println!(
|
|
||||||
" GPG sign: {}",
|
|
||||||
if config.commit.gpg_sign {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(" Max subject length: {}", config.commit.max_subject_length);
|
|
||||||
|
|
||||||
println!("\n{}", "Tag Configuration:".bold());
|
println!("\n{}", "Tag Configuration:".bold());
|
||||||
println!(" Version prefix: '{}'", config.tag.version_prefix);
|
println!(" Version prefix: '{}'", config.tag.version_prefix);
|
||||||
@@ -331,22 +318,6 @@ impl ConfigCommand {
|
|||||||
"no".red()
|
"no".red()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
println!(
|
|
||||||
" GPG sign: {}",
|
|
||||||
if config.tag.gpg_sign {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Include changelog: {}",
|
|
||||||
if config.tag.include_changelog {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
println!("\n{}", "Language Configuration:".bold());
|
println!("\n{}", "Language Configuration:".bold());
|
||||||
let language = manager.get_language().unwrap_or(Language::English);
|
let language = manager.get_language().unwrap_or(Language::English);
|
||||||
@@ -378,243 +349,17 @@ impl ConfigCommand {
|
|||||||
"no".red()
|
"no".red()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
println!(
|
|
||||||
" Include hashes: {}",
|
|
||||||
if config.changelog.include_hashes {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Include authors: {}",
|
|
||||||
if config.changelog.include_authors {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Group by type: {}",
|
|
||||||
if config.changelog.group_by_type {
|
|
||||||
"yes".green()
|
|
||||||
} else {
|
|
||||||
"no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
println!("\n{}", "Security:".bold());
|
||||||
}
|
println!(" Repository mappings: {} mapping(s)", config.repo_profiles.len());
|
||||||
|
|
||||||
async fn list_config(&self, config_path: &Option<PathBuf>) -> Result<()> {
|
|
||||||
let manager = self.get_manager(config_path)?;
|
|
||||||
let config = manager.config();
|
|
||||||
|
|
||||||
println!("{}", "\nQuiCommit Configuration".bold());
|
|
||||||
println!("{}", "═".repeat(80));
|
|
||||||
|
|
||||||
println!("\n{}", "📁 General Configuration:".bold().blue());
|
|
||||||
println!(" Config file: {}", manager.path().display());
|
|
||||||
println!(
|
println!(
|
||||||
" Default profile: {}",
|
" Keyring: {}",
|
||||||
config.default_profile.as_deref().unwrap_or("(none)").cyan()
|
if manager.keyring().is_available() {
|
||||||
);
|
"available".green()
|
||||||
println!(" Profiles: {} profile(s)", config.profiles.len());
|
|
||||||
println!(
|
|
||||||
" Repository mappings: {} mapping(s)",
|
|
||||||
config.repo_profiles.len()
|
|
||||||
);
|
|
||||||
|
|
||||||
println!("\n{}", "🤖 LLM Configuration:".bold().blue());
|
|
||||||
println!(" Provider: {}", config.llm.provider.cyan());
|
|
||||||
println!(" Model: {}", config.llm.model.cyan());
|
|
||||||
println!(" Base URL: {}", manager.llm_base_url());
|
|
||||||
println!(
|
|
||||||
" API Key: {}",
|
|
||||||
mask_api_key(manager.get_api_key().as_deref())
|
|
||||||
);
|
|
||||||
println!(" Max tokens: {}", config.llm.max_tokens);
|
|
||||||
println!(" Temperature: {}", config.llm.temperature);
|
|
||||||
println!(" Timeout: {}s", config.llm.timeout);
|
|
||||||
|
|
||||||
println!("\n{}", "📝 Commit Configuration:".bold().blue());
|
|
||||||
println!(" Format: {}", config.commit.format.to_string().cyan());
|
|
||||||
println!(
|
|
||||||
" Auto-generate: {}",
|
|
||||||
if config.commit.auto_generate {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
} else {
|
||||||
"✗ no".red()
|
"unavailable".red()
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
println!(
|
|
||||||
" Allow empty: {}",
|
|
||||||
if config.commit.allow_empty {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" GPG sign: {}",
|
|
||||||
if config.commit.gpg_sign {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Default scope: {}",
|
|
||||||
config
|
|
||||||
.commit
|
|
||||||
.default_scope
|
|
||||||
.as_deref()
|
|
||||||
.unwrap_or("(none)")
|
|
||||||
.cyan()
|
|
||||||
);
|
|
||||||
println!(" Max subject length: {}", config.commit.max_subject_length);
|
|
||||||
println!(
|
|
||||||
" Require scope: {}",
|
|
||||||
if config.commit.require_scope {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Require body: {}",
|
|
||||||
if config.commit.require_body {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
if !config.commit.body_required_types.is_empty() {
|
|
||||||
println!(
|
|
||||||
" Body required types: {}",
|
|
||||||
config.commit.body_required_types.join(", ").cyan()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("\n{}", "🏷️ Tag Configuration:".bold().blue());
|
|
||||||
println!(" Version prefix: '{}'", config.tag.version_prefix.cyan());
|
|
||||||
println!(
|
|
||||||
" Auto-generate: {}",
|
|
||||||
if config.tag.auto_generate {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" GPG sign: {}",
|
|
||||||
if config.tag.gpg_sign {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Include changelog: {}",
|
|
||||||
if config.tag.include_changelog {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Annotation template: {}",
|
|
||||||
config
|
|
||||||
.tag
|
|
||||||
.annotation_template
|
|
||||||
.as_deref()
|
|
||||||
.unwrap_or("(none)")
|
|
||||||
.cyan()
|
|
||||||
);
|
|
||||||
|
|
||||||
println!("\n{}", "📋 Changelog Configuration:".bold().blue());
|
|
||||||
println!(" Path: {}", config.changelog.path);
|
|
||||||
println!(
|
|
||||||
" Auto-generate: {}",
|
|
||||||
if config.changelog.auto_generate {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Format: {}",
|
|
||||||
format!("{:?}", config.changelog.format).cyan()
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Include hashes: {}",
|
|
||||||
if config.changelog.include_hashes {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Include authors: {}",
|
|
||||||
if config.changelog.include_authors {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Group by type: {}",
|
|
||||||
if config.changelog.group_by_type {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
if !config.changelog.custom_categories.is_empty() {
|
|
||||||
println!(
|
|
||||||
" Custom categories: {} category(ies)",
|
|
||||||
config.changelog.custom_categories.len()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("\n{}", "🎨 Theme Configuration:".bold().blue());
|
|
||||||
println!(
|
|
||||||
" Colors: {}",
|
|
||||||
if config.theme.colors {
|
|
||||||
"✓ enabled".green()
|
|
||||||
} else {
|
|
||||||
"✗ disabled".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" Icons: {}",
|
|
||||||
if config.theme.icons {
|
|
||||||
"✓ enabled".green()
|
|
||||||
} else {
|
|
||||||
"✗ disabled".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
println!(" Date format: {}", config.theme.date_format.cyan());
|
|
||||||
|
|
||||||
println!("\n{}", "🔒 Security:".bold().blue());
|
|
||||||
println!(
|
|
||||||
" Encrypt sensitive: {}",
|
|
||||||
if config.encrypt_sensitive {
|
|
||||||
"✓ yes".green()
|
|
||||||
} else {
|
|
||||||
"✗ no".red()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
println!("\n{}", "🔑 Keyring:".bold().blue());
|
|
||||||
let keyring = manager.keyring();
|
|
||||||
if keyring.is_available() {
|
|
||||||
println!(" Status: {}", "✓ available".green());
|
|
||||||
println!(" Backend: {}", keyring.get_status_message());
|
|
||||||
} else {
|
|
||||||
println!(" Status: {}", "✗ unavailable".red());
|
|
||||||
println!(" Note: {}", keyring.get_status_message());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -671,7 +416,22 @@ impl ConfigCommand {
|
|||||||
manager.set_auto_generate_commits(value == "true");
|
manager.set_auto_generate_commits(value == "true");
|
||||||
}
|
}
|
||||||
"tag.version_prefix" => manager.set_version_prefix(value.to_string()),
|
"tag.version_prefix" => manager.set_version_prefix(value.to_string()),
|
||||||
|
"tag.auto_generate" => {
|
||||||
|
manager.config_mut().tag.auto_generate = value == "true";
|
||||||
|
}
|
||||||
"changelog.path" => manager.set_changelog_path(value.to_string()),
|
"changelog.path" => manager.set_changelog_path(value.to_string()),
|
||||||
|
"changelog.auto_generate" => {
|
||||||
|
manager.config_mut().changelog.auto_generate = value == "true";
|
||||||
|
}
|
||||||
|
"language.output_language" => {
|
||||||
|
manager.set_output_language(value.to_string());
|
||||||
|
}
|
||||||
|
"language.keep_types_english" => {
|
||||||
|
manager.set_keep_types_english(value == "true");
|
||||||
|
}
|
||||||
|
"language.keep_changelog_types_english" => {
|
||||||
|
manager.set_keep_changelog_types_english(value == "true");
|
||||||
|
}
|
||||||
_ => bail!("Unknown configuration key: {}", key),
|
_ => bail!("Unknown configuration key: {}", key),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -702,7 +462,14 @@ impl ConfigCommand {
|
|||||||
"commit.format" => config.commit.format.to_string(),
|
"commit.format" => config.commit.format.to_string(),
|
||||||
"commit.auto_generate" => config.commit.auto_generate.to_string(),
|
"commit.auto_generate" => config.commit.auto_generate.to_string(),
|
||||||
"tag.version_prefix" => config.tag.version_prefix.clone(),
|
"tag.version_prefix" => config.tag.version_prefix.clone(),
|
||||||
|
"tag.auto_generate" => config.tag.auto_generate.to_string(),
|
||||||
"changelog.path" => config.changelog.path.clone(),
|
"changelog.path" => config.changelog.path.clone(),
|
||||||
|
"changelog.auto_generate" => config.changelog.auto_generate.to_string(),
|
||||||
|
"language.output_language" => config.language.output_language.clone(),
|
||||||
|
"language.keep_types_english" => config.language.keep_types_english.to_string(),
|
||||||
|
"language.keep_changelog_types_english" => {
|
||||||
|
config.language.keep_changelog_types_english.to_string()
|
||||||
|
}
|
||||||
_ => bail!("Unknown configuration key: {}", key),
|
_ => bail!("Unknown configuration key: {}", key),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
458
src/commands/credential.rs
Normal file
458
src/commands/credential.rs
Normal file
@@ -0,0 +1,458 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use clap::{Parser, Subcommand};
|
||||||
|
use std::io::{self, BufRead, Write};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use crate::config::manager::ConfigManager;
|
||||||
|
use crate::config::{TokenConfig, TokenType};
|
||||||
|
|
||||||
|
/// Git credential helper command.
|
||||||
|
///
|
||||||
|
/// Implements the git credential helper protocol
|
||||||
|
/// (https://git-scm.com/docs/gitcredentials). Intended to be invoked by git
|
||||||
|
/// via `credential.helper` configuration, not by end users. Hidden from the
|
||||||
|
/// main help output.
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(hide = true)]
|
||||||
|
pub struct CredentialCommand {
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: CredentialSubcommand,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum CredentialSubcommand {
|
||||||
|
/// Read attributes on stdin and output credentials on stdout.
|
||||||
|
#[command(hide = true)]
|
||||||
|
Get,
|
||||||
|
/// Read attributes (including password) on stdin and store them.
|
||||||
|
#[command(hide = true)]
|
||||||
|
Store,
|
||||||
|
/// Read attributes on stdin and erase any matching stored credentials.
|
||||||
|
#[command(hide = true)]
|
||||||
|
Erase,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CredentialCommand {
|
||||||
|
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
|
||||||
|
match &self.command {
|
||||||
|
CredentialSubcommand::Get => Self::get(config_path),
|
||||||
|
CredentialSubcommand::Store => Self::store(config_path),
|
||||||
|
CredentialSubcommand::Erase => Self::erase(config_path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_manager(config_path: &Option<PathBuf>) -> Result<ConfigManager> {
|
||||||
|
match config_path {
|
||||||
|
Some(path) => ConfigManager::with_path(path),
|
||||||
|
None => ConfigManager::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `git credential get`: look up a PAT for the requested host and emit it
|
||||||
|
/// on stdout following the git credential helper protocol.
|
||||||
|
fn get(config_path: Option<PathBuf>) -> Result<()> {
|
||||||
|
let attrs = CredentialAttributes::from_stdin()?;
|
||||||
|
|
||||||
|
let host = match attrs.host.as_deref() {
|
||||||
|
Some(h) if !h.is_empty() => h,
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let service = host_to_service(host);
|
||||||
|
|
||||||
|
let manager = match Self::get_manager(&config_path) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(_) => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let (profile_name, pat) = match find_pat_for_service(&manager, &service) {
|
||||||
|
Some(tuple) => tuple,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Prefer a git-supplied username; fall back to the profile's user_name.
|
||||||
|
let username = attrs.username.clone().or_else(|| {
|
||||||
|
manager
|
||||||
|
.get_profile(&profile_name)
|
||||||
|
.map(|p| p.user_name.clone())
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = CredentialAttributes {
|
||||||
|
protocol: attrs.protocol.clone(),
|
||||||
|
host: attrs.host.clone(),
|
||||||
|
path: attrs.path.clone(),
|
||||||
|
username,
|
||||||
|
password: Some(pat),
|
||||||
|
};
|
||||||
|
output.to_stdout()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `git credential store`: persist the PAT provided by git using the
|
||||||
|
/// existing keyring-backed storage, associated with a matching profile.
|
||||||
|
fn store(config_path: Option<PathBuf>) -> Result<()> {
|
||||||
|
let attrs = CredentialAttributes::from_stdin()?;
|
||||||
|
|
||||||
|
let host = match attrs.host.as_deref() {
|
||||||
|
Some(h) if !h.is_empty() => h,
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let service = host_to_service(host);
|
||||||
|
|
||||||
|
let password = match attrs.password.as_deref() {
|
||||||
|
Some(p) if !p.is_empty() => p,
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut manager = Self::get_manager(&config_path)?;
|
||||||
|
|
||||||
|
let profile_name = match find_profile_for_store(&manager, attrs.username.as_deref()) {
|
||||||
|
Some(name) => name,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Store PAT in keyring using the existing profile-bound logic.
|
||||||
|
if let Err(e) = manager.store_pat_for_profile(&profile_name, &service, password) {
|
||||||
|
eprintln!("[quicommit credential] failed to store PAT: {}", e);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register the token in the profile config if not already present.
|
||||||
|
let already_has = manager
|
||||||
|
.get_profile(&profile_name)
|
||||||
|
.map(|p| p.tokens.contains_key(&service))
|
||||||
|
.unwrap_or(false);
|
||||||
|
if !already_has {
|
||||||
|
let _ = manager.add_token_to_profile(
|
||||||
|
&profile_name,
|
||||||
|
service.clone(),
|
||||||
|
TokenConfig::new(TokenType::Personal),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
manager.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `git credential erase`: remove any PAT stored for the requested host
|
||||||
|
/// from the keyring and the associated profile config entries.
|
||||||
|
fn erase(config_path: Option<PathBuf>) -> Result<()> {
|
||||||
|
let attrs = CredentialAttributes::from_stdin()?;
|
||||||
|
|
||||||
|
let host = match attrs.host.as_deref() {
|
||||||
|
Some(h) if !h.is_empty() => h,
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let service = host_to_service(host);
|
||||||
|
|
||||||
|
let mut manager = Self::get_manager(&config_path)?;
|
||||||
|
|
||||||
|
let profile_names: Vec<String> = manager
|
||||||
|
.list_profiles()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|name| {
|
||||||
|
manager
|
||||||
|
.get_profile(name)
|
||||||
|
.map(|p| p.tokens.contains_key(&service))
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for name in &profile_names {
|
||||||
|
if let Err(e) = manager.remove_token_from_profile(name, &service) {
|
||||||
|
eprintln!(
|
||||||
|
"[quicommit credential] failed to erase PAT for '{}': {}",
|
||||||
|
name, e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
manager.save()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Credential attributes exchanged with git via stdin/stdout following the
|
||||||
|
/// git credential helper protocol (`key=value`, one per line, blank line ends).
|
||||||
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CredentialAttributes {
|
||||||
|
pub protocol: Option<String>,
|
||||||
|
pub host: Option<String>,
|
||||||
|
pub path: Option<String>,
|
||||||
|
pub username: Option<String>,
|
||||||
|
pub password: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CredentialAttributes {
|
||||||
|
/// Read attributes from stdin following the git credential helper protocol.
|
||||||
|
pub fn from_stdin() -> Result<Self> {
|
||||||
|
let stdin = io::stdin();
|
||||||
|
let mut attrs = Self::default();
|
||||||
|
for line in stdin.lock().lines() {
|
||||||
|
let line =
|
||||||
|
line.context("Failed to read credential attributes from stdin")?;
|
||||||
|
if line.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some((key, value)) = line.split_once('=') {
|
||||||
|
match key {
|
||||||
|
"protocol" => attrs.protocol = Some(value.to_string()),
|
||||||
|
"host" => attrs.host = Some(value.to_string()),
|
||||||
|
"path" => attrs.path = Some(value.to_string()),
|
||||||
|
"username" => attrs.username = Some(value.to_string()),
|
||||||
|
"password" => attrs.password = Some(value.to_string()),
|
||||||
|
_ => {} // ignore unknown keys
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(attrs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write attributes to stdout following the git credential helper protocol.
|
||||||
|
pub fn to_stdout(&self) -> Result<()> {
|
||||||
|
let stdout = io::stdout();
|
||||||
|
let mut handle = stdout.lock();
|
||||||
|
if let Some(ref v) = self.protocol {
|
||||||
|
writeln!(handle, "protocol={}", v)?;
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.host {
|
||||||
|
writeln!(handle, "host={}", v)?;
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.path {
|
||||||
|
writeln!(handle, "path={}", v)?;
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.username {
|
||||||
|
writeln!(handle, "username={}", v)?;
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.password {
|
||||||
|
writeln!(handle, "password={}", v)?;
|
||||||
|
}
|
||||||
|
writeln!(handle)?; // blank line terminates the attribute list
|
||||||
|
handle.flush()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse attributes from a text block following the git credential helper
|
||||||
|
/// protocol. Intended for testing and non-stdin input handling.
|
||||||
|
pub fn parse_str(input: &str) -> Self {
|
||||||
|
let mut attrs = Self::default();
|
||||||
|
for line in input.lines() {
|
||||||
|
if line.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some((key, value)) = line.split_once('=') {
|
||||||
|
match key {
|
||||||
|
"protocol" => attrs.protocol = Some(value.to_string()),
|
||||||
|
"host" => attrs.host = Some(value.to_string()),
|
||||||
|
"path" => attrs.path = Some(value.to_string()),
|
||||||
|
"username" => attrs.username = Some(value.to_string()),
|
||||||
|
"password" => attrs.password = Some(value.to_string()),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
attrs
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serialize attributes to a string following the git credential helper
|
||||||
|
/// protocol. Intended for testing and non-stdout output handling.
|
||||||
|
pub fn serialize(&self) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
if let Some(ref v) = self.protocol {
|
||||||
|
out.push_str(&format!("protocol={}\n", v));
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.host {
|
||||||
|
out.push_str(&format!("host={}\n", v));
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.path {
|
||||||
|
out.push_str(&format!("path={}\n", v));
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.username {
|
||||||
|
out.push_str(&format!("username={}\n", v));
|
||||||
|
}
|
||||||
|
if let Some(ref v) = self.password {
|
||||||
|
out.push_str(&format!("password={}\n", v));
|
||||||
|
}
|
||||||
|
out.push('\n');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a git host to a service name used by the keyring-backed PAT storage.
|
||||||
|
///
|
||||||
|
/// Common git hosting services are mapped to short canonical names. Unknown
|
||||||
|
/// hosts are used as-is (lowercased, trailing slash trimmed).
|
||||||
|
pub fn host_to_service(host: &str) -> String {
|
||||||
|
let host = host.to_lowercase();
|
||||||
|
let host = host.trim_end_matches('/');
|
||||||
|
match host {
|
||||||
|
"github.com" | "www.github.com" => "github".to_string(),
|
||||||
|
"gitlab.com" | "www.gitlab.com" => "gitlab".to_string(),
|
||||||
|
"bitbucket.org" | "www.bitbucket.org" => "bitbucket".to_string(),
|
||||||
|
"codeberg.org" | "www.codeberg.org" => "codeberg".to_string(),
|
||||||
|
"gitea.com" | "www.gitea.com" => "gitea".to_string(),
|
||||||
|
"gitee.com" | "www.gitee.com" => "gitee".to_string(),
|
||||||
|
other => other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Search all profiles for one that has a PAT stored for the given service.
|
||||||
|
/// Returns the profile name and the PAT value.
|
||||||
|
fn find_pat_for_service(manager: &ConfigManager, service: &str) -> Option<(String, String)> {
|
||||||
|
for profile_name in manager.list_profiles() {
|
||||||
|
if manager.has_pat_for_profile(profile_name, service) {
|
||||||
|
if let Ok(Some(pat)) = manager.get_pat_for_profile(profile_name, service) {
|
||||||
|
return Some((profile_name.clone(), pat));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determine which profile to use when storing a credential.
|
||||||
|
///
|
||||||
|
/// Prefers a profile whose `user_name` or `user_email` matches the
|
||||||
|
/// git-supplied username; otherwise falls back to the default profile.
|
||||||
|
fn find_profile_for_store(
|
||||||
|
manager: &ConfigManager,
|
||||||
|
username: Option<&str>,
|
||||||
|
) -> Option<String> {
|
||||||
|
if let Some(username) = username {
|
||||||
|
for name in manager.list_profiles() {
|
||||||
|
if let Some(profile) = manager.get_profile(name) {
|
||||||
|
if profile.user_name == username || profile.user_email == username {
|
||||||
|
return Some(name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
manager.default_profile_name().cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract a PAT for the given host from saved credentials across all profiles.
|
||||||
|
///
|
||||||
|
/// This is intended for use by other parts of the application (e.g. when
|
||||||
|
/// verifying access to a git hosting service) and searches every configured
|
||||||
|
/// profile for a stored PAT matching the host.
|
||||||
|
pub fn get_pat_for_host(host: &str) -> Result<Option<String>> {
|
||||||
|
let manager = ConfigManager::new()?;
|
||||||
|
let service = host_to_service(host);
|
||||||
|
Ok(find_pat_for_service(&manager, &service).map(|(_, pat)| pat))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_host_to_service_known_hosts() {
|
||||||
|
assert_eq!(host_to_service("github.com"), "github");
|
||||||
|
assert_eq!(host_to_service("www.github.com"), "github");
|
||||||
|
assert_eq!(host_to_service("gitlab.com"), "gitlab");
|
||||||
|
assert_eq!(host_to_service("bitbucket.org"), "bitbucket");
|
||||||
|
assert_eq!(host_to_service("codeberg.org"), "codeberg");
|
||||||
|
assert_eq!(host_to_service("gitea.com"), "gitea");
|
||||||
|
assert_eq!(host_to_service("gitee.com"), "gitee");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_host_to_service_case_insensitive() {
|
||||||
|
assert_eq!(host_to_service("GitHub.Com"), "github");
|
||||||
|
assert_eq!(host_to_service("GITLAB.COM"), "gitlab");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_host_to_service_trailing_slash() {
|
||||||
|
assert_eq!(host_to_service("github.com/"), "github");
|
||||||
|
assert_eq!(host_to_service("gitlab.com//"), "gitlab");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_host_to_service_unknown_host() {
|
||||||
|
assert_eq!(host_to_service("example.com"), "example.com");
|
||||||
|
assert_eq!(host_to_service("git.internal.corp"), "git.internal.corp");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_parse_basic() {
|
||||||
|
let input = "protocol=https\nhost=github.com\nusername=octocat\npassword=ghp_token123\n\n";
|
||||||
|
let attrs = CredentialAttributes::parse_str(input);
|
||||||
|
assert_eq!(attrs.protocol.as_deref(), Some("https"));
|
||||||
|
assert_eq!(attrs.host.as_deref(), Some("github.com"));
|
||||||
|
assert_eq!(attrs.username.as_deref(), Some("octocat"));
|
||||||
|
assert_eq!(attrs.password.as_deref(), Some("ghp_token123"));
|
||||||
|
assert!(attrs.path.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_parse_with_path() {
|
||||||
|
let input = "protocol=https\nhost=github.com\npath=owner/repo.git\n\n";
|
||||||
|
let attrs = CredentialAttributes::parse_str(input);
|
||||||
|
assert_eq!(attrs.path.as_deref(), Some("owner/repo.git"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_parse_empty() {
|
||||||
|
let attrs = CredentialAttributes::parse_str("");
|
||||||
|
assert!(attrs.protocol.is_none());
|
||||||
|
assert!(attrs.host.is_none());
|
||||||
|
assert!(attrs.username.is_none());
|
||||||
|
assert!(attrs.password.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_parse_ignores_unknown_keys() {
|
||||||
|
let input = "protocol=https\nhost=github.com\nunknown=value\nfoo=bar\n\n";
|
||||||
|
let attrs = CredentialAttributes::parse_str(input);
|
||||||
|
assert_eq!(attrs.protocol.as_deref(), Some("https"));
|
||||||
|
assert_eq!(attrs.host.as_deref(), Some("github.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_parse_stops_at_blank_line() {
|
||||||
|
let input = "protocol=https\nhost=github.com\n\npassword=should_be_ignored\n";
|
||||||
|
let attrs = CredentialAttributes::parse_str(input);
|
||||||
|
assert_eq!(attrs.protocol.as_deref(), Some("https"));
|
||||||
|
assert_eq!(attrs.host.as_deref(), Some("github.com"));
|
||||||
|
assert!(attrs.password.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_serialize_roundtrip() {
|
||||||
|
let attrs = CredentialAttributes {
|
||||||
|
protocol: Some("https".to_string()),
|
||||||
|
host: Some("github.com".to_string()),
|
||||||
|
path: None,
|
||||||
|
username: Some("octocat".to_string()),
|
||||||
|
password: Some("ghp_token".to_string()),
|
||||||
|
};
|
||||||
|
let serialized = attrs.serialize();
|
||||||
|
let reparsed = CredentialAttributes::parse_str(&serialized);
|
||||||
|
assert_eq!(attrs, reparsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_serialize_includes_blank_line() {
|
||||||
|
let attrs = CredentialAttributes {
|
||||||
|
protocol: Some("https".to_string()),
|
||||||
|
host: Some("github.com".to_string()),
|
||||||
|
path: None,
|
||||||
|
username: None,
|
||||||
|
password: None,
|
||||||
|
};
|
||||||
|
let serialized = attrs.serialize();
|
||||||
|
assert!(serialized.ends_with("\n\n"));
|
||||||
|
assert!(serialized.contains("protocol=https\n"));
|
||||||
|
assert!(serialized.contains("host=github.com\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_credential_attributes_default() {
|
||||||
|
let attrs = CredentialAttributes::default();
|
||||||
|
assert!(attrs.protocol.is_none());
|
||||||
|
assert!(attrs.host.is_none());
|
||||||
|
assert!(attrs.path.is_none());
|
||||||
|
assert!(attrs.username.is_none());
|
||||||
|
assert!(attrs.password.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -331,6 +331,17 @@ impl InitCommand {
|
|||||||
.default(ssh_dir.join("id_rsa").display().to_string())
|
.default(ssh_dir.join("id_rsa").display().to_string())
|
||||||
.interact_text()?;
|
.interact_text()?;
|
||||||
|
|
||||||
|
let pub_key_path: String = Input::new()
|
||||||
|
.with_prompt("SSH public key path (optional, leave empty to auto-detect)")
|
||||||
|
.default(ssh_dir.join("id_rsa.pub").display().to_string())
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let public_key_path = if pub_key_path.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(PathBuf::from(pub_key_path))
|
||||||
|
};
|
||||||
|
|
||||||
let has_passphrase = Confirm::new()
|
let has_passphrase = Confirm::new()
|
||||||
.with_prompt(messages.has_passphrase())
|
.with_prompt(messages.has_passphrase())
|
||||||
.default(false)
|
.default(false)
|
||||||
@@ -342,13 +353,38 @@ impl InitCommand {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let agent_forwarding = Confirm::new()
|
||||||
|
.with_prompt("Enable SSH agent forwarding (-A)?")
|
||||||
|
.default(false)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
let known_hosts: String = Input::new()
|
||||||
|
.with_prompt("Custom known_hosts file path (optional)")
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let known_hosts_file = if known_hosts.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(PathBuf::from(known_hosts))
|
||||||
|
};
|
||||||
|
|
||||||
|
let custom_cmd: String = Input::new()
|
||||||
|
.with_prompt("Custom SSH command (optional, overrides all other SSH settings)")
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let ssh_command = if custom_cmd.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(custom_cmd)
|
||||||
|
};
|
||||||
|
|
||||||
Ok(SshConfig {
|
Ok(SshConfig {
|
||||||
private_key_path: Some(PathBuf::from(key_path)),
|
private_key_path: Some(PathBuf::from(key_path)),
|
||||||
public_key_path: None,
|
public_key_path,
|
||||||
passphrase,
|
passphrase,
|
||||||
agent_forwarding: false,
|
agent_forwarding,
|
||||||
ssh_command: None,
|
ssh_command,
|
||||||
known_hosts_file: None,
|
known_hosts_file,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod changelog;
|
pub mod changelog;
|
||||||
pub mod commit;
|
pub mod commit;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod credential;
|
||||||
pub mod init;
|
pub mod init;
|
||||||
pub mod profile;
|
pub mod profile;
|
||||||
pub mod tag;
|
pub mod tag;
|
||||||
|
|||||||
@@ -345,6 +345,13 @@ impl ProfileCommand {
|
|||||||
if profile.has_gpg() {
|
if profile.has_gpg() {
|
||||||
println!(" {} GPG configured", "🔒".to_string().dimmed());
|
println!(" {} GPG configured", "🔒".to_string().dimmed());
|
||||||
}
|
}
|
||||||
|
if profile.signing_key().is_some() {
|
||||||
|
println!(
|
||||||
|
" {} Signing key: {}",
|
||||||
|
"🔏".to_string().dimmed(),
|
||||||
|
profile.signing_key().unwrap().dimmed()
|
||||||
|
);
|
||||||
|
}
|
||||||
if profile.has_tokens() {
|
if profile.has_tokens() {
|
||||||
println!(
|
println!(
|
||||||
" {} {} token(s)",
|
" {} {} token(s)",
|
||||||
@@ -596,11 +603,64 @@ impl ProfileCommand {
|
|||||||
println!("Organization: {}", org);
|
println!("Organization: {}", org);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(ref key) = profile.signing_key {
|
||||||
|
println!("Signing key: {}", key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Profile settings
|
||||||
|
println!("\n{}", "Settings:".bold());
|
||||||
|
println!(
|
||||||
|
" Auto-sign commits: {}",
|
||||||
|
if profile.settings.auto_sign_commits {
|
||||||
|
"yes"
|
||||||
|
} else {
|
||||||
|
"no"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
" Auto-sign tags: {}",
|
||||||
|
if profile.settings.auto_sign_tags {
|
||||||
|
"yes"
|
||||||
|
} else {
|
||||||
|
"no"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if let Some(ref fmt) = profile.settings.default_commit_format {
|
||||||
|
println!(" Default commit format: {}", fmt.to_string());
|
||||||
|
}
|
||||||
|
if !profile.settings.repo_patterns.is_empty() {
|
||||||
|
println!(" Repo patterns: {:?}", profile.settings.repo_patterns);
|
||||||
|
}
|
||||||
|
if let Some(ref provider) = profile.settings.llm_provider {
|
||||||
|
println!(" Preferred LLM: {}", provider);
|
||||||
|
}
|
||||||
|
if let Some(ref template) = profile.settings.commit_template {
|
||||||
|
println!(" Commit template: {}", template);
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(ref ssh) = profile.ssh {
|
if let Some(ref ssh) = profile.ssh {
|
||||||
println!("\n{}", "SSH Configuration:".bold());
|
println!("\n{}", "SSH Configuration:".bold());
|
||||||
if let Some(ref path) = ssh.private_key_path {
|
if let Some(ref path) = ssh.private_key_path {
|
||||||
println!(" Private key: {:?}", path);
|
println!(" Private key: {:?}", path);
|
||||||
}
|
}
|
||||||
|
if let Some(ref path) = ssh.public_key_path {
|
||||||
|
println!(" Public key: {:?}", path);
|
||||||
|
} else if let Some(ref path) = ssh.effective_public_key_path() {
|
||||||
|
println!(" Public key: {:?} (auto-detected)", path);
|
||||||
|
}
|
||||||
|
println!(
|
||||||
|
" Agent forwarding: {}",
|
||||||
|
if ssh.agent_forwarding { "yes" } else { "no" }
|
||||||
|
);
|
||||||
|
if let Some(ref cmd) = ssh.ssh_command {
|
||||||
|
println!(" Custom command: {}", cmd);
|
||||||
|
}
|
||||||
|
if let Some(ref kh) = ssh.known_hosts_file {
|
||||||
|
println!(" Known hosts file: {:?}", kh);
|
||||||
|
}
|
||||||
|
if ssh.passphrase.is_some() {
|
||||||
|
println!(" Passphrase: [set]");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref gpg) = profile.gpg {
|
if let Some(ref gpg) = profile.gpg {
|
||||||
@@ -749,9 +809,9 @@ impl ProfileCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn edit_profile(&self, name: &str, config_path: &Option<PathBuf>) -> Result<()> {
|
async fn edit_profile(&self, name: &str, config_path: &Option<PathBuf>) -> Result<()> {
|
||||||
let mut manager = self.get_manager(config_path)?;
|
let manager = self.get_manager(config_path)?;
|
||||||
|
|
||||||
let profile = manager
|
let mut profile = manager
|
||||||
.get_profile(name)
|
.get_profile(name)
|
||||||
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", name))?
|
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", name))?
|
||||||
.clone();
|
.clone();
|
||||||
@@ -772,16 +832,54 @@ impl ProfileCommand {
|
|||||||
})
|
})
|
||||||
.interact_text()?;
|
.interact_text()?;
|
||||||
|
|
||||||
let mut new_profile = GitProfile::new(name.to_string(), user_name, user_email);
|
profile.user_name = user_name;
|
||||||
new_profile.description = profile.description;
|
profile.user_email = user_email;
|
||||||
new_profile.is_work = profile.is_work;
|
|
||||||
new_profile.organization = profile.organization;
|
|
||||||
new_profile.ssh = profile.ssh;
|
|
||||||
new_profile.gpg = profile.gpg;
|
|
||||||
new_profile.tokens = profile.tokens;
|
|
||||||
new_profile.usage = profile.usage;
|
|
||||||
|
|
||||||
manager.update_profile(name, new_profile)?;
|
// Sub-menu loop for optional configuration
|
||||||
|
loop {
|
||||||
|
println!();
|
||||||
|
let options = vec![
|
||||||
|
"Done / Save changes",
|
||||||
|
"Edit SSH configuration",
|
||||||
|
"Edit GPG configuration",
|
||||||
|
"Edit signing preferences",
|
||||||
|
"Manage tokens",
|
||||||
|
];
|
||||||
|
let selection = Select::new()
|
||||||
|
.with_prompt("What would you like to edit?")
|
||||||
|
.items(&options)
|
||||||
|
.default(0)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
match selection {
|
||||||
|
0 => break,
|
||||||
|
1 => {
|
||||||
|
profile.ssh = Some(self.setup_ssh_interactive().await?);
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
profile.gpg = Some(self.setup_gpg_interactive().await?);
|
||||||
|
}
|
||||||
|
3 => {
|
||||||
|
profile.settings.auto_sign_commits = Confirm::new()
|
||||||
|
.with_prompt("Auto-sign commits?")
|
||||||
|
.default(profile.settings.auto_sign_commits)
|
||||||
|
.interact()?;
|
||||||
|
profile.settings.auto_sign_tags = Confirm::new()
|
||||||
|
.with_prompt("Auto-sign tags?")
|
||||||
|
.default(profile.settings.auto_sign_tags)
|
||||||
|
.interact()?;
|
||||||
|
}
|
||||||
|
4 => {
|
||||||
|
self.edit_tokens_interactive(&mut profile, &manager).await?;
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload manager as mut to save
|
||||||
|
let config_path = manager.path().to_path_buf();
|
||||||
|
let mut manager = ConfigManager::with_path(&config_path)?;
|
||||||
|
manager.update_profile(name, profile)?;
|
||||||
manager.save()?;
|
manager.save()?;
|
||||||
|
|
||||||
println!("{} Profile '{}' updated", "✓".green(), name);
|
println!("{} Profile '{}' updated", "✓".green(), name);
|
||||||
@@ -789,6 +887,50 @@ impl ProfileCommand {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn edit_tokens_interactive(
|
||||||
|
&self,
|
||||||
|
profile: &mut GitProfile,
|
||||||
|
manager: &ConfigManager,
|
||||||
|
) -> Result<()> {
|
||||||
|
loop {
|
||||||
|
println!();
|
||||||
|
let mut options: Vec<String> = profile
|
||||||
|
.tokens
|
||||||
|
.keys()
|
||||||
|
.map(|s| format!("Remove token: {}", s))
|
||||||
|
.collect();
|
||||||
|
options.push("Add new token".to_string());
|
||||||
|
options.push("Back".to_string());
|
||||||
|
|
||||||
|
let selection = Select::new()
|
||||||
|
.with_prompt(format!("Manage tokens for '{}'", profile.name))
|
||||||
|
.items(&options)
|
||||||
|
.default(options.len() - 1)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
if selection == options.len() - 1 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if selection < profile.tokens.len() {
|
||||||
|
let service: String = profile
|
||||||
|
.tokens
|
||||||
|
.keys()
|
||||||
|
.nth(selection)
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
profile.remove_token(&service);
|
||||||
|
println!(
|
||||||
|
"{} Token '{}' removed",
|
||||||
|
"✓".green(),
|
||||||
|
service.cyan()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
self.setup_token_interactive(profile, manager).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
async fn set_default(&self, name: &str, config_path: &Option<PathBuf>) -> Result<()> {
|
async fn set_default(&self, name: &str, config_path: &Option<PathBuf>) -> Result<()> {
|
||||||
let mut manager = self.get_manager(config_path)?;
|
let mut manager = self.get_manager(config_path)?;
|
||||||
|
|
||||||
@@ -1231,18 +1373,56 @@ impl ProfileCommand {
|
|||||||
.map(|h| h.join(".ssh"))
|
.map(|h| h.join(".ssh"))
|
||||||
.unwrap_or_else(|| PathBuf::from("~/.ssh"));
|
.unwrap_or_else(|| PathBuf::from("~/.ssh"));
|
||||||
|
|
||||||
|
println!("\n{}", "SSH Configuration".bold());
|
||||||
|
|
||||||
let key_path: String = Input::new()
|
let key_path: String = Input::new()
|
||||||
.with_prompt("SSH private key path")
|
.with_prompt("SSH private key path")
|
||||||
.default(ssh_dir.join("id_rsa").display().to_string())
|
.default(ssh_dir.join("id_rsa").display().to_string())
|
||||||
.interact_text()?;
|
.interact_text()?;
|
||||||
|
|
||||||
|
let pub_key_path: String = Input::new()
|
||||||
|
.with_prompt("SSH public key path (optional, leave empty to auto-detect)")
|
||||||
|
.default(ssh_dir.join("id_rsa.pub").display().to_string())
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let public_key_path = if pub_key_path.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(PathBuf::from(pub_key_path))
|
||||||
|
};
|
||||||
|
|
||||||
|
let agent_forwarding = Confirm::new()
|
||||||
|
.with_prompt("Enable SSH agent forwarding (-A)?")
|
||||||
|
.default(false)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
let known_hosts: String = Input::new()
|
||||||
|
.with_prompt("Custom known_hosts file path (optional)")
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let known_hosts_file = if known_hosts.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(PathBuf::from(known_hosts))
|
||||||
|
};
|
||||||
|
|
||||||
|
let custom_cmd: String = Input::new()
|
||||||
|
.with_prompt("Custom SSH command (optional, overrides all other SSH settings)")
|
||||||
|
.allow_empty(true)
|
||||||
|
.interact_text()?;
|
||||||
|
let ssh_command = if custom_cmd.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(custom_cmd)
|
||||||
|
};
|
||||||
|
|
||||||
Ok(SshConfig {
|
Ok(SshConfig {
|
||||||
private_key_path: Some(PathBuf::from(key_path)),
|
private_key_path: Some(PathBuf::from(key_path)),
|
||||||
public_key_path: None,
|
public_key_path,
|
||||||
passphrase: None,
|
passphrase: None,
|
||||||
agent_forwarding: false,
|
agent_forwarding,
|
||||||
ssh_command: None,
|
ssh_command,
|
||||||
known_hosts_file: None,
|
known_hosts_file,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ use std::path::PathBuf;
|
|||||||
use crate::config::{Language, manager::ConfigManager};
|
use crate::config::{Language, manager::ConfigManager};
|
||||||
use crate::generator::ContentGenerator;
|
use crate::generator::ContentGenerator;
|
||||||
use crate::git::tag::{
|
use crate::git::tag::{
|
||||||
TagBuilder, VersionBump, bump_version, get_latest_version, suggest_version_bump,
|
ConfigVersion, TagBuilder, VersionBump, bump_version, get_latest_version,
|
||||||
|
read_project_versions, suggest_version_bump,
|
||||||
};
|
};
|
||||||
use crate::git::{GitRepo, find_repo};
|
use crate::git::{GitRepo, find_repo};
|
||||||
use crate::i18n::Messages;
|
use crate::i18n::Messages;
|
||||||
@@ -63,6 +64,11 @@ pub struct TagCommand {
|
|||||||
/// Skip interactive prompts
|
/// Skip interactive prompts
|
||||||
#[arg(short = 'y', long)]
|
#[arg(short = 'y', long)]
|
||||||
yes: bool,
|
yes: bool,
|
||||||
|
|
||||||
|
/// Auto-detect version from project config (Cargo.toml/pyproject.toml),
|
||||||
|
/// falling back to commit analysis with confirmation. Mutually exclusive with --bump.
|
||||||
|
#[arg(short = 'A', long, conflicts_with = "bump")]
|
||||||
|
auto: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TagCommand {
|
impl TagCommand {
|
||||||
@@ -80,6 +86,9 @@ impl TagCommand {
|
|||||||
// Determine tag name
|
// Determine tag name
|
||||||
let tag_name = if let Some(name) = &self.name {
|
let tag_name = if let Some(name) = &self.name {
|
||||||
name.clone()
|
name.clone()
|
||||||
|
} else if self.auto {
|
||||||
|
self.auto_detect_version(&repo, &config.tag.version_prefix, &messages)
|
||||||
|
.await?
|
||||||
} else if let Some(bump_str) = &self.bump {
|
} else if let Some(bump_str) = &self.bump {
|
||||||
// Calculate bumped version
|
// Calculate bumped version
|
||||||
let prefix = &config.tag.version_prefix;
|
let prefix = &config.tag.version_prefix;
|
||||||
@@ -319,12 +328,95 @@ impl TagCommand {
|
|||||||
|
|
||||||
println!("{}", messages.ai_generating_tag(commits.len()));
|
println!("{}", messages.ai_generating_tag(commits.len()));
|
||||||
|
|
||||||
let generator = ContentGenerator::new_with_think(&manager, self.think).await?;
|
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
|
||||||
generator
|
generator
|
||||||
.generate_tag_message(version, &commits, language)
|
.generate_tag_message(version, &commits, language)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn auto_detect_version(
|
||||||
|
&self,
|
||||||
|
repo: &GitRepo,
|
||||||
|
prefix: &str,
|
||||||
|
messages: &Messages,
|
||||||
|
) -> Result<String> {
|
||||||
|
let project_dir = std::env::current_dir()?;
|
||||||
|
|
||||||
|
// 1. Try reading from project config files
|
||||||
|
let config_versions = read_project_versions(&project_dir);
|
||||||
|
|
||||||
|
if !config_versions.is_empty() {
|
||||||
|
if config_versions.len() == 1 {
|
||||||
|
let cv = &config_versions[0];
|
||||||
|
let tag_name = format!("{}{}", prefix, cv.version);
|
||||||
|
println!(
|
||||||
|
"{} ({}): {}",
|
||||||
|
messages.found_version_in(),
|
||||||
|
cv.source,
|
||||||
|
tag_name.cyan()
|
||||||
|
);
|
||||||
|
return Ok(tag_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Multiple config files: let user choose
|
||||||
|
return self.select_config_version(&config_versions, prefix, messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Fall back to commit analysis
|
||||||
|
println!("{}", messages.auto_detect_bump());
|
||||||
|
let commits = repo.get_commits(50)?;
|
||||||
|
let bump = suggest_version_bump(&commits);
|
||||||
|
let latest = get_latest_version(repo, prefix)?.unwrap_or_else(|| Version::new(0, 0, 0));
|
||||||
|
let version = bump_version(&latest, bump, None);
|
||||||
|
let tag_name = format!("{}{}", prefix, version);
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"{} {:?} → {}",
|
||||||
|
messages.suggested_bump(),
|
||||||
|
bump,
|
||||||
|
tag_name.cyan()
|
||||||
|
);
|
||||||
|
|
||||||
|
if !self.yes {
|
||||||
|
let confirm = Confirm::new()
|
||||||
|
.with_prompt(messages.use_this_version())
|
||||||
|
.default(true)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
if !confirm {
|
||||||
|
// Fall through to interactive version selection
|
||||||
|
return self
|
||||||
|
.select_version_interactive(repo, prefix, messages)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(tag_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select_config_version(
|
||||||
|
&self,
|
||||||
|
config_versions: &[ConfigVersion],
|
||||||
|
prefix: &str,
|
||||||
|
messages: &Messages,
|
||||||
|
) -> Result<String> {
|
||||||
|
println!("\n{}", messages.found_multiple_versions().bold());
|
||||||
|
|
||||||
|
let items: Vec<String> = config_versions
|
||||||
|
.iter()
|
||||||
|
.map(|cv| format!("{} → {}{}", cv.source, prefix, cv.version))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let selection = Select::new()
|
||||||
|
.with_prompt(messages.select_version_to_use())
|
||||||
|
.items(&items)
|
||||||
|
.default(0)
|
||||||
|
.interact()?;
|
||||||
|
|
||||||
|
let cv = &config_versions[selection];
|
||||||
|
Ok(format!("{}{}", prefix, cv.version))
|
||||||
|
}
|
||||||
|
|
||||||
fn input_message_interactive(&self, version: &str, messages: &Messages) -> Result<String> {
|
fn input_message_interactive(&self, version: &str, messages: &Messages) -> Result<String> {
|
||||||
let default_msg = format!("Release {}", version);
|
let default_msg = format!("Release {}", version);
|
||||||
|
|
||||||
|
|||||||
@@ -386,6 +386,22 @@ impl ConfigManager {
|
|||||||
self.config.repo_profiles.get(repo_path)
|
self.config.repo_profiles.get(repo_path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Find profiles whose repo_patterns match the given repo path
|
||||||
|
pub fn match_profiles_by_repo_pattern(&self, repo_path: &str) -> Vec<&GitProfile> {
|
||||||
|
self.config
|
||||||
|
.profiles
|
||||||
|
.values()
|
||||||
|
.filter(|p| {
|
||||||
|
p.settings.repo_patterns.iter().any(|pattern| {
|
||||||
|
let trimmed = pattern.trim_matches('*');
|
||||||
|
repo_path.ends_with(trimmed)
|
||||||
|
|| repo_path.starts_with(trimmed)
|
||||||
|
|| repo_path == trimmed
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
// LLM configuration
|
// LLM configuration
|
||||||
|
|
||||||
/// Get LLM provider
|
/// Get LLM provider
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ pub struct AppConfig {
|
|||||||
pub version: String,
|
pub version: String,
|
||||||
|
|
||||||
/// Default profile name
|
/// Default profile name
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub default_profile: Option<String>,
|
pub default_profile: Option<String>,
|
||||||
|
|
||||||
/// All configured profiles
|
/// All configured profiles
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||||
pub profiles: HashMap<String, GitProfile>,
|
pub profiles: HashMap<String, GitProfile>,
|
||||||
|
|
||||||
/// LLM configuration
|
/// LLM configuration
|
||||||
@@ -40,17 +41,9 @@ pub struct AppConfig {
|
|||||||
pub changelog: ChangelogConfig,
|
pub changelog: ChangelogConfig,
|
||||||
|
|
||||||
/// Repository-specific profile mappings
|
/// Repository-specific profile mappings
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||||
pub repo_profiles: HashMap<String, String>,
|
pub repo_profiles: HashMap<String, String>,
|
||||||
|
|
||||||
/// Whether to encrypt sensitive data
|
|
||||||
#[serde(default = "default_true")]
|
|
||||||
pub encrypt_sensitive: bool,
|
|
||||||
|
|
||||||
/// Theme settings
|
|
||||||
#[serde(default)]
|
|
||||||
pub theme: ThemeConfig,
|
|
||||||
|
|
||||||
/// Language settings
|
/// Language settings
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub language: LanguageConfig,
|
pub language: LanguageConfig,
|
||||||
@@ -67,8 +60,6 @@ impl Default for AppConfig {
|
|||||||
tag: TagConfig::default(),
|
tag: TagConfig::default(),
|
||||||
changelog: ChangelogConfig::default(),
|
changelog: ChangelogConfig::default(),
|
||||||
repo_profiles: HashMap::new(),
|
repo_profiles: HashMap::new(),
|
||||||
encrypt_sensitive: true,
|
|
||||||
theme: ThemeConfig::default(),
|
|
||||||
language: LanguageConfig::default(),
|
language: LanguageConfig::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,11 +72,12 @@ pub struct LlmConfig {
|
|||||||
#[serde(default = "default_llm_provider")]
|
#[serde(default = "default_llm_provider")]
|
||||||
pub provider: String,
|
pub provider: String,
|
||||||
|
|
||||||
/// Model to use (stored in config, not in keyring)
|
/// Model to use
|
||||||
#[serde(default = "default_model")]
|
#[serde(default = "default_model")]
|
||||||
pub model: String,
|
pub model: String,
|
||||||
|
|
||||||
/// API base URL (optional, will use provider default if not set)
|
/// API base URL (optional, will use provider default if not set)
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub base_url: Option<String>,
|
pub base_url: Option<String>,
|
||||||
|
|
||||||
/// Maximum tokens for generation
|
/// Maximum tokens for generation
|
||||||
@@ -104,8 +96,8 @@ pub struct LlmConfig {
|
|||||||
#[serde(default = "default_api_key_storage")]
|
#[serde(default = "default_api_key_storage")]
|
||||||
pub api_key_storage: String,
|
pub api_key_storage: String,
|
||||||
|
|
||||||
/// API key (stored in config for fallback, encrypted if encrypt_sensitive is true)
|
/// API key (stored in config for fallback)
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub api_key: Option<String>,
|
pub api_key: Option<String>,
|
||||||
|
|
||||||
/// Enable thinking/reasoning mode (deepseek, kimi, anthropic)
|
/// Enable thinking/reasoning mode (deepseek, kimi, anthropic)
|
||||||
@@ -113,7 +105,7 @@ pub struct LlmConfig {
|
|||||||
pub thinking_enabled: bool,
|
pub thinking_enabled: bool,
|
||||||
|
|
||||||
/// Budget tokens for thinking mode (Anthropic Claude 4)
|
/// Budget tokens for thinking mode (Anthropic Claude 4)
|
||||||
#[serde(default)]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub thinking_budget_tokens: Option<u32>,
|
pub thinking_budget_tokens: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,33 +140,6 @@ pub struct CommitConfig {
|
|||||||
/// Enable AI generation by default
|
/// Enable AI generation by default
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
pub auto_generate: bool,
|
pub auto_generate: bool,
|
||||||
|
|
||||||
/// Allow empty commits
|
|
||||||
#[serde(default)]
|
|
||||||
pub allow_empty: bool,
|
|
||||||
|
|
||||||
/// Sign commits with GPG
|
|
||||||
#[serde(default)]
|
|
||||||
pub gpg_sign: bool,
|
|
||||||
|
|
||||||
/// Default scope (optional)
|
|
||||||
pub default_scope: Option<String>,
|
|
||||||
|
|
||||||
/// Maximum subject length
|
|
||||||
#[serde(default = "default_max_subject_length")]
|
|
||||||
pub max_subject_length: usize,
|
|
||||||
|
|
||||||
/// Require scope
|
|
||||||
#[serde(default)]
|
|
||||||
pub require_scope: bool,
|
|
||||||
|
|
||||||
/// Require body for certain types
|
|
||||||
#[serde(default)]
|
|
||||||
pub require_body: bool,
|
|
||||||
|
|
||||||
/// Types that require body
|
|
||||||
#[serde(default = "default_body_required_types")]
|
|
||||||
pub body_required_types: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for CommitConfig {
|
impl Default for CommitConfig {
|
||||||
@@ -182,13 +147,6 @@ impl Default for CommitConfig {
|
|||||||
Self {
|
Self {
|
||||||
format: default_commit_format(),
|
format: default_commit_format(),
|
||||||
auto_generate: true,
|
auto_generate: true,
|
||||||
allow_empty: false,
|
|
||||||
gpg_sign: false,
|
|
||||||
default_scope: None,
|
|
||||||
max_subject_length: default_max_subject_length(),
|
|
||||||
require_scope: false,
|
|
||||||
require_body: false,
|
|
||||||
body_required_types: default_body_required_types(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -220,18 +178,6 @@ pub struct TagConfig {
|
|||||||
/// Enable AI generation for tag messages
|
/// Enable AI generation for tag messages
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
pub auto_generate: bool,
|
pub auto_generate: bool,
|
||||||
|
|
||||||
/// Sign tags with GPG
|
|
||||||
#[serde(default)]
|
|
||||||
pub gpg_sign: bool,
|
|
||||||
|
|
||||||
/// Include changelog in annotated tags
|
|
||||||
#[serde(default = "default_true")]
|
|
||||||
pub include_changelog: bool,
|
|
||||||
|
|
||||||
/// Default annotation template
|
|
||||||
#[serde(default)]
|
|
||||||
pub annotation_template: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for TagConfig {
|
impl Default for TagConfig {
|
||||||
@@ -239,9 +185,6 @@ impl Default for TagConfig {
|
|||||||
Self {
|
Self {
|
||||||
version_prefix: default_version_prefix(),
|
version_prefix: default_version_prefix(),
|
||||||
auto_generate: true,
|
auto_generate: true,
|
||||||
gpg_sign: false,
|
|
||||||
include_changelog: true,
|
|
||||||
annotation_template: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -256,26 +199,6 @@ pub struct ChangelogConfig {
|
|||||||
/// Enable AI generation for changelog entries
|
/// Enable AI generation for changelog entries
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
pub auto_generate: bool,
|
pub auto_generate: bool,
|
||||||
|
|
||||||
/// Changelog format
|
|
||||||
#[serde(default = "default_changelog_format")]
|
|
||||||
pub format: ChangelogFormat,
|
|
||||||
|
|
||||||
/// Include commit hashes
|
|
||||||
#[serde(default)]
|
|
||||||
pub include_hashes: bool,
|
|
||||||
|
|
||||||
/// Include authors
|
|
||||||
#[serde(default)]
|
|
||||||
pub include_authors: bool,
|
|
||||||
|
|
||||||
/// Group by type
|
|
||||||
#[serde(default = "default_true")]
|
|
||||||
pub group_by_type: bool,
|
|
||||||
|
|
||||||
/// Custom categories
|
|
||||||
#[serde(default)]
|
|
||||||
pub custom_categories: Vec<ChangelogCategory>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ChangelogConfig {
|
impl Default for ChangelogConfig {
|
||||||
@@ -283,56 +206,6 @@ impl Default for ChangelogConfig {
|
|||||||
Self {
|
Self {
|
||||||
path: default_changelog_path(),
|
path: default_changelog_path(),
|
||||||
auto_generate: true,
|
auto_generate: true,
|
||||||
format: default_changelog_format(),
|
|
||||||
include_hashes: false,
|
|
||||||
include_authors: false,
|
|
||||||
group_by_type: true,
|
|
||||||
custom_categories: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Changelog format
|
|
||||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
|
||||||
#[serde(rename_all = "kebab-case")]
|
|
||||||
pub enum ChangelogFormat {
|
|
||||||
KeepAChangelog,
|
|
||||||
GitHubReleases,
|
|
||||||
Custom,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Changelog category mapping
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct ChangelogCategory {
|
|
||||||
/// Category title
|
|
||||||
pub title: String,
|
|
||||||
|
|
||||||
/// Commit types included in this category
|
|
||||||
pub types: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Theme configuration
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct ThemeConfig {
|
|
||||||
/// Enable colors
|
|
||||||
#[serde(default = "default_true")]
|
|
||||||
pub colors: bool,
|
|
||||||
|
|
||||||
/// Enable icons
|
|
||||||
#[serde(default = "default_true")]
|
|
||||||
pub icons: bool,
|
|
||||||
|
|
||||||
/// Preferred date format
|
|
||||||
#[serde(default = "default_date_format")]
|
|
||||||
pub date_format: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ThemeConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
colors: true,
|
|
||||||
icons: true,
|
|
||||||
date_format: default_date_format(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -415,6 +288,7 @@ impl Language {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Default value functions
|
// Default value functions
|
||||||
|
|
||||||
fn default_version() -> String {
|
fn default_version() -> String {
|
||||||
"1".to_string()
|
"1".to_string()
|
||||||
}
|
}
|
||||||
@@ -447,14 +321,6 @@ fn default_commit_format() -> CommitFormat {
|
|||||||
CommitFormat::Conventional
|
CommitFormat::Conventional
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_max_subject_length() -> usize {
|
|
||||||
100
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_body_required_types() -> Vec<String> {
|
|
||||||
vec!["feat".to_string(), "fix".to_string()]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_version_prefix() -> String {
|
fn default_version_prefix() -> String {
|
||||||
"v".to_string()
|
"v".to_string()
|
||||||
}
|
}
|
||||||
@@ -463,14 +329,6 @@ fn default_changelog_path() -> String {
|
|||||||
"CHANGELOG.md".to_string()
|
"CHANGELOG.md".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_changelog_format() -> ChangelogFormat {
|
|
||||||
ChangelogFormat::KeepAChangelog
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_date_format() -> String {
|
|
||||||
"%Y-%m-%d".to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_output_language() -> String {
|
fn default_output_language() -> String {
|
||||||
"en".to_string()
|
"en".to_string()
|
||||||
}
|
}
|
||||||
@@ -509,21 +367,6 @@ impl AppConfig {
|
|||||||
let config_dir = dirs::config_dir().context("Could not find config directory")?;
|
let config_dir = dirs::config_dir().context("Could not find config directory")?;
|
||||||
Ok(config_dir.join("quicommit").join("config.toml"))
|
Ok(config_dir.join("quicommit").join("config.toml"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// /// Get profile for a repository
|
|
||||||
// pub fn get_profile_for_repo(&self, repo_path: &str) -> Option<&GitProfile> {
|
|
||||||
// let profile_name = self.repo_profiles.get(repo_path)?;
|
|
||||||
// self.profiles.get(profile_name)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /// Set profile for a repository
|
|
||||||
// pub fn set_profile_for_repo(&mut self, repo_path: String, profile_name: String) -> Result<()> {
|
|
||||||
// if !self.profiles.contains_key(&profile_name) {
|
|
||||||
// anyhow::bail!("Profile '{}' does not exist", profile_name);
|
|
||||||
// }
|
|
||||||
// self.repo_profiles.insert(repo_path, profile_name);
|
|
||||||
// Ok(())
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encrypted PAT data for export
|
/// Encrypted PAT data for export
|
||||||
|
|||||||
@@ -124,6 +124,11 @@ impl GitProfile {
|
|||||||
.or_else(|| self.gpg.as_ref().map(|g| g.key_id.as_str()))
|
.or_else(|| self.gpg.as_ref().map(|g| g.key_id.as_str()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the commit template if set
|
||||||
|
pub fn commit_template(&self) -> Option<&str> {
|
||||||
|
self.settings.commit_template.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
/// Add a token to the profile
|
/// Add a token to the profile
|
||||||
pub fn add_token(&mut self, service: String, token: TokenConfig) {
|
pub fn add_token(&mut self, service: String, token: TokenConfig) {
|
||||||
self.tokens.insert(service, token);
|
self.tokens.insert(service, token);
|
||||||
@@ -159,78 +164,120 @@ impl GitProfile {
|
|||||||
pub fn apply_to_repo(&self, repo: &git2::Repository) -> Result<()> {
|
pub fn apply_to_repo(&self, repo: &git2::Repository) -> Result<()> {
|
||||||
let mut config = repo.config()?;
|
let mut config = repo.config()?;
|
||||||
|
|
||||||
config.set_str("user.name", &self.user_name)?;
|
// Clean up old managed keys that the new profile won't set
|
||||||
config.set_str("user.email", &self.user_email)?;
|
if self.ssh.as_ref().and_then(|s| s.git_ssh_command()).is_none() {
|
||||||
|
let _ = config.remove("core.sshCommand");
|
||||||
if let Some(key) = self.signing_key() {
|
}
|
||||||
config.set_str("user.signingkey", key)?;
|
if self.signing_key().is_none() {
|
||||||
|
let _ = config.remove("user.signingkey");
|
||||||
if self.settings.auto_sign_commits {
|
let _ = config.remove("commit.gpgsign");
|
||||||
config.set_bool("commit.gpgsign", true)?;
|
let _ = config.remove("tag.gpgsign");
|
||||||
}
|
}
|
||||||
|
if self.gpg.is_none() {
|
||||||
if self.settings.auto_sign_tags {
|
let _ = config.remove("gpg.program");
|
||||||
config.set_bool("tag.gpgsign", true)?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref ssh) = self.ssh
|
// Apply new values; track whether we've written past name/email for rollback
|
||||||
&& let Some(ref key_path) = ssh.private_key_path
|
let mut wrote_optional = false;
|
||||||
{
|
let result = (|| -> Result<()> {
|
||||||
let path_str = key_path.display().to_string();
|
config.set_str("user.name", &self.user_name)?;
|
||||||
#[cfg(target_os = "windows")]
|
config.set_str("user.email", &self.user_email)?;
|
||||||
{
|
|
||||||
config.set_str(
|
if let Some(ref gpg) = self.gpg {
|
||||||
"core.sshCommand",
|
config.set_str("gpg.program", &gpg.program)?;
|
||||||
&format!("ssh -i \"{}\"", path_str.replace('\\', "/")),
|
wrote_optional = true;
|
||||||
)?;
|
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
{
|
if let Some(key) = self.signing_key() {
|
||||||
config.set_str("core.sshCommand", &format!("ssh -i '{}'", path_str))?;
|
config.set_str("user.signingkey", key)?;
|
||||||
|
if self.settings.auto_sign_commits {
|
||||||
|
config.set_bool("commit.gpgsign", true)?;
|
||||||
|
}
|
||||||
|
if self.settings.auto_sign_tags {
|
||||||
|
config.set_bool("tag.gpgsign", true)?;
|
||||||
|
}
|
||||||
|
wrote_optional = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(ref ssh) = self.ssh {
|
||||||
|
if let Some(ssh_cmd) = ssh.git_ssh_command() {
|
||||||
|
config.set_str("core.sshCommand", &ssh_cmd)?;
|
||||||
|
wrote_optional = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
|
||||||
|
if result.is_err() && wrote_optional {
|
||||||
|
let _ = config.remove("core.sshCommand");
|
||||||
|
let _ = config.remove("user.signingkey");
|
||||||
|
let _ = config.remove("commit.gpgsign");
|
||||||
|
let _ = config.remove("tag.gpgsign");
|
||||||
|
let _ = config.remove("gpg.program");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply this profile globally
|
/// Apply this profile globally
|
||||||
pub fn apply_global(&self) -> Result<()> {
|
pub fn apply_global(&self) -> Result<()> {
|
||||||
let mut config = git2::Config::open_default()?;
|
let mut config = git2::Config::open_default()?;
|
||||||
|
|
||||||
config.set_str("user.name", &self.user_name)?;
|
// Clean up old managed keys that the new profile won't set
|
||||||
config.set_str("user.email", &self.user_email)?;
|
if self.ssh.as_ref().and_then(|s| s.git_ssh_command()).is_none() {
|
||||||
|
let _ = config.remove("core.sshCommand");
|
||||||
if let Some(key) = self.signing_key() {
|
}
|
||||||
config.set_str("user.signingkey", key)?;
|
if self.signing_key().is_none() {
|
||||||
|
let _ = config.remove("user.signingkey");
|
||||||
if self.settings.auto_sign_commits {
|
let _ = config.remove("commit.gpgsign");
|
||||||
config.set_bool("commit.gpgsign", true)?;
|
let _ = config.remove("tag.gpgsign");
|
||||||
}
|
}
|
||||||
|
if self.gpg.is_none() {
|
||||||
if self.settings.auto_sign_tags {
|
let _ = config.remove("gpg.program");
|
||||||
config.set_bool("tag.gpgsign", true)?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref ssh) = self.ssh
|
// Apply new values; track whether we've written past name/email for rollback
|
||||||
&& let Some(ref key_path) = ssh.private_key_path
|
let mut wrote_optional = false;
|
||||||
{
|
let result = (|| -> Result<()> {
|
||||||
let path_str = key_path.display().to_string();
|
config.set_str("user.name", &self.user_name)?;
|
||||||
#[cfg(target_os = "windows")]
|
config.set_str("user.email", &self.user_email)?;
|
||||||
{
|
|
||||||
config.set_str(
|
if let Some(ref gpg) = self.gpg {
|
||||||
"core.sshCommand",
|
config.set_str("gpg.program", &gpg.program)?;
|
||||||
&format!("ssh -i \"{}\"", path_str.replace('\\', "/")),
|
wrote_optional = true;
|
||||||
)?;
|
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
{
|
if let Some(key) = self.signing_key() {
|
||||||
config.set_str("core.sshCommand", &format!("ssh -i '{}'", path_str))?;
|
config.set_str("user.signingkey", key)?;
|
||||||
|
if self.settings.auto_sign_commits {
|
||||||
|
config.set_bool("commit.gpgsign", true)?;
|
||||||
|
}
|
||||||
|
if self.settings.auto_sign_tags {
|
||||||
|
config.set_bool("tag.gpgsign", true)?;
|
||||||
|
}
|
||||||
|
wrote_optional = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(ref ssh) = self.ssh {
|
||||||
|
if let Some(ssh_cmd) = ssh.git_ssh_command() {
|
||||||
|
config.set_str("core.sshCommand", &ssh_cmd)?;
|
||||||
|
wrote_optional = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
|
||||||
|
if result.is_err() && wrote_optional {
|
||||||
|
let _ = config.remove("core.sshCommand");
|
||||||
|
let _ = config.remove("user.signingkey");
|
||||||
|
let _ = config.remove("commit.gpgsign");
|
||||||
|
let _ = config.remove("tag.gpgsign");
|
||||||
|
let _ = config.remove("gpg.program");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compare with current git configuration
|
/// Compare with current git configuration
|
||||||
@@ -349,25 +396,72 @@ impl SshConfig {
|
|||||||
bail!("SSH public key does not exist: {:?}", path);
|
bail!("SSH public key does not exist: {:?}", path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(ref path) = self.known_hosts_file
|
||||||
|
&& !path.exists()
|
||||||
|
{
|
||||||
|
bail!("SSH known_hosts file does not exist: {:?}", path);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get SSH command for git
|
/// Get the effective public key path, deriving from private key if not explicitly set
|
||||||
|
pub fn effective_public_key_path(&self) -> Option<std::path::PathBuf> {
|
||||||
|
self.public_key_path.clone().or_else(|| {
|
||||||
|
self.private_key_path.as_ref().map(|pk| {
|
||||||
|
let mut pub_path = pk.clone();
|
||||||
|
let ext = pk
|
||||||
|
.extension()
|
||||||
|
.map(|e| format!("{}.pub", e.to_string_lossy()))
|
||||||
|
.unwrap_or_else(|| "pub".to_string());
|
||||||
|
pub_path.set_extension(&ext);
|
||||||
|
pub_path
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the effective SSH command for git config
|
||||||
|
///
|
||||||
|
/// Priority: custom `ssh_command` > constructed from key/agent/known_hosts
|
||||||
pub fn git_ssh_command(&self) -> Option<String> {
|
pub fn git_ssh_command(&self) -> Option<String> {
|
||||||
if let Some(ref cmd) = self.ssh_command {
|
if let Some(ref cmd) = self.ssh_command {
|
||||||
Some(cmd.clone())
|
return Some(cmd.clone());
|
||||||
} else if let Some(ref key_path) = self.private_key_path {
|
}
|
||||||
|
|
||||||
|
let mut parts: Vec<String> = vec!["ssh".to_string()];
|
||||||
|
|
||||||
|
if self.agent_forwarding {
|
||||||
|
parts.push("-A".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ref key_path) = self.private_key_path {
|
||||||
let path_str = key_path.display().to_string();
|
let path_str = key_path.display().to_string();
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
Some(format!("ssh -i \"{}\"", path_str.replace('\\', "/")))
|
parts.push(format!("-i \"{}\"", path_str.replace('\\', "/")));
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
{
|
{
|
||||||
Some(format!("ssh -i '{}'", path_str))
|
parts.push(format!("-i '{}'", path_str));
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
|
||||||
|
if let Some(ref known_hosts) = self.known_hosts_file {
|
||||||
|
let kh_str = known_hosts.display().to_string();
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
parts.push(format!("-o UserKnownHostsFile=\"{}\"", kh_str.replace('\\', "/")));
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
{
|
||||||
|
parts.push(format!("-o UserKnownHostsFile='{}'", kh_str));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if parts.len() == 1 {
|
||||||
None
|
None
|
||||||
|
} else {
|
||||||
|
Some(parts.join(" "))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,28 @@
|
|||||||
use crate::config::manager::ConfigManager;
|
use crate::config::manager::ConfigManager;
|
||||||
use crate::config::{CommitFormat, Language};
|
use crate::config::{CommitFormat, Language};
|
||||||
use crate::git::{CommitInfo, GitRepo};
|
use crate::git::{CommitInfo, GitRepo};
|
||||||
use crate::llm::{GeneratedCommit, LlmClient};
|
use crate::llm::parsing::GeneratedCommit;
|
||||||
|
use crate::llm::rig::LlmClient;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
/// Content generator using LLM
|
/// Content generator using LLM
|
||||||
pub struct ContentGenerator {
|
pub struct ContentGenerator {
|
||||||
llm_client: LlmClient,
|
llm_client: LlmClient,
|
||||||
|
template: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentGenerator {
|
impl ContentGenerator {
|
||||||
/// Create new content generator
|
/// Create new content generator
|
||||||
pub async fn new(manager: &ConfigManager) -> Result<Self> {
|
pub async fn new(manager: &ConfigManager) -> Result<Self> {
|
||||||
Self::new_with_think(manager, false).await
|
Self::new_with_think(manager, false, None).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new content generator with thinking override
|
/// Create new content generator with thinking override and optional commit template
|
||||||
pub async fn new_with_think(manager: &ConfigManager, think_override: bool) -> Result<Self> {
|
pub async fn new_with_think(
|
||||||
|
manager: &ConfigManager,
|
||||||
|
think_override: bool,
|
||||||
|
template: Option<String>,
|
||||||
|
) -> Result<Self> {
|
||||||
let mut thinking_enabled = if think_override {
|
let mut thinking_enabled = if think_override {
|
||||||
true
|
true
|
||||||
} else {
|
} else {
|
||||||
@@ -42,7 +48,10 @@ impl ContentGenerator {
|
|||||||
anyhow::bail!("LLM provider '{}' is not available", manager.llm_provider());
|
anyhow::bail!("LLM provider '{}' is not available", manager.llm_provider());
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Self { llm_client })
|
Ok(Self {
|
||||||
|
llm_client,
|
||||||
|
template,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn supports_thinking(provider: &str) -> bool {
|
fn supports_thinking(provider: &str) -> bool {
|
||||||
@@ -66,7 +75,7 @@ impl ContentGenerator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
self.llm_client
|
self.llm_client
|
||||||
.generate_commit_message(&truncated_diff, format, language)
|
.generate_commit_message(&truncated_diff, format, language, self.template.as_deref())
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -409,8 +409,8 @@ pub fn generate_from_history(
|
|||||||
if let Some(from) = from_tag {
|
if let Some(from) = from_tag {
|
||||||
repo.get_commits_between(from, to_ref)
|
repo.get_commits_between(from, to_ref)
|
||||||
} else {
|
} else {
|
||||||
// Get last 50 commits if no tag specified
|
// Get all commits from the beginning (no from_tag = initial changelog)
|
||||||
repo.get_commits(50)
|
repo.get_commits(usize::MAX)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,3 +476,137 @@ impl ChangelogEntry {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Extract version strings from Keep a Changelog content.
|
||||||
|
/// Returns versions sorted by semver descending (highest first).
|
||||||
|
/// Excludes "Unreleased".
|
||||||
|
pub fn parse_changelog_versions(content: &str) -> Vec<String> {
|
||||||
|
use semver::Version;
|
||||||
|
|
||||||
|
let mut versions: Vec<String> = vec![];
|
||||||
|
for line in content.lines() {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
if trimmed.starts_with("## [") {
|
||||||
|
if let Some(end) = trimmed.find(']') {
|
||||||
|
let version = &trimmed[4..end];
|
||||||
|
if version != "Unreleased" && !version.is_empty() {
|
||||||
|
versions.push(version.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Sort by semver descending so highest version is first
|
||||||
|
versions.sort_by(|a, b| {
|
||||||
|
match (Version::parse(a), Version::parse(b)) {
|
||||||
|
(Ok(va), Ok(vb)) => vb.cmp(&va),
|
||||||
|
(Ok(_), Err(_)) => std::cmp::Ordering::Less,
|
||||||
|
(Err(_), Ok(_)) => std::cmp::Ordering::Greater,
|
||||||
|
(Err(_), Err(_)) => std::cmp::Ordering::Equal,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
versions
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert a new changelog entry into existing changelog content.
|
||||||
|
/// The new entry is placed after the header and before the first existing version section.
|
||||||
|
/// If no existing version sections are found, the new entry is appended after the header.
|
||||||
|
pub fn insert_changelog_entry(existing: &str, new_entry: &str) -> String {
|
||||||
|
// Find the first version section (## [x.y.z])
|
||||||
|
if let Some(first_ver_pos) = existing.find("\n## [") {
|
||||||
|
let (header, rest) = existing.split_at(first_ver_pos);
|
||||||
|
// Ensure new_entry ends with a blank line before the next section
|
||||||
|
let entry = new_entry.trim_end();
|
||||||
|
format!("{}\n{}\n{}", header.trim_end(), entry, rest)
|
||||||
|
} else {
|
||||||
|
// No existing version sections — append after header
|
||||||
|
format!("{}\n{}", existing.trim_end(), new_entry.trim_end())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_changelog_versions_extracts_versions() {
|
||||||
|
let content = "# Changelog\n\n## [0.2.0] - 2024-03-01\n### Added\n- feature B\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let versions = parse_changelog_versions(content);
|
||||||
|
assert_eq!(versions, vec!["0.2.0", "0.1.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_changelog_versions_sorts_highest_first() {
|
||||||
|
// Versions in reversed order — should still return highest first
|
||||||
|
let content = "# Changelog\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n\n## [0.3.0] - 2024-04-01\n### Added\n- feature C\n\n## [0.2.0] - 2024-03-01\n### Added\n- feature B\n";
|
||||||
|
let versions = parse_changelog_versions(content);
|
||||||
|
assert_eq!(versions, vec!["0.3.0", "0.2.0", "0.1.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_changelog_versions_excludes_unreleased() {
|
||||||
|
let content = "# Changelog\n\n## [Unreleased]\n### Added\n- wip\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let versions = parse_changelog_versions(content);
|
||||||
|
assert_eq!(versions, vec!["0.1.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_changelog_versions_empty_content() {
|
||||||
|
let versions = parse_changelog_versions("");
|
||||||
|
assert!(versions.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_changelog_versions_no_versions() {
|
||||||
|
let content = "# Changelog\n\nSome description text.\n";
|
||||||
|
let versions = parse_changelog_versions(content);
|
||||||
|
assert!(versions.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert_changelog_entry_between_header_and_existing() {
|
||||||
|
let existing = "# Changelog\n\nAll notable changes...\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let new_entry = "## [0.2.0] - 2024-03-01\n### Added\n- feature B\n";
|
||||||
|
let result = insert_changelog_entry(existing, new_entry);
|
||||||
|
|
||||||
|
// New entry should appear after header, before 0.1.0
|
||||||
|
assert!(result.contains("## [0.2.0]"));
|
||||||
|
assert!(result.contains("## [0.1.0]"));
|
||||||
|
let pos_new = result.find("## [0.2.0]").unwrap();
|
||||||
|
let pos_old = result.find("## [0.1.0]").unwrap();
|
||||||
|
assert!(pos_new < pos_old, "new version should be before old version");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert_changelog_entry_preserves_all_existing_content() {
|
||||||
|
let existing = "# Changelog\n\nAll notable changes...\n\n## [0.2.0] - 2024-03-01\n### Added\n- feature B\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let new_entry = "## [0.3.0] - 2024-04-01\n### Added\n- feature C\n";
|
||||||
|
let result = insert_changelog_entry(existing, new_entry);
|
||||||
|
|
||||||
|
assert!(result.contains("## [0.3.0]"));
|
||||||
|
assert!(result.contains("## [0.2.0]"));
|
||||||
|
assert!(result.contains("## [0.1.0]"));
|
||||||
|
assert!(result.contains("feature A"), "oldest content preserved");
|
||||||
|
assert!(result.contains("feature B"), "middle content preserved");
|
||||||
|
assert!(result.contains("feature C"), "new content present");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert_changelog_entry_empty_existing() {
|
||||||
|
let existing = "# Changelog\n\nAll notable changes...\n\n";
|
||||||
|
let new_entry = "## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let result = insert_changelog_entry(existing, new_entry);
|
||||||
|
assert!(result.contains("## [0.1.0]"));
|
||||||
|
assert!(result.contains("# Changelog"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_insert_changelog_entry_extra_blank_lines_in_header() {
|
||||||
|
let existing = "# Changelog\n\n\n\n## [0.1.0] - 2024-02-01\n### Added\n- feature A\n";
|
||||||
|
let new_entry = "## [0.2.0] - 2024-03-01\n### Added\n- feature B\n";
|
||||||
|
let result = insert_changelog_entry(existing, new_entry);
|
||||||
|
|
||||||
|
let pos_new = result.find("## [0.2.0]").unwrap();
|
||||||
|
let pos_old = result.find("## [0.1.0]").unwrap();
|
||||||
|
assert!(pos_new < pos_old, "new version should be before old version");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
274
src/git/mod.rs
274
src/git/mod.rs
@@ -533,27 +533,116 @@ impl GitRepo {
|
|||||||
Ok(files)
|
Ok(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stage files
|
/// Stage files, skipping paths matched by .gitignore rules
|
||||||
pub fn stage_files<P: AsRef<Path>>(&self, paths: &[P]) -> Result<()> {
|
/// Returns the list of skipped paths (those matched by .gitignore)
|
||||||
|
pub fn stage_files<P: AsRef<Path>>(&self, paths: &[P]) -> Result<Vec<String>> {
|
||||||
let mut index = self.repo.index()?;
|
let mut index = self.repo.index()?;
|
||||||
|
let mut skipped = Vec::new();
|
||||||
|
|
||||||
for path in paths {
|
for path in paths {
|
||||||
let path = path.as_ref();
|
let path = path.as_ref();
|
||||||
if path.is_absolute() {
|
let rel_path = if path.is_absolute() {
|
||||||
if let Ok(rel_path) = path.strip_prefix(&self.path) {
|
match path.strip_prefix(&self.path) {
|
||||||
index.add_path(rel_path)?;
|
Ok(p) => p,
|
||||||
|
Err(_) => {
|
||||||
|
// Outside repo, skip
|
||||||
|
skipped.push(path.to_string_lossy().to_string());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
index.add_path(path)?;
|
path
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if the path is ignored by .gitignore
|
||||||
|
if self.is_path_ignored(rel_path)? {
|
||||||
|
skipped.push(rel_path.to_string_lossy().to_string());
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
index.add_path(rel_path)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
index.write()?;
|
index.write()?;
|
||||||
Ok(())
|
Ok(skipped)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stage all changes including subdirectories
|
/// Check if a path is ignored by .gitignore rules
|
||||||
pub fn stage_all(&self) -> Result<()> {
|
pub fn is_path_ignored<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
|
||||||
|
// Convert to relative path if absolute
|
||||||
|
let rel_path = if path.is_absolute() {
|
||||||
|
match path.strip_prefix(&self.path) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(_) => return Ok(false), // Outside repo, not ignored
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
path
|
||||||
|
};
|
||||||
|
|
||||||
|
let path_str = match rel_path.to_str() {
|
||||||
|
Some(s) => s,
|
||||||
|
None => return Ok(false), // Non-UTF8 path, not ignored
|
||||||
|
};
|
||||||
|
|
||||||
|
let output = std::process::Command::new("git")
|
||||||
|
.args(["check-ignore", "--quiet", "--", path_str])
|
||||||
|
.current_dir(&self.path)
|
||||||
|
.output()?;
|
||||||
|
|
||||||
|
// Exit code 0: ignored, 1: not ignored, other: error
|
||||||
|
match output.status.code() {
|
||||||
|
Some(0) => Ok(true),
|
||||||
|
Some(1) => Ok(false),
|
||||||
|
_ => Ok(false), // Treat errors as not ignored
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove files from index that are tracked but should be ignored by .gitignore
|
||||||
|
pub fn remove_ignored_from_index(&self) -> Result<Vec<String>> {
|
||||||
|
let output = std::process::Command::new("git")
|
||||||
|
.args(["ls-files", "--cached", "-i", "--exclude-standard"])
|
||||||
|
.current_dir(&self.path)
|
||||||
|
.output()?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
bail!("Failed to list ignored tracked files: {}", stderr);
|
||||||
|
}
|
||||||
|
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
let ignored_files: Vec<String> = stdout
|
||||||
|
.lines()
|
||||||
|
.map(|l| l.trim().to_string())
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if ignored_files.is_empty() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove these files from the index (keep working tree files)
|
||||||
|
let mut args = vec!["rm", "--cached", "--quiet", "--"];
|
||||||
|
for file in &ignored_files {
|
||||||
|
args.push(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rm_output = std::process::Command::new("git")
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(&self.path)
|
||||||
|
.output()?;
|
||||||
|
|
||||||
|
if !rm_output.status.success() {
|
||||||
|
let stderr = String::from_utf8_lossy(&rm_output.stderr);
|
||||||
|
bail!("Failed to remove ignored files from index: {}", stderr);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ignored_files)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage all changes including subdirectories, then remove ignored tracked files
|
||||||
|
pub fn stage_all(&self) -> Result<Vec<String>> {
|
||||||
// Use git command for reliable staging (handles all edge cases)
|
// Use git command for reliable staging (handles all edge cases)
|
||||||
let output = std::process::Command::new("git")
|
let output = std::process::Command::new("git")
|
||||||
.args(["add", "-A"])
|
.args(["add", "-A"])
|
||||||
@@ -569,7 +658,14 @@ impl GitRepo {
|
|||||||
// Force refresh the git2 index to pick up changes from git CLI
|
// Force refresh the git2 index to pick up changes from git CLI
|
||||||
let _ = self.repo.index()?.write();
|
let _ = self.repo.index()?.write();
|
||||||
|
|
||||||
Ok(())
|
// Remove files that are tracked but should be ignored by .gitignore
|
||||||
|
match self.remove_ignored_from_index() {
|
||||||
|
Ok(removed) => Ok(removed),
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("Warning: failed to clean ignored files from index: {}", e);
|
||||||
|
Ok(Vec::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unstage files
|
/// Unstage files
|
||||||
@@ -766,24 +862,34 @@ impl GitRepo {
|
|||||||
let name = String::from_utf8_lossy(name);
|
let name = String::from_utf8_lossy(name);
|
||||||
let name = name.strip_prefix("refs/tags/").unwrap_or(&name);
|
let name = name.strip_prefix("refs/tags/").unwrap_or(&name);
|
||||||
|
|
||||||
if let Ok(commit) = self.repo.find_commit(oid) {
|
// Use find_object + peel_to_commit to handle both lightweight
|
||||||
tags.push(TagInfo {
|
// (oid is a commit) and annotated (oid is a tag object) tags.
|
||||||
name: name.to_string(),
|
if let Ok(obj) = self.repo.find_object(oid, None) {
|
||||||
target: oid.to_string(),
|
if let Ok(commit) = obj.peel_to_commit() {
|
||||||
message: commit.message().unwrap_or("").to_string(),
|
tags.push(TagInfo {
|
||||||
time: commit.time().seconds(),
|
name: name.to_string(),
|
||||||
});
|
target: commit.id().to_string(),
|
||||||
|
message: commit.message().unwrap_or("").to_string(),
|
||||||
|
time: commit.time().seconds(),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// Sort tags by time (newest first)
|
// Sort tags by semver (descending), then by time
|
||||||
tags.sort_by(|a, b| b.time.cmp(&a.time));
|
crate::git::tag::sort_tags_by_semver(&mut tags);
|
||||||
|
|
||||||
Ok(tags)
|
Ok(tags)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Find a tag whose version (stripping 'v' prefix) matches the given version string.
|
||||||
|
pub fn find_tag_by_version(&self, version: &str) -> Option<TagInfo> {
|
||||||
|
let tags = self.get_tags().ok()?;
|
||||||
|
tags.into_iter().find(|t| t.version_name() == version)
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a tag
|
/// Create a tag
|
||||||
pub fn create_tag(&self, name: &str, message: Option<&str>, sign: bool) -> Result<()> {
|
pub fn create_tag(&self, name: &str, message: Option<&str>, sign: bool) -> Result<()> {
|
||||||
let head = self.repo.head()?;
|
let head = self.repo.head()?;
|
||||||
@@ -975,6 +1081,13 @@ pub struct TagInfo {
|
|||||||
pub time: i64,
|
pub time: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TagInfo {
|
||||||
|
/// Return the version portion of the tag name (stripping leading 'v' if present).
|
||||||
|
pub fn version_name(&self) -> &str {
|
||||||
|
self.name.strip_prefix('v').unwrap_or(&self.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Repository status summary
|
/// Repository status summary
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct StatusSummary {
|
pub struct StatusSummary {
|
||||||
@@ -1345,3 +1458,126 @@ pub struct ConfigDiff {
|
|||||||
pub left: String,
|
pub left: String,
|
||||||
pub right: String,
|
pub right: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use git2::Signature;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
fn init_test_repo() -> (TempDir, GitRepo) {
|
||||||
|
let dir = TempDir::new().unwrap();
|
||||||
|
let repo = git2::Repository::init(dir.path()).unwrap();
|
||||||
|
|
||||||
|
// Configure git user
|
||||||
|
let mut config = repo.config().unwrap();
|
||||||
|
config.set_str("user.name", "Test User").unwrap();
|
||||||
|
config.set_str("user.email", "test@example.com").unwrap();
|
||||||
|
|
||||||
|
// Create an initial commit (needed for tags)
|
||||||
|
let sig = Signature::now("Test User", "test@example.com").unwrap();
|
||||||
|
let tree_id = {
|
||||||
|
let mut index = repo.index().unwrap();
|
||||||
|
index.write_tree().unwrap()
|
||||||
|
};
|
||||||
|
let tree = repo.find_tree(tree_id).unwrap();
|
||||||
|
repo.commit(Some("HEAD"), &sig, &sig, "initial commit", &tree, &[])
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let git_repo = GitRepo::open(dir.path()).unwrap();
|
||||||
|
(dir, git_repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_tags_returns_annotated_tags() {
|
||||||
|
let (_dir, repo) = init_test_repo();
|
||||||
|
let sig = Signature::now("Test User", "test@example.com").unwrap();
|
||||||
|
let head = repo.repo.head().unwrap().peel_to_commit().unwrap();
|
||||||
|
|
||||||
|
// Create an annotated tag (what QuiCommit creates by default)
|
||||||
|
repo.repo
|
||||||
|
.tag("v0.2.0", head.as_object(), &sig, "Release v0.2.0", false)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let tags = repo.get_tags().unwrap();
|
||||||
|
let tag_names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
tag_names.contains(&"v0.2.0"),
|
||||||
|
"annotated tag v0.2.0 should appear in tags list, got: {:?}",
|
||||||
|
tag_names
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_tags_returns_lightweight_tags() {
|
||||||
|
let (_dir, repo) = init_test_repo();
|
||||||
|
let head = repo.repo.head().unwrap().peel_to_commit().unwrap();
|
||||||
|
|
||||||
|
// Create a lightweight tag
|
||||||
|
repo.repo.tag("v0.1.0", head.as_object(), &repo.repo.signature().unwrap(), "", false)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let tags = repo.get_tags().unwrap();
|
||||||
|
let tag_names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
tag_names.contains(&"v0.1.0"),
|
||||||
|
"lightweight tag v0.1.0 should appear in tags list, got: {:?}",
|
||||||
|
tag_names
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_tags_returns_mixed_annotated_and_lightweight() {
|
||||||
|
let (_dir, repo) = init_test_repo();
|
||||||
|
let sig = Signature::now("Test User", "test@example.com").unwrap();
|
||||||
|
let head = repo.repo.head().unwrap().peel_to_commit().unwrap();
|
||||||
|
|
||||||
|
// Create annotated tag
|
||||||
|
repo.repo
|
||||||
|
.tag("v0.2.0", head.as_object(), &sig, "annotated", false)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Create lightweight tag
|
||||||
|
repo.repo
|
||||||
|
.tag("v0.1.0", head.as_object(), &repo.repo.signature().unwrap(), "", false)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let tags = repo.get_tags().unwrap();
|
||||||
|
let tag_names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
tag_names.contains(&"v0.2.0"),
|
||||||
|
"annotated tag should be present, got: {:?}",
|
||||||
|
tag_names
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
tag_names.contains(&"v0.1.0"),
|
||||||
|
"lightweight tag should be present, got: {:?}",
|
||||||
|
tag_names
|
||||||
|
);
|
||||||
|
assert_eq!(tags.len(), 2, "should have exactly 2 tags");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_get_tags_target_points_to_commit_not_tag_object() {
|
||||||
|
let (_dir, repo) = init_test_repo();
|
||||||
|
let sig = Signature::now("Test User", "test@example.com").unwrap();
|
||||||
|
let head = repo.repo.head().unwrap().peel_to_commit().unwrap();
|
||||||
|
let expected_commit_id = head.id().to_string();
|
||||||
|
|
||||||
|
// Create annotated tag
|
||||||
|
repo.repo
|
||||||
|
.tag("v0.2.0", head.as_object(), &sig, "annotated", false)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let tags = repo.get_tags().unwrap();
|
||||||
|
let tag = tags.iter().find(|t| t.name == "v0.2.0").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
tag.target, expected_commit_id,
|
||||||
|
"tag.target should be the commit OID, not the tag object OID"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
454
src/git/tag.rs
454
src/git/tag.rs
@@ -1,6 +1,7 @@
|
|||||||
use super::GitRepo;
|
use super::GitRepo;
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use semver::Version;
|
use semver::Version;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
/// Tag builder for creating tags
|
/// Tag builder for creating tags
|
||||||
pub struct TagBuilder {
|
pub struct TagBuilder {
|
||||||
@@ -327,3 +328,456 @@ pub fn list_tags(
|
|||||||
Ok(filtered)
|
Ok(filtered)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sort tags by semver version descending, then by time descending.
|
||||||
|
/// Non-semver tags are placed after semver tags, sorted by time descending.
|
||||||
|
pub fn sort_tags_by_semver(tags: &mut [super::TagInfo]) {
|
||||||
|
use semver::Version;
|
||||||
|
|
||||||
|
tags.sort_by(|a, b| {
|
||||||
|
match (
|
||||||
|
Version::parse(a.version_name()),
|
||||||
|
Version::parse(b.version_name()),
|
||||||
|
) {
|
||||||
|
(Ok(va), Ok(vb)) => {
|
||||||
|
// Both semver: version descending, then time descending as tiebreaker
|
||||||
|
vb.cmp(&va).then_with(|| b.time.cmp(&a.time))
|
||||||
|
}
|
||||||
|
(Ok(_), Err(_)) => std::cmp::Ordering::Less, // semver tags first
|
||||||
|
(Err(_), Ok(_)) => std::cmp::Ordering::Greater, // semver tags first
|
||||||
|
(Err(_), Err(_)) => b.time.cmp(&a.time), // both non-semver: time descending
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A version found in a project config file, tagged with its source.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConfigVersion {
|
||||||
|
/// Source file name, e.g. "Cargo.toml", "package.json"
|
||||||
|
pub source: String,
|
||||||
|
/// Parsed semantic version
|
||||||
|
pub version: Version,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read project versions from all supported config files in the project root.
|
||||||
|
///
|
||||||
|
/// If `go.mod` exists the function returns an empty `Vec` immediately — Go projects
|
||||||
|
/// use git tags as the version authority and store nothing in go.mod.
|
||||||
|
///
|
||||||
|
/// Otherwise every supported format is tried. Results are returned in a stable
|
||||||
|
/// order (see `PARSER_ORDER`). Files that don't exist or whose version can't be
|
||||||
|
/// parsed are silently skipped.
|
||||||
|
pub fn read_project_versions(project_dir: &Path) -> Vec<ConfigVersion> {
|
||||||
|
// Go projects: go.mod has no version field; skip directly to commit analysis
|
||||||
|
if project_dir.join("go.mod").exists() {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsers: &[(&str, fn(&Path) -> Option<Version>)] = PARSER_ORDER;
|
||||||
|
let mut results = Vec::new();
|
||||||
|
|
||||||
|
for &(source, parser) in parsers {
|
||||||
|
if let Some(v) = parser(project_dir) {
|
||||||
|
results.push(ConfigVersion {
|
||||||
|
source: source.to_string(),
|
||||||
|
version: v,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable order for parser dispatch. No priority implied — all results are
|
||||||
|
/// surfaced to the user when more than one is found.
|
||||||
|
type Parser = fn(&Path) -> Option<Version>;
|
||||||
|
const PARSER_ORDER: &[(&str, Parser)] = &[
|
||||||
|
("Cargo.toml", try_cargo_toml),
|
||||||
|
("package.json", try_package_json),
|
||||||
|
("pyproject.toml", try_pyproject_toml),
|
||||||
|
("pom.xml", try_pom_xml),
|
||||||
|
("pubspec.yaml", try_pubspec_yaml),
|
||||||
|
("build.sbt", try_build_sbt),
|
||||||
|
("project.clj", try_project_clj),
|
||||||
|
("mix.exs", try_mix_exs),
|
||||||
|
("package.yaml", try_package_yaml),
|
||||||
|
("Project.toml", try_project_toml_julia),
|
||||||
|
("composer.json", try_composer_json),
|
||||||
|
(".csproj", try_csproj),
|
||||||
|
("CMakeLists.txt", try_cmake_lists),
|
||||||
|
("meson.build", try_meson_build),
|
||||||
|
(".gemspec", try_gemspec),
|
||||||
|
];
|
||||||
|
|
||||||
|
// ── Structured parsers ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
fn try_cargo_toml(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("Cargo.toml")).ok()?;
|
||||||
|
let value = content.parse::<toml::Value>().ok()?;
|
||||||
|
let version_str = value.get("package")?.get("version")?.as_str()?;
|
||||||
|
Version::parse(version_str).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_pyproject_toml(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("pyproject.toml")).ok()?;
|
||||||
|
let value = content.parse::<toml::Value>().ok()?;
|
||||||
|
let version_str = value.get("project")?.get("version")?.as_str()?;
|
||||||
|
Version::parse(version_str).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_project_toml_julia(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("Project.toml")).ok()?;
|
||||||
|
let value = content.parse::<toml::Value>().ok()?;
|
||||||
|
let version_str = value.get("version")?.as_str()?;
|
||||||
|
Version::parse(version_str).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_package_json(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("package.json")).ok()?;
|
||||||
|
let value: serde_json::Value = serde_json::from_str(&content).ok()?;
|
||||||
|
let version_str = value.get("version")?.as_str()?;
|
||||||
|
Version::parse(version_str).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_composer_json(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("composer.json")).ok()?;
|
||||||
|
let value: serde_json::Value = serde_json::from_str(&content).ok()?;
|
||||||
|
let version_str = value.get("version")?.as_str()?;
|
||||||
|
Version::parse(version_str).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_pom_xml(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("pom.xml")).ok()?;
|
||||||
|
let doc = roxmltree::Document::parse(&content).ok()?;
|
||||||
|
let project = doc.root_element();
|
||||||
|
// Read <version> that is a direct child of <project>, not inside <parent>
|
||||||
|
for child in project.children() {
|
||||||
|
if child.is_element() && child.tag_name().name() == "version" {
|
||||||
|
if let Some(t) = child.text() {
|
||||||
|
return Version::parse(t.trim()).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_csproj(dir: &Path) -> Option<Version> {
|
||||||
|
// Find any .csproj file in the root (take the first)
|
||||||
|
let csproj = std::fs::read_dir(dir)
|
||||||
|
.ok()?
|
||||||
|
.filter_map(|e| e.ok())
|
||||||
|
.map(|e| e.path())
|
||||||
|
.find(|p| p.extension().map_or(false, |ext| ext == "csproj"))?;
|
||||||
|
let content = std::fs::read_to_string(&csproj).ok()?;
|
||||||
|
let doc = roxmltree::Document::parse(&content).ok()?;
|
||||||
|
// Look for <Version> (preferred) or <VersionPrefix> anywhere in the document
|
||||||
|
for node in doc.descendants() {
|
||||||
|
if node.is_element() {
|
||||||
|
match node.tag_name().name() {
|
||||||
|
"Version" => {
|
||||||
|
if let Some(t) = node.text() {
|
||||||
|
return Version::parse(t.trim()).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"VersionPrefix" => {
|
||||||
|
if let Some(t) = node.text() {
|
||||||
|
return Version::parse(t.trim()).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Regex-based parsers (code-as-config or simple data formats) ─────
|
||||||
|
|
||||||
|
fn try_pubspec_yaml(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("pubspec.yaml")).ok()?;
|
||||||
|
let re =
|
||||||
|
regex::Regex::new(r##"(?m)^version\s*:\s*['"]?(\d+\.\d+\.\d+[^'"#\s]*)['"]?"##).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_package_yaml(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("package.yaml")).ok()?;
|
||||||
|
let re =
|
||||||
|
regex::Regex::new(r##"(?m)^version\s*:\s*['"]?(\d+\.\d+\.\d+[^'"#\s]*)['"]?"##).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_gemspec(dir: &Path) -> Option<Version> {
|
||||||
|
// A directory may contain multiple .gemspec files; take the first.
|
||||||
|
let gemspec = std::fs::read_dir(dir)
|
||||||
|
.ok()?
|
||||||
|
.filter_map(|e| e.ok())
|
||||||
|
.map(|e| e.path())
|
||||||
|
.find(|p| p.extension().map_or(false, |ext| ext == "gemspec"))?;
|
||||||
|
let content = std::fs::read_to_string(&gemspec).ok()?;
|
||||||
|
let re =
|
||||||
|
regex::Regex::new(r#"spec\.version\s*=\s*["'](\d+\.\d+\.\d+[^"']*)["']"#).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_build_sbt(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("build.sbt")).ok()?;
|
||||||
|
let re = regex::Regex::new(r#"version\s*:=\s*["'](\d+\.\d+\.\d+[^"']*)["']"#).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_project_clj(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("project.clj")).ok()?;
|
||||||
|
let re = regex::Regex::new(r#"\(defproject\s+[^\s]+\s+"(\d+\.\d+\.\d+[^"]*)""#).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_mix_exs(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("mix.exs")).ok()?;
|
||||||
|
let re = regex::Regex::new(r#"version\s*:\s*["'](\d+\.\d+\.\d+[^"']*)["']"#).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_cmake_lists(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("CMakeLists.txt")).ok()?;
|
||||||
|
let re =
|
||||||
|
regex::Regex::new(r"project\s*\([^)]*VERSION\s+(\d+\.\d+\.\d+[^\s)]*)").ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_meson_build(dir: &Path) -> Option<Version> {
|
||||||
|
let content = std::fs::read_to_string(dir.join("meson.build")).ok()?;
|
||||||
|
let re =
|
||||||
|
regex::Regex::new(r#"version\s*:\s*["'](\d+\.\d+\.\d+[^"']*)["']"#).ok()?;
|
||||||
|
let caps = re.captures(&content)?;
|
||||||
|
Version::parse(caps.get(1)?.as_str()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::git::TagInfo;
|
||||||
|
|
||||||
|
fn make_tag(name: &str, time: i64) -> TagInfo {
|
||||||
|
TagInfo {
|
||||||
|
name: name.to_string(),
|
||||||
|
target: "abc123".to_string(),
|
||||||
|
message: String::new(),
|
||||||
|
time,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_by_semver_descending() {
|
||||||
|
let mut tags = vec![
|
||||||
|
make_tag("v1.0.0", 100),
|
||||||
|
make_tag("v2.0.0", 200),
|
||||||
|
make_tag("v1.5.0", 150),
|
||||||
|
];
|
||||||
|
sort_tags_by_semver(&mut tags);
|
||||||
|
let names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["v2.0.0", "v1.5.0", "v1.0.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_semver_ties_broken_by_time() {
|
||||||
|
let mut tags = vec![
|
||||||
|
make_tag("v1.0.0", 100),
|
||||||
|
make_tag("v1.0.0", 300),
|
||||||
|
make_tag("v1.0.0", 200),
|
||||||
|
];
|
||||||
|
sort_tags_by_semver(&mut tags);
|
||||||
|
let times: Vec<i64> = tags.iter().map(|t| t.time).collect();
|
||||||
|
assert_eq!(times, vec![300, 200, 100]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_non_semver_tags_at_end() {
|
||||||
|
let mut tags = vec![
|
||||||
|
make_tag("release-2024", 400),
|
||||||
|
make_tag("v1.0.0", 100),
|
||||||
|
make_tag("staging", 300),
|
||||||
|
make_tag("v0.2.0", 200),
|
||||||
|
];
|
||||||
|
sort_tags_by_semver(&mut tags);
|
||||||
|
let names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
assert_eq!(names[0], "v1.0.0");
|
||||||
|
assert_eq!(names[1], "v0.2.0");
|
||||||
|
assert_eq!(names[2], "release-2024");
|
||||||
|
assert_eq!(names[3], "staging");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_no_prefix_semver() {
|
||||||
|
let mut tags = vec![
|
||||||
|
make_tag("1.0.0", 100),
|
||||||
|
make_tag("2.0.0", 200),
|
||||||
|
make_tag("0.1.0", 50),
|
||||||
|
];
|
||||||
|
sort_tags_by_semver(&mut tags);
|
||||||
|
let names: Vec<&str> = tags.iter().map(|t| t.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["2.0.0", "1.0.0", "0.1.0"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sort_all_non_semver_by_time() {
|
||||||
|
let mut tags = vec![
|
||||||
|
make_tag("release-2024", 100),
|
||||||
|
make_tag("release-2023", 300),
|
||||||
|
make_tag("beta", 200),
|
||||||
|
];
|
||||||
|
sort_tags_by_semver(&mut tags);
|
||||||
|
let times: Vec<i64> = tags.iter().map(|t| t.time).collect();
|
||||||
|
assert_eq!(times, vec![300, 200, 100]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_cargo_toml() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("Cargo.toml"),
|
||||||
|
"[package]\nname = \"test\"\nversion = \"0.3.0\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "Cargo.toml");
|
||||||
|
assert_eq!(versions[0].version, Version::new(0, 3, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_pyproject_toml() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("pyproject.toml"),
|
||||||
|
"[project]\nname = \"test\"\nversion = \"0.2.1\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "pyproject.toml");
|
||||||
|
assert_eq!(versions[0].version, Version::new(0, 2, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_no_config_files() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert!(versions.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_multiple_configs_returns_all() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("Cargo.toml"),
|
||||||
|
"[package]\nname = \"test\"\nversion = \"0.3.0\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("pyproject.toml"),
|
||||||
|
"[project]\nname = \"test\"\nversion = \"0.2.1\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 2);
|
||||||
|
// Order is defined by PARSER_ORDER: Cargo.toml before pyproject.toml
|
||||||
|
assert_eq!(versions[0].source, "Cargo.toml");
|
||||||
|
assert_eq!(versions[0].version, Version::new(0, 3, 0));
|
||||||
|
assert_eq!(versions[1].source, "pyproject.toml");
|
||||||
|
assert_eq!(versions[1].version, Version::new(0, 2, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_package_json() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("package.json"),
|
||||||
|
r#"{"name": "test", "version": "1.2.3"}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "package.json");
|
||||||
|
assert_eq!(versions[0].version, Version::new(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_pom_xml() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("pom.xml"),
|
||||||
|
"<project><modelVersion>4.0.0</modelVersion><version>2.0.0</version></project>",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "pom.xml");
|
||||||
|
assert_eq!(versions[0].version, Version::new(2, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_pom_xml_ignores_parent_version() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("pom.xml"),
|
||||||
|
"<project><parent><version>3.0.0</version></parent><version>2.0.0</version></project>",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].version, Version::new(2, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_pubspec_yaml() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("pubspec.yaml"),
|
||||||
|
"name: myapp\nversion: 1.0.0+1\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "pubspec.yaml");
|
||||||
|
assert_eq!(
|
||||||
|
versions[0].version,
|
||||||
|
Version::parse("1.0.0+1").unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_go_mod_skips_all() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(dir.path().join("go.mod"), "module example.com/m\n").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("Cargo.toml"),
|
||||||
|
"[package]\nname = \"test\"\nversion = \"0.3.0\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// go.mod triggers immediate return — Cargo.toml is ignored
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert!(versions.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_read_versions_project_toml_julia() {
|
||||||
|
let dir = tempfile::TempDir::new().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("Project.toml"),
|
||||||
|
"name = \"MyPkg\"\nversion = \"0.1.0\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let versions = read_project_versions(dir.path());
|
||||||
|
assert_eq!(versions.len(), 1);
|
||||||
|
assert_eq!(versions[0].source, "Project.toml");
|
||||||
|
assert_eq!(versions[0].version, Version::new(0, 1, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -930,6 +930,42 @@ impl Messages {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn found_version_in(&self) -> &str {
|
||||||
|
match self.language {
|
||||||
|
Language::English => "Found version in",
|
||||||
|
Language::Chinese => "在配置文件中找到版本",
|
||||||
|
Language::Japanese => "設定ファイルでバージョンが見つかりました",
|
||||||
|
Language::Korean => "구성 파일에서 버전을 찾음",
|
||||||
|
Language::Spanish => "Versión encontrada en",
|
||||||
|
Language::French => "Version trouvée dans",
|
||||||
|
Language::German => "Version gefunden in",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn found_multiple_versions(&self) -> &str {
|
||||||
|
match self.language {
|
||||||
|
Language::English => "Found versions in multiple config files:",
|
||||||
|
Language::Chinese => "在多个配置文件中找到版本:",
|
||||||
|
Language::Japanese => "複数の設定ファイルでバージョンが見つかりました:",
|
||||||
|
Language::Korean => "여러 구성 파일에서 버전을 찾음:",
|
||||||
|
Language::Spanish => "Versiones encontradas en múltiples archivos:",
|
||||||
|
Language::French => "Versions trouvées dans plusieurs fichiers :",
|
||||||
|
Language::German => "Versionen in mehreren Dateien gefunden:",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn select_version_to_use(&self) -> &str {
|
||||||
|
match self.language {
|
||||||
|
Language::English => "Select version to use",
|
||||||
|
Language::Chinese => "选择要使用的版本",
|
||||||
|
Language::Japanese => "使用するバージョンを選択",
|
||||||
|
Language::Korean => "사용할 버전 선택",
|
||||||
|
Language::Spanish => "Seleccionar versión a usar",
|
||||||
|
Language::French => "Sélectionner la version à utiliser",
|
||||||
|
Language::German => "Zu verwendende Version auswählen",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn profile_description(&self) -> &str {
|
pub fn profile_description(&self) -> &str {
|
||||||
match self.language {
|
match self.language {
|
||||||
Language::English => "Profile description (optional)",
|
Language::English => "Profile description (optional)",
|
||||||
|
|||||||
9
src/lib.rs
Normal file
9
src/lib.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
pub mod commands;
|
||||||
|
pub mod config;
|
||||||
|
pub mod generator;
|
||||||
|
pub mod git;
|
||||||
|
pub mod i18n;
|
||||||
|
pub mod llm;
|
||||||
|
pub mod utils;
|
||||||
@@ -1,655 +0,0 @@
|
|||||||
use super::thinking::ThinkingStateManager;
|
|
||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// Anthropic Claude API client
|
|
||||||
pub struct AnthropicClient {
|
|
||||||
api_key: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
thinking_enabled: bool,
|
|
||||||
thinking_budget_tokens: u32,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
top_p: Option<f32>,
|
|
||||||
thinking_state: Option<Arc<ThinkingStateManager>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct MessagesRequest {
|
|
||||||
model: String,
|
|
||||||
max_tokens: u32,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
top_p: Option<f32>,
|
|
||||||
messages: Vec<AnthropicMessage>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
system: Option<Vec<SystemContent>>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
thinking: Option<ThinkingConfig>,
|
|
||||||
stream: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Clone)]
|
|
||||||
struct SystemContent {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
content_type: String,
|
|
||||||
text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ThinkingConfig {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
thinking_type: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
budget_tokens: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct AnthropicMessage {
|
|
||||||
role: String,
|
|
||||||
content: AnthropicContent,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
#[serde(untagged)]
|
|
||||||
enum AnthropicContent {
|
|
||||||
Text(String),
|
|
||||||
Blocks(Vec<ContentBlock>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct ContentBlock {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
content_type: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
text: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct MessagesResponse {
|
|
||||||
content: Vec<ResponseContentBlock>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ResponseContentBlock {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
content_type: String,
|
|
||||||
text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorResponse {
|
|
||||||
error: AnthropicError,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct AnthropicError {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
error_type: String,
|
|
||||||
message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Streaming SSE event structures ---
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct SseEvent {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
event_type: String,
|
|
||||||
#[serde(default)]
|
|
||||||
message: Option<SseMessage>,
|
|
||||||
#[serde(default)]
|
|
||||||
index: Option<u32>,
|
|
||||||
#[serde(default)]
|
|
||||||
content_block: Option<SseContentBlock>,
|
|
||||||
#[serde(default)]
|
|
||||||
delta: Option<SseDelta>,
|
|
||||||
#[serde(default)]
|
|
||||||
usage: Option<SseUsage>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct SseMessage {
|
|
||||||
#[serde(default)]
|
|
||||||
content: Option<Vec<SseContentBlock>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct SseContentBlock {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
content_type: String,
|
|
||||||
#[serde(default)]
|
|
||||||
thinking: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
text: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct SseDelta {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
delta_type: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
thinking: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
text: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct SseUsage {
|
|
||||||
#[serde(default)]
|
|
||||||
output_tokens: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnthropicClient {
|
|
||||||
pub fn new(api_key: &str, model: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(60))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
thinking_budget_tokens: 1024,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
|
|
||||||
self.client = create_http_client(timeout)?;
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking(mut self, enabled: bool) -> Self {
|
|
||||||
self.thinking_enabled = enabled;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking_budget_tokens(mut self, budget_tokens: u32) -> Self {
|
|
||||||
self.thinking_budget_tokens = budget_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_top_p(mut self, top_p: f32) -> Self {
|
|
||||||
self.top_p = Some(top_p);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking_state(mut self, state: Arc<ThinkingStateManager>) -> Self {
|
|
||||||
self.thinking_state = Some(state);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
Ok(ANTHROPIC_MODELS.iter().map(|&m| m.to_string()).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn validate_key(&self) -> Result<bool> {
|
|
||||||
let url = "https://api.anthropic.com/v1/messages";
|
|
||||||
|
|
||||||
let request = MessagesRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
max_tokens: 5,
|
|
||||||
temperature: Some(0.0),
|
|
||||||
top_p: None,
|
|
||||||
messages: vec![AnthropicMessage {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: AnthropicContent::Text("Hi".to_string()),
|
|
||||||
}],
|
|
||||||
system: None,
|
|
||||||
thinking: None,
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("x-api-key", &self.api_key)
|
|
||||||
.header("anthropic-version", "2023-06-01")
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
match response {
|
|
||||||
Ok(resp) => {
|
|
||||||
if resp.status().is_success() {
|
|
||||||
Ok(true)
|
|
||||||
} else {
|
|
||||||
let status = resp.status();
|
|
||||||
if status.as_u16() == 401 {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
let text = resp.text().await.unwrap_or_default();
|
|
||||||
bail!("Anthropic API error: {} - {}", status, text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => Err(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for AnthropicClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![AnthropicMessage {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: AnthropicContent::Text(prompt.to_string()),
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.messages_request_with_retry(messages, None).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let messages = vec![AnthropicMessage {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: AnthropicContent::Text(user.to_string()),
|
|
||||||
}];
|
|
||||||
|
|
||||||
let system = if system.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(vec![SystemContent {
|
|
||||||
content_type: "text".to_string(),
|
|
||||||
text: system.to_string(),
|
|
||||||
}])
|
|
||||||
};
|
|
||||||
|
|
||||||
self.messages_request_with_retry(messages, system).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
self.validate_key().await.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"anthropic"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnthropicClient {
|
|
||||||
async fn messages_request_with_retry(
|
|
||||||
&self,
|
|
||||||
messages: Vec<AnthropicMessage>,
|
|
||||||
system: Option<Vec<SystemContent>>,
|
|
||||||
) -> Result<String> {
|
|
||||||
let mut last_error = None;
|
|
||||||
|
|
||||||
for attempt in 1..=3 {
|
|
||||||
match self
|
|
||||||
.messages_request(messages.clone(), system.clone())
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(result) => return Ok(result),
|
|
||||||
Err(e) => {
|
|
||||||
let err_msg = e.to_string();
|
|
||||||
let is_retryable = err_msg.contains("timeout")
|
|
||||||
|| err_msg.contains("connection")
|
|
||||||
|| err_msg.contains("temporary")
|
|
||||||
|| err_msg.contains("5")
|
|
||||||
&& (err_msg.contains("500")
|
|
||||||
|| err_msg.contains("502")
|
|
||||||
|| err_msg.contains("503")
|
|
||||||
|| err_msg.contains("504"));
|
|
||||||
|
|
||||||
if !is_retryable || attempt == 3 {
|
|
||||||
last_error = Some(e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_millis(500 * 2u64.pow(attempt - 1))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("Request failed after retries")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn messages_request(
|
|
||||||
&self,
|
|
||||||
messages: Vec<AnthropicMessage>,
|
|
||||||
system: Option<Vec<SystemContent>>,
|
|
||||||
) -> Result<String> {
|
|
||||||
if self.thinking_enabled {
|
|
||||||
self.streaming_messages_request(messages, system).await
|
|
||||||
} else {
|
|
||||||
self.non_streaming_messages_request(messages, system).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn non_streaming_messages_request(
|
|
||||||
&self,
|
|
||||||
messages: Vec<AnthropicMessage>,
|
|
||||||
system: Option<Vec<SystemContent>>,
|
|
||||||
) -> Result<String> {
|
|
||||||
let url = "https://api.anthropic.com/v1/messages";
|
|
||||||
|
|
||||||
let temperature = if self.temperature == 0.0 {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(self.temperature)
|
|
||||||
};
|
|
||||||
|
|
||||||
let request = MessagesRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
max_tokens: self.max_tokens,
|
|
||||||
temperature,
|
|
||||||
top_p: self.top_p,
|
|
||||||
messages,
|
|
||||||
system,
|
|
||||||
thinking: Some(ThinkingConfig {
|
|
||||||
thinking_type: "disabled".to_string(),
|
|
||||||
budget_tokens: None,
|
|
||||||
}),
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("x-api-key", &self.api_key)
|
|
||||||
.header("anthropic-version", "2023-06-01")
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to Anthropic")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"Anthropic API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("Anthropic API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: MessagesResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Anthropic response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.content
|
|
||||||
.into_iter()
|
|
||||||
.find(|c| c.content_type == "text")
|
|
||||||
.map(|c| c.text.trim().to_string())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No text response from Anthropic"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Streaming request for thinking mode, filters thinking content blocks
|
|
||||||
async fn streaming_messages_request(
|
|
||||||
&self,
|
|
||||||
messages: Vec<AnthropicMessage>,
|
|
||||||
system: Option<Vec<SystemContent>>,
|
|
||||||
) -> Result<String> {
|
|
||||||
let url = "https://api.anthropic.com/v1/messages";
|
|
||||||
|
|
||||||
let thinking = ThinkingConfig {
|
|
||||||
thinking_type: "enabled".to_string(),
|
|
||||||
budget_tokens: Some(self.thinking_budget_tokens),
|
|
||||||
};
|
|
||||||
|
|
||||||
// max_tokens must exceed budget_tokens
|
|
||||||
let max_tokens = (self.max_tokens).max(self.thinking_budget_tokens + 100);
|
|
||||||
|
|
||||||
let request = MessagesRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
max_tokens,
|
|
||||||
temperature: None, // must be omitted for thinking mode
|
|
||||||
top_p: None,
|
|
||||||
messages,
|
|
||||||
system,
|
|
||||||
thinking: Some(thinking),
|
|
||||||
stream: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("x-api-key", &self.api_key)
|
|
||||||
.header("anthropic-version", "2023-06-01")
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("Accept", "text/event-stream")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send streaming request to Anthropic")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"Anthropic API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("Anthropic API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut content_buffer = String::new();
|
|
||||||
let mut in_thinking = false;
|
|
||||||
let mut has_reasoning = false;
|
|
||||||
let mut has_content = false;
|
|
||||||
|
|
||||||
let thinking_state = self.thinking_state.as_ref();
|
|
||||||
|
|
||||||
let mut byte_stream = response.bytes_stream();
|
|
||||||
let mut line_buffer = String::new();
|
|
||||||
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
|
|
||||||
while let Some(chunk) = byte_stream.next().await {
|
|
||||||
let chunk = chunk.context("Failed to read streaming response chunk")?;
|
|
||||||
let chunk_str =
|
|
||||||
String::from_utf8(chunk.to_vec()).context("Invalid UTF-8 in stream chunk")?;
|
|
||||||
|
|
||||||
line_buffer.push_str(&chunk_str);
|
|
||||||
|
|
||||||
while let Some(line_end) = line_buffer.find('\n') {
|
|
||||||
let line = line_buffer[..line_end].trim().to_string();
|
|
||||||
line_buffer = line_buffer[line_end + 1..].to_string();
|
|
||||||
|
|
||||||
if line.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse SSE event line
|
|
||||||
if let Some(data) = line.strip_prefix("data: ") {
|
|
||||||
if let Ok(event) = serde_json::from_str::<SseEvent>(data) {
|
|
||||||
match event.event_type.as_str() {
|
|
||||||
"content_block_start" => {
|
|
||||||
if let Some(ref block) = event.content_block {
|
|
||||||
if block.content_type == "thinking" {
|
|
||||||
in_thinking = true;
|
|
||||||
if !has_reasoning {
|
|
||||||
has_reasoning = true;
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.start_thinking();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"content_block_delta" => {
|
|
||||||
if let Some(ref delta) = event.delta {
|
|
||||||
// Thinking delta - ignore content but track state
|
|
||||||
if delta.thinking.is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Text delta - collect
|
|
||||||
if in_thinking && delta.text.is_some() {
|
|
||||||
// Transition from thinking to text
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
in_thinking = false;
|
|
||||||
}
|
|
||||||
if let Some(ref text) = delta.text
|
|
||||||
&& !text.is_empty()
|
|
||||||
{
|
|
||||||
has_content = true;
|
|
||||||
content_buffer.push_str(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"content_block_stop" => {
|
|
||||||
if in_thinking {
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
in_thinking = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure thinking state is ended
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = content_buffer.trim().to_string();
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
if has_reasoning && !has_content {
|
|
||||||
bail!(
|
|
||||||
"Anthropic returned thinking content but no final answer. \
|
|
||||||
The model may have entered an incomplete thinking state. \
|
|
||||||
Please try again or disable thinking mode."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bail!(
|
|
||||||
"No response from Anthropic. \
|
|
||||||
If thinking mode is enabled, try disabling it or ensure the model supports it."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Available Anthropic models (Claude 4 series with extended thinking)
|
|
||||||
pub const ANTHROPIC_MODELS: &[&str] = &[
|
|
||||||
"claude-opus-4-7",
|
|
||||||
"claude-sonnet-4-6",
|
|
||||||
"claude-haiku-4-5",
|
|
||||||
// Legacy models
|
|
||||||
"claude-3-opus-20240229",
|
|
||||||
"claude-3-sonnet-20240229",
|
|
||||||
"claude-3-haiku-20240307",
|
|
||||||
"claude-2.1",
|
|
||||||
"claude-2.0",
|
|
||||||
"claude-instant-1.2",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn is_valid_model(model: &str) -> bool {
|
|
||||||
ANTHROPIC_MODELS.contains(&model)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_model_validation_claude4() {
|
|
||||||
assert!(is_valid_model("claude-opus-4-7"));
|
|
||||||
assert!(is_valid_model("claude-sonnet-4-6"));
|
|
||||||
assert!(is_valid_model("claude-haiku-4-5"));
|
|
||||||
assert!(is_valid_model("claude-3-sonnet-20240229"));
|
|
||||||
assert!(!is_valid_model("invalid-model"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_thinking_config_serialization() {
|
|
||||||
let config = ThinkingConfig {
|
|
||||||
thinking_type: "enabled".to_string(),
|
|
||||||
budget_tokens: Some(2048),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&config).unwrap();
|
|
||||||
assert!(json.contains(r#""type":"enabled""#));
|
|
||||||
assert!(json.contains(r#""budget_tokens":2048"#));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_thinking_config_disabled_serialization() {
|
|
||||||
let config = ThinkingConfig {
|
|
||||||
thinking_type: "disabled".to_string(),
|
|
||||||
budget_tokens: None,
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&config).unwrap();
|
|
||||||
assert_eq!(json, r#"{"type":"disabled"}"#);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_system_content_serialization() {
|
|
||||||
let content = SystemContent {
|
|
||||||
content_type: "text".to_string(),
|
|
||||||
text: "You are helpful.".to_string(),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&content).unwrap();
|
|
||||||
assert!(json.contains(r#""type":"text""#));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_sse_event_parsing_content_block_start() {
|
|
||||||
let json = r#"{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#;
|
|
||||||
let event: SseEvent = serde_json::from_str(json).unwrap();
|
|
||||||
assert_eq!(event.event_type, "content_block_start");
|
|
||||||
assert_eq!(event.content_block.unwrap().content_type, "thinking");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_sse_event_parsing_text_delta() {
|
|
||||||
let json = r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}"#;
|
|
||||||
let event: SseEvent = serde_json::from_str(json).unwrap();
|
|
||||||
assert_eq!(event.event_type, "content_block_delta");
|
|
||||||
assert_eq!(event.delta.unwrap().text, Some("Hello".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_anthropic_content_text() {
|
|
||||||
let msg = AnthropicMessage {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: AnthropicContent::Text("Hello".to_string()),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&msg).unwrap();
|
|
||||||
assert!(json.contains(r#""content":"Hello""#));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,622 +0,0 @@
|
|||||||
use super::thinking::ThinkingStateManager;
|
|
||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// DeepSeek API client
|
|
||||||
pub struct DeepSeekClient {
|
|
||||||
base_url: String,
|
|
||||||
api_key: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
thinking_enabled: bool,
|
|
||||||
reasoning_effort: Option<String>,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
thinking_state: Option<Arc<ThinkingStateManager>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ChatCompletionRequest {
|
|
||||||
model: String,
|
|
||||||
messages: Vec<Message>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
max_tokens: Option<u32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
top_p: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
presence_penalty: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
frequency_penalty: Option<f32>,
|
|
||||||
stream: bool,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
thinking: Option<ThinkingConfig>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
reasoning_effort: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ThinkingConfig {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
thinking_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
struct Message {
|
|
||||||
role: String,
|
|
||||||
content: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ChatCompletionResponse {
|
|
||||||
choices: Vec<Choice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct Choice {
|
|
||||||
message: Message,
|
|
||||||
#[serde(default)]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Streaming response structures ---
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChunk {
|
|
||||||
choices: Vec<StreamChoice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChoice {
|
|
||||||
delta: StreamDelta,
|
|
||||||
#[serde(default)]
|
|
||||||
finish_reason: Option<String>,
|
|
||||||
index: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
|
||||||
struct StreamDelta {
|
|
||||||
#[serde(default)]
|
|
||||||
content: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorResponse {
|
|
||||||
error: ApiError,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ApiError {
|
|
||||||
message: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
error_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeepSeekClient {
|
|
||||||
pub fn new(api_key: &str, model: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(300))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: "https://api.deepseek.com".to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
reasoning_effort: None,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_base_url(api_key: &str, model: &str, base_url: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(300))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: base_url.trim_end_matches('/').to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
reasoning_effort: None,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
|
|
||||||
self.client = create_http_client(timeout)?;
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking(mut self, enabled: bool) -> Self {
|
|
||||||
self.thinking_enabled = enabled;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_reasoning_effort(mut self, effort: Option<String>) -> Self {
|
|
||||||
self.reasoning_effort = effort;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking_state(mut self, state: Arc<ThinkingStateManager>) -> Self {
|
|
||||||
self.thinking_state = Some(state);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
let url = format!("{}/models", self.base_url);
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.get(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to list DeepSeek models")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
bail!("DeepSeek API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelsResponse {
|
|
||||||
data: Vec<ModelId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelId {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ModelsResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse DeepSeek response")?;
|
|
||||||
|
|
||||||
Ok(result.data.into_iter().map(|m| m.id).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn validate_key(&self) -> Result<bool> {
|
|
||||||
match self.list_models().await {
|
|
||||||
Ok(_) => Ok(true),
|
|
||||||
Err(e) => {
|
|
||||||
let err_str = e.to_string();
|
|
||||||
if err_str.contains("401") || err_str.contains("Unauthorized") {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for DeepSeekClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: prompt.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let mut messages = vec![];
|
|
||||||
|
|
||||||
if !system.is_empty() {
|
|
||||||
messages.push(Message {
|
|
||||||
role: "system".to_string(),
|
|
||||||
content: system.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
messages.push(Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: user.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
});
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
self.validate_key().await.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"deepseek"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeepSeekClient {
|
|
||||||
async fn chat_completion_with_retry(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let mut last_error = None;
|
|
||||||
|
|
||||||
for attempt in 1..=3 {
|
|
||||||
match self.chat_completion(messages.clone()).await {
|
|
||||||
Ok(result) => return Ok(result),
|
|
||||||
Err(e) => {
|
|
||||||
let err_msg = e.to_string();
|
|
||||||
// 网络临时错误才重试
|
|
||||||
let is_retryable = err_msg.contains("timeout")
|
|
||||||
|| err_msg.contains("connection")
|
|
||||||
|| err_msg.contains("temporary")
|
|
||||||
|| err_msg.contains("5")
|
|
||||||
&& (err_msg.contains("500")
|
|
||||||
|| err_msg.contains("502")
|
|
||||||
|| err_msg.contains("503")
|
|
||||||
|| err_msg.contains("504"));
|
|
||||||
|
|
||||||
if !is_retryable || attempt == 3 {
|
|
||||||
last_error = Some(e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 指数退避
|
|
||||||
tokio::time::sleep(Duration::from_millis(500 * 2u64.pow(attempt - 1))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("Request failed after retries")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!("{}/chat/completions", self.base_url);
|
|
||||||
|
|
||||||
let thinking = Some(ThinkingConfig {
|
|
||||||
thinking_type: if self.thinking_enabled {
|
|
||||||
"enabled".to_string()
|
|
||||||
} else {
|
|
||||||
"disabled".to_string()
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// 思考模式下,temperature/top_p 等参数不应传递
|
|
||||||
// 非思考模式下可以正常传递
|
|
||||||
let (temperature, max_tokens, top_p, presence_penalty, frequency_penalty) =
|
|
||||||
if self.thinking_enabled {
|
|
||||||
(None, Some(self.max_tokens), None, None, None)
|
|
||||||
} else {
|
|
||||||
(
|
|
||||||
Some(self.temperature),
|
|
||||||
Some(self.max_tokens),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let reasoning_effort = if self.thinking_enabled {
|
|
||||||
self.reasoning_effort.clone()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
messages: messages.clone(),
|
|
||||||
max_tokens,
|
|
||||||
temperature,
|
|
||||||
top_p,
|
|
||||||
presence_penalty,
|
|
||||||
frequency_penalty,
|
|
||||||
stream: self.thinking_enabled,
|
|
||||||
thinking,
|
|
||||||
reasoning_effort,
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.thinking_enabled {
|
|
||||||
self.streaming_chat_completion(&url, &request).await
|
|
||||||
} else {
|
|
||||||
self.non_streaming_chat_completion(&url, &request).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 非流式请求(非思考模式)
|
|
||||||
async fn non_streaming_chat_completion(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
request: &ChatCompletionRequest,
|
|
||||||
) -> Result<String> {
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to DeepSeek")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"DeepSeek API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("DeepSeek API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ChatCompletionResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse DeepSeek response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.choices
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|c| c.message.content.trim().to_string())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No response from DeepSeek"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 流式请求(思考模式),处理 reasoning_content 和 content
|
|
||||||
async fn streaming_chat_completion(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
request: &ChatCompletionRequest,
|
|
||||||
) -> Result<String> {
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("Accept", "text/event-stream")
|
|
||||||
.json(request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send streaming request to DeepSeek")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"DeepSeek API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("DeepSeek API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut content_buffer = String::new();
|
|
||||||
let mut has_reasoning = false;
|
|
||||||
let mut has_content = false;
|
|
||||||
let mut stream_ended = false;
|
|
||||||
|
|
||||||
let thinking_state = self.thinking_state.as_ref();
|
|
||||||
|
|
||||||
let mut byte_stream = response.bytes_stream();
|
|
||||||
let mut line_buffer = String::new();
|
|
||||||
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
|
|
||||||
while let Some(chunk) = byte_stream.next().await {
|
|
||||||
let chunk = chunk.context("Failed to read streaming response chunk")?;
|
|
||||||
let chunk_str =
|
|
||||||
String::from_utf8(chunk.to_vec()).context("Invalid UTF-8 in stream chunk")?;
|
|
||||||
|
|
||||||
line_buffer.push_str(&chunk_str);
|
|
||||||
|
|
||||||
// 处理完整行
|
|
||||||
while let Some(line_end) = line_buffer.find('\n') {
|
|
||||||
let line = line_buffer[..line_end].trim().to_string();
|
|
||||||
line_buffer = line_buffer[line_end + 1..].to_string();
|
|
||||||
|
|
||||||
if line.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// SSE 格式:data: {...} 或 data: [DONE]
|
|
||||||
if line == "data: [DONE]" {
|
|
||||||
stream_ended = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(json_str) = line.strip_prefix("data: ") {
|
|
||||||
match serde_json::from_str::<StreamChunk>(json_str) {
|
|
||||||
Ok(chunk) => {
|
|
||||||
for choice in &chunk.choices {
|
|
||||||
// 处理 reasoning_content
|
|
||||||
if let Some(ref reasoning) = choice.delta.reasoning_content
|
|
||||||
&& !reasoning.is_empty()
|
|
||||||
{
|
|
||||||
if !has_reasoning {
|
|
||||||
has_reasoning = true;
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.start_thinking();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// reasoning_content 不对外输出,仅用于内部状态判断
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理 content
|
|
||||||
if let Some(ref content) = choice.delta.content
|
|
||||||
&& !content.is_empty()
|
|
||||||
{
|
|
||||||
// reasoning 结束,content 开始出现时移除 thinking 标识
|
|
||||||
if has_reasoning
|
|
||||||
&& !has_content
|
|
||||||
&& let Some(state) = thinking_state
|
|
||||||
{
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
has_content = true;
|
|
||||||
content_buffer.push_str(content);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查 finish_reason
|
|
||||||
if let Some(ref reason) = choice.finish_reason
|
|
||||||
&& reason == "stop"
|
|
||||||
{
|
|
||||||
stream_ended = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
// 忽略无法解析的行(可能是心跳或注释)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if stream_ended {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 确保思考状态已结束
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = content_buffer.trim().to_string();
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
if has_reasoning && !has_content {
|
|
||||||
bail!(
|
|
||||||
"DeepSeek returned reasoning content but no final answer. \
|
|
||||||
The model may have entered an incomplete thinking state. \
|
|
||||||
Please try again or disable thinking mode."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bail!(
|
|
||||||
"No response from DeepSeek. \
|
|
||||||
If thinking mode is enabled, try disabling it or ensure the model supports it."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 可用 DeepSeek 模型列表
|
|
||||||
/// deepseek-chat / deepseek-reasoner 将于 2026-07-24 停用,推荐使用 V4 系列
|
|
||||||
pub const DEEPSEEK_MODELS: &[&str] = &[
|
|
||||||
"deepseek-v4-flash",
|
|
||||||
"deepseek-v4-pro",
|
|
||||||
// 兼容旧版模型 ID(将于 2026-07-24 停用)
|
|
||||||
"deepseek-chat",
|
|
||||||
"deepseek-reasoner",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn is_valid_model(model: &str) -> bool {
|
|
||||||
DEEPSEEK_MODELS.contains(&model)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_model_validation_v4() {
|
|
||||||
assert!(is_valid_model("deepseek-v4-flash"));
|
|
||||||
assert!(is_valid_model("deepseek-v4-pro"));
|
|
||||||
assert!(is_valid_model("deepseek-chat"));
|
|
||||||
assert!(is_valid_model("deepseek-reasoner"));
|
|
||||||
assert!(!is_valid_model("invalid-model"));
|
|
||||||
assert!(!is_valid_model("deepseek-v3"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_client_builder_defaults() {
|
|
||||||
let client = DeepSeekClient::new("test-key", "deepseek-v4-flash").unwrap();
|
|
||||||
assert!(!client.thinking_enabled);
|
|
||||||
assert_eq!(client.max_tokens, 500);
|
|
||||||
assert_eq!(client.temperature, 0.7);
|
|
||||||
assert!(client.reasoning_effort.is_none());
|
|
||||||
assert!(client.thinking_state.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_client_builder_with_thinking() {
|
|
||||||
let client = DeepSeekClient::new("test-key", "deepseek-v4-flash")
|
|
||||||
.unwrap()
|
|
||||||
.with_thinking(true)
|
|
||||||
.with_reasoning_effort(Some("high".to_string()))
|
|
||||||
.with_max_tokens(1000)
|
|
||||||
.with_temperature(0.5);
|
|
||||||
|
|
||||||
assert!(client.thinking_enabled);
|
|
||||||
assert_eq!(client.reasoning_effort, Some("high".to_string()));
|
|
||||||
assert_eq!(client.max_tokens, 1000);
|
|
||||||
assert_eq!(client.temperature, 0.5);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_thinking_config_serialization() {
|
|
||||||
let config = ThinkingConfig {
|
|
||||||
thinking_type: "enabled".to_string(),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&config).unwrap();
|
|
||||||
assert_eq!(json, r#"{"type":"enabled"}"#);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_message_serialization_without_reasoning() {
|
|
||||||
let msg = Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: "Hello".to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&msg).unwrap();
|
|
||||||
assert!(!json.contains("reasoning_content"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_stream_delta_parsing() {
|
|
||||||
let json = r#"{"content":"Hello","reasoning_content":null}"#;
|
|
||||||
let delta: StreamDelta = serde_json::from_str(json).unwrap();
|
|
||||||
assert_eq!(delta.content, Some("Hello".to_string()));
|
|
||||||
assert!(delta.reasoning_content.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_stream_delta_reasoning_only() {
|
|
||||||
let json = r#"{"content":null,"reasoning_content":"Let me think..."}"#;
|
|
||||||
let delta: StreamDelta = serde_json::from_str(json).unwrap();
|
|
||||||
assert!(delta.content.is_none());
|
|
||||||
assert_eq!(delta.reasoning_content, Some("Let me think...".to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
587
src/llm/kimi.rs
587
src/llm/kimi.rs
@@ -1,587 +0,0 @@
|
|||||||
use super::thinking::ThinkingStateManager;
|
|
||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// Kimi API client (Moonshot AI)
|
|
||||||
pub struct KimiClient {
|
|
||||||
base_url: String,
|
|
||||||
api_key: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
thinking_enabled: bool,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
thinking_state: Option<Arc<ThinkingStateManager>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ChatCompletionRequest {
|
|
||||||
model: String,
|
|
||||||
messages: Vec<Message>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
max_tokens: Option<u32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
stream: bool,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
thinking: Option<ThinkingConfig>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ThinkingConfig {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
thinking_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
struct Message {
|
|
||||||
role: String,
|
|
||||||
content: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ChatCompletionResponse {
|
|
||||||
choices: Vec<Choice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct Choice {
|
|
||||||
message: Message,
|
|
||||||
#[serde(default)]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Streaming response structures ---
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChunk {
|
|
||||||
choices: Vec<StreamChoice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChoice {
|
|
||||||
delta: StreamDelta,
|
|
||||||
#[serde(default)]
|
|
||||||
finish_reason: Option<String>,
|
|
||||||
index: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
|
||||||
struct StreamDelta {
|
|
||||||
#[serde(default)]
|
|
||||||
content: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorResponse {
|
|
||||||
error: ApiError,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ApiError {
|
|
||||||
message: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
error_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl KimiClient {
|
|
||||||
pub fn new(api_key: &str, model: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(300))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: "https://api.moonshot.cn/v1".to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 1.0,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_base_url(api_key: &str, model: &str, base_url: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(300))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: base_url.trim_end_matches('/').to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 1.0,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
|
|
||||||
self.client = create_http_client(timeout)?;
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking(mut self, enabled: bool) -> Self {
|
|
||||||
self.thinking_enabled = enabled;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking_state(mut self, state: Arc<ThinkingStateManager>) -> Self {
|
|
||||||
self.thinking_state = Some(state);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
let url = format!("{}/models", self.base_url);
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.get(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to list Kimi models")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
bail!("Kimi API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelsResponse {
|
|
||||||
data: Vec<ModelId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelId {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ModelsResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Kimi response")?;
|
|
||||||
|
|
||||||
Ok(result.data.into_iter().map(|m| m.id).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn validate_key(&self) -> Result<bool> {
|
|
||||||
match self.list_models().await {
|
|
||||||
Ok(_) => Ok(true),
|
|
||||||
Err(e) => {
|
|
||||||
let err_str = e.to_string();
|
|
||||||
if err_str.contains("401") || err_str.contains("Unauthorized") {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for KimiClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: prompt.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let mut messages = vec![];
|
|
||||||
|
|
||||||
if !system.is_empty() {
|
|
||||||
messages.push(Message {
|
|
||||||
role: "system".to_string(),
|
|
||||||
content: system.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
messages.push(Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: user.to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
});
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
self.validate_key().await.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"kimi"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl KimiClient {
|
|
||||||
async fn chat_completion_with_retry(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let mut last_error = None;
|
|
||||||
|
|
||||||
for attempt in 1..=3 {
|
|
||||||
match self.chat_completion(messages.clone()).await {
|
|
||||||
Ok(result) => return Ok(result),
|
|
||||||
Err(e) => {
|
|
||||||
let err_msg = e.to_string();
|
|
||||||
let is_retryable = err_msg.contains("timeout")
|
|
||||||
|| err_msg.contains("connection")
|
|
||||||
|| err_msg.contains("temporary")
|
|
||||||
|| err_msg.contains("5")
|
|
||||||
&& (err_msg.contains("500")
|
|
||||||
|| err_msg.contains("502")
|
|
||||||
|| err_msg.contains("503")
|
|
||||||
|| err_msg.contains("504"));
|
|
||||||
|
|
||||||
if !is_retryable || attempt == 3 {
|
|
||||||
last_error = Some(e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_millis(500 * 2u64.pow(attempt - 1))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("Request failed after retries")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!("{}/chat/completions", self.base_url);
|
|
||||||
|
|
||||||
let thinking = Some(ThinkingConfig {
|
|
||||||
thinking_type: if self.thinking_enabled {
|
|
||||||
"enabled".to_string()
|
|
||||||
} else {
|
|
||||||
"disabled".to_string()
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Kimi API temperature 要求:
|
|
||||||
// - 思考模式: temperature 必须为 1.0
|
|
||||||
// - 非思考模式: temperature 必须为 0.6
|
|
||||||
let temperature = if self.thinking_enabled {
|
|
||||||
Some(1.0)
|
|
||||||
} else {
|
|
||||||
Some(0.6)
|
|
||||||
};
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
messages: messages.clone(),
|
|
||||||
max_tokens: Some(self.max_tokens),
|
|
||||||
temperature,
|
|
||||||
stream: self.thinking_enabled,
|
|
||||||
thinking,
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.thinking_enabled {
|
|
||||||
self.streaming_chat_completion(&url, &request).await
|
|
||||||
} else {
|
|
||||||
self.non_streaming_chat_completion(&url, &request).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 非流式请求(非思考模式)
|
|
||||||
async fn non_streaming_chat_completion(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
request: &ChatCompletionRequest,
|
|
||||||
) -> Result<String> {
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to Kimi")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"Kimi API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("Kimi API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ChatCompletionResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Kimi response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.choices
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|c| {
|
|
||||||
let content = c.message.content.trim().to_string();
|
|
||||||
if content.is_empty() {
|
|
||||||
c.reasoning_content
|
|
||||||
.or(c.message.reasoning_content)
|
|
||||||
.map(|r| r.trim().to_string())
|
|
||||||
.unwrap_or_default()
|
|
||||||
} else {
|
|
||||||
content
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No response from Kimi"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 流式请求(思考模式),处理 reasoning_content 和 content
|
|
||||||
async fn streaming_chat_completion(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
request: &ChatCompletionRequest,
|
|
||||||
) -> Result<String> {
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("Accept", "text/event-stream")
|
|
||||||
.json(request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send streaming request to Kimi")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"Kimi API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("Kimi API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut content_buffer = String::new();
|
|
||||||
let mut has_reasoning = false;
|
|
||||||
let mut has_content = false;
|
|
||||||
let mut stream_ended = false;
|
|
||||||
|
|
||||||
let thinking_state = self.thinking_state.as_ref();
|
|
||||||
|
|
||||||
let mut byte_stream = response.bytes_stream();
|
|
||||||
let mut line_buffer = String::new();
|
|
||||||
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
|
|
||||||
while let Some(chunk) = byte_stream.next().await {
|
|
||||||
let chunk = chunk.context("Failed to read streaming response chunk")?;
|
|
||||||
let chunk_str =
|
|
||||||
String::from_utf8(chunk.to_vec()).context("Invalid UTF-8 in stream chunk")?;
|
|
||||||
|
|
||||||
line_buffer.push_str(&chunk_str);
|
|
||||||
|
|
||||||
while let Some(line_end) = line_buffer.find('\n') {
|
|
||||||
let line = line_buffer[..line_end].trim().to_string();
|
|
||||||
line_buffer = line_buffer[line_end + 1..].to_string();
|
|
||||||
|
|
||||||
if line.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if line == "data: [DONE]" {
|
|
||||||
stream_ended = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(json_str) = line.strip_prefix("data: ") {
|
|
||||||
match serde_json::from_str::<StreamChunk>(json_str) {
|
|
||||||
Ok(chunk) => {
|
|
||||||
for choice in &chunk.choices {
|
|
||||||
if let Some(ref reasoning) = choice.delta.reasoning_content
|
|
||||||
&& !reasoning.is_empty()
|
|
||||||
{
|
|
||||||
if !has_reasoning {
|
|
||||||
has_reasoning = true;
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.start_thinking();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(ref content) = choice.delta.content
|
|
||||||
&& !content.is_empty()
|
|
||||||
{
|
|
||||||
if has_reasoning
|
|
||||||
&& !has_content
|
|
||||||
&& let Some(state) = thinking_state
|
|
||||||
{
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
has_content = true;
|
|
||||||
content_buffer.push_str(content);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(ref reason) = choice.finish_reason
|
|
||||||
&& reason == "stop"
|
|
||||||
{
|
|
||||||
stream_ended = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
// 忽略无法解析的行
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if stream_ended {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 确保思考状态已结束
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = content_buffer.trim().to_string();
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
if has_reasoning && !has_content {
|
|
||||||
bail!(
|
|
||||||
"Kimi returned reasoning content but no final answer. \
|
|
||||||
The model may have entered an incomplete thinking state. \
|
|
||||||
Please try again or disable thinking mode."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bail!(
|
|
||||||
"No response from Kimi. \
|
|
||||||
If thinking mode is enabled, try disabling it or ensure the model supports it."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 可用 Kimi 模型列表
|
|
||||||
pub const KIMI_MODELS: &[&str] = &[
|
|
||||||
// K2 系列(推荐)
|
|
||||||
"kimi-k2.6",
|
|
||||||
"kimi-k2.5",
|
|
||||||
"kimi-k2-thinking",
|
|
||||||
"kimi-k2-thinking-turbo",
|
|
||||||
"kimi-k2-instruct",
|
|
||||||
"kimi-k2-instruct-0905",
|
|
||||||
// 兼容旧版模型 ID
|
|
||||||
"moonshot-v1-8k",
|
|
||||||
"moonshot-v1-32k",
|
|
||||||
"moonshot-v1-128k",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn is_valid_model(model: &str) -> bool {
|
|
||||||
KIMI_MODELS.contains(&model)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_model_validation_k2() {
|
|
||||||
assert!(is_valid_model("kimi-k2.6"));
|
|
||||||
assert!(is_valid_model("kimi-k2.5"));
|
|
||||||
assert!(is_valid_model("kimi-k2-thinking"));
|
|
||||||
assert!(is_valid_model("kimi-k2-thinking-turbo"));
|
|
||||||
assert!(is_valid_model("moonshot-v1-8k"));
|
|
||||||
assert!(is_valid_model("moonshot-v1-32k"));
|
|
||||||
assert!(is_valid_model("moonshot-v1-128k"));
|
|
||||||
assert!(!is_valid_model("invalid-model"));
|
|
||||||
assert!(!is_valid_model("kimi-k1.5"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_client_builder_defaults() {
|
|
||||||
let client = KimiClient::new("test-key", "kimi-k2.6").unwrap();
|
|
||||||
assert!(!client.thinking_enabled);
|
|
||||||
assert_eq!(client.max_tokens, 500);
|
|
||||||
assert_eq!(client.temperature, 1.0);
|
|
||||||
assert!(client.thinking_state.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_client_builder_with_thinking() {
|
|
||||||
let client = KimiClient::new("test-key", "kimi-k2.6")
|
|
||||||
.unwrap()
|
|
||||||
.with_thinking(true)
|
|
||||||
.with_max_tokens(1000)
|
|
||||||
.with_temperature(0.5);
|
|
||||||
|
|
||||||
assert!(client.thinking_enabled);
|
|
||||||
assert_eq!(client.max_tokens, 1000);
|
|
||||||
assert_eq!(client.temperature, 0.5);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_thinking_config_serialization() {
|
|
||||||
let config = ThinkingConfig {
|
|
||||||
thinking_type: "enabled".to_string(),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&config).unwrap();
|
|
||||||
assert_eq!(json, r#"{"type":"enabled"}"#);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_client_new_defaults() {
|
|
||||||
let client = KimiClient::new("test-key", "kimi-k2.6").unwrap();
|
|
||||||
assert_eq!(client.name(), "kimi");
|
|
||||||
assert!(!client.thinking_enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_message_serialization() {
|
|
||||||
let msg = Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: "Hello".to_string(),
|
|
||||||
reasoning_content: None,
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&msg).unwrap();
|
|
||||||
assert!(!json.contains("reasoning_content"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1213
src/llm/mod.rs
1213
src/llm/mod.rs
File diff suppressed because it is too large
Load Diff
@@ -1,229 +0,0 @@
|
|||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// Ollama API client
|
|
||||||
pub struct OllamaClient {
|
|
||||||
base_url: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
top_p: Option<f32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct GenerateRequest {
|
|
||||||
model: String,
|
|
||||||
prompt: String,
|
|
||||||
system: Option<String>,
|
|
||||||
stream: bool,
|
|
||||||
options: GenerationOptions,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Default)]
|
|
||||||
struct GenerationOptions {
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
num_predict: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct GenerateResponse {
|
|
||||||
response: String,
|
|
||||||
done: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ListModelsResponse {
|
|
||||||
models: Vec<ModelInfo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ModelInfo {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OllamaClient {
|
|
||||||
/// Create new Ollama client
|
|
||||||
pub fn new(base_url: &str, model: &str) -> Self {
|
|
||||||
let client =
|
|
||||||
create_http_client(Duration::from_secs(120)).expect("Failed to create HTTP client");
|
|
||||||
|
|
||||||
Self {
|
|
||||||
base_url: base_url.trim_end_matches('/').to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set timeout
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
|
||||||
self.client = create_http_client(timeout).expect("Failed to create HTTP client");
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_top_p(mut self, top_p: f32) -> Self {
|
|
||||||
self.top_p = Some(top_p);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// List available models
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
let url = format!("{}/api/tags", self.base_url);
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.get(&url)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to list Ollama models")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
anyhow::bail!("Ollama API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ListModelsResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Ollama response")?;
|
|
||||||
|
|
||||||
Ok(result.models.into_iter().map(|m| m.name).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pull a model
|
|
||||||
pub async fn pull_model(&self, model: &str) -> Result<()> {
|
|
||||||
let url = format!("{}/api/pull", self.base_url);
|
|
||||||
|
|
||||||
let request = serde_json::json!({
|
|
||||||
"name": model,
|
|
||||||
"stream": false,
|
|
||||||
});
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to pull Ollama model")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
anyhow::bail!("Ollama pull error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if model exists
|
|
||||||
pub async fn model_exists(&self, model: &str) -> bool {
|
|
||||||
match self.list_models().await {
|
|
||||||
Ok(models) => models.contains(&model.to_string()),
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for OllamaClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
self.generate_with_system("", prompt).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let url = format!("{}/api/generate", self.base_url);
|
|
||||||
|
|
||||||
let system = if system.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(system.to_string())
|
|
||||||
};
|
|
||||||
|
|
||||||
let request = GenerateRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
prompt: user.to_string(),
|
|
||||||
system,
|
|
||||||
stream: false,
|
|
||||||
options: GenerationOptions {
|
|
||||||
temperature: Some(self.temperature),
|
|
||||||
num_predict: Some(self.max_tokens),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to Ollama")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
anyhow::bail!("Ollama API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: GenerateResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Ollama response")?;
|
|
||||||
|
|
||||||
Ok(result.response.trim().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
let url = format!("{}/api/tags", self.base_url);
|
|
||||||
|
|
||||||
match self.client.get(&url).send().await {
|
|
||||||
Ok(response) => response.status().is_success(),
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"ollama"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
// These tests require a running Ollama server
|
|
||||||
#[tokio::test]
|
|
||||||
#[ignore]
|
|
||||||
async fn test_ollama_connection() {
|
|
||||||
let client = OllamaClient::new("http://localhost:11434", "llama2");
|
|
||||||
assert!(client.is_available().await);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
#[ignore]
|
|
||||||
async fn test_ollama_generate() {
|
|
||||||
let client = OllamaClient::new("http://localhost:11434", "llama2");
|
|
||||||
let response = client.generate("Hello, how are you?").await;
|
|
||||||
assert!(response.is_ok());
|
|
||||||
println!("Response: {}", response.unwrap());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,659 +0,0 @@
|
|||||||
use super::thinking::ThinkingStateManager;
|
|
||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// OpenAI API client with o-series reasoning support
|
|
||||||
pub struct OpenAiClient {
|
|
||||||
base_url: String,
|
|
||||||
api_key: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
thinking_enabled: bool,
|
|
||||||
reasoning_effort: Option<String>,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
top_p: Option<f32>,
|
|
||||||
thinking_state: Option<Arc<ThinkingStateManager>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ChatCompletionRequest {
|
|
||||||
model: String,
|
|
||||||
messages: Vec<Message>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
max_tokens: Option<u32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
top_p: Option<f32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
reasoning_effort: Option<String>,
|
|
||||||
stream: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct Message {
|
|
||||||
role: String,
|
|
||||||
content: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ChatCompletionResponse {
|
|
||||||
choices: Vec<Choice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct Choice {
|
|
||||||
message: Message,
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Streaming response structures ---
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChunk {
|
|
||||||
choices: Vec<StreamChoice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct StreamChoice {
|
|
||||||
delta: StreamDelta,
|
|
||||||
#[serde(default)]
|
|
||||||
finish_reason: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
|
||||||
struct StreamDelta {
|
|
||||||
#[serde(default)]
|
|
||||||
content: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
reasoning_content: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorResponse {
|
|
||||||
error: ApiError,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ApiError {
|
|
||||||
message: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
error_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OpenAiClient {
|
|
||||||
/// Create new OpenAI client
|
|
||||||
pub fn new(base_url: &str, api_key: &str, model: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(60))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: base_url.trim_end_matches('/').to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
reasoning_effort: None,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
|
|
||||||
self.client = create_http_client(timeout)?;
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking(mut self, enabled: bool) -> Self {
|
|
||||||
self.thinking_enabled = enabled;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_reasoning_effort(mut self, effort: Option<String>) -> Self {
|
|
||||||
self.reasoning_effort = effort;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_top_p(mut self, top_p: f32) -> Self {
|
|
||||||
self.top_p = Some(top_p);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_thinking_state(mut self, state: Arc<ThinkingStateManager>) -> Self {
|
|
||||||
self.thinking_state = Some(state);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
let url = format!("{}/models", self.base_url);
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.get(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to list OpenAI models")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
bail!("OpenAI API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelsResponse {
|
|
||||||
data: Vec<Model>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Model {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ModelsResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse OpenAI response")?;
|
|
||||||
|
|
||||||
Ok(result.data.into_iter().map(|m| m.id).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn validate_key(&self) -> Result<bool> {
|
|
||||||
match self.list_models().await {
|
|
||||||
Ok(_) => Ok(true),
|
|
||||||
Err(e) => {
|
|
||||||
let err_str = e.to_string();
|
|
||||||
if err_str.contains("401") || err_str.contains("Unauthorized") {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for OpenAiClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: prompt.to_string(),
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let mut messages = vec![];
|
|
||||||
|
|
||||||
if !system.is_empty() {
|
|
||||||
messages.push(Message {
|
|
||||||
role: "system".to_string(),
|
|
||||||
content: system.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
messages.push(Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: user.to_string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
self.chat_completion_with_retry(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
self.validate_key().await.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"openai"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OpenAiClient {
|
|
||||||
async fn chat_completion_with_retry(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let mut last_error = None;
|
|
||||||
|
|
||||||
for attempt in 1..=3 {
|
|
||||||
match self.chat_completion(messages.clone()).await {
|
|
||||||
Ok(result) => return Ok(result),
|
|
||||||
Err(e) => {
|
|
||||||
let err_msg = e.to_string();
|
|
||||||
let is_retryable = err_msg.contains("timeout")
|
|
||||||
|| err_msg.contains("connection")
|
|
||||||
|| err_msg.contains("temporary")
|
|
||||||
|| err_msg.contains("5")
|
|
||||||
&& (err_msg.contains("500")
|
|
||||||
|| err_msg.contains("502")
|
|
||||||
|| err_msg.contains("503")
|
|
||||||
|| err_msg.contains("504"));
|
|
||||||
|
|
||||||
if !is_retryable || attempt == 3 {
|
|
||||||
last_error = Some(e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_millis(500 * 2u64.pow(attempt - 1))).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("Request failed after retries")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
if self.thinking_enabled {
|
|
||||||
self.streaming_chat_completion(messages).await
|
|
||||||
} else {
|
|
||||||
self.non_streaming_chat_completion(messages).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn non_streaming_chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!("{}/chat/completions", self.base_url);
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
messages,
|
|
||||||
max_tokens: Some(self.max_tokens),
|
|
||||||
temperature: Some(self.temperature),
|
|
||||||
top_p: self.top_p,
|
|
||||||
reasoning_effort: if is_reasoning_model(&self.model) {
|
|
||||||
Some("none".to_string())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to OpenAI")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"OpenAI API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("OpenAI API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ChatCompletionResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse OpenAI response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.choices
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|c| c.message.content.trim().to_string())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No response from OpenAI"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Streaming request for reasoning mode, filters reasoning_content from output
|
|
||||||
async fn streaming_chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!("{}/chat/completions", self.base_url);
|
|
||||||
|
|
||||||
// For reasoning/thinking mode, omit temperature and top_p
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
messages,
|
|
||||||
max_tokens: Some(self.max_tokens),
|
|
||||||
temperature: None,
|
|
||||||
top_p: None,
|
|
||||||
reasoning_effort: self.reasoning_effort.clone(),
|
|
||||||
stream: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("Accept", "text/event-stream")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send streaming request to OpenAI")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"OpenAI API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("OpenAI API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut content_buffer = String::new();
|
|
||||||
let mut has_reasoning = false;
|
|
||||||
let mut has_content = false;
|
|
||||||
|
|
||||||
let thinking_state = self.thinking_state.as_ref();
|
|
||||||
|
|
||||||
let mut byte_stream = response.bytes_stream();
|
|
||||||
let mut line_buffer = String::new();
|
|
||||||
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
|
|
||||||
while let Some(chunk) = byte_stream.next().await {
|
|
||||||
let chunk = chunk.context("Failed to read streaming response chunk")?;
|
|
||||||
let chunk_str =
|
|
||||||
String::from_utf8(chunk.to_vec()).context("Invalid UTF-8 in stream chunk")?;
|
|
||||||
|
|
||||||
line_buffer.push_str(&chunk_str);
|
|
||||||
|
|
||||||
while let Some(line_end) = line_buffer.find('\n') {
|
|
||||||
let line = line_buffer[..line_end].trim().to_string();
|
|
||||||
line_buffer = line_buffer[line_end + 1..].to_string();
|
|
||||||
|
|
||||||
if line.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if line == "data: [DONE]" {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(json_str) = line.strip_prefix("data: ") {
|
|
||||||
if let Ok(chunk) = serde_json::from_str::<StreamChunk>(json_str) {
|
|
||||||
for choice in &chunk.choices {
|
|
||||||
// Handle reasoning_content (o-series)
|
|
||||||
if let Some(ref reasoning) = choice.delta.reasoning_content
|
|
||||||
&& !reasoning.is_empty()
|
|
||||||
{
|
|
||||||
if !has_reasoning {
|
|
||||||
has_reasoning = true;
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.start_thinking();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle content
|
|
||||||
if let Some(ref content) = choice.delta.content
|
|
||||||
&& !content.is_empty()
|
|
||||||
{
|
|
||||||
if has_reasoning
|
|
||||||
&& !has_content
|
|
||||||
&& let Some(state) = thinking_state
|
|
||||||
{
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
has_content = true;
|
|
||||||
content_buffer.push_str(content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(state) = thinking_state {
|
|
||||||
state.end_thinking();
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = content_buffer.trim().to_string();
|
|
||||||
|
|
||||||
if result.is_empty() {
|
|
||||||
if has_reasoning && !has_content {
|
|
||||||
bail!(
|
|
||||||
"OpenAI returned reasoning content but no final answer. \
|
|
||||||
The model may have entered an incomplete reasoning state. \
|
|
||||||
Please try again or disable thinking mode."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bail!(
|
|
||||||
"No response from OpenAI. \
|
|
||||||
If thinking mode is enabled, try disabling it or ensure the model supports reasoning."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Azure OpenAI client (extends OpenAI with Azure-specific config)
|
|
||||||
pub struct AzureOpenAiClient {
|
|
||||||
endpoint: String,
|
|
||||||
api_key: String,
|
|
||||||
deployment: String,
|
|
||||||
api_version: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
thinking_enabled: bool,
|
|
||||||
reasoning_effort: Option<String>,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
top_p: Option<f32>,
|
|
||||||
thinking_state: Option<Arc<ThinkingStateManager>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AzureOpenAiClient {
|
|
||||||
pub fn new(endpoint: &str, api_key: &str, deployment: &str, api_version: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(60))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
endpoint: endpoint.trim_end_matches('/').to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
deployment: deployment.to_string(),
|
|
||||||
api_version: api_version.to_string(),
|
|
||||||
client,
|
|
||||||
thinking_enabled: false,
|
|
||||||
reasoning_effort: None,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
thinking_state: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!(
|
|
||||||
"{}/openai/deployments/{}/chat/completions?api-version={}",
|
|
||||||
self.endpoint, self.deployment, self.api_version
|
|
||||||
);
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.deployment.clone(),
|
|
||||||
messages,
|
|
||||||
max_tokens: Some(self.max_tokens),
|
|
||||||
temperature: Some(self.temperature),
|
|
||||||
top_p: self.top_p,
|
|
||||||
reasoning_effort: self.reasoning_effort.clone(),
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.header("api-key", &self.api_key)
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to Azure OpenAI")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
bail!("Azure OpenAI API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ChatCompletionResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse Azure OpenAI response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.choices
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|c| c.message.content.trim().to_string())
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No response from Azure OpenAI"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for AzureOpenAiClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: prompt.to_string(),
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.chat_completion(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let mut messages = vec![];
|
|
||||||
|
|
||||||
if !system.is_empty() {
|
|
||||||
messages.push(Message {
|
|
||||||
role: "system".to_string(),
|
|
||||||
content: system.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
messages.push(Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: user.to_string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
self.chat_completion(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
let url = format!(
|
|
||||||
"{}/openai/deployments/{}/chat/completions?api-version={}",
|
|
||||||
self.endpoint, self.deployment, self.api_version
|
|
||||||
);
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.deployment.clone(),
|
|
||||||
messages: vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: "Hi".to_string(),
|
|
||||||
}],
|
|
||||||
max_tokens: Some(5),
|
|
||||||
temperature: Some(0.0),
|
|
||||||
top_p: None,
|
|
||||||
reasoning_effort: None,
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
match self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.header("api-key", &self.api_key)
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(response) => response.status().is_success(),
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"azure-openai"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Available OpenAI models (including o-series with reasoning)
|
|
||||||
pub const OPENAI_MODELS: &[&str] = &[
|
|
||||||
"o4-mini",
|
|
||||||
"o3",
|
|
||||||
"o3-mini",
|
|
||||||
"o1",
|
|
||||||
"o1-mini",
|
|
||||||
"o1-pro",
|
|
||||||
"gpt-4.1",
|
|
||||||
"gpt-4.1-mini",
|
|
||||||
"gpt-4.1-nano",
|
|
||||||
"gpt-4o",
|
|
||||||
"gpt-4o-mini",
|
|
||||||
"gpt-4-turbo",
|
|
||||||
"gpt-4",
|
|
||||||
"gpt-3.5-turbo",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn is_valid_model(model: &str) -> bool {
|
|
||||||
OPENAI_MODELS.contains(&model)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_reasoning_model(model: &str) -> bool {
|
|
||||||
model.starts_with("o")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_model_validation_o_series() {
|
|
||||||
assert!(is_valid_model("o4-mini"));
|
|
||||||
assert!(is_valid_model("o3"));
|
|
||||||
assert!(is_valid_model("o1"));
|
|
||||||
assert!(is_valid_model("gpt-4o"));
|
|
||||||
assert!(is_valid_model("gpt-3.5-turbo"));
|
|
||||||
assert!(!is_valid_model("invalid-model"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_stream_delta_reasoning_parsing() {
|
|
||||||
let json = r#"{"content":null,"reasoning_content":"Let me think..."}"#;
|
|
||||||
let delta: StreamDelta = serde_json::from_str(json).unwrap();
|
|
||||||
assert!(delta.content.is_none());
|
|
||||||
assert_eq!(delta.reasoning_content, Some("Let me think...".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_stream_delta_content_parsing() {
|
|
||||||
let json = r#"{"content":"Hello","reasoning_content":null}"#;
|
|
||||||
let delta: StreamDelta = serde_json::from_str(json).unwrap();
|
|
||||||
assert_eq!(delta.content, Some("Hello".to_string()));
|
|
||||||
assert!(delta.reasoning_content.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
use super::{LlmProvider, create_http_client};
|
|
||||||
use anyhow::{Context, Result, bail};
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// OpenRouter API client
|
|
||||||
pub struct OpenRouterClient {
|
|
||||||
base_url: String,
|
|
||||||
api_key: String,
|
|
||||||
model: String,
|
|
||||||
client: reqwest::Client,
|
|
||||||
max_tokens: u32,
|
|
||||||
temperature: f32,
|
|
||||||
top_p: Option<f32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
struct ChatCompletionRequest {
|
|
||||||
model: String,
|
|
||||||
messages: Vec<Message>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
max_tokens: Option<u32>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
temperature: Option<f32>,
|
|
||||||
stream: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
struct Message {
|
|
||||||
role: String,
|
|
||||||
content: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ChatCompletionResponse {
|
|
||||||
choices: Vec<Choice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct Choice {
|
|
||||||
message: Message,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorResponse {
|
|
||||||
error: ApiError,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ApiError {
|
|
||||||
message: String,
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
error_type: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OpenRouterClient {
|
|
||||||
/// Create new OpenRouter client
|
|
||||||
pub fn new(api_key: &str, model: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(60))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: "https://openrouter.ai/api/v1".to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create with custom base URL
|
|
||||||
pub fn with_base_url(api_key: &str, model: &str, base_url: &str) -> Result<Self> {
|
|
||||||
let client = create_http_client(Duration::from_secs(60))?;
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
base_url: base_url.trim_end_matches('/').to_string(),
|
|
||||||
api_key: api_key.to_string(),
|
|
||||||
model: model.to_string(),
|
|
||||||
client,
|
|
||||||
max_tokens: 500,
|
|
||||||
temperature: 0.7,
|
|
||||||
top_p: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set timeout
|
|
||||||
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
|
|
||||||
self.client = create_http_client(timeout)?;
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
|
|
||||||
self.max_tokens = max_tokens;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_temperature(mut self, temperature: f32) -> Self {
|
|
||||||
self.temperature = temperature;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_top_p(mut self, top_p: f32) -> Self {
|
|
||||||
self.top_p = Some(top_p);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// List available models
|
|
||||||
pub async fn list_models(&self) -> Result<Vec<String>> {
|
|
||||||
let url = format!("{}/models", self.base_url);
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.get(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("HTTP-Referer", "https://quicommit.dev")
|
|
||||||
.header("X-Title", "QuiCommit")
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to list OpenRouter models")?;
|
|
||||||
|
|
||||||
if !response.status().is_success() {
|
|
||||||
let status = response.status();
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
bail!("OpenRouter API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ModelsResponse {
|
|
||||||
data: Vec<Model>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Model {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ModelsResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse OpenRouter response")?;
|
|
||||||
|
|
||||||
Ok(result.data.into_iter().map(|m| m.id).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Validate API key
|
|
||||||
pub async fn validate_key(&self) -> Result<bool> {
|
|
||||||
match self.list_models().await {
|
|
||||||
Ok(_) => Ok(true),
|
|
||||||
Err(e) => {
|
|
||||||
let err_str = e.to_string();
|
|
||||||
if err_str.contains("401") || err_str.contains("Unauthorized") {
|
|
||||||
Ok(false)
|
|
||||||
} else {
|
|
||||||
Err(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LlmProvider for OpenRouterClient {
|
|
||||||
async fn generate(&self, prompt: &str) -> Result<String> {
|
|
||||||
let messages = vec![Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: prompt.to_string(),
|
|
||||||
}];
|
|
||||||
|
|
||||||
self.chat_completion(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
|
|
||||||
let mut messages = vec![];
|
|
||||||
|
|
||||||
if !system.is_empty() {
|
|
||||||
messages.push(Message {
|
|
||||||
role: "system".to_string(),
|
|
||||||
content: system.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
messages.push(Message {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: user.to_string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
self.chat_completion(messages).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_available(&self) -> bool {
|
|
||||||
self.validate_key().await.unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"openrouter"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OpenRouterClient {
|
|
||||||
async fn chat_completion(&self, messages: Vec<Message>) -> Result<String> {
|
|
||||||
let url = format!("{}/chat/completions", self.base_url);
|
|
||||||
|
|
||||||
let request = ChatCompletionRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
messages,
|
|
||||||
max_tokens: Some(self.max_tokens),
|
|
||||||
temperature: Some(self.temperature),
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = self
|
|
||||||
.client
|
|
||||||
.post(&url)
|
|
||||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("HTTP-Referer", "https://quicommit.dev")
|
|
||||||
.header("X-Title", "QuiCommit")
|
|
||||||
.json(&request)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.context("Failed to send request to OpenRouter")?;
|
|
||||||
|
|
||||||
let status = response.status();
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
let text = response.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
// Try to parse error
|
|
||||||
if let Ok(error) = serde_json::from_str::<ErrorResponse>(&text) {
|
|
||||||
bail!(
|
|
||||||
"OpenRouter API error: {} ({})",
|
|
||||||
error.error.message,
|
|
||||||
error.error.error_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bail!("OpenRouter API error: {} - {}", status, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: ChatCompletionResponse = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.context("Failed to parse OpenRouter response")?;
|
|
||||||
|
|
||||||
result
|
|
||||||
.choices
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|c| c.message.content.trim().to_string())
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("No response from OpenRouter"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Popular OpenRouter models
|
|
||||||
pub const OPENROUTER_MODELS: &[&str] = &[
|
|
||||||
"openai/gpt-3.5-turbo",
|
|
||||||
"openai/gpt-4",
|
|
||||||
"openai/gpt-4-turbo",
|
|
||||||
"anthropic/claude-3-opus",
|
|
||||||
"anthropic/claude-3-sonnet",
|
|
||||||
"anthropic/claude-3-haiku",
|
|
||||||
"google/gemini-pro",
|
|
||||||
"meta-llama/llama-2-70b-chat",
|
|
||||||
"mistralai/mixtral-8x7b-instruct",
|
|
||||||
"01-ai/yi-34b-chat",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Check if a model name is valid
|
|
||||||
pub fn is_valid_model(_model: &str) -> bool {
|
|
||||||
// Since OpenRouter supports many models, we'll allow any model name
|
|
||||||
// but provide some popular ones as suggestions
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_model_validation() {
|
|
||||||
assert!(is_valid_model("openai/gpt-4"));
|
|
||||||
assert!(is_valid_model("custom/model"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
281
src/llm/parsing.rs
Normal file
281
src/llm/parsing.rs
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
use anyhow::{Result, bail};
|
||||||
|
|
||||||
|
/// Parse commit response from LLM
|
||||||
|
pub(crate) fn parse_commit_response(
|
||||||
|
response: &str,
|
||||||
|
format: crate::config::CommitFormat,
|
||||||
|
) -> Result<GeneratedCommit> {
|
||||||
|
// Clean markdown code fences from the response
|
||||||
|
let cleaned = strip_code_fences(response);
|
||||||
|
|
||||||
|
let lines: Vec<&str> = cleaned
|
||||||
|
.lines()
|
||||||
|
.map(|l| l.trim())
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if lines.is_empty() {
|
||||||
|
let preview: String = response.chars().take(200).collect();
|
||||||
|
bail!(
|
||||||
|
"LLM returned empty or whitespace-only response. \
|
||||||
|
Raw response preview: '{}'. \
|
||||||
|
Hint: If using DeepSeek/Kimi with thinking enabled, \
|
||||||
|
the model may have returned reasoning_content only. \
|
||||||
|
Try disabling thinking mode or switching models.",
|
||||||
|
preview
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the line most likely to be the commit subject
|
||||||
|
let first_line = find_commit_subject_line(&lines, format);
|
||||||
|
|
||||||
|
// Parse based on format
|
||||||
|
match format {
|
||||||
|
crate::config::CommitFormat::Conventional => {
|
||||||
|
parse_conventional_commit(first_line, &lines, response)
|
||||||
|
}
|
||||||
|
crate::config::CommitFormat::Commitlint => {
|
||||||
|
parse_commitlint_commit(first_line, &lines, response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove surrounding markdown code fences (```) from LLM output
|
||||||
|
fn strip_code_fences(response: &str) -> String {
|
||||||
|
let mut lines: Vec<&str> = response.lines().collect();
|
||||||
|
|
||||||
|
// Strip leading fence lines (``` or ```lang)
|
||||||
|
while lines.first().map_or(false, |l| l.trim().starts_with("```")) {
|
||||||
|
lines.remove(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip trailing fence lines
|
||||||
|
while lines.last().map_or(false, |l| l.trim() == "```") {
|
||||||
|
lines.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the line that is most likely the commit subject among extracted lines
|
||||||
|
fn find_commit_subject_line<'a>(
|
||||||
|
lines: &[&'a str],
|
||||||
|
format: crate::config::CommitFormat,
|
||||||
|
) -> &'a str {
|
||||||
|
let valid_types = crate::utils::validators::get_commit_types(matches!(
|
||||||
|
format,
|
||||||
|
crate::config::CommitFormat::Commitlint
|
||||||
|
));
|
||||||
|
|
||||||
|
// First pass: line starting with a known type that also has proper syntax
|
||||||
|
// (e.g. "type:", "type(scope):", "type!:")
|
||||||
|
for &line in lines {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
for &t in valid_types {
|
||||||
|
if let Some(rest) = trimmed.strip_prefix(t) {
|
||||||
|
if rest.starts_with(':') || rest.starts_with('(') || rest.starts_with("!:") {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second pass: any line containing a colon (generic "prefix: description")
|
||||||
|
for &line in lines {
|
||||||
|
if line.contains(':') {
|
||||||
|
return line.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: return the first line as-is
|
||||||
|
lines[0].trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_conventional_commit(
|
||||||
|
first_line: &str,
|
||||||
|
lines: &[&str],
|
||||||
|
raw_response: &str,
|
||||||
|
) -> Result<GeneratedCommit> {
|
||||||
|
// Parse: type(scope)!: description
|
||||||
|
let parts: Vec<&str> = first_line.splitn(2, ':').collect();
|
||||||
|
if parts.len() != 2 {
|
||||||
|
let preview: String = raw_response.chars().take(300).collect();
|
||||||
|
bail!(
|
||||||
|
"Invalid conventional commit format: missing colon.\n\
|
||||||
|
Parsed subject line: '{}'\n\
|
||||||
|
Raw response preview: '{}'\n\
|
||||||
|
Expected: <type>[optional scope]: <description>",
|
||||||
|
first_line,
|
||||||
|
preview
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let type_part = parts[0];
|
||||||
|
let description = parts[1].trim();
|
||||||
|
|
||||||
|
// Extract type, scope, and breaking indicator
|
||||||
|
let breaking = type_part.ends_with('!');
|
||||||
|
let type_part = type_part.trim_end_matches('!');
|
||||||
|
|
||||||
|
let (commit_type, scope) = if let Some(start) = type_part.find('(') {
|
||||||
|
if let Some(end) = type_part.find(')') {
|
||||||
|
let t = &type_part[..start];
|
||||||
|
let s = &type_part[start + 1..end];
|
||||||
|
(t.to_string(), Some(s.to_string()))
|
||||||
|
} else {
|
||||||
|
bail!("Invalid scope format: missing closing parenthesis");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(type_part.to_string(), None)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extract body and footer
|
||||||
|
let (body, footer) = extract_body_footer(lines);
|
||||||
|
|
||||||
|
Ok(GeneratedCommit {
|
||||||
|
commit_type,
|
||||||
|
scope,
|
||||||
|
description: description.to_string(),
|
||||||
|
body,
|
||||||
|
footer,
|
||||||
|
breaking,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_commitlint_commit(
|
||||||
|
first_line: &str,
|
||||||
|
lines: &[&str],
|
||||||
|
raw_response: &str,
|
||||||
|
) -> Result<GeneratedCommit> {
|
||||||
|
// Similar parsing but with commitlint rules
|
||||||
|
let parts: Vec<&str> = first_line.splitn(2, ':').collect();
|
||||||
|
if parts.len() != 2 {
|
||||||
|
let preview: String = raw_response.chars().take(300).collect();
|
||||||
|
bail!(
|
||||||
|
"Invalid commit format: missing colon.\n\
|
||||||
|
Parsed subject line: '{}'\n\
|
||||||
|
Raw response preview: '{}'\n\
|
||||||
|
Expected: <type>[optional scope]: <subject>",
|
||||||
|
first_line,
|
||||||
|
preview
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let type_part = parts[0];
|
||||||
|
let subject = parts[1].trim();
|
||||||
|
|
||||||
|
let (commit_type, scope) = if let Some(start) = type_part.find('(') {
|
||||||
|
if let Some(end) = type_part.find(')') {
|
||||||
|
let t = &type_part[..start];
|
||||||
|
let s = &type_part[start + 1..end];
|
||||||
|
(t.to_string(), Some(s.to_string()))
|
||||||
|
} else {
|
||||||
|
(type_part.to_string(), None)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(type_part.to_string(), None)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (body, footer) = extract_body_footer(&lines);
|
||||||
|
|
||||||
|
Ok(GeneratedCommit {
|
||||||
|
commit_type,
|
||||||
|
scope,
|
||||||
|
description: subject.to_string(),
|
||||||
|
body,
|
||||||
|
footer,
|
||||||
|
breaking: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_body_footer(lines: &[&str]) -> (Option<String>, Option<String>) {
|
||||||
|
if lines.len() <= 1 {
|
||||||
|
return (None, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rest: Vec<&str> = lines[1..]
|
||||||
|
.iter()
|
||||||
|
.skip_while(|l| l.trim().is_empty())
|
||||||
|
.copied()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if rest.is_empty() {
|
||||||
|
return (None, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look for footer markers
|
||||||
|
let footer_markers = [
|
||||||
|
"BREAKING CHANGE:",
|
||||||
|
"Closes",
|
||||||
|
"Fixes",
|
||||||
|
"Refs",
|
||||||
|
"Co-authored-by:",
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut body_lines = vec![];
|
||||||
|
let mut footer_lines = vec![];
|
||||||
|
let mut in_footer = false;
|
||||||
|
|
||||||
|
for line in &rest {
|
||||||
|
if footer_markers.iter().any(|m| line.starts_with(m)) {
|
||||||
|
in_footer = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if in_footer {
|
||||||
|
footer_lines.push(*line);
|
||||||
|
} else {
|
||||||
|
body_lines.push(*line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let body = if body_lines.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(body_lines.join("\n"))
|
||||||
|
};
|
||||||
|
|
||||||
|
let footer = if footer_lines.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(footer_lines.join("\n"))
|
||||||
|
};
|
||||||
|
|
||||||
|
(body, footer)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generated commit structure
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct GeneratedCommit {
|
||||||
|
pub commit_type: String,
|
||||||
|
pub scope: Option<String>,
|
||||||
|
pub description: String,
|
||||||
|
pub body: Option<String>,
|
||||||
|
pub footer: Option<String>,
|
||||||
|
pub breaking: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GeneratedCommit {
|
||||||
|
/// Format as conventional commit
|
||||||
|
pub fn to_conventional(&self) -> String {
|
||||||
|
crate::utils::formatter::format_conventional_commit(
|
||||||
|
&self.commit_type,
|
||||||
|
self.scope.as_deref(),
|
||||||
|
&self.description,
|
||||||
|
self.body.as_deref(),
|
||||||
|
self.footer.as_deref(),
|
||||||
|
self.breaking,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Format as commitlint commit
|
||||||
|
pub fn to_commitlint(&self) -> String {
|
||||||
|
crate::utils::formatter::format_commitlint_commit(
|
||||||
|
&self.commit_type,
|
||||||
|
self.scope.as_deref(),
|
||||||
|
&self.description,
|
||||||
|
self.body.as_deref(),
|
||||||
|
self.footer.as_deref(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
618
src/llm/prompts.rs
Normal file
618
src/llm/prompts.rs
Normal file
@@ -0,0 +1,618 @@
|
|||||||
|
use crate::config::Language;
|
||||||
|
|
||||||
|
/// Get commit system prompt based on format and language
|
||||||
|
pub(crate) fn get_commit_system_prompt(
|
||||||
|
format: crate::config::CommitFormat,
|
||||||
|
language: Language,
|
||||||
|
) -> &'static str {
|
||||||
|
match (format, language) {
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::Chinese) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_ZH
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::Japanese) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_JA
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::Korean) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_KO
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::Spanish) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_ES
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::French) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_FR
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, Language::German) => {
|
||||||
|
CONVENTIONAL_COMMIT_SYSTEM_PROMPT_DE
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Conventional, _) => CONVENTIONAL_COMMIT_SYSTEM_PROMPT,
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::Chinese) => COMMITLINT_SYSTEM_PROMPT_ZH,
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::Japanese) => {
|
||||||
|
COMMITLINT_SYSTEM_PROMPT_JA
|
||||||
|
}
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::Korean) => COMMITLINT_SYSTEM_PROMPT_KO,
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::Spanish) => COMMITLINT_SYSTEM_PROMPT_ES,
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::French) => COMMITLINT_SYSTEM_PROMPT_FR,
|
||||||
|
(crate::config::CommitFormat::Commitlint, Language::German) => COMMITLINT_SYSTEM_PROMPT_DE,
|
||||||
|
(crate::config::CommitFormat::Commitlint, _) => COMMITLINT_SYSTEM_PROMPT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_tag_system_prompt(language: Language) -> &'static str {
|
||||||
|
match language {
|
||||||
|
Language::Chinese => TAG_MESSAGE_SYSTEM_PROMPT_ZH,
|
||||||
|
Language::Japanese => TAG_MESSAGE_SYSTEM_PROMPT_JA,
|
||||||
|
Language::Korean => TAG_MESSAGE_SYSTEM_PROMPT_KO,
|
||||||
|
Language::Spanish => TAG_MESSAGE_SYSTEM_PROMPT_ES,
|
||||||
|
Language::French => TAG_MESSAGE_SYSTEM_PROMPT_FR,
|
||||||
|
Language::German => TAG_MESSAGE_SYSTEM_PROMPT_DE,
|
||||||
|
_ => TAG_MESSAGE_SYSTEM_PROMPT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_changelog_system_prompt(language: Language) -> &'static str {
|
||||||
|
match language {
|
||||||
|
Language::Chinese => CHANGELOG_SYSTEM_PROMPT_ZH,
|
||||||
|
Language::Japanese => CHANGELOG_SYSTEM_PROMPT_JA,
|
||||||
|
Language::Korean => CHANGELOG_SYSTEM_PROMPT_KO,
|
||||||
|
Language::Spanish => CHANGELOG_SYSTEM_PROMPT_ES,
|
||||||
|
Language::French => CHANGELOG_SYSTEM_PROMPT_FR,
|
||||||
|
Language::German => CHANGELOG_SYSTEM_PROMPT_DE,
|
||||||
|
_ => CHANGELOG_SYSTEM_PROMPT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// System prompts for LLM
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT: &str = r#"You are a helpful assistant that generates conventional commit messages.
|
||||||
|
|
||||||
|
Analyze the git diff provided and generate a commit message following the Conventional Commits specification.
|
||||||
|
|
||||||
|
Format: <type>[optional scope]: <description>
|
||||||
|
|
||||||
|
Types:
|
||||||
|
- feat: A new feature
|
||||||
|
- fix: A bug fix
|
||||||
|
- docs: Documentation only changes
|
||||||
|
- style: Changes that don't affect code meaning (formatting, semicolons, etc.)
|
||||||
|
- refactor: Code change that neither fixes a bug nor adds a feature
|
||||||
|
- perf: Code change that improves performance
|
||||||
|
- test: Adding or correcting tests
|
||||||
|
- build: Changes to build system or dependencies
|
||||||
|
- ci: Changes to CI configuration
|
||||||
|
- chore: Other changes that don't modify src or test files
|
||||||
|
- revert: Reverts a previous commit
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
1. Use lowercase for type and scope
|
||||||
|
2. Keep description under 100 characters
|
||||||
|
3. Use imperative mood ("add" not "added")
|
||||||
|
4. Don't capitalize first letter
|
||||||
|
5. No period at the end
|
||||||
|
6. Include scope if the change is specific to a module/component
|
||||||
|
|
||||||
|
Output ONLY the commit message, nothing else.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成符合 Conventional Commits 规范的提交消息的助手。
|
||||||
|
|
||||||
|
分析提供的 git diff,并生成符合 Conventional Commits 规范的提交消息。
|
||||||
|
|
||||||
|
格式: <type>[可选作用域]: <描述>
|
||||||
|
|
||||||
|
类型:
|
||||||
|
- feat: 新功能
|
||||||
|
- fix: 修复错误
|
||||||
|
- docs: 仅文档更改
|
||||||
|
- style: 不影响代码含义的更改(格式化、分号等)
|
||||||
|
- refactor: 既不修复错误也不添加功能的代码更改
|
||||||
|
- perf: 提高性能的代码更改
|
||||||
|
- test: 添加或更正测试
|
||||||
|
- build: 更改构建系统或依赖项
|
||||||
|
- ci: 更改 CI 配置
|
||||||
|
- chore: 其他不修改 src 或测试文件的更改
|
||||||
|
- revert: 撤销之前的提交
|
||||||
|
|
||||||
|
规则:
|
||||||
|
1. 类型和小写使用小写
|
||||||
|
2. 描述保持在 100 个字符以内
|
||||||
|
3. 使用祈使语气("添加"而不是"已添加")
|
||||||
|
4. 不要大写首字母
|
||||||
|
5. 结尾不要句号
|
||||||
|
6. 如果更改特定于模块/组件,请包含作用域
|
||||||
|
7. 仅输出提交消息,不要输出其他内容。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_JA: &str = r#"あなたはConventional Commits仕様に従ったコミットメッセージを生成するアシスタントです。
|
||||||
|
|
||||||
|
提供されたgit diffを分析し、Conventional Commits仕様に従ったコミットメッセージを生成してください。
|
||||||
|
|
||||||
|
形式: <type>[オプションのスコープ]: <説明>
|
||||||
|
|
||||||
|
タイプ:
|
||||||
|
- feat: 新機能
|
||||||
|
- fix: バグ修正
|
||||||
|
- docs: ドキュメントのみの変更
|
||||||
|
- style: コードの意味に影響しない変更(フォーマット、セミコロンなど)
|
||||||
|
- refactor: バグ修正や機能追加を伴わないコード変更
|
||||||
|
- perf: パフォーマンスを向上させるコード変更
|
||||||
|
- test: テストの追加または修正
|
||||||
|
- build: ビルドシステムまたは依存関係の変更
|
||||||
|
- ci: CI設定の変更
|
||||||
|
- chore: srcやテストファイルを変更しないその他の変更
|
||||||
|
- revert: 以前のコミットを取り消す
|
||||||
|
|
||||||
|
ルール:
|
||||||
|
1. タイプとスコープは小文字を使用
|
||||||
|
2. 説明は100文字以内にする
|
||||||
|
3. 命令形を使用する("追加"ではなく"追加する")
|
||||||
|
4. 先頭を大文字にしない
|
||||||
|
5. 最後にピリオドを付けない
|
||||||
|
6. 変更がモジュール/コンポーネントに固有の場合はスコープを含める
|
||||||
|
7. コミットメッセージのみを出力し、それ以外は出力しないでください。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_KO: &str = r#"당신은 Conventional Commits 사양에 따른 커밋 메시지를 생성하는 도우미입니다.
|
||||||
|
|
||||||
|
제공된 git diff를 분석하고 Conventional Commits 사양에 따른 커밋 메시지를 생성하세요.
|
||||||
|
|
||||||
|
형식: <type>[선택적 범위]: <설명>
|
||||||
|
|
||||||
|
유형:
|
||||||
|
- feat: 새 기능
|
||||||
|
- fix: 버그 수정
|
||||||
|
- docs: 문서 변경만
|
||||||
|
- style: 코드 의미에 영향을 주지 않는 변경(서식, 세미콜론 등)
|
||||||
|
- refactor: 버그를 수정하거나 기능을 추가하지 않는 코드 변경
|
||||||
|
- perf: 성능을 향상시키는 코드 변경
|
||||||
|
- test: 테스트 추가 또는 수정
|
||||||
|
- build: 빌드 시스템 또는 종속성 변경
|
||||||
|
- ci: CI 구성 변경
|
||||||
|
- chore: src 또는 테스트 파일을 수정하지 않는 기타 변경
|
||||||
|
- revert: 이전 커밋 되돌리기
|
||||||
|
|
||||||
|
규칙:
|
||||||
|
1. 유형과 범위는 소문자 사용
|
||||||
|
2. 설명은 100자 이내로 유지
|
||||||
|
3. 명령형 사용("추가"가 아닌 "추가하다")
|
||||||
|
4. 첫 글자 대문자화하지 않음
|
||||||
|
5. 끝에 마침표 사용하지 않음
|
||||||
|
6. 변경 사항이 모듈/구성 요소에 특정한 경우 범위 포함
|
||||||
|
7. 커밋 메시지만 출력하고 다른 내용은 출력하지 마세요.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_ES: &str = r#"Eres un asistente que genera mensajes de commit siguiendo la especificación Conventional Commits.
|
||||||
|
|
||||||
|
Analiza el diff de git proporcionado y genera un mensaje de commit siguiendo la especificación Conventional Commits.
|
||||||
|
|
||||||
|
Formato: <tipo>[alcance opcional]: <descripción>
|
||||||
|
|
||||||
|
Tipos:
|
||||||
|
- feat: Una nueva característica
|
||||||
|
- fix: Una corrección de error
|
||||||
|
- docs: Solo cambios en documentación
|
||||||
|
- style: Cambios que no afectan el significado del código (formato, punto y coma, etc.)
|
||||||
|
- refactor: Cambio de código que no corrige un error ni agrega una característica
|
||||||
|
- perf: Cambio de código que mejora el rendimiento
|
||||||
|
- test: Agregar o corregir pruebas
|
||||||
|
- build: Cambios en el sistema de construcción o dependencias
|
||||||
|
- ci: Cambios en la configuración de CI
|
||||||
|
- chore: Otros cambios que no modifican archivos src o de prueba
|
||||||
|
- revert: Revierte un commit anterior
|
||||||
|
|
||||||
|
Reglas:
|
||||||
|
1. Usa minúsculas para tipo y alcance
|
||||||
|
2. Mantén la descripción bajo 100 caracteres
|
||||||
|
3. Usa modo imperativo ("agregar" no "agregado")
|
||||||
|
4. No capitalices la primera letra
|
||||||
|
5. Sin punto al final
|
||||||
|
6. Incluye alcance si el cambio es específico de un módulo/componente
|
||||||
|
7. Genera SOLO el mensaje de commit, nada más.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_FR: &str = r#"Vous êtes un assistant qui génère des messages de commit suivant la spécification Conventional Commits.
|
||||||
|
|
||||||
|
Analysez le diff git fourni et générez un message de commit suivant la spécification Conventional Commits.
|
||||||
|
|
||||||
|
Format: <type>[portée optionnelle]: <description>
|
||||||
|
|
||||||
|
Types:
|
||||||
|
- feat: Une nouvelle fonctionnalité
|
||||||
|
- fix: Une correction de bug
|
||||||
|
- docs: Changements de documentation uniquement
|
||||||
|
- style: Changements qui n'affectent pas la signification du code (formatage, points-virgules, etc.)
|
||||||
|
- refactor: Changement de code qui ne corrige pas un bug ni n'ajoute une fonctionnalité
|
||||||
|
- perf: Changement de code qui améliore les performances
|
||||||
|
- test: Ajout ou correction de tests
|
||||||
|
- build: Changements du système de build ou des dépendances
|
||||||
|
- ci: Changements de la configuration CI
|
||||||
|
- chore: Autres changements qui ne modifient pas les fichiers src ou de test
|
||||||
|
- revert: Révertit un commit précédent
|
||||||
|
|
||||||
|
Règles:
|
||||||
|
1. Utilisez des minuscules pour le type et la portée
|
||||||
|
2. Gardez la description sous 100 caractères
|
||||||
|
3. Utilisez le mode impératif ("ajouter" non "ajouté")
|
||||||
|
4. Ne capitalisez pas la première lettre
|
||||||
|
5. Pas de point à la fin
|
||||||
|
6. Incluez la portée si le changement est spécifique à un module/composant
|
||||||
|
7. Générez SEULEMENT le message de commit, rien d'autre.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_DE: &str = r#"Sie sind ein Assistent, der Commit-Nachrichten gemäß der Conventional Commits-Spezifikation generiert.
|
||||||
|
|
||||||
|
Analysieren Sie den bereitgestellten git diff und generieren Sie eine Commit-Nachricht gemäß der Conventional Commits-Spezifikation.
|
||||||
|
|
||||||
|
Format: <typ>[optionaler Bereich]: <beschreibung>
|
||||||
|
|
||||||
|
Typen:
|
||||||
|
- feat: Eine neue Funktion
|
||||||
|
- fix: Ein Bugfix
|
||||||
|
- docs: Nur Dokumentationsänderungen
|
||||||
|
- style: Änderungen, die die Code-Bedeutung nicht beeinflussen (Formatierung, Semikolons usw.)
|
||||||
|
- refactor: Code-Änderung, die weder einen Bug behebt noch eine Funktion hinzufügt
|
||||||
|
- perf: Code-Änderung, die die Leistung verbessert
|
||||||
|
- test: Hinzufügen oder Korrigieren von Tests
|
||||||
|
- build: Änderungen am Build-System oder Abhängigkeiten
|
||||||
|
- ci: Änderungen an der CI-Konfiguration
|
||||||
|
- chore: Andere Änderungen, die src- oder Testdateien nicht ändern
|
||||||
|
- revert: Setzt einen vorherigen Commit zurück
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
1. Verwenden Sie Kleinbuchstaben für Typ und Bereich
|
||||||
|
2. Halten Sie die Beschreibung unter 100 Zeichen
|
||||||
|
3. Verwenden Sie den Imperativ ("hinzufügen" nicht "hinzugefügt")
|
||||||
|
4. Großschreiben Sie den ersten Buchstaben nicht
|
||||||
|
5. Kein Punkt am Ende
|
||||||
|
6. Fügen Sie einen Bereich ein, wenn die Änderung spezifisch für ein Modul/Komponente ist
|
||||||
|
7. Geben Sie NUR die Commit-Nachricht aus, nichts anderes.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT: &str = r#"You are a helpful assistant that generates commit messages following @commitlint/config-conventional.
|
||||||
|
|
||||||
|
Analyze the git diff and generate a commit message.
|
||||||
|
|
||||||
|
Format: <type>[optional scope]: <subject>
|
||||||
|
|
||||||
|
Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
1. Subject should not start with uppercase
|
||||||
|
2. Subject should not end with period
|
||||||
|
3. Subject should be 4-100 characters
|
||||||
|
4. Use imperative mood
|
||||||
|
5. Be concise but descriptive
|
||||||
|
6. Output ONLY the commit message, nothing else.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成符合 @commitlint/config-conventional 规范的提交消息的助手。
|
||||||
|
|
||||||
|
分析 git diff 并生成提交消息。
|
||||||
|
|
||||||
|
格式: <type>[可选作用域]: <主题>
|
||||||
|
|
||||||
|
类型: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
规则:
|
||||||
|
1. 主题不应以大写字母开头
|
||||||
|
2. 主题不应以句号结尾
|
||||||
|
3. 主题应为 4-100 个字符
|
||||||
|
4. 使用祈使语气
|
||||||
|
5. 简洁但描述性强
|
||||||
|
6. 仅输出提交消息,不要输出其他额外内容。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_JA: &str = r#"あなたは@commitlint/config-conventionalに従ったコミットメッセージを生成するアシスタントです。
|
||||||
|
|
||||||
|
git diffを分析し、コミットメッセージを生成してください。
|
||||||
|
|
||||||
|
形式: <type>[オプションのスコープ]: <件名>
|
||||||
|
|
||||||
|
タイプ: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
ルール:
|
||||||
|
1. 件名は大文字で始めないでください
|
||||||
|
2. 件名はピリオドで終わらないでください
|
||||||
|
3. 件名は4-100文字である必要があります
|
||||||
|
4. 命令形を使用してください
|
||||||
|
5. 簡潔ですが説明的であること
|
||||||
|
6. コミットメッセージのみを出力し、それ以外は出力しないでください。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_KO: &str = r#"당신은 @commitlint/config-conventional에 따른 커밋 메시지를 생성하는 도우미입니다.
|
||||||
|
|
||||||
|
git diff를 분석하고 커밋 메시지를 생성하세요.
|
||||||
|
|
||||||
|
형식: <type>[선택적 범위]: <제목>
|
||||||
|
|
||||||
|
유형: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
규칙:
|
||||||
|
1. 제목은 대문자로 시작하지 않아야 합니다
|
||||||
|
2. 제목은 마침표로 끝나지 않아야 합니다
|
||||||
|
3. 제목은 4-100자여야 합니다
|
||||||
|
4. 명령형을 사용하세요
|
||||||
|
5. 간결하지만 설명적이어야 합니다
|
||||||
|
6. 커밋 메시지만 출력하고 다른 내용은 출력하지 마세요.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_ES: &str = r#"Eres un asistente que genera mensajes de commit siguiendo @commitlint/config-conventional.
|
||||||
|
|
||||||
|
Analiza el diff de git y genera un mensaje de commit.
|
||||||
|
|
||||||
|
Formato: <tipo>[alcance opcional]: <asunto>
|
||||||
|
|
||||||
|
Tipos: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
Reglas:
|
||||||
|
1. El asunto no debe comenzar con mayúscula
|
||||||
|
2. El asunto no debe terminar con punto
|
||||||
|
3. El asunto debe tener 4-100 caracteres
|
||||||
|
4. Usa modo imperativo
|
||||||
|
5. Sé conciso pero descriptivo
|
||||||
|
6. Genera SOLO el mensaje de commit, nada más.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_FR: &str = r#"Vous êtes un assistant qui génère des messages de commit suivant @commitlint/config-conventional.
|
||||||
|
|
||||||
|
Analysez le diff git et générez un message de commit.
|
||||||
|
|
||||||
|
Format: <type>[portée optionnelle]: <sujet>
|
||||||
|
|
||||||
|
Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
Règles:
|
||||||
|
1. Le sujet ne doit pas commencer par une majuscule
|
||||||
|
2. Le sujet ne doit pas se terminer par un point
|
||||||
|
3. Le sujet doit avoir 4-100 caractères
|
||||||
|
4. Utilisez le mode impératif
|
||||||
|
5. Soyez concis mais descriptif
|
||||||
|
6. Générez SEULEMENT le message de commit, rien d'autre.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const COMMITLINT_SYSTEM_PROMPT_DE: &str = r#"Sie sind ein Assistent, der Commit-Nachrichten gemäß @commitlint/config-conventional generiert.
|
||||||
|
|
||||||
|
Analysieren Sie den git diff und generieren Sie eine Commit-Nachricht.
|
||||||
|
|
||||||
|
Format: <typ>[optionaler Bereich]: <betreff>
|
||||||
|
|
||||||
|
Typen: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
1. Der Betreff sollte nicht mit einem Großbuchstaben beginnen
|
||||||
|
2. Der Betreff sollte nicht mit einem Punkt enden
|
||||||
|
3. Der Betreff sollte 4-100 Zeichen haben
|
||||||
|
4. Verwenden Sie den Imperativ
|
||||||
|
5. Seien Sie prägnant aber beschreibend
|
||||||
|
6. Geben Sie NUR die Commit-Nachricht aus, nichts anderes.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT: &str = r#"You are a helpful assistant that generates git tag annotation messages.
|
||||||
|
|
||||||
|
Given a version number and a list of commits, generate a concise but informative tag message.
|
||||||
|
|
||||||
|
The message should:
|
||||||
|
1. Start with a brief summary of the release
|
||||||
|
2. Group changes by type (features, fixes, etc.)
|
||||||
|
3. Be suitable for a git annotated tag
|
||||||
|
|
||||||
|
Format:
|
||||||
|
<version> Release
|
||||||
|
|
||||||
|
Summary of changes...
|
||||||
|
|
||||||
|
Changes:
|
||||||
|
- Feature: description
|
||||||
|
- Fix: description
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成 git 标签注释消息的助手。
|
||||||
|
|
||||||
|
给定版本号和提交列表,生成简洁但信息丰富的标签消息。
|
||||||
|
|
||||||
|
消息应该:
|
||||||
|
1. 以发布的简要摘要开始
|
||||||
|
2. 按类型分组更改(功能、修复等)
|
||||||
|
3. 适合 git 标注标签
|
||||||
|
|
||||||
|
格式:
|
||||||
|
<version> 发布
|
||||||
|
|
||||||
|
更改摘要...
|
||||||
|
|
||||||
|
更改:
|
||||||
|
- 功能:描述
|
||||||
|
- 修复:描述
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_JA: &str = r#"あなたはgitタグ注釈メッセージを生成するアシスタントです。
|
||||||
|
|
||||||
|
バージョン番号とコミットのリストを考慮して、簡潔ですが情報豊富なタグメッセージを生成してください。
|
||||||
|
|
||||||
|
メッセージは以下のようであるべきです:
|
||||||
|
1. リリースの簡単な要約から始める
|
||||||
|
2. タイプ別に変更をグループ化する(機能、修正など)
|
||||||
|
3. git注釈タグに適している
|
||||||
|
|
||||||
|
形式:
|
||||||
|
<version> リリース
|
||||||
|
|
||||||
|
変更の概要...
|
||||||
|
|
||||||
|
変更:
|
||||||
|
- 機能:説明
|
||||||
|
- 修正:説明
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_KO: &str = r#"당신은 git 태그 주석 메시지를 생성하는 도우미입니다.
|
||||||
|
|
||||||
|
버전 번호와 커밋 목록을 고려하여 간결하지만 정보가 풍부한 태그 메시지를 생성하세요.
|
||||||
|
|
||||||
|
메시지는 다음과 같아야 합니다:
|
||||||
|
1. 릴리스의 간단한 요약으로 시작
|
||||||
|
2. 유형별로 변경 사항 그룹화(기능, 수정 등)
|
||||||
|
3. git 주석 태그에 적합
|
||||||
|
|
||||||
|
형식:
|
||||||
|
<version> 릴리스
|
||||||
|
|
||||||
|
변경 사항 요약...
|
||||||
|
|
||||||
|
변경 사항:
|
||||||
|
- 기능: 설명
|
||||||
|
- 수정: 설명
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_ES: &str = r#"Eres un asistente que genera mensajes de anotación de etiquetas git.
|
||||||
|
|
||||||
|
Dado un número de versión y una lista de commits, genera un mensaje de etiqueta conciso pero informativo.
|
||||||
|
|
||||||
|
El mensaje debe:
|
||||||
|
1. Comenzar con un resumen breve de la versión
|
||||||
|
2. Agrupar cambios por tipo (características, correcciones, etc.)
|
||||||
|
3. Ser adecuado para una etiqueta git anotada
|
||||||
|
|
||||||
|
Formato:
|
||||||
|
<version> Versión
|
||||||
|
|
||||||
|
Resumen de cambios...
|
||||||
|
|
||||||
|
Cambios:
|
||||||
|
- Característica: descripción
|
||||||
|
- Corrección: descripción
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_FR: &str = r#"Vous êtes un assistant qui génère des messages d'annotation de balises git.
|
||||||
|
|
||||||
|
Étant donné un numéro de version et une liste de commits, générez un message de balise concis mais informatif.
|
||||||
|
|
||||||
|
Le message doit :
|
||||||
|
1. Commencer par un bref résumé de la version
|
||||||
|
2. Grouper les changements par type (fonctionnalités, corrections, etc.)
|
||||||
|
3. Être adapté à une balise git annotée
|
||||||
|
|
||||||
|
Format :
|
||||||
|
<version> Version
|
||||||
|
|
||||||
|
Résumé des changements...
|
||||||
|
|
||||||
|
Changements :
|
||||||
|
- Fonctionnalité : description
|
||||||
|
- Correction : description
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const TAG_MESSAGE_SYSTEM_PROMPT_DE: &str = r#"Sie sind ein Assistent, der git-Tag-Anmerkungsnachrichten generiert.
|
||||||
|
|
||||||
|
Gegeben eine Versionsnummer und eine Liste von Commits, generieren Sie eine prägnante aber informative Tag-Nachricht.
|
||||||
|
|
||||||
|
Die Nachricht sollte:
|
||||||
|
1. Mit einer kurzen Zusammenfassung der Version beginnen
|
||||||
|
2. Änderungen nach Typ gruppieren (Funktionen, Fixes, etc.)
|
||||||
|
3. Für ein git-annotiertes Tag geeignet sein
|
||||||
|
|
||||||
|
Format:
|
||||||
|
<version> Version
|
||||||
|
|
||||||
|
Zusammenfassung der Änderungen...
|
||||||
|
|
||||||
|
Änderungen:
|
||||||
|
- Funktion: Beschreibung
|
||||||
|
- Fix: Beschreibung
|
||||||
|
...
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT: &str = r#"You are a helpful assistant that generates changelog entries.
|
||||||
|
|
||||||
|
Given a version and a list of commits, generate a well-formatted changelog section.
|
||||||
|
|
||||||
|
Group commits by:
|
||||||
|
- Features (feat)
|
||||||
|
- Bug Fixes (fix)
|
||||||
|
- Documentation (docs)
|
||||||
|
- Other Changes
|
||||||
|
|
||||||
|
Format in markdown with proper headings and bullet points.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成变更日志条目的助手。
|
||||||
|
|
||||||
|
给定版本和提交列表,生成格式良好的变更日志部分。
|
||||||
|
|
||||||
|
按以下方式分组提交:
|
||||||
|
- 功能 (feat)
|
||||||
|
- 错误修复 (fix)
|
||||||
|
- 文档 (docs)
|
||||||
|
- 其他更改
|
||||||
|
|
||||||
|
使用适当的标题和项目符号以 markdown 格式输出。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_JA: &str = r#"あなたは変更ログエントリを生成するアシスタントです。
|
||||||
|
|
||||||
|
バージョンとコミットのリストを考慮して、適切にフォーマットされた変更ログセクションを生成してください。
|
||||||
|
|
||||||
|
コミットを以下でグループ化してください:
|
||||||
|
- 機能 (feat)
|
||||||
|
- バグ修正 (fix)
|
||||||
|
- ドキュメント (docs)
|
||||||
|
- その他の変更
|
||||||
|
|
||||||
|
適切な見出しと箇条書きを使用してmarkdown形式でフォーマットしてください。
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_KO: &str = r#"당신은 변경 로그 항목을 생성하는 도우미입니다.
|
||||||
|
|
||||||
|
버전과 커밋 목록을 고려하여 잘 포맷된 변경 로그 섹션을 생성하세요.
|
||||||
|
|
||||||
|
다음으로 커밋을 그룹화하세요:
|
||||||
|
- 기능 (feat)
|
||||||
|
- 버그 수정 (fix)
|
||||||
|
- 문서 (docs)
|
||||||
|
- 기타 변경 사항
|
||||||
|
|
||||||
|
적절한 제목과 글머리 기호를 사용하여 markdown 형식으로 포맷하세요.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_ES: &str = r#"Eres un asistente que genera entradas de registro de cambios.
|
||||||
|
|
||||||
|
Dada una versión y una lista de commits, genera una sección de registro de cambios bien formateada.
|
||||||
|
|
||||||
|
Agrupa los commits por:
|
||||||
|
- Características (feat)
|
||||||
|
- Correcciones de errores (fix)
|
||||||
|
- Documentación (docs)
|
||||||
|
- Otros cambios
|
||||||
|
|
||||||
|
Formatea en markdown con encabezados y viñetas apropiados.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_FR: &str = r#"Vous êtes un assistant qui génère des entrées de journal des modifications.
|
||||||
|
|
||||||
|
Étant donné une version et une liste de commits, générez une section de journal des modifications bien formatée.
|
||||||
|
|
||||||
|
Groupez les commits par :
|
||||||
|
- Fonctionnalités (feat)
|
||||||
|
- Corrections de bugs (fix)
|
||||||
|
- Documentation (docs)
|
||||||
|
- Autres modifications
|
||||||
|
|
||||||
|
Formatez en markdown avec des en-têtes et des puces appropriés.
|
||||||
|
"#;
|
||||||
|
|
||||||
|
const CHANGELOG_SYSTEM_PROMPT_DE: &str = r#"Sie sind ein Assistent, der Changelog-Einträge generiert.
|
||||||
|
|
||||||
|
Gegeben eine Version und eine Liste von Commits, generieren Sie einen gut formatierten Changelog-Abschnitt.
|
||||||
|
|
||||||
|
Gruppieren Sie Commits nach:
|
||||||
|
- Funktionen (feat)
|
||||||
|
- Bugfixes (fix)
|
||||||
|
- Dokumentation (docs)
|
||||||
|
- Andere Änderungen
|
||||||
|
|
||||||
|
Formatieren Sie in Markdown mit geeigneten Überschriften und Aufzählungspunkten.
|
||||||
|
"#;
|
||||||
1456
src/llm/rig/mod.rs
Normal file
1456
src/llm/rig/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
19
src/main.rs
19
src/main.rs
@@ -5,17 +5,9 @@ use clap::{Parser, Subcommand};
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
|
|
||||||
mod commands;
|
use quicommit::commands::{
|
||||||
mod config;
|
changelog::ChangelogCommand, commit::CommitCommand, config::ConfigCommand,
|
||||||
mod generator;
|
credential::CredentialCommand, init::InitCommand, profile::ProfileCommand, tag::TagCommand,
|
||||||
mod git;
|
|
||||||
mod i18n;
|
|
||||||
mod llm;
|
|
||||||
mod utils;
|
|
||||||
|
|
||||||
use commands::{
|
|
||||||
changelog::ChangelogCommand, commit::CommitCommand, config::ConfigCommand, init::InitCommand,
|
|
||||||
profile::ProfileCommand, tag::TagCommand,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// QuiCommit - AI-powered Git assistant
|
/// QuiCommit - AI-powered Git assistant
|
||||||
@@ -71,6 +63,10 @@ enum Commands {
|
|||||||
/// Manage configuration settings
|
/// Manage configuration settings
|
||||||
#[command(alias = "cfg")]
|
#[command(alias = "cfg")]
|
||||||
Config(ConfigCommand),
|
Config(ConfigCommand),
|
||||||
|
|
||||||
|
/// Git credential helper (hidden, invoked by git)
|
||||||
|
#[command(hide = true)]
|
||||||
|
Credential(CredentialCommand),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -100,5 +96,6 @@ async fn main() -> Result<()> {
|
|||||||
Commands::Changelog(cmd) => cmd.execute(config_path).await,
|
Commands::Changelog(cmd) => cmd.execute(config_path).await,
|
||||||
Commands::Profile(cmd) => cmd.execute(config_path).await,
|
Commands::Profile(cmd) => cmd.execute(config_path).await,
|
||||||
Commands::Config(cmd) => cmd.execute(config_path).await,
|
Commands::Config(cmd) => cmd.execute(config_path).await,
|
||||||
|
Commands::Credential(cmd) => cmd.execute(config_path).await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -150,11 +150,6 @@ impl KeyringManager {
|
|||||||
.set_password(token)
|
.set_password(token)
|
||||||
.context("Failed to store PAT in keyring")?;
|
.context("Failed to store PAT in keyring")?;
|
||||||
|
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] PAT stored in keyring: service={}, user={}",
|
|
||||||
keyring_service, keyring_user
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,20 +170,8 @@ impl KeyringManager {
|
|||||||
.context("Failed to create keyring entry for PAT")?;
|
.context("Failed to create keyring entry for PAT")?;
|
||||||
|
|
||||||
match entry.get_password() {
|
match entry.get_password() {
|
||||||
Ok(token) => {
|
Ok(token) => Ok(Some(token)),
|
||||||
eprintln!(
|
Err(keyring::Error::NoEntry) => Ok(None),
|
||||||
"[DEBUG] PAT retrieved from keyring: service={}, user={}",
|
|
||||||
keyring_service, keyring_user
|
|
||||||
);
|
|
||||||
Ok(Some(token))
|
|
||||||
}
|
|
||||||
Err(keyring::Error::NoEntry) => {
|
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] PAT not found in keyring: service={}, user={}",
|
|
||||||
keyring_service, keyring_user
|
|
||||||
);
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
Err(e) => Err(e.into()),
|
Err(e) => Err(e.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,11 +191,6 @@ impl KeyringManager {
|
|||||||
.delete_credential()
|
.delete_credential()
|
||||||
.context("Failed to delete PAT from keyring")?;
|
.context("Failed to delete PAT from keyring")?;
|
||||||
|
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] PAT deleted from keyring: service={}, user={}",
|
|
||||||
keyring_service, keyring_user
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,12 +207,7 @@ impl KeyringManager {
|
|||||||
services: &[String],
|
services: &[String],
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
for service in services {
|
for service in services {
|
||||||
if let Err(e) = self.delete_pat(profile_name, user_email, service) {
|
let _ = self.delete_pat(profile_name, user_email, service);
|
||||||
eprintln!(
|
|
||||||
"[DEBUG] Failed to delete PAT for service '{}': {}",
|
|
||||||
service, e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ pub fn password_input(prompt: &str) -> Result<String> {
|
|||||||
|
|
||||||
/// Check if running in a terminal
|
/// Check if running in a terminal
|
||||||
pub fn is_terminal() -> bool {
|
pub fn is_terminal() -> bool {
|
||||||
atty::is(atty::Stream::Stdout)
|
std::io::IsTerminal::is_terminal(&io::stdout())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Format duration in human-readable format
|
/// Format duration in human-readable format
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use lazy_static::lazy_static;
|
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
/// Conventional commit types
|
/// Conventional commit types
|
||||||
pub const CONVENTIONAL_TYPES: &[&str] = &[
|
pub const CONVENTIONAL_TYPES: &[&str] = &[
|
||||||
@@ -37,32 +37,33 @@ pub const COMMITLINT_TYPES: &[&str] = &[
|
|||||||
"security", // Security-related changes
|
"security", // Security-related changes
|
||||||
];
|
];
|
||||||
|
|
||||||
lazy_static! {
|
/// Regex for conventional commit format
|
||||||
/// Regex for conventional commit format
|
static CONVENTIONAL_COMMIT_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||||
static ref CONVENTIONAL_COMMIT_REGEX: Regex = Regex::new(
|
Regex::new(
|
||||||
r"^(?P<type>feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?: (?P<description>.+)$"
|
r"^(?P<type>feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?: (?P<description>.+)$",
|
||||||
).unwrap();
|
)
|
||||||
|
.unwrap()
|
||||||
|
});
|
||||||
|
|
||||||
/// Regex for scope validation
|
/// Regex for scope validation
|
||||||
static ref SCOPE_REGEX: Regex = Regex::new(
|
static SCOPE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-z0-9-]+$").unwrap());
|
||||||
r"^[a-z0-9-]+$"
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
/// Regex for version tag validation (semver)
|
/// Regex for version tag validation (semver)
|
||||||
static ref SEMVER_REGEX: Regex = Regex::new(
|
static SEMVER_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||||
r"^v?(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
|
Regex::new(
|
||||||
).unwrap();
|
r"^v?(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
});
|
||||||
|
|
||||||
/// Regex for email validation
|
/// Regex for email validation
|
||||||
static ref EMAIL_REGEX: Regex = Regex::new(
|
static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||||
r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
|
Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
|
||||||
).unwrap();
|
});
|
||||||
|
|
||||||
/// Regex for GPG key ID validation
|
/// Regex for GPG key ID validation
|
||||||
static ref GPG_KEY_ID_REGEX: Regex = Regex::new(
|
static GPG_KEY_ID_REGEX: LazyLock<Regex> =
|
||||||
r"^[A-F0-9]{16,40}$"
|
LazyLock::new(|| Regex::new(r"^[A-F0-9]{16,40}$").unwrap());
|
||||||
).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Validate conventional commit message
|
/// Validate conventional commit message
|
||||||
pub fn validate_conventional_commit(message: &str) -> Result<()> {
|
pub fn validate_conventional_commit(message: &str) -> Result<()> {
|
||||||
|
|||||||
@@ -126,31 +126,14 @@ api_key_storage = "keyring"
|
|||||||
[commit]
|
[commit]
|
||||||
format = "conventional"
|
format = "conventional"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
allow_empty = false
|
|
||||||
gpg_sign = false
|
|
||||||
max_subject_length = 100
|
|
||||||
require_scope = false
|
|
||||||
require_body = false
|
|
||||||
body_required_types = ["feat", "fix"]
|
|
||||||
|
|
||||||
[tag]
|
[tag]
|
||||||
version_prefix = "v"
|
version_prefix = "v"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
gpg_sign = false
|
|
||||||
include_changelog = true
|
|
||||||
|
|
||||||
[changelog]
|
[changelog]
|
||||||
path = "CHANGELOG.md"
|
path = "CHANGELOG.md"
|
||||||
auto_generate = true
|
auto_generate = true
|
||||||
format = "keep-a-changelog"
|
|
||||||
include_hashes = false
|
|
||||||
include_authors = false
|
|
||||||
group_by_type = true
|
|
||||||
|
|
||||||
[theme]
|
|
||||||
colors = true
|
|
||||||
icons = true
|
|
||||||
date_format = "%Y-%m-%d"
|
|
||||||
|
|
||||||
[language]
|
[language]
|
||||||
output_language = "en"
|
output_language = "en"
|
||||||
|
|||||||
1124
tests/credential_tests.rs
Normal file
1124
tests/credential_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
266
tests/gitignore_tests.rs
Normal file
266
tests/gitignore_tests.rs
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
use quicommit::git::GitRepo;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Run a git command in the given directory, returning stdout as a String.
|
||||||
|
/// Panics if the command fails.
|
||||||
|
fn git(dir: &Path, args: &[&str]) -> String {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.args(args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.output()
|
||||||
|
.expect("Failed to execute git command");
|
||||||
|
if !output.status.success() {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
panic!("git {:?} failed in {:?}: {}", args, dir, stderr);
|
||||||
|
}
|
||||||
|
String::from_utf8_lossy(&output.stdout).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize a new git repo in the given directory and configure a local
|
||||||
|
/// user identity so commits can be created.
|
||||||
|
fn init_repo(dir: &Path) {
|
||||||
|
git(dir, &["init"]);
|
||||||
|
git(dir, &["config", "user.name", "Test User"]);
|
||||||
|
git(dir, &["config", "user.email", "test@example.com"]);
|
||||||
|
// Disable commit signing in case the global config enables it.
|
||||||
|
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a file with the given content, creating parent directories as needed.
|
||||||
|
fn write_file(dir: &Path, rel_path: &str, content: &str) {
|
||||||
|
let file_path = dir.join(rel_path);
|
||||||
|
if let Some(parent) = file_path.parent() {
|
||||||
|
fs::create_dir_all(parent).expect("Failed to create parent directories");
|
||||||
|
}
|
||||||
|
fs::write(&file_path, content).expect("Failed to write file");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the list of files in the index as a String (one path per line).
|
||||||
|
fn ls_files(dir: &Path) -> String {
|
||||||
|
git(dir, &["ls-files"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Tests for is_path_ignored
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_path_ignored_with_ignored_path() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
write_file(repo_path, ".gitignore", "__pycache__/\n");
|
||||||
|
write_file(repo_path, "__pycache__/foo.pyc", "bytecode");
|
||||||
|
write_file(repo_path, "subdir/__pycache__/bar.pyc", "more bytecode");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
|
||||||
|
// Top-level ignored file
|
||||||
|
assert!(
|
||||||
|
repo.is_path_ignored("__pycache__/foo.pyc").unwrap(),
|
||||||
|
"__pycache__/foo.pyc should be ignored"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Nested ignored file under a subdirectory
|
||||||
|
assert!(
|
||||||
|
repo.is_path_ignored("subdir/__pycache__/bar.pyc").unwrap(),
|
||||||
|
"subdir/__pycache__/bar.pyc should be ignored"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_is_path_ignored_with_non_ignored_path() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
write_file(repo_path, ".gitignore", "__pycache__/\n");
|
||||||
|
write_file(repo_path, "src/main.rs", "fn main() {}");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!repo.is_path_ignored("src/main.rs").unwrap(),
|
||||||
|
"src/main.rs should not be ignored"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Tests for stage_all
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_stage_all_removes_ignored_tracked_files() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
// Create and commit __pycache__/foo.pyc so it becomes a tracked file.
|
||||||
|
write_file(repo_path, "__pycache__/foo.pyc", "original bytecode");
|
||||||
|
git(repo_path, &["add", "__pycache__/foo.pyc"]);
|
||||||
|
git(repo_path, &["commit", "-m", "initial commit"]);
|
||||||
|
|
||||||
|
// Add a .gitignore that now ignores __pycache__/.
|
||||||
|
write_file(repo_path, ".gitignore", "__pycache__/\n");
|
||||||
|
|
||||||
|
// Modify the tracked file so the working tree has unstaged changes.
|
||||||
|
write_file(repo_path, "__pycache__/foo.pyc", "modified bytecode");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
let removed = repo.stage_all().expect("stage_all should succeed");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
removed.iter().any(|f| f == "__pycache__/foo.pyc"),
|
||||||
|
"stage_all should return __pycache__/foo.pyc in removed list, got: {:?}",
|
||||||
|
removed
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify the file is no longer in the index.
|
||||||
|
let files = ls_files(repo_path);
|
||||||
|
assert!(
|
||||||
|
!files.lines().any(|l| l == "__pycache__/foo.pyc"),
|
||||||
|
"__pycache__/foo.pyc should no longer be in the index, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_stage_all_no_ignored_files_returns_empty() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
write_file(repo_path, ".gitignore", "*.log\n");
|
||||||
|
write_file(repo_path, "src/main.rs", "fn main() {}");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
let removed = repo.stage_all().expect("stage_all should succeed");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
removed.is_empty(),
|
||||||
|
"stage_all should return empty Vec when no ignored files are tracked, got: {:?}",
|
||||||
|
removed
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify src/main.rs was staged.
|
||||||
|
let files = ls_files(repo_path);
|
||||||
|
assert!(
|
||||||
|
files.lines().any(|l| l == "src/main.rs"),
|
||||||
|
"src/main.rs should be in the index, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Tests for stage_files
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_stage_files_skips_ignored_paths() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
write_file(repo_path, ".gitignore", "__pycache__/\n");
|
||||||
|
write_file(repo_path, "__pycache__/foo.pyc", "bytecode");
|
||||||
|
write_file(repo_path, "src/main.rs", "fn main() {}");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
let skipped = repo
|
||||||
|
.stage_files(&["__pycache__/foo.pyc", "src/main.rs"])
|
||||||
|
.expect("stage_files should succeed");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
skipped.iter().any(|f| f == "__pycache__/foo.pyc"),
|
||||||
|
"skipped list should contain __pycache__/foo.pyc, got: {:?}",
|
||||||
|
skipped
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!skipped.iter().any(|f| f == "src/main.rs"),
|
||||||
|
"skipped list should not contain src/main.rs, got: {:?}",
|
||||||
|
skipped
|
||||||
|
);
|
||||||
|
|
||||||
|
let files = ls_files(repo_path);
|
||||||
|
assert!(
|
||||||
|
files.lines().any(|l| l == "src/main.rs"),
|
||||||
|
"src/main.rs should be staged, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!files.lines().any(|l| l == "__pycache__/foo.pyc"),
|
||||||
|
"__pycache__/foo.pyc should not be staged, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_stage_files_all_paths_ignored() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
write_file(repo_path, ".gitignore", "__pycache__/\n");
|
||||||
|
write_file(repo_path, "__pycache__/foo.pyc", "bytecode");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
let skipped = repo
|
||||||
|
.stage_files(&["__pycache__/foo.pyc"])
|
||||||
|
.expect("stage_files should succeed");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
skipped.iter().any(|f| f == "__pycache__/foo.pyc"),
|
||||||
|
"skipped list should contain __pycache__/foo.pyc, got: {:?}",
|
||||||
|
skipped
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify the index remains empty (the file was not staged).
|
||||||
|
let files = ls_files(repo_path);
|
||||||
|
assert!(
|
||||||
|
files.trim().is_empty(),
|
||||||
|
"index should be empty, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_stage_files_normal_paths_unchanged_behavior() {
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let repo_path = temp_dir.path();
|
||||||
|
init_repo(repo_path);
|
||||||
|
|
||||||
|
// No .gitignore (or one that does not match these paths).
|
||||||
|
write_file(repo_path, "src/main.rs", "fn main() {}");
|
||||||
|
write_file(repo_path, "src/lib.rs", "pub fn lib() {}");
|
||||||
|
|
||||||
|
let repo = GitRepo::open(repo_path).expect("Failed to open repo");
|
||||||
|
let skipped = repo
|
||||||
|
.stage_files(&["src/main.rs", "src/lib.rs"])
|
||||||
|
.expect("stage_files should succeed");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
skipped.is_empty(),
|
||||||
|
"skipped list should be empty, got: {:?}",
|
||||||
|
skipped
|
||||||
|
);
|
||||||
|
|
||||||
|
let files = ls_files(repo_path);
|
||||||
|
assert!(
|
||||||
|
files.lines().any(|l| l == "src/main.rs"),
|
||||||
|
"src/main.rs should be staged, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
files.lines().any(|l| l == "src/lib.rs"),
|
||||||
|
"src/lib.rs should be staged, got: {}",
|
||||||
|
files
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user