20 Commits

Author SHA1 Message Date
349ff56299 chore(release): bump version to 0.5.0 and update changelog 2026-07-24 17:59:22 +08:00
206bde0786 fix: 修复 tag/changelog 生成范围,增加 --auto 模式
- fix(get_tags): 使用 find_object+peel_to_commit 支持 annotated tag
- fix(changelog): insert_changelog_entry 替换覆盖逻辑,保留已有章节
- feat: parse_changelog_versions 按 semver 降序提取版本
- feat: sort_tags_by_semver 取代纯时间排序
- feat(tag --auto): 优先读 Cargo.toml/pyproject.toml,回退 commit 分析
- feat(changelog): 无 --from 时自动检测 changelog 最高已有版本
- refactor: TagInfo::version_name(), GitRepo::find_tag_by_version()
2026-07-24 17:41:18 +08:00
995d263a48 feat(commit): 添加.gitignore文件过滤功能,自动跳过被忽略的文件
在自动暂存和`--all`模式下,检测并跳过被.gitignore规则匹配的文件,暂存完成后显示被移除的被忽略文件列表
2026-07-20 17:33:57 +08:00
19aff8a6c1 feat: 新增 Git credential helper 协议支持,实现 get|store|erase 子命令 2026-07-16 11:38:06 +08:00
b6bc091502 feat(commands): 添加 git credential helper 命令 2026-07-16 11:26:41 +08:00
14ebb6857a feat(commit): 添加提交消息模板支持
- 移除 config 命令中未使用的 List 子命令及相关显示字段
- 统一 ChangelogCommand 和 CommitCommand 的 ContentGenerator 初始化方式
2026-06-03 15:20:50 +08:00
459670f363 fix(llm): 修复 Kimi API temperature 参数配置 2026-06-01 17:48:42 +08:00
7636d0b5a6 feat(llm): 统一思考模式配置,支持显式禁用状态 2026-06-01 17:39:36 +08:00
928ebb61b4 refactor(llm): renumber system prompt rules 2026-05-27 15:37:51 +08:00
7e85cdd8b0 chore(release): 升级版本号至 0.3.0 2026-05-27 15:16:26 +08:00
90074e6e32 style: 格式化代码并优化导入顺序 2026-05-27 15:15:15 +08:00
b8182e7538 修复kimi返回信息的读取错误 2026-05-27 14:50:47 +08:00
4331b9306e LLM支持优化 2026-05-26 17:43:42 +08:00
a08bc809bb 修复bug 2026-05-26 16:30:28 +08:00
1063369d96 feat(deepseek): 添加 DeepSeek reasoning 模式支持 2026-05-26 16:27:49 +08:00
3a57d25a76 docs: 添加 QuiCommit 项目路线图文档 2026-05-14 17:04:13 +08:00
8152edba39 chore: 删除构建输出日志文件 2026-05-13 13:54:50 +08:00
679db5b1db chore: 清理大量未使用的变量、方法及结构体警告 2026-05-13 13:54:20 +08:00
b1ad68c7b5 build: 升级版本号至 0.2.0 2026-05-13 12:08:03 +08:00
280d6ec5c9 feat(generator): 按文件重要性对暂存差异排序 2026-05-13 12:07:01 +08:00
47 changed files with 8488 additions and 2605 deletions

6
.gitignore vendored
View File

@@ -6,6 +6,7 @@ Cargo.lock
# IDE
.idea/
.trae/
.vscode/
*.swp
*.swo
@@ -21,3 +22,8 @@ test_output/
# Config (for development)
config.toml
.claude/
CLAUDE.md
**/agents/
.scratch/
CONTEXT.md

81
AGENTS.md Normal file
View 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`.

View File

@@ -9,6 +9,70 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
暂无。
## [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
### ✨ 新功能
- 按文件重要性对暂存差异排序,优先处理核心变更
- DeepSeek 新增 reasoning 推理模式支持
- LLM 统一思考模式配置,支持显式启用/禁用思考状态
- 新增 `thinking.rs` 思考状态管理模块
### 🐞 错误修复
- 修复 Kimi 返回信息的读取错误
- 修复 DeepSeek 和 Kimi 流式响应的解析问题
### 📚 文档
- 新增 ROADMAP.md 项目路线图文档
### 🔧 其他变更
- LLM 模块大规模重构所有提供商Anthropic、DeepSeek、Kimi、Ollama、OpenAI、OpenRouter适配流式响应处理
- 代码格式化并优化导入顺序
- 清理大量未使用的变量、方法及结构体警告
- 清理构建输出日志文件
- 重新编号 LLM 系统提示规则
- i18n 多语言消息格式修复
- 各命令模块commit、tag、changelog、config、profile、init持续优化
## [0.1.11] - 2026-03-23
### ✨ 新功能

View File

@@ -1,9 +1,9 @@
[package]
name = "quicommit"
version = "0.1.11"
version = "0.5.0"
edition = "2024"
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"
repository = "https://git.lyz.one/SidneyZhang/QuiCommit"
keywords = ["git", "commit", "ai", "cli", "automation"]
@@ -33,7 +33,7 @@ git2 = "0.20.3"
which = "6.0"
# HTTP client for LLM APIs
reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false }
reqwest = { version = "0.12", features = ["json", "rustls-tls", "stream"], default-features = false }
tokio = { version = "1.35", features = ["full"] }
# Error handling
@@ -57,6 +57,7 @@ sha2 = "0.10"
hex = "0.4"
textwrap = "0.16"
async-trait = "0.1"
futures-util = "0.3"
serde_json = "1.0"
atty = "0.2"
@@ -83,11 +84,13 @@ mockall = "0.12"
wiremock = "0.6"
[profile.release]
opt-level = 3
lto = true
opt-level = "s"
lto = "thin"
codegen-units = 1
panic = "abort"
strip = true
debug = false
[profile.dev]
opt-level = 0
opt-level = 1
debug = true

122
RAODMAP.md Normal file
View File

@@ -0,0 +1,122 @@
# QuiCommit Roadmap
## 已完成 ✅
- [x] 基础 Git 操作commit、tag、changelog
- [x] AI 驱动提交信息生成Conventional Commits / commitlint 格式)
- [x] 多 LLM 提供商支持Ollama、OpenAI、Anthropic、Kimi、DeepSeek、OpenRouter
- [x] 多 Git Profile 管理SSH 密钥 + GPG 签名)
- [x] 语义化版本自动升级与 AI 发布说明
- [x] Keep a Changelog 格式自动生成
- [x] 系统密钥环安全存储 API Key
- [x] 敏感数据加密存储AES-GCM + Argon2
- [x] 交互式 CLI 预览与确认
- [x] 7 种语言国际化支持
- [x] 配置导出/导入(支持加密保护)
- [x] Profile Token 管理PAT 等)
---
## 进行中 🚧
暂无。
---
## 计划中 📋
### 1. Git 凭证管理器
将 Git 凭证管理集成到 QuiCommit 中,统一管理 HTTPS 仓库的身份认证。
- [x] **Git Credential Helper 集成**
- 实现 `git credential-store` / `git-credential-libsecret` 等标准的 credential helper 协议
- 支持 `quicommit credential get|store|erase` 子命令
- 与系统密钥环无缝对接,复用已有的 `KeyringManager`
- [x] **跨平台支持**
- Windows集成 Windows Credential Manager
- macOS集成 Keychain
- Linux通过 Secret Service / D-Bus 对接 GNOME Keyring / KWallet
- [x] **安全增强**
- 支持 PATPersonal Access Token按 scope / 有效期管理
- 支持凭证过期检查和自动提醒
---
### 2. 新增模型支持
扩展 LLM 提供商和模型覆盖范围,满足更多场景和偏好。
- [x] **新增 DeepSeek 最新模型**
- 支持 `deepseek-chat`DeepSeek-V3
- 支持 `deepseek-reasoner`DeepSeek-R1
- 支持 `deepseek-v4`
- [ ] **新增国内模型提供商**
- 通义千问 (Qwen) — 阿里云 DashScope API
- 文心一言 (ERNIE) — 百度千帆 API
- 智谱 GLM — ChatGLM API
- 百川 (Baichuan) — Baichuan API
- [ ] **新增国际模型提供商**
- Google Gemini API
- Mistral AI API
- Cohere API
- Groq (LPU 推理加速)
- [ ] **本地模型扩展**
- 支持 llama.cpp 服务端(兼容 OpenAI API 格式)
- 支持 vLLM 部署的模型
- 本地模型推荐列表与一键配置向导
- [ ] **模型能力适配**
- 不同模型的 token 限制自适应
- 模型特定的 prompt 模板优化
- 支持 function calling / tool use用于复杂生成场景
---
### 3. 生成体验优化
提升 AI 生成提交信息、标签说明和变更日志时的用户体验。
- [ ] **流式输出与实时反馈**
- [x] 支持 SSEServer-Sent Events流式生成
- [ ]终端打字机效果实时显示生成内容
- [ ]流式生成过程中支持 `Ctrl+C` 中断
- [ ] **生成质量提升**
- 基于 commitlint 规则的后校验与自动修正
- 支持 Few-shot 示例引导(用户可自定义示例库)
- 生成结果的置信度评分与多候选方案
- [ ] **Diff 上下文增强**
- 智能 diff 摘要(大改动时自动压缩关键信息)
- 支持 `.gitattributes` 排除/包含规则
- 按文件类型分组生成更精准的提交描述
- [ ] **交互式编辑增强**
- 生成后支持内联编辑(类似 `git rebase -i` 体验)
- 支持重新生成指定部分(如 scope、description
- 历史提交信息学习与风格适配
- [ ] **批量操作支持**
- 批量生成多个 commit分组暂存区变更
- `--dry-run` 预览模式(只生成本地查看,不写 Git
- [ ] **性能优化**
- API 请求并发优化(多个模型同时生成候选)
- 本地缓存常用 prompt 模板
- 减少不必要的 diff 计算
---
## 长远规划 🌟
- [ ] **VS Code 扩展** — 在 IDE 内直接使用 QuiCommit
- [ ] **GitHub Action / GitLab CI 集成** — 自动化 PR 标题和描述生成
- [ ] **团队协作** — 共享 commit 风格配置、prompt 模板库
- [ ] **Web Dashboard** — 可视化管理多仓库的 Git 活动与 AI 生成统计
- [ ] **插件系统** — 允许社区贡献自定义 LLM 提供商和生成策略

132
README.md
View File

@@ -63,7 +63,7 @@ quicommit commit
# Manual commit
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
# Skip confirmation
@@ -72,16 +72,24 @@ quicommit commit --yes
# Use date-based commit message
quicommit commit --date
# Enable LLM thinking/reasoning mode for this commit
quicommit commit --think
# Push after committing
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
```bash
# Auto-detect version bump
quicommit tag
# Auto-detect version from Cargo.toml/pyproject.toml, fall back to commit analysis
quicommit tag --auto
# Specify bump type
quicommit tag --bump minor
@@ -98,11 +106,14 @@ quicommit tag --push
### Generate Changelog
```bash
# Generate for unreleased changes
# Generate for unreleased changes (auto-detects --from from the highest version in the existing changelog)
quicommit changelog
# 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
quicommit changelog --generate
@@ -160,12 +171,69 @@ quicommit profile stats
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
```bash
# Configure Ollama (local)
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
quicommit config set-llm openai
@@ -239,6 +307,7 @@ quicommit config reset --force
| `quicommit changelog` | `cl` | Generate changelog |
| `quicommit profile` | `p` | Manage Git profiles |
| `quicommit config` | `cfg` | Manage settings |
| `quicommit credential` | — | Git credential helper (hidden, invoked by Git) |
### Commit Options
@@ -251,13 +320,14 @@ quicommit config reset --force
| `-b, --breaking` | Mark as breaking change |
| `-d, --date` | Use date-based commit message |
| `--manual` | Manual input, skip AI |
| `-a, --all` | Stage all changes |
| `-a, --all` | Stage all changes (skips `.gitignore`-matched files) |
| `-S, --sign` | GPG sign commit |
| `--amend` | Amend previous commit |
| `--dry-run` | Show without committing |
| `--conventional` | Use Conventional Commits format |
| `--commitlint` | Use commitlint format |
| `--no-verify` | Skip commit message verification |
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
| `-y, --yes` | Skip confirmation |
| `--push` | Push after committing |
| `--remote` | Specify remote repository (default: origin) |
@@ -268,6 +338,7 @@ quicommit config reset --force
|--------|-------------|
| `-n, --name` | Tag name |
| `-b, --bump` | Version bump (major/minor/patch) |
| `-A, --auto` | Auto-detect version from Cargo.toml/pyproject.toml, fall back to commit analysis (conflicts with `--bump`) |
| `-m, --message` | Tag message |
| `-g, --generate` | AI-generate message |
| `-S, --sign` | GPG sign tag |
@@ -276,6 +347,7 @@ quicommit config reset --force
| `-p, --push` | Push to remote |
| `-r, --remote` | Specify remote repository (default: origin) |
| `--dry-run` | Dry run |
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
| `-y, --yes` | Skip confirmation |
### Changelog Options
@@ -283,16 +355,16 @@ quicommit config reset --force
| Option | Description |
|--------|-------------|
| `-o, --output` | Output file path |
| `-v, --version` | Generate for specific version |
| `-f, --from` | Generate from specific tag |
| `--version` | Generate for specific version |
| `-f, --from` | Generate from specific tag (auto-detected from existing changelog if omitted) |
| `-t, --to` | Generate to specific ref (default: HEAD) |
| `-i, --init` | Initialize new changelog file |
| `-g, --generate` | AI-generate changelog |
| `--prepend` | Prepend to existing changelog |
| `--include-hashes` | Include commit hashes |
| `--include-authors` | Include authors |
| `--format` | Format (keep-a-changelog, github-releases) |
| `--dry-run` | Dry run (output to stdout) |
| `--think` | Enable LLM thinking/reasoning mode (overrides config) |
| `-y, --yes` | Skip confirmation |
## Configuration File
@@ -332,58 +404,25 @@ use_agent = true
[llm]
provider = "ollama"
model = "llama2"
# base_url = "http://localhost:11434"
max_tokens = 500
temperature = 0.7
timeout = 30
[llm.ollama]
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"
api_key_storage = "keyring"
thinking_enabled = false
[commit]
format = "conventional"
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]
version_prefix = "v"
auto_generate = true
gpg_sign = false
include_changelog = true
[changelog]
path = "CHANGELOG.md"
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]
"/path/to/work/project" = "work"
@@ -402,9 +441,6 @@ date_format = "%Y-%m-%d"
```bash
# View current configuration
quicommit config list
# Show configuration details
quicommit config show
# Edit configuration file

View File

@@ -1,10 +1,11 @@
use std::env;
fn main() {
// Only generate completions when explicitly requested
if env::var("GENERATE_COMPLETIONS").is_ok() {
println!("cargo:warning=To generate shell completions, run: cargo run --bin quicommit -- completions");
println!(
"cargo:warning=To generate shell completions, run: cargo run --bin quicommit -- completions"
);
}
// Rerun if build.rs changes

View File

@@ -46,61 +46,35 @@ use_agent = true
# LLM Configuration
[llm]
# Provider: ollama, openai, or anthropic
# Provider: ollama, openai, anthropic, kimi, deepseek, openrouter
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
temperature = 0.7
timeout = 30
# Ollama settings (local LLM)
[llm.ollama]
url = "http://localhost:11434"
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"
# API key storage: keyring, config, environment
api_key_storage = "keyring"
# Enable thinking/reasoning mode (deepseek, kimi, anthropic)
thinking_enabled = false
# Commit settings
[commit]
# Format: conventional or commitlint
format = "conventional"
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]
version_prefix = "v"
auto_generate = true
gpg_sign = false
include_changelog = true
# Changelog settings
[changelog]
path = "CHANGELOG.md"
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
# [repo_profiles]

View File

@@ -62,7 +62,7 @@ quicommit commit
# 手动提交
quicommit commit --manual -t feat -m "添加新功能"
# 暂存所有文件并提交
# 暂存所有文件并提交(自动跳过 .gitignore 匹配的文件)
quicommit commit -a
# 跳过确认直接提交
@@ -71,16 +71,24 @@ quicommit commit --yes
# 使用日期格式的提交信息
quicommit commit --date
# 为本次提交启用 LLM 思考/推理模式
quicommit commit --think
# 提交后推送到远程
quicommit commit --push
```
在暂存更改时(自动暂存或 `--all` 模式),会自动跳过匹配 `.gitignore` 规则的文件,并清理索引中已被忽略的已跟踪文件,最后打印出被跳过的文件列表。
### 创建标签
```bash
# 自动检测版本升级
quicommit tag
# 从 Cargo.toml/pyproject.toml 自动检测版本,回退到基于 commit 的分析
quicommit tag --auto
# 指定版本升级类型
quicommit tag --bump minor
@@ -97,11 +105,14 @@ quicommit tag --push
### 生成变更日志
```bash
# 生成未发布变更的变更日志
# 生成未发布变更的变更日志(未指定 --from 时自动从现有 changelog 的最高版本检测)
quicommit changelog
# 为特定版本生成
quicommit changelog -v 1.0.0
quicommit changelog --version 1.0.0
# 从指定标签生成
quicommit changelog --from v0.9.0
# AI生成变更日志
quicommit changelog --generate
@@ -159,12 +170,64 @@ quicommit profile stats
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 提示中输入了 PATGit 要求
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配置
```bash
# 配置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
quicommit config set-llm openai
@@ -238,6 +301,7 @@ quicommit config reset --force
| `quicommit changelog` | `cl` | 生成变更日志 |
| `quicommit profile` | `p` | 管理Git配置 |
| `quicommit config` | `cfg` | 管理应用配置 |
| `quicommit credential` | — | Git凭据助手隐藏由Git调用 |
### commit命令选项
@@ -250,13 +314,14 @@ quicommit config reset --force
| `-b, --breaking` | 标记为破坏性变更 |
| `-d, --date` | 使用日期格式的提交信息 |
| `--manual` | 手动输入跳过AI生成 |
| `-a, --all` | 暂存所有更改 |
| `-a, --all` | 暂存所有更改(自动跳过 `.gitignore` 匹配的文件) |
| `-S, --sign` | GPG签名提交 |
| `--amend` | 修改上一次提交 |
| `--dry-run` | 试运行,不实际提交 |
| `--conventional` | 使用Conventional Commits格式 |
| `--commitlint` | 使用commitlint格式 |
| `--no-verify` | 不验证提交信息 |
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
| `--push` | 提交后推送到远程 |
| `--remote` | 指定远程仓库默认origin |
@@ -267,6 +332,7 @@ quicommit config reset --force
|------|------|
| `-n, --name` | 标签名称 |
| `-b, --bump` | 版本升级类型major/minor/patch |
| `-A, --auto` | 从 Cargo.toml/pyproject.toml 自动检测版本,回退到基于 commit 的分析(与 `--bump` 互斥) |
| `-m, --message` | 标签信息 |
| `-g, --generate` | AI生成标签信息 |
| `-S, --sign` | GPG签名标签 |
@@ -275,6 +341,7 @@ quicommit config reset --force
| `-p, --push` | 推送到远程 |
| `-r, --remote` | 指定远程仓库默认origin |
| `--dry-run` | 试运行 |
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
### changelog命令选项
@@ -282,16 +349,16 @@ quicommit config reset --force
| 选项 | 说明 |
|------|------|
| `-o, --output` | 输出文件路径 |
| `-v, --version` | 为特定版本生成 |
| `-f, --from` | 从指定标签生成 |
| `--version` | 为特定版本生成 |
| `-f, --from` | 从指定标签生成(未指定时自动从现有 changelog 的最高版本检测) |
| `-t, --to` | 生成到指定引用默认HEAD |
| `-i, --init` | 初始化新的变更日志文件 |
| `-g, --generate` | AI生成变更日志 |
| `--prepend` | 添加到现有变更日志开头 |
| `--include-hashes` | 包含提交哈希 |
| `--include-authors` | 包含作者信息 |
| `--format` | 格式keep-a-changelog、github-releases |
| `--dry-run` | 试运行输出到stdout |
| `--think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
## 配置文件
@@ -331,58 +398,25 @@ use_agent = true
[llm]
provider = "ollama"
model = "llama2"
# base_url = "http://localhost:11434"
max_tokens = 500
temperature = 0.7
timeout = 30
[llm.ollama]
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"
api_key_storage = "keyring"
thinking_enabled = false
[commit]
format = "conventional"
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]
version_prefix = "v"
auto_generate = true
gpg_sign = false
include_changelog = true
[changelog]
path = "CHANGELOG.md"
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]
"/path/to/work/project" = "work"
@@ -401,9 +435,6 @@ date_format = "%Y-%m-%d"
```bash
# 查看当前配置
quicommit config list
# 显示配置详情
quicommit config show
# 编辑配置文件

View File

@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use chrono::Utc;
use clap::Parser;
use colored::Colorize;
@@ -7,8 +7,9 @@ use std::path::PathBuf;
use crate::config::{Language, manager::ConfigManager};
use crate::generator::ContentGenerator;
use crate::git::GitRepo;
use crate::git::find_repo;
use crate::git::{changelog::*, CommitInfo};
use crate::git::{CommitInfo, changelog::*};
use crate::i18n::{Messages, translate_changelog_category};
/// Generate changelog
@@ -55,6 +56,10 @@ pub struct ChangelogCommand {
#[arg(long)]
dry_run: bool,
/// Enable thinking mode for this changelog (override config)
#[arg(long)]
think: bool,
/// Skip interactive prompts
#[arg(short = 'y', long)]
yes: bool,
@@ -74,8 +79,9 @@ impl ChangelogCommand {
// Initialize changelog if requested
if self.init {
let path = self.output.as_ref()
.map(|p| p.clone())
let path = self
.output
.clone()
.unwrap_or_else(|| PathBuf::from(&config.changelog.path));
init_changelog(&path)?;
@@ -84,8 +90,9 @@ impl ChangelogCommand {
}
// Determine output path
let output_path = self.output.as_ref()
.map(|p| p.clone())
let output_path = self
.output
.clone()
.unwrap_or_else(|| PathBuf::from(&config.changelog.path));
// Determine format
@@ -94,7 +101,10 @@ impl ChangelogCommand {
Some("keep") | Some("keep-a-changelog") => ChangelogFormat::KeepAChangelog,
Some("custom") => ChangelogFormat::Custom,
None => ChangelogFormat::KeepAChangelog,
Some(f) => bail!("Unknown format: {}. Use: keep-a-changelog, github-releases", f),
Some(f) => bail!(
"Unknown format: {}. Use: keep-a-changelog, github-releases",
f
),
};
// Get version
@@ -111,7 +121,10 @@ impl ChangelogCommand {
// Get 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() {
bail!("{}", messages.no_commits_found());
@@ -148,7 +161,7 @@ impl ChangelogCommand {
println!("{}", "".repeat(60));
let confirm = Confirm::new()
.with_prompt(&messages.write_to_file(&format!("{:?}", output_path)))
.with_prompt(messages.write_to_file(&format!("{:?}", output_path)))
.default(true)
.interact()?;
@@ -158,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() {
let existing = std::fs::read_to_string(&output_path)?;
let new_content = if existing.is_empty() {
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 {
format!("{}{}", CHANGELOG_HEADER, changelog)
insert_changelog_entry(&existing, &changelog)
};
std::fs::write(&output_path, new_content)?;
} else {
@@ -197,6 +190,28 @@ impl ChangelogCommand {
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(
&self,
version: &str,
@@ -208,8 +223,10 @@ impl ChangelogCommand {
println!("{}", messages.ai_generating_changelog());
let generator = ContentGenerator::new(&manager).await?;
generator.generate_changelog_entry(version, commits, language).await
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
generator
.generate_changelog_entry(version, commits, language)
.await
}
fn generate_with_template(
@@ -237,12 +254,13 @@ impl ChangelogCommand {
}
fn translate_changelog_categories(&self, changelog: &str, language: Language) -> String {
let translated = changelog
changelog
.lines()
.map(|line| {
if line.starts_with("## ") || line.starts_with("### ") {
let category = line.trim_start_matches("## ").trim_start_matches("### ");
let translated_category = translate_changelog_category(category, language, false);
let translated_category =
translate_changelog_category(category, language, false);
if line.starts_with("## ") {
format!("## {}", translated_category)
} else {
@@ -253,7 +271,6 @@ impl ChangelogCommand {
}
})
.collect::<Vec<_>>()
.join("\n");
translated
.join("\n")
}
}

View File

@@ -1,14 +1,14 @@
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result, bail};
use clap::Parser;
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
use std::path::PathBuf;
use crate::config::{Language, manager::ConfigManager};
use crate::config::CommitFormat;
use crate::config::{Language, manager::ConfigManager};
use crate::generator::ContentGenerator;
use crate::git::{find_repo, GitRepo};
use crate::git::commit::{CommitBuilder, create_date_commit_message};
use crate::git::{GitRepo, find_repo};
use crate::i18n::Messages;
use crate::utils::validators::get_commit_types;
@@ -71,6 +71,10 @@ pub struct CommitCommand {
#[arg(long)]
no_verify: bool,
/// Enable thinking mode for this commit (override config)
#[arg(short = 't', long)]
think: bool,
/// Skip interactive prompts
#[arg(short = 'y', long)]
yes: bool,
@@ -117,8 +121,17 @@ impl CommitCommand {
// 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 {
println!("{}", messages.auto_stage_changes().yellow());
repo.stage_all()?;
let removed = repo.stage_all()?;
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
let new_status = repo.status_summary()?;
@@ -129,8 +142,17 @@ impl CommitCommand {
// Stage all if requested
if self.all {
repo.stage_all()?;
let removed = repo.stage_all()?;
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
@@ -179,14 +201,22 @@ impl CommitCommand {
let result = if self.amend {
if self.dry_run {
println!("\n{} {}", messages.dry_run(), "- commit not amended.".yellow());
println!(
"\n{} {}",
messages.dry_run(),
"- commit not amended.".yellow()
);
return Ok(());
}
self.amend_commit(&repo, &commit_message)?;
None
} else {
if self.dry_run {
println!("\n{} {}", messages.dry_run(), "- commit not created.".yellow());
println!(
"\n{} {}",
messages.dry_run(),
"- commit not created.".yellow()
);
return Ok(());
}
CommitBuilder::new()
@@ -196,9 +226,13 @@ impl CommitCommand {
};
if let Some(commit_oid) = result {
println!("{} {}", messages.commit_created().green().bold(), commit_oid.to_string()[..8].to_string().cyan());
println!(
"{} {}",
messages.commit_created().green().bold(),
commit_oid.to_string()[..8].to_string().cyan()
);
} else {
println!("{} {}", messages.commit_amended().green().bold(), "successfully");
println!("{} successfully", messages.commit_amended().green().bold());
}
// Push after commit if requested or ask user
@@ -228,8 +262,9 @@ impl CommitCommand {
}
fn create_manual_commit(&self, format: CommitFormat) -> Result<String> {
let description = self.message.clone()
.ok_or_else(|| anyhow::anyhow!("Description required for manual commit. Use -m <message>"))?;
let description = self.message.clone().ok_or_else(|| {
anyhow::anyhow!("Description required for manual commit. Use -m <message>")
})?;
// Try to extract commit type from message if not provided
let commit_type = if let Some(ref ct) = self.commit_type {
@@ -255,10 +290,20 @@ impl CommitCommand {
builder.build_message()
}
async fn generate_commit(&self, repo: &GitRepo, format: CommitFormat, messages: &Messages) -> Result<String> {
async fn generate_commit(
&self,
repo: &GitRepo,
format: CommitFormat,
messages: &Messages,
) -> Result<String> {
let manager = ConfigManager::new()?;
let generator = ContentGenerator::new(&manager).await
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
.context("Failed to initialize LLM. Use --manual for manual commit.")?;
println!("{}", messages.ai_analyzing());
@@ -266,15 +311,23 @@ impl CommitCommand {
let language = manager.get_language().unwrap_or(Language::English);
let generated = if self.yes {
generator.generate_commit_from_repo(repo, format, language).await?
generator
.generate_commit_from_repo(repo, format, language)
.await?
} else {
generator.generate_commit_interactive(repo, format, language).await?
generator
.generate_commit_interactive(repo, format, language)
.await?
};
Ok(generated.to_conventional())
}
async fn create_interactive_commit(&self, format: CommitFormat, messages: &Messages) -> Result<String> {
async fn create_interactive_commit(
&self,
format: CommitFormat,
messages: &Messages,
) -> Result<String> {
let types = get_commit_types(format == CommitFormat::Commitlint);
// Select type
@@ -358,7 +411,8 @@ impl CommitCommand {
"GPG signing failed. Please check:\n\
1. GPG signing key is configured (git config --get user.signingkey)\n\
2. GPG agent is running\n\
3. You can sign commits manually (try: git commit --amend -S)".to_string()
3. You can sign commits manually (try: git commit --amend -S)"
.to_string()
} else {
stdout.to_string()
}

View File

@@ -1,13 +1,15 @@
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use colored::Colorize;
use dialoguer::{Confirm, Input, Select, Password};
use dialoguer::{Confirm, Input, Password, Select};
use std::path::PathBuf;
use crate::config::{Language, manager::ConfigManager, ExportData, EncryptedPat};
use crate::config::CommitFormat;
use crate::utils::keyring::{get_supported_providers, get_default_model, get_default_base_url, provider_needs_api_key};
use crate::utils::crypto::{encrypt, decrypt};
use crate::config::{EncryptedPat, ExportData, Language, manager::ConfigManager};
use crate::utils::crypto::{decrypt, encrypt};
use crate::utils::keyring::{
get_default_base_url, get_default_model, get_supported_providers, provider_needs_api_key,
};
/// Mask API key with asterisks for security
fn mask_api_key(key: Option<&str>) -> String {
@@ -35,9 +37,6 @@ enum ConfigSubcommand {
/// Show current configuration
Show,
/// List all configuration information (with masked API keys)
List,
/// Edit configuration file
Edit,
@@ -165,24 +164,56 @@ impl ConfigCommand {
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
match &self.command {
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::Set { key, value }) => self.set_value(key, value, &config_path).await,
Some(ConfigSubcommand::Set { key, value }) => {
self.set_value(key, value, &config_path).await
}
Some(ConfigSubcommand::Get { key }) => self.get_value(key, &config_path).await,
Some(ConfigSubcommand::SetLlm { provider, model, base_url, api_key }) => {
self.set_llm(provider.as_deref(), model.as_deref(), base_url.as_deref(), api_key.as_deref(), &config_path).await
Some(ConfigSubcommand::SetLlm {
provider,
model,
base_url,
api_key,
}) => {
self.set_llm(
provider.as_deref(),
model.as_deref(),
base_url.as_deref(),
api_key.as_deref(),
&config_path,
)
.await
}
Some(ConfigSubcommand::SetApiKey { key }) => self.set_api_key(key, &config_path).await,
Some(ConfigSubcommand::DeleteApiKey) => self.delete_api_key(&config_path).await,
Some(ConfigSubcommand::SetCommitFormat { format }) => self.set_commit_format(format, &config_path).await,
Some(ConfigSubcommand::SetVersionPrefix { prefix }) => self.set_version_prefix(prefix, &config_path).await,
Some(ConfigSubcommand::SetChangelogPath { path }) => self.set_changelog_path(path, &config_path).await,
Some(ConfigSubcommand::SetLanguage { language }) => self.set_language(language.as_deref(), &config_path).await,
Some(ConfigSubcommand::SetKeepTypesEnglish { keep }) => self.set_keep_types_english(*keep, &config_path).await,
Some(ConfigSubcommand::SetKeepChangelogTypesEnglish { keep }) => self.set_keep_changelog_types_english(*keep, &config_path).await,
Some(ConfigSubcommand::SetCommitFormat { format }) => {
self.set_commit_format(format, &config_path).await
}
Some(ConfigSubcommand::SetVersionPrefix { prefix }) => {
self.set_version_prefix(prefix, &config_path).await
}
Some(ConfigSubcommand::SetChangelogPath { path }) => {
self.set_changelog_path(path, &config_path).await
}
Some(ConfigSubcommand::SetLanguage { language }) => {
self.set_language(language.as_deref(), &config_path).await
}
Some(ConfigSubcommand::SetKeepTypesEnglish { keep }) => {
self.set_keep_types_english(*keep, &config_path).await
}
Some(ConfigSubcommand::SetKeepChangelogTypesEnglish { keep }) => {
self.set_keep_changelog_types_english(*keep, &config_path)
.await
}
Some(ConfigSubcommand::Reset { force }) => self.reset(*force, &config_path).await,
Some(ConfigSubcommand::Export { output, password }) => self.export_config(output.as_deref(), password.as_deref(), &config_path).await,
Some(ConfigSubcommand::Import { file, password }) => self.import_config(file, password.as_deref(), &config_path).await,
Some(ConfigSubcommand::Export { output, password }) => {
self.export_config(output.as_deref(), password.as_deref(), &config_path)
.await
}
Some(ConfigSubcommand::Import { file, password }) => {
self.import_config(file, password.as_deref(), &config_path)
.await
}
Some(ConfigSubcommand::ListModels) => self.list_models(&config_path).await,
Some(ConfigSubcommand::TestLlm) => self.test_llm(&config_path).await,
Some(ConfigSubcommand::Path) => self.show_path(&config_path).await,
@@ -246,8 +277,10 @@ impl ConfigCommand {
println!("\n{}", "General:".bold());
println!(" Config file: {}", manager.path().display());
println!(" Default profile: {}",
config.default_profile.as_deref().unwrap_or("(none)").cyan());
println!(
" Default profile: {}",
config.default_profile.as_deref().unwrap_or("(none)").cyan()
);
println!(" Profiles: {}", config.profiles.len());
println!("\n{}", "LLM Configuration:".bold());
@@ -266,103 +299,67 @@ impl ConfigCommand {
println!("\n{}", "Commit Configuration:".bold());
println!(" Format: {}", config.commit.format.to_string().cyan());
println!(" Auto-generate: {}", if config.commit.auto_generate { "yes".green() } else { "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!(
" Auto-generate: {}",
if config.commit.auto_generate {
"yes".green()
} else {
"no".red()
}
);
println!("\n{}", "Tag Configuration:".bold());
println!(" Version prefix: '{}'", config.tag.version_prefix);
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!(
" Auto-generate: {}",
if config.tag.auto_generate {
"yes".green()
} else {
"no".red()
}
);
println!("\n{}", "Language Configuration:".bold());
let language = manager.get_language().unwrap_or(Language::English);
println!(" Output language: {}", language.display_name().cyan());
println!(" Keep commit types in English: {}", if manager.keep_types_english() { "yes".green() } else { "no".red() });
println!(" Keep changelog types in English: {}", if manager.keep_changelog_types_english() { "yes".green() } else { "no".red() });
println!(
" Keep commit types in English: {}",
if manager.keep_types_english() {
"yes".green()
} else {
"no".red()
}
);
println!(
" Keep changelog types in English: {}",
if manager.keep_changelog_types_english() {
"yes".green()
} else {
"no".red()
}
);
println!("\n{}", "Changelog Configuration:".bold());
println!(" Path: {}", config.changelog.path);
println!(" Auto-generate: {}", if config.changelog.auto_generate { "yes".green() } else { "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(())
}
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!(" Default profile: {}",
config.default_profile.as_deref().unwrap_or("(none)").cyan());
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 { "✗ no".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());
println!(
" Auto-generate: {}",
if config.changelog.auto_generate {
"yes".green()
} else {
println!(" Status: {}", "✗ unavailable".red());
println!(" Note: {}", keyring.get_status_message());
"no".red()
}
);
println!("\n{}", "Security:".bold());
println!(" Repository mappings: {} mapping(s)", config.repo_profiles.len());
println!(
" Keyring: {}",
if manager.keyring().is_available() {
"available".green()
} else {
"unavailable".red()
}
);
Ok(())
}
@@ -393,8 +390,15 @@ impl ConfigCommand {
let timeout: u64 = value.parse()?;
manager.config_mut().llm.timeout = timeout;
}
"llm.thinking_enabled" => {
manager.config_mut().llm.thinking_enabled = value == "true";
}
"llm.thinking_budget_tokens" => {
let budget: u32 = value.parse()?;
manager.config_mut().llm.thinking_budget_tokens = Some(budget);
}
"llm.api_key_storage" => {
let valid_values = vec!["keyring", "config", "environment"];
let valid_values = ["keyring", "config", "environment"];
if !valid_values.contains(&value) {
bail!("Invalid value: {}. Use: {}", value, valid_values.join(", "));
}
@@ -412,7 +416,22 @@ impl ConfigCommand {
manager.set_auto_generate_commits(value == "true");
}
"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.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),
}
@@ -433,11 +452,24 @@ impl ConfigCommand {
"llm.max_tokens" => config.llm.max_tokens.to_string(),
"llm.temperature" => config.llm.temperature.to_string(),
"llm.timeout" => config.llm.timeout.to_string(),
"llm.thinking_enabled" => config.llm.thinking_enabled.to_string(),
"llm.thinking_budget_tokens" => config
.llm
.thinking_budget_tokens
.map(|v| v.to_string())
.unwrap_or_else(|| "none".to_string()),
"llm.api_key_storage" => config.llm.api_key_storage.clone(),
"commit.format" => config.commit.format.to_string(),
"commit.auto_generate" => config.commit.auto_generate.to_string(),
"tag.version_prefix" => config.tag.version_prefix.clone(),
"tag.auto_generate" => config.tag.auto_generate.to_string(),
"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),
};
@@ -445,13 +477,24 @@ impl ConfigCommand {
Ok(())
}
async fn set_llm(&self, provider: Option<&str>, model: Option<&str>, base_url: Option<&str>, api_key: Option<&str>, config_path: &Option<PathBuf>) -> Result<()> {
async fn set_llm(
&self,
provider: Option<&str>,
model: Option<&str>,
base_url: Option<&str>,
api_key: Option<&str>,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
let selected_provider = if let Some(p) = provider {
let providers = get_supported_providers();
if !providers.contains(&p) {
bail!("Invalid provider: {}. Valid options: {}", p, providers.join(", "));
bail!(
"Invalid provider: {}. Valid options: {}",
p,
providers.join(", ")
);
}
p.to_string()
} else {
@@ -462,7 +505,7 @@ impl ConfigCommand {
"Anthropic Claude",
"Kimi (Moonshot AI)",
"DeepSeek",
"OpenRouter"
"OpenRouter",
];
let provider_idx = Select::new()
@@ -478,7 +521,10 @@ impl ConfigCommand {
let keyring_available = keyring.is_available();
if !keyring_available && provider_needs_api_key(&selected_provider) {
println!("\n{}", "⚠ Keyring is not available on this system.".yellow());
println!(
"\n{}",
"⚠ Keyring is not available on this system.".yellow()
);
println!("{}", keyring.get_status_message().yellow());
}
@@ -530,21 +576,20 @@ impl ConfigCommand {
.interact()?;
if overwrite {
let key: String = Input::new()
.with_prompt("API key")
.interact_text()?;
let key: String = Input::new().with_prompt("API key").interact_text()?;
Some(key)
} else {
None
}
} else {
let key: String = Input::new()
.with_prompt("API key")
.interact_text()?;
let key: String = Input::new().with_prompt("API key").interact_text()?;
Some(key)
}
} else {
println!("\n{}", "Please set the QUICOMMIT_API_KEY environment variable.".yellow());
println!(
"\n{}",
"Please set the QUICOMMIT_API_KEY environment variable.".yellow()
);
None
}
} else {
@@ -557,7 +602,10 @@ impl ConfigCommand {
if let Some(key) = selected_api_key {
manager.set_api_key(&key)?;
println!("\n{} API key stored securely in system keyring", "".green());
println!(
"\n{} API key stored securely in system keyring",
"".green()
);
}
manager.save()?;
@@ -584,22 +632,38 @@ impl ConfigCommand {
match storage_method.as_str() {
"keyring" => {
if !manager.keyring().is_available() {
bail!("Keyring is not available. Set QUICOMMIT_API_KEY environment variable instead or change api_key_storage to 'config'.");
bail!(
"Keyring is not available. Set QUICOMMIT_API_KEY environment variable instead or change api_key_storage to 'config'."
);
}
manager.set_api_key(key)?;
println!("{} API key stored securely in system keyring for {}", "".green(), provider.cyan());
},
println!(
"{} API key stored securely in system keyring for {}",
"".green(),
provider.cyan()
);
}
"config" => {
// Store API key directly in config file
manager.config_mut().llm.api_key = Some(key.to_string());
manager.save()?;
println!("{} API key stored in configuration file for {}", "".green(), provider.cyan());
println!("{} Note: API key is stored in plain text. Consider using 'keyring' storage for better security.", "".yellow());
},
println!(
"{} API key stored in configuration file for {}",
"".green(),
provider.cyan()
);
println!(
"{} Note: API key is stored in plain text. Consider using 'keyring' storage for better security.",
"".yellow()
);
}
"environment" => {
bail!("API key storage set to 'environment'. Please set QUICOMMIT_{}_API_KEY environment variable.", provider.to_uppercase());
},
bail!(
"API key storage set to 'environment'. Please set QUICOMMIT_{}_API_KEY environment variable.",
provider.to_uppercase()
);
}
_ => {
bail!("Invalid API key storage method: {}", storage_method);
}
@@ -621,17 +685,29 @@ impl ConfigCommand {
}
manager.delete_api_key()?;
println!("{} API key deleted from system keyring for {}", "".green(), provider.cyan());
},
println!(
"{} API key deleted from system keyring for {}",
"".green(),
provider.cyan()
);
}
"config" => {
// Remove API key from config file
manager.config_mut().llm.api_key = None;
manager.save()?;
println!("{} API key deleted from configuration file for {}", "".green(), provider.cyan());
},
println!(
"{} API key deleted from configuration file for {}",
"".green(),
provider.cyan()
);
}
"environment" => {
println!("{} API key storage set to 'environment'. Please remove QUICOMMIT_{}_API_KEY environment variable manually.", "".blue(), provider.to_uppercase());
},
println!(
"{} API key storage set to 'environment'. Please remove QUICOMMIT_{}_API_KEY environment variable manually.",
"".blue(),
provider.to_uppercase()
);
}
_ => {
bail!("Invalid API key storage method: {}", storage_method);
}
@@ -652,7 +728,11 @@ impl ConfigCommand {
manager.set_commit_format(format);
manager.save()?;
println!("{} Commit format set to {}", "".green(), format.to_string().cyan());
println!(
"{} Commit format set to {}",
"".green(),
format.to_string().cyan()
);
Ok(())
}
@@ -674,14 +754,18 @@ impl ConfigCommand {
Ok(())
}
async fn set_language(&self, language: Option<&str>, config_path: &Option<PathBuf>) -> Result<()> {
async fn set_language(
&self,
language: Option<&str>,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
let lang_code = if let Some(l) = language {
l.to_string()
} else {
println!("{}", "Select Output Language:".bold());
let languages = vec![
let languages = [
("en", "English"),
("zh", "中文"),
("ja", "日本語"),
@@ -692,10 +776,7 @@ impl ConfigCommand {
];
let lang_names: Vec<&str> = languages.iter().map(|(_, n)| *n).collect();
let idx = Select::new()
.items(&lang_names)
.default(0)
.interact()?;
let idx = Select::new().items(&lang_names).default(0).interact()?;
languages[idx].0.to_string()
};
@@ -703,25 +784,45 @@ impl ConfigCommand {
manager.set_output_language(lang_code.clone());
manager.save()?;
println!("{} Output language set to {}", "".green(), lang_code.cyan());
println!(
"{} Output language set to {}",
"".green(),
lang_code.cyan()
);
Ok(())
}
async fn set_keep_types_english(&self, keep: bool, config_path: &Option<PathBuf>) -> Result<()> {
async fn set_keep_types_english(
&self,
keep: bool,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
manager.set_keep_types_english(keep);
manager.save()?;
println!("{} Keep commit types in English: {}", "".green(), keep.to_string().cyan());
println!(
"{} Keep commit types in English: {}",
"".green(),
keep.to_string().cyan()
);
Ok(())
}
async fn set_keep_changelog_types_english(&self, keep: bool, config_path: &Option<PathBuf>) -> Result<()> {
async fn set_keep_changelog_types_english(
&self,
keep: bool,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
manager.set_keep_changelog_types_english(keep);
manager.save()?;
println!("{} Keep changelog types in English: {}", "".green(), keep.to_string().cyan());
println!(
"{} Keep changelog types in English: {}",
"".green(),
keep.to_string().cyan()
);
Ok(())
}
@@ -746,7 +847,12 @@ impl ConfigCommand {
Ok(())
}
async fn export_config(&self, output: Option<&str>, password: Option<&str>, config_path: &Option<PathBuf>) -> Result<()> {
async fn export_config(
&self,
output: Option<&str>,
password: Option<&str>,
config_path: &Option<PathBuf>,
) -> Result<()> {
let manager = self.get_manager(config_path)?;
let toml = manager.export()?;
@@ -788,9 +894,20 @@ impl ConfigCommand {
}
if has_pats {
println!("{} {}", "".yellow(), "WARNING: Exporting without encryption.".bold());
println!(" {}", "Personal Access Tokens (PATs) stored in keyring will NOT be exported.".yellow());
println!(" {}", "To export PATs securely, please enable encryption.".yellow());
println!(
"{} {}",
"".yellow(),
"WARNING: Exporting without encryption.".bold()
);
println!(
" {}",
"Personal Access Tokens (PATs) stored in keyring will NOT be exported."
.yellow()
);
println!(
" {}",
"To export PATs securely, please enable encryption.".yellow()
);
println!();
}
@@ -800,7 +917,9 @@ impl ConfigCommand {
for (profile_name, profile) in manager.config().profiles.iter() {
for service in profile.tokens.keys() {
if let Ok(Some(pat_value)) = manager.get_pat_for_profile(profile_name, service) {
if let Ok(Some(pat_value)) =
manager.get_pat_for_profile(profile_name, service)
{
let encrypted_token = encrypt(pat_value.as_bytes(), &pwd)?;
encrypted_pats.push(EncryptedPat {
profile_name: profile_name.clone(),
@@ -826,7 +945,11 @@ impl ConfigCommand {
Some(path) => {
std::fs::write(path, &export_content)?;
if export_content.starts_with("ENCRYPTED:") {
println!("{} Configuration encrypted and exported to {}", "".green(), path);
println!(
"{} Configuration encrypted and exported to {}",
"".green(),
path
);
} else {
println!("{} Configuration exported to {}", "".green(), path);
}
@@ -839,7 +962,12 @@ impl ConfigCommand {
Ok(())
}
async fn import_config(&self, file: &str, password: Option<&str>, config_path: &Option<PathBuf>) -> Result<()> {
async fn import_config(
&self,
file: &str,
password: Option<&str>,
config_path: &Option<PathBuf>,
) -> Result<()> {
let content = std::fs::read_to_string(file)?;
let (config_content, encrypted_pats, pwd) = if content.starts_with("ENCRYPTED:") {
@@ -856,7 +984,10 @@ impl ConfigCommand {
let decrypted = match decrypt(encrypted_data, &pwd) {
Ok(d) => d,
Err(e) => {
bail!("Failed to decrypt configuration: {}. Please check your password.", e);
bail!(
"Failed to decrypt configuration: {}. Please check your password.",
e
);
}
};
@@ -864,12 +995,12 @@ impl ConfigCommand {
.map_err(|e| anyhow::anyhow!("Invalid UTF-8 in decrypted content: {}", e))?;
match serde_json::from_str::<ExportData>(&decrypted_str) {
Ok(export_data) => {
(export_data.config, Some(export_data.encrypted_pats), Some(pwd))
}
Err(_) => {
(decrypted_str, None, Some(pwd))
}
Ok(export_data) => (
export_data.config,
Some(export_data.encrypted_pats),
Some(pwd),
),
Err(_) => (decrypted_str, None, Some(pwd)),
}
} else {
(content, None, None)
@@ -879,8 +1010,9 @@ impl ConfigCommand {
manager.import(&config_content)?;
manager.save()?;
if let (Some(pats), Some(pwd)) = (encrypted_pats, pwd) {
if !pats.is_empty() {
if let (Some(pats), Some(pwd)) = (encrypted_pats, pwd)
&& !pats.is_empty()
{
println!();
println!("{}", "Importing Personal Access Tokens...".bold());
@@ -889,55 +1021,63 @@ impl ConfigCommand {
for pat in pats {
match decrypt(&pat.encrypted_token, &pwd) {
Ok(token_bytes) => {
match String::from_utf8(token_bytes) {
Ok(token_bytes) => match String::from_utf8(token_bytes) {
Ok(token_value) => {
if manager.keyring().is_available() {
match manager.store_pat_for_profile(
&pat.profile_name,
&pat.service,
&token_value
&token_value,
) {
Ok(_) => {
println!(" {} Token for {} ({}) imported to keyring",
println!(
" {} Token for {} ({}) imported to keyring",
"".green(),
pat.profile_name.cyan(),
pat.service.yellow());
pat.service.yellow()
);
imported_count += 1;
}
Err(e) => {
println!(" {} Failed to store token for {} ({}): {}",
println!(
" {} Failed to store token for {} ({}): {}",
"".red(),
pat.profile_name,
pat.service,
e);
e
);
failed_count += 1;
}
}
} else {
println!(" {} Keyring not available, cannot store token for {} ({})",
println!(
" {} Keyring not available, cannot store token for {} ({})",
"".yellow(),
pat.profile_name,
pat.service);
pat.service
);
failed_count += 1;
}
}
Err(e) => {
println!(" {} Invalid token format for {} ({}): {}",
println!(
" {} Invalid token format for {} ({}): {}",
"".red(),
pat.profile_name,
pat.service,
e);
e
);
failed_count += 1;
}
}
}
},
Err(e) => {
println!(" {} Failed to decrypt token for {} ({}): {}",
println!(
" {} Failed to decrypt token for {} ({}): {}",
"".red(),
pat.profile_name,
pat.service,
e);
e
);
failed_count += 1;
}
}
@@ -945,11 +1085,18 @@ impl ConfigCommand {
println!();
if imported_count > 0 {
println!("{} {} token(s) imported to keyring", "".green(), imported_count);
println!(
"{} {} token(s) imported to keyring",
"".green(),
imported_count
);
}
if failed_count > 0 {
println!("{} {} token(s) failed to import", "".yellow(), failed_count);
}
println!(
"{} {} token(s) failed to import",
"".yellow(),
failed_count
);
}
}
@@ -969,31 +1116,41 @@ impl ConfigCommand {
println!("Ollama models (local):");
println!(" llama2, llama2-uncensored, llama2:13b");
println!(" codellama, codellama:34b");
println!(" mistral, mixtral");
println!(" phi, gemma");
println!(" mistral, mixtral, phi, gemma");
println!("\nRun 'ollama list' to see installed models");
}
"openai" => {
println!("OpenAI models:");
println!(" gpt-4, gpt-4-turbo, gpt-4o");
println!(" gpt-3.5-turbo, gpt-3.5-turbo-16k");
println!(" o-series (reasoning): o4-mini, o3, o3-mini, o1, o1-mini, o1-pro");
println!(" GPT-4: gpt-4.1, gpt-4.1-mini, gpt-4.1-nano, gpt-4o, gpt-4o-mini");
println!(" Legacy: gpt-4-turbo, gpt-4, gpt-3.5-turbo");
println!("\nUse --think/-t with o-series models for reasoning mode.");
}
"anthropic" => {
println!("Anthropic Claude models:");
println!(" claude-3-opus-20240229");
println!(" claude-3-sonnet-20240229");
println!(" claude-3-haiku-20240307");
println!(
" Claude 4 (thinking): claude-opus-4-7, claude-sonnet-4-6, claude-haiku-4-5"
);
println!(
" Claude 3.5: claude-3-opus-20240229, claude-3-sonnet-20240229, claude-3-haiku-20240307"
);
println!(" Legacy: claude-2.1, claude-2.0, claude-instant-1.2");
println!("\nUse --think/-t with Claude 4 models for extended thinking.");
}
"kimi" => {
println!("Kimi (Moonshot AI) models:");
println!(" moonshot-v1-8k");
println!(" moonshot-v1-32k");
println!(" moonshot-v1-128k");
println!(
" K2 (thinking): kimi-k2.6, kimi-k2.5, kimi-k2-thinking, kimi-k2-thinking-turbo"
);
println!(" K2 instruct: kimi-k2-instruct, kimi-k2-instruct-0905");
println!(" Legacy: moonshot-v1-8k, moonshot-v1-32k, moonshot-v1-128k");
println!("\nUse --think/-t with K2 models for thinking mode.");
}
"deepseek" => {
println!("DeepSeek models:");
println!(" deepseek-chat");
println!(" deepseek-coder");
println!(" V4: deepseek-v4-flash, deepseek-v4-pro");
println!(" Legacy: deepseek-chat, deepseek-reasoner (deprecated 2026-07-24)");
println!("\nUse --think/-t for reasoning mode.");
}
"openrouter" => {
println!("OpenRouter models (examples):");
@@ -1023,7 +1180,14 @@ impl ConfigCommand {
let has_key = manager.has_api_key();
if provider_needs_api_key(manager.llm_provider()) {
println!(" API Key: {}", if has_key { "✓ configured".green() } else { "✗ not set".red() });
println!(
" API Key: {}",
if has_key {
"✓ configured".green()
} else {
"✗ not set".red()
}
);
}
println!("\n{}", "Sending test request...".dimmed());

458
src/commands/credential.rs Normal file
View 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());
}
}

View File

@@ -4,11 +4,11 @@ use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
use std::path::PathBuf;
use crate::config::{GitProfile, Language};
use crate::config::manager::ConfigManager;
use crate::config::profile::{GpgConfig, SshConfig};
use crate::config::{GitProfile, Language};
use crate::i18n::Messages;
use crate::utils::keyring::{get_supported_providers, get_default_model, provider_needs_api_key};
use crate::utils::keyring::{get_default_model, get_supported_providers, provider_needs_api_key};
use crate::utils::validators::validate_email;
/// Initialize quicommit configuration
@@ -28,9 +28,8 @@ impl InitCommand {
let messages = Messages::new(Language::English);
println!("{}", messages.initializing().bold().cyan());
let config_path = config_path.unwrap_or_else(|| {
crate::config::AppConfig::default_path().unwrap()
});
let config_path =
config_path.unwrap_or_else(|| crate::config::AppConfig::default_path().unwrap());
if config_path.exists() && !self.reset {
if !self.yes {
@@ -44,7 +43,10 @@ impl InitCommand {
return Ok(());
}
} else {
println!("{}", "Configuration already exists. Use --reset to overwrite.".yellow());
println!(
"{}",
"Configuration already exists. Use --reset to overwrite.".yellow()
);
return Ok(());
}
}
@@ -80,14 +82,14 @@ impl InitCommand {
async fn quick_setup(&self, manager: &mut ConfigManager) -> Result<()> {
let git_config = git2::Config::open_default()?;
let user_name = git_config.get_string("user.name").unwrap_or_else(|_| "User".to_string());
let user_email = git_config.get_string("user.email").unwrap_or_else(|_| "user@example.com".to_string());
let user_name = git_config
.get_string("user.name")
.unwrap_or_else(|_| "User".to_string());
let user_email = git_config
.get_string("user.email")
.unwrap_or_else(|_| "user@example.com".to_string());
let profile = GitProfile::new(
"default".to_string(),
user_name,
user_email,
);
let profile = GitProfile::new("default".to_string(), user_name, user_email);
manager.add_profile("default".to_string(), profile)?;
manager.set_default_profile(Some("default".to_string()))?;
@@ -102,7 +104,7 @@ impl InitCommand {
println!("\n{}", messages.setup_profile().bold());
println!("\n{}", messages.select_output_language().bold());
let languages = vec![
let languages = [
Language::English,
Language::Chinese,
Language::Japanese,
@@ -111,11 +113,11 @@ impl InitCommand {
Language::French,
Language::German,
];
let language_names: Vec<String> = languages.iter().map(|l| l.display_name().to_string()).collect();
let language_idx = Select::new()
.items(&language_names)
.default(0)
.interact()?;
let language_names: Vec<String> = languages
.iter()
.map(|l| l.display_name().to_string())
.collect();
let language_idx = Select::new().items(&language_names).default(0).interact()?;
let selected_language = languages[language_idx];
manager.set_output_language(selected_language.to_code().to_string());
@@ -129,11 +131,13 @@ impl InitCommand {
let git_config = git2::Config::open_default().ok();
let default_name = git_config.as_ref()
let default_name = git_config
.as_ref()
.and_then(|c| c.get_string("user.name").ok())
.unwrap_or_default();
let default_email = git_config.as_ref()
let default_email = git_config
.as_ref()
.and_then(|c| c.get_string("user.email").ok())
.unwrap_or_default();
@@ -145,9 +149,7 @@ impl InitCommand {
let user_email: String = Input::new()
.with_prompt(messages.git_user_email())
.default(default_email)
.validate_with(|input: &String| {
validate_email(input).map_err(|e| e.to_string())
})
.validate_with(|input: &String| validate_email(input).map_err(|e| e.to_string()))
.interact_text()?;
let description: String = Input::new()
@@ -161,9 +163,11 @@ impl InitCommand {
.interact()?;
let organization = if is_work {
Some(Input::new()
Some(
Input::new()
.with_prompt(messages.organization_name())
.interact_text()?)
.interact_text()?,
)
} else {
None
};
@@ -190,11 +194,7 @@ impl InitCommand {
None
};
let mut profile = GitProfile::new(
profile_name.clone(),
user_name,
user_email,
);
let mut profile = GitProfile::new(profile_name.clone(), user_name, user_email);
if !description.is_empty() {
profile.description = Some(description);
@@ -216,7 +216,7 @@ impl InitCommand {
"Anthropic Claude",
"Kimi (Moonshot AI)",
"DeepSeek",
"OpenRouter"
"OpenRouter",
];
let provider_idx = Select::new()
@@ -231,17 +231,26 @@ impl InitCommand {
let keyring_available = keyring.is_available();
if !keyring_available {
println!("\n{}", "⚠ Keyring is not available on this system.".yellow());
println!(
"\n{}",
"⚠ Keyring is not available on this system.".yellow()
);
println!("{}", keyring.get_status_message().yellow());
}
let api_key = if provider_needs_api_key(&provider) {
let env_key = std::env::var("QUICOMMIT_API_KEY")
.or_else(|_| std::env::var(format!("QUICOMMIT_{}_API_KEY", provider.to_uppercase())))
.or_else(|_| {
std::env::var(format!("QUICOMMIT_{}_API_KEY", provider.to_uppercase()))
})
.ok();
if let Some(_key) = env_key {
println!("\n{} {}", "".green(), "Found API key in environment variable.".green());
println!(
"\n{} {}",
"".green(),
"Found API key in environment variable.".green()
);
None
} else if keyring_available {
let prompt = match provider.as_str() {
@@ -253,12 +262,13 @@ impl InitCommand {
_ => "API Key",
};
let key: String = Input::new()
.with_prompt(prompt)
.interact_text()?;
let key: String = Input::new().with_prompt(prompt).interact_text()?;
Some(key)
} else {
println!("\n{}", "Please set the QUICOMMIT_API_KEY environment variable.".yellow());
println!(
"\n{}",
"Please set the QUICOMMIT_API_KEY environment variable.".yellow()
);
None
}
} else {
@@ -284,9 +294,7 @@ impl InitCommand {
.interact()?;
if use_custom_url {
let url: String = Input::new()
.with_prompt("Base URL")
.interact_text()?;
let url: String = Input::new().with_prompt("Base URL").interact_text()?;
Some(url)
} else {
None
@@ -297,11 +305,15 @@ impl InitCommand {
manager.set_llm_model(model);
manager.set_llm_base_url(base_url);
if let Some(key) = api_key {
if provider_needs_api_key(&provider) {
if let Some(key) = api_key
&& provider_needs_api_key(&provider)
{
manager.set_api_key(&key)?;
println!("\n{} {}", "".green(), "API key stored securely in system keyring.".green());
}
println!(
"\n{} {}",
"".green(),
"API key stored securely in system keyring.".green()
);
}
Ok(())
@@ -319,6 +331,17 @@ impl InitCommand {
.default(ssh_dir.join("id_rsa").display().to_string())
.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()
.with_prompt(messages.has_passphrase())
.default(false)
@@ -330,13 +353,38 @@ impl InitCommand {
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 {
private_key_path: Some(PathBuf::from(key_path)),
public_key_path: None,
public_key_path,
passphrase,
agent_forwarding: false,
ssh_command: None,
known_hosts_file: None,
agent_forwarding,
ssh_command,
known_hosts_file,
})
}

View File

@@ -1,6 +1,7 @@
pub mod changelog;
pub mod commit;
pub mod config;
pub mod credential;
pub mod init;
pub mod profile;
pub mod tag;

View File

@@ -1,12 +1,12 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
use std::path::PathBuf;
use crate::config::manager::ConfigManager;
use crate::config::{GitProfile, TokenConfig, TokenType};
use crate::config::profile::{GpgConfig, SshConfig};
use crate::config::{GitProfile, TokenConfig, TokenType};
use crate::git::find_repo;
use crate::utils::validators::validate_profile_name;
@@ -127,18 +127,35 @@ impl ProfileCommand {
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
match &self.command {
Some(ProfileSubcommand::Add) => self.add_profile(&config_path).await,
Some(ProfileSubcommand::Remove { name }) => self.remove_profile(name, &config_path).await,
Some(ProfileSubcommand::Remove { name }) => {
self.remove_profile(name, &config_path).await
}
Some(ProfileSubcommand::List) => self.list_profiles(&config_path).await,
Some(ProfileSubcommand::Show { name }) => self.show_profile(name.as_deref(), &config_path).await,
Some(ProfileSubcommand::Show { name }) => {
self.show_profile(name.as_deref(), &config_path).await
}
Some(ProfileSubcommand::Edit { name }) => self.edit_profile(name, &config_path).await,
Some(ProfileSubcommand::SetDefault { name }) => self.set_default(name, &config_path).await,
Some(ProfileSubcommand::SetDefault { name }) => {
self.set_default(name, &config_path).await
}
Some(ProfileSubcommand::SetRepo { name }) => self.set_repo(name, &config_path).await,
Some(ProfileSubcommand::Apply { name, global }) => self.apply_profile(name.as_deref(), *global, &config_path).await,
Some(ProfileSubcommand::Apply { name, global }) => {
self.apply_profile(name.as_deref(), *global, &config_path)
.await
}
Some(ProfileSubcommand::Switch) => self.switch_profile(&config_path).await,
Some(ProfileSubcommand::Copy { from, to }) => self.copy_profile(from, to, &config_path).await,
Some(ProfileSubcommand::Token { token_command }) => self.handle_token_command(token_command, &config_path).await,
Some(ProfileSubcommand::Check { name }) => self.check_profile(name.as_deref(), &config_path).await,
Some(ProfileSubcommand::Stats { name }) => self.show_stats(name.as_deref(), &config_path).await,
Some(ProfileSubcommand::Copy { from, to }) => {
self.copy_profile(from, to, &config_path).await
}
Some(ProfileSubcommand::Token { token_command }) => {
self.handle_token_command(token_command, &config_path).await
}
Some(ProfileSubcommand::Check { name }) => {
self.check_profile(name.as_deref(), &config_path).await
}
Some(ProfileSubcommand::Stats { name }) => {
self.show_stats(name.as_deref(), &config_path).await
}
None => self.list_profiles(&config_path).await,
}
}
@@ -158,18 +175,14 @@ impl ProfileCommand {
let name: String = Input::new()
.with_prompt("Profile name")
.validate_with(|input: &String| {
validate_profile_name(input).map_err(|e| e.to_string())
})
.validate_with(|input: &String| validate_profile_name(input).map_err(|e| e.to_string()))
.interact_text()?;
if manager.has_profile(&name) {
bail!("Profile '{}' already exists", name);
}
let user_name: String = Input::new()
.with_prompt("Git user name")
.interact_text()?;
let user_name: String = Input::new().with_prompt("Git user name").interact_text()?;
let user_email: String = Input::new()
.with_prompt("Git user email")
@@ -189,9 +202,7 @@ impl ProfileCommand {
.interact()?;
let organization = if is_work {
Some(Input::new()
.with_prompt("Organization")
.interact_text()?)
Some(Input::new().with_prompt("Organization").interact_text()?)
} else {
None
};
@@ -234,7 +245,11 @@ impl ProfileCommand {
manager.add_profile(name.clone(), profile)?;
manager.save()?;
println!("{} Profile '{}' added successfully", "".green(), name.cyan());
println!(
"{} Profile '{}' added successfully",
"".green(),
name.cyan()
);
if manager.default_profile().is_none() {
let set_default = Confirm::new()
@@ -260,7 +275,10 @@ impl ProfileCommand {
}
let confirm = Confirm::new()
.with_prompt(&format!("Are you sure you want to remove profile '{}'?", name))
.with_prompt(format!(
"Are you sure you want to remove profile '{}'?",
name
))
.default(false)
.interact()?;
@@ -274,7 +292,11 @@ impl ProfileCommand {
manager.remove_profile(name)?;
manager.save()?;
println!("{} Profile '{}' removed (including all stored tokens)", "".green(), name);
println!(
"{} Profile '{}' removed (including all stored tokens)",
"".green(),
name
);
Ok(())
}
@@ -299,8 +321,16 @@ impl ProfileCommand {
let profile = manager.get_profile(name).unwrap();
let is_default = default.map(|d| d == name).unwrap_or(false);
let marker = if is_default { "".green() } else { "".dimmed() };
let work_marker = if profile.is_work { " [work]".yellow() } else { "".normal() };
let marker = if is_default {
"".green()
} else {
"".dimmed()
};
let work_marker = if profile.is_work {
" [work]".yellow()
} else {
"".normal()
};
println!("{} {}{}", marker, name.cyan().bold(), work_marker);
println!(" {} <{}>", profile.user_name, profile.user_email);
@@ -315,12 +345,27 @@ impl ProfileCommand {
if profile.has_gpg() {
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() {
println!(" {} {} token(s)", "🔐".to_string().dimmed(), profile.tokens.len());
println!(
" {} {} token(s)",
"🔐".to_string().dimmed(),
profile.tokens.len()
);
}
if let Some(ref usage) = profile.usage.last_used {
println!(" {} Last used: {}", "📊".to_string().dimmed(), usage.dimmed());
println!(
" {} Last used: {}",
"📊".to_string().dimmed(),
usage.dimmed()
);
}
println!();
@@ -333,16 +378,17 @@ impl ProfileCommand {
let manager = self.get_manager(config_path)?;
match find_repo(std::env::current_dir()?.as_path()) {
Ok(repo) => {
self.show_repo_status(&repo, &manager, name).await
}
Err(_) => {
self.show_global_status(&manager, name).await
}
Ok(repo) => self.show_repo_status(&repo, &manager, name).await,
Err(_) => self.show_global_status(&manager, name).await,
}
}
async fn show_repo_status(&self, repo: &crate::git::GitRepo, manager: &ConfigManager, name: Option<&str>) -> Result<()> {
async fn show_repo_status(
&self,
repo: &crate::git::GitRepo,
manager: &ConfigManager,
name: Option<&str>,
) -> Result<()> {
use crate::git::MergedUserConfig;
let merged_config = MergedUserConfig::from_repo(repo.inner())?;
@@ -352,7 +398,10 @@ impl ProfileCommand {
println!("{}", "".repeat(60));
println!("Repository: {}", repo_path.cyan());
println!("\n{}", "Git User Configuration (merged local/global):".bold());
println!(
"\n{}",
"Git User Configuration (merged local/global):".bold()
);
println!("{}", "".repeat(60));
self.print_config_entry("User name", &merged_config.name);
@@ -375,19 +424,41 @@ impl ProfileCommand {
match (&matching_profile, repo_profile_name) {
(Some(profile), Some(mapped_name)) => {
if profile.name == *mapped_name {
println!("{} Profile '{}' is mapped to this repository", "".green(), profile.name.cyan());
println!(
"{} Profile '{}' is mapped to this repository",
"".green(),
profile.name.cyan()
);
println!(" This repository's git config matches the saved profile.");
} else {
println!("{} Profile '{}' matches current config", "".green(), profile.name.cyan());
println!(" But repository is mapped to different profile: {}", mapped_name.yellow());
println!(
"{} Profile '{}' matches current config",
"".green(),
profile.name.cyan()
);
println!(
" But repository is mapped to different profile: {}",
mapped_name.yellow()
);
}
}
(Some(profile), None) => {
println!("{} Profile '{}' matches current config", "".green(), profile.name.cyan());
println!(" {} This repository is not mapped to any profile.", "".yellow());
println!(
"{} Profile '{}' matches current config",
"".green(),
profile.name.cyan()
);
println!(
" {} This repository is not mapped to any profile.",
"".yellow()
);
}
(None, Some(mapped_name)) => {
println!("{} Repository is mapped to profile '{}'", "".yellow(), mapped_name.cyan());
println!(
"{} Repository is mapped to profile '{}'",
"".yellow(),
mapped_name.cyan()
);
println!(" But current git config does not match this profile!");
if let Some(mapped_profile) = manager.get_profile(mapped_name) {
@@ -417,14 +488,18 @@ impl ProfileCommand {
}
if merged_config.is_complete() {
println!("\n {} Would you like to save this identity as a new profile?", "💡".yellow());
println!(
"\n {} Would you like to save this identity as a new profile?",
"💡".yellow()
);
let save = Confirm::new()
.with_prompt("Save current git identity as new profile?")
.default(true)
.interact()?;
if save {
self.save_current_identity_as_profile(&merged_config, manager).await?;
self.save_current_identity_as_profile(&merged_config, manager)
.await?;
}
}
}
@@ -432,7 +507,10 @@ impl ProfileCommand {
if let Some(profile_name) = name {
if let Some(profile) = manager.get_profile(profile_name) {
println!("\n{}", format!("Requested Profile: {}", profile_name).bold());
println!(
"\n{}",
format!("Requested Profile: {}", profile_name).bold()
);
println!("{}", "".repeat(60));
self.print_profile_details(profile);
} else {
@@ -486,8 +564,16 @@ impl ProfileCommand {
Some(value) => {
println!("{} {}: {}", source_indicator, label, value);
if entry.local_value.is_some() && entry.global_value.is_some() {
println!(" {} local: {}", "".dimmed(), entry.local_value.as_ref().unwrap());
println!(" {} global: {}", "".dimmed(), entry.global_value.as_ref().unwrap());
println!(
" {} local: {}",
"".dimmed(),
entry.local_value.as_ref().unwrap()
);
println!(
" {} global: {}",
"".dimmed(),
entry.global_value.as_ref().unwrap()
);
}
}
None => {
@@ -504,17 +590,77 @@ impl ProfileCommand {
println!("Description: {}", desc);
}
println!("Work profile: {}", if profile.is_work { "yes".yellow() } else { "no".normal() });
println!(
"Work profile: {}",
if profile.is_work {
"yes".yellow()
} else {
"no".normal()
}
);
if let Some(ref org) = profile.organization {
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 {
println!("\n{}", "SSH Configuration:".bold());
if let Some(ref path) = ssh.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 {
@@ -543,7 +689,11 @@ impl ProfileCommand {
}
}
async fn save_current_identity_as_profile(&self, merged_config: &crate::git::MergedUserConfig, manager: &ConfigManager) -> Result<()> {
async fn save_current_identity_as_profile(
&self,
merged_config: &crate::git::MergedUserConfig,
manager: &ConfigManager,
) -> Result<()> {
let config_path = manager.path().to_path_buf();
let mut manager = ConfigManager::with_path(&config_path)?;
@@ -557,14 +707,15 @@ impl ProfileCommand {
let profile_name: String = Input::new()
.with_prompt("Profile name")
.default(default_name)
.validate_with(|input: &String| {
validate_profile_name(input).map_err(|e| e.to_string())
})
.validate_with(|input: &String| validate_profile_name(input).map_err(|e| e.to_string()))
.interact_text()?;
if manager.has_profile(&profile_name) {
let overwrite = Confirm::new()
.with_prompt(&format!("Profile '{}' already exists. Overwrite?", profile_name))
.with_prompt(format!(
"Profile '{}' already exists. Overwrite?",
profile_name
))
.default(false)
.interact()?;
if !overwrite {
@@ -575,7 +726,7 @@ impl ProfileCommand {
let description: String = Input::new()
.with_prompt("Description (optional)")
.default(format!("Imported from existing git config"))
.default("Imported from existing git config".to_string())
.allow_empty(true)
.interact_text()?;
@@ -585,9 +736,7 @@ impl ProfileCommand {
.interact()?;
let organization = if is_work {
Some(Input::new()
.with_prompt("Organization")
.interact_text()?)
Some(Input::new().with_prompt("Organization").interact_text()?)
} else {
None
};
@@ -635,7 +784,11 @@ impl ProfileCommand {
manager.add_profile(profile_name.clone(), profile)?;
manager.save()?;
println!("{} Profile '{}' saved successfully", "".green(), profile_name.cyan());
println!(
"{} Profile '{}' saved successfully",
"".green(),
profile_name.cyan()
);
let set_default = Confirm::new()
.with_prompt("Set as default profile?")
@@ -645,16 +798,21 @@ impl ProfileCommand {
if set_default {
manager.set_default_profile(Some(profile_name.clone()))?;
manager.save()?;
println!("{} Set '{}' as default profile", "".green(), profile_name.cyan());
println!(
"{} Set '{}' as default profile",
"".green(),
profile_name.cyan()
);
}
Ok(())
}
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.get_profile(name)
let mut profile = manager
.get_profile(name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", name))?
.clone();
@@ -674,16 +832,54 @@ impl ProfileCommand {
})
.interact_text()?;
let mut new_profile = GitProfile::new(name.to_string(), user_name, user_email);
new_profile.description = profile.description;
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;
profile.user_name = user_name;
profile.user_email = user_email;
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()?;
println!("{} Profile '{}' updated", "".green(), name);
@@ -691,6 +887,50 @@ impl ProfileCommand {
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<()> {
let mut manager = self.get_manager(config_path)?;
@@ -711,31 +951,47 @@ impl ProfileCommand {
manager.set_repo_profile(repo_path.clone(), name.to_string())?;
// Get the profile and apply it to the repository
let profile = manager.get_profile(name)
let profile = manager
.get_profile(name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", name))?;
profile.apply_to_repo(repo.inner())?;
manager.record_profile_usage(name, Some(repo_path))?;
manager.save()?;
println!("{} Set '{}' for current repository", "".green(), name.cyan());
println!("{} Applied profile '{}' to current repository", "".green(), name.cyan());
println!(
"{} Set '{}' for current repository",
"".green(),
name.cyan()
);
println!(
"{} Applied profile '{}' to current repository",
"".green(),
name.cyan()
);
Ok(())
}
async fn apply_profile(&self, name: Option<&str>, global: bool, config_path: &Option<PathBuf>) -> Result<()> {
async fn apply_profile(
&self,
name: Option<&str>,
global: bool,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
let profile_name = if let Some(n) = name {
n.to_string()
} else {
manager.default_profile_name()
manager
.default_profile_name()
.ok_or_else(|| anyhow::anyhow!("No default profile set"))?
.clone()
};
let profile = manager.get_profile(&profile_name)
let profile = manager
.get_profile(&profile_name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", profile_name))?
.clone();
@@ -748,11 +1004,19 @@ impl ProfileCommand {
if global {
profile.apply_global()?;
println!("{} Applied profile '{}' globally", "".green(), profile.name.cyan());
println!(
"{} Applied profile '{}' globally",
"".green(),
profile.name.cyan()
);
} else {
let repo = find_repo(std::env::current_dir()?.as_path())?;
profile.apply_to_repo(repo.inner())?;
println!("{} Applied profile '{}' to current repository", "".green(), profile.name.cyan());
println!(
"{} Applied profile '{}' to current repository",
"".green(),
profile.name.cyan()
);
}
manager.record_profile_usage(&profile_name, repo_path)?;
@@ -764,7 +1028,8 @@ impl ProfileCommand {
async fn switch_profile(&self, config_path: &Option<PathBuf>) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
let profiles: Vec<String> = manager.list_profiles()
let profiles: Vec<String> = manager
.list_profiles()
.into_iter()
.map(|s| s.to_string())
.collect();
@@ -798,17 +1063,24 @@ impl ProfileCommand {
.interact()?;
if apply {
self.apply_profile(Some(selected), false, config_path).await?;
self.apply_profile(Some(selected), false, config_path)
.await?;
}
}
Ok(())
}
async fn copy_profile(&self, from: &str, to: &str, config_path: &Option<PathBuf>) -> Result<()> {
async fn copy_profile(
&self,
from: &str,
to: &str,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
let source = manager.get_profile(from)
let source = manager
.get_profile(from)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", from))?
.clone();
@@ -821,20 +1093,38 @@ impl ProfileCommand {
manager.add_profile(to.to_string(), new_profile)?;
manager.save()?;
println!("{} Copied profile '{}' to '{}'", "".green(), from, to.cyan());
println!(
"{} Copied profile '{}' to '{}'",
"".green(),
from,
to.cyan()
);
Ok(())
}
async fn handle_token_command(&self, cmd: &TokenSubcommand, config_path: &Option<PathBuf>) -> Result<()> {
async fn handle_token_command(
&self,
cmd: &TokenSubcommand,
config_path: &Option<PathBuf>,
) -> Result<()> {
match cmd {
TokenSubcommand::Add { profile, service } => self.add_token(profile, service, config_path).await,
TokenSubcommand::Remove { profile, service } => self.remove_token(profile, service, config_path).await,
TokenSubcommand::Add { profile, service } => {
self.add_token(profile, service, config_path).await
}
TokenSubcommand::Remove { profile, service } => {
self.remove_token(profile, service, config_path).await
}
TokenSubcommand::List { profile } => self.list_tokens(profile, config_path).await,
}
}
async fn add_token(&self, profile_name: &str, service: &str, config_path: &Option<PathBuf>) -> Result<()> {
async fn add_token(
&self,
profile_name: &str,
service: &str,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
if !manager.has_profile(profile_name) {
@@ -842,14 +1132,19 @@ impl ProfileCommand {
}
if !manager.keyring().is_available() {
bail!("Keyring is not available. Cannot store PAT securely. Please ensure your system keyring is accessible.");
bail!(
"Keyring is not available. Cannot store PAT securely. Please ensure your system keyring is accessible."
);
}
println!("{}", format!("\nAdd token to profile '{}'", profile_name).bold());
println!(
"{}",
format!("\nAdd token to profile '{}'", profile_name).bold()
);
println!("{}", "".repeat(40));
let token_value: String = Input::new()
.with_prompt(&format!("Token for {}", service))
.with_prompt(format!("Token for {}", service))
.interact_text()?;
let token_type_options = vec!["Personal", "OAuth", "Deploy", "App"];
@@ -882,12 +1177,22 @@ impl ProfileCommand {
manager.add_token_to_profile(profile_name, service.to_string(), token)?;
manager.save()?;
println!("{} Token for '{}' added to profile '{}' (stored securely in keyring)", "".green(), service.cyan(), profile_name);
println!(
"{} Token for '{}' added to profile '{}' (stored securely in keyring)",
"".green(),
service.cyan(),
profile_name
);
Ok(())
}
async fn remove_token(&self, profile_name: &str, service: &str, config_path: &Option<PathBuf>) -> Result<()> {
async fn remove_token(
&self,
profile_name: &str,
service: &str,
config_path: &Option<PathBuf>,
) -> Result<()> {
let mut manager = self.get_manager(config_path)?;
if !manager.has_profile(profile_name) {
@@ -895,7 +1200,10 @@ impl ProfileCommand {
}
let confirm = Confirm::new()
.with_prompt(&format!("Remove token '{}' from profile '{}'?", service, profile_name))
.with_prompt(format!(
"Remove token '{}' from profile '{}'?",
service, profile_name
))
.default(false)
.interact()?;
@@ -907,7 +1215,12 @@ impl ProfileCommand {
manager.remove_token_from_profile(profile_name, service)?;
manager.save()?;
println!("{} Token '{}' removed from profile '{}' (deleted from keyring)", "".green(), service, profile_name);
println!(
"{} Token '{}' removed from profile '{}' (deleted from keyring)",
"".green(),
service,
profile_name
);
Ok(())
}
@@ -915,15 +1228,23 @@ impl ProfileCommand {
async fn list_tokens(&self, profile_name: &str, config_path: &Option<PathBuf>) -> Result<()> {
let manager = self.get_manager(config_path)?;
let profile = manager.get_profile(profile_name)
let profile = manager
.get_profile(profile_name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", profile_name))?;
if profile.tokens.is_empty() {
println!("{} No tokens configured for profile '{}'", "".yellow(), profile_name);
println!(
"{} No tokens configured for profile '{}'",
"".yellow(),
profile_name
);
return Ok(());
}
println!("{}", format!("\nTokens for profile '{}':", profile_name).bold());
println!(
"{}",
format!("\nTokens for profile '{}':", profile_name).bold()
);
println!("{}", "".repeat(40));
for (service, token) in &profile.tokens {
@@ -934,7 +1255,12 @@ impl ProfileCommand {
format!("[{}]", "not stored".yellow())
};
println!("{} {} ({})", service.cyan().bold(), status, token.token_type);
println!(
"{} {} ({})",
service.cyan().bold(),
status,
token.token_type
);
if let Some(ref desc) = token.description {
println!(" {}", desc);
}
@@ -952,7 +1278,8 @@ impl ProfileCommand {
let profile_name = if let Some(n) = name {
n.to_string()
} else {
manager.default_profile_name()
manager
.default_profile_name()
.ok_or_else(|| anyhow::anyhow!("No default profile set"))?
.clone()
};
@@ -960,13 +1287,26 @@ impl ProfileCommand {
let repo = find_repo(std::env::current_dir()?.as_path())?;
let comparison = manager.check_profile_config(&profile_name, repo.inner())?;
println!("{}", format!("\nChecking profile '{}' against git configuration", profile_name).bold());
println!(
"{}",
format!(
"\nChecking profile '{}' against git configuration",
profile_name
)
.bold()
);
println!("{}", "".repeat(60));
if comparison.matches {
println!("{} Profile configuration matches git settings", "".green().bold());
println!(
"{} Profile configuration matches git settings",
"".green().bold()
);
} else {
println!("{} Profile configuration differs from git settings", "".red().bold());
println!(
"{} Profile configuration differs from git settings",
"".red().bold()
);
println!("\n{}", "Differences:".bold());
for diff in &comparison.differences {
@@ -983,7 +1323,8 @@ impl ProfileCommand {
let manager = self.get_manager(config_path)?;
if let Some(n) = name {
let profile = manager.get_profile(n)
let profile = manager
.get_profile(n)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", n))?;
self.show_single_profile_stats(profile);
@@ -1032,25 +1373,61 @@ impl ProfileCommand {
.map(|h| h.join(".ssh"))
.unwrap_or_else(|| PathBuf::from("~/.ssh"));
println!("\n{}", "SSH Configuration".bold());
let key_path: String = Input::new()
.with_prompt("SSH private key path")
.default(ssh_dir.join("id_rsa").display().to_string())
.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 {
private_key_path: Some(PathBuf::from(key_path)),
public_key_path: None,
public_key_path,
passphrase: None,
agent_forwarding: false,
ssh_command: None,
known_hosts_file: None,
agent_forwarding,
ssh_command,
known_hosts_file,
})
}
async fn setup_gpg_interactive(&self) -> Result<GpgConfig> {
let key_id: String = Input::new()
.with_prompt("GPG key ID")
.interact_text()?;
let key_id: String = Input::new().with_prompt("GPG key ID").interact_text()?;
Ok(GpgConfig {
key_id,
@@ -1061,9 +1438,16 @@ impl ProfileCommand {
})
}
async fn setup_token_interactive(&self, profile: &mut GitProfile, manager: &ConfigManager) -> Result<()> {
async fn setup_token_interactive(
&self,
profile: &mut GitProfile,
manager: &ConfigManager,
) -> Result<()> {
if !manager.keyring().is_available() {
println!("{} Keyring is not available. Cannot store PAT securely.", "".yellow());
println!(
"{} Keyring is not available. Cannot store PAT securely.",
"".yellow()
);
let continue_anyway = Confirm::new()
.with_prompt("Continue without secure token storage?")
.default(false)
@@ -1077,9 +1461,7 @@ impl ProfileCommand {
.with_prompt("Service name (e.g., github, gitlab)")
.interact_text()?;
let token_value: String = Input::new()
.with_prompt("Token value")
.interact_text()?;
let token_value: String = Input::new().with_prompt("Token value").interact_text()?;
let token = TokenConfig::new(TokenType::Personal);

View File

@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use clap::Parser;
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
@@ -6,11 +6,12 @@ use semver::Version;
use std::path::PathBuf;
use crate::config::{Language, manager::ConfigManager};
use crate::git::{find_repo, GitRepo};
use crate::generator::ContentGenerator;
use crate::git::tag::{
bump_version, get_latest_version, suggest_version_bump, TagBuilder, VersionBump,
TagBuilder, VersionBump, bump_version, get_latest_version, read_project_version,
suggest_version_bump,
};
use crate::git::{GitRepo, find_repo};
use crate::i18n::Messages;
/// Generate and create Git tags
@@ -56,9 +57,18 @@ pub struct TagCommand {
#[arg(long)]
dry_run: bool,
/// Enable thinking mode for this tag (override config)
#[arg(short = 't', long)]
think: bool,
/// Skip interactive prompts
#[arg(short = 'y', long)]
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 {
@@ -76,11 +86,14 @@ impl TagCommand {
// Determine tag name
let tag_name = if let Some(name) = &self.name {
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 {
// Calculate bumped version
let prefix = &config.tag.version_prefix;
let latest = get_latest_version(&repo, prefix)?
.unwrap_or_else(|| Version::new(0, 0, 0));
let latest =
get_latest_version(&repo, prefix)?.unwrap_or_else(|| Version::new(0, 0, 0));
let bump = VersionBump::from_str(bump_str)?;
let new_version = bump_version(&latest, bump, None);
@@ -88,11 +101,18 @@ impl TagCommand {
format!("{}{}", prefix, new_version)
} else {
// Interactive mode
self.select_version_interactive(&repo, &config.tag.version_prefix, &messages).await?
self.select_version_interactive(&repo, &config.tag.version_prefix, &messages)
.await?
};
// Validate tag name (if it looks like a version)
if tag_name.starts_with('v') || tag_name.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
if tag_name.starts_with('v')
|| tag_name
.chars()
.next()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
{
let version_str = tag_name.trim_start_matches('v');
if let Err(e) = crate::utils::validators::validate_semver(version_str) {
println!("{}: {}", "Warning".yellow(), e);
@@ -116,7 +136,10 @@ impl TagCommand {
} else if let Some(msg) = &self.message {
Some(msg.clone())
} else if self.generate || (config.tag.auto_generate && !self.yes) {
Some(self.generate_tag_message(&repo, &tag_name, &messages).await?)
Some(
self.generate_tag_message(&repo, &tag_name, &messages)
.await?,
)
} else if !self.yes {
Some(self.input_message_interactive(&tag_name, &messages)?)
} else {
@@ -184,7 +207,12 @@ impl TagCommand {
Ok(())
}
async fn select_version_interactive(&self, repo: &GitRepo, prefix: &str, messages: &Messages) -> Result<String> {
async fn select_version_interactive(
&self,
repo: &GitRepo,
prefix: &str,
messages: &Messages,
) -> Result<String> {
loop {
let latest = get_latest_version(repo, prefix)?;
@@ -216,11 +244,18 @@ impl TagCommand {
// Auto-detect
let commits = repo.get_commits(50)?;
let bump = suggest_version_bump(&commits);
let version = latest.as_ref()
let version = latest
.as_ref()
.map(|v| bump_version(v, bump, None))
.unwrap_or_else(|| Version::new(0, 1, 0));
println!("{} {:?}{}{}", messages.suggested_bump(), bump, prefix, version);
println!(
"{} {:?}{}{}",
messages.suggested_bump(),
bump,
prefix,
version
);
let confirm = Confirm::new()
.with_prompt(messages.use_this_version())
@@ -233,19 +268,22 @@ impl TagCommand {
// User rejected, continue the loop
}
1 => {
let version = latest.as_ref()
let version = latest
.as_ref()
.map(|v| bump_version(v, VersionBump::Major, None))
.unwrap_or_else(|| Version::new(1, 0, 0));
return Ok(format!("{}{}", prefix, version));
}
2 => {
let version = latest.as_ref()
let version = latest
.as_ref()
.map(|v| bump_version(v, VersionBump::Minor, None))
.unwrap_or_else(|| Version::new(0, 1, 0));
return Ok(format!("{}{}", prefix, version));
}
3 => {
let version = latest.as_ref()
let version = latest
.as_ref()
.map(|v| bump_version(v, VersionBump::Patch, None))
.unwrap_or_else(|| Version::new(0, 0, 1));
return Ok(format!("{}{}", prefix, version));
@@ -268,7 +306,12 @@ impl TagCommand {
}
}
async fn generate_tag_message(&self, repo: &GitRepo, version: &str, messages: &Messages) -> Result<String> {
async fn generate_tag_message(
&self,
repo: &GitRepo,
version: &str,
messages: &Messages,
) -> Result<String> {
let manager = ConfigManager::new()?;
let language = manager.get_language().unwrap_or(Language::English);
@@ -285,8 +328,61 @@ impl TagCommand {
println!("{}", messages.ai_generating_tag(commits.len()));
let generator = ContentGenerator::new(&manager).await?;
generator.generate_tag_message(version, &commits, language).await
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
generator
.generate_tag_message(version, &commits, language)
.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
if let Some(version) = read_project_version(&project_dir) {
let tag_name = format!("{}{}", prefix, version);
println!(
"{} {}",
messages.latest_version(),
tag_name.cyan()
);
return Ok(tag_name);
}
// 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 input_message_interactive(&self, version: &str, messages: &Messages) -> Result<String> {

View File

@@ -1,6 +1,8 @@
use super::{AppConfig, GitProfile, TokenConfig};
use crate::utils::keyring::{KeyringManager, get_default_base_url, get_default_model, provider_needs_api_key};
use anyhow::{bail, Context, Result};
use crate::utils::keyring::{
KeyringManager, get_default_base_url, get_default_model, provider_needs_api_key,
};
use anyhow::{Context, Result, bail};
// use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -136,11 +138,11 @@ impl ConfigManager {
/// Set default profile
pub fn set_default_profile(&mut self, name: Option<String>) -> Result<()> {
if let Some(ref n) = name {
if !self.config.profiles.contains_key(n) {
if let Some(ref n) = name
&& !self.config.profiles.contains_key(n)
{
bail!("Profile '{}' does not exist", n);
}
}
self.config.default_profile = name;
self.modified = true;
Ok(())
@@ -178,7 +180,12 @@ impl ConfigManager {
// Token management
/// Add a token to a profile (stores token in keyring)
pub fn add_token_to_profile(&mut self, profile_name: &str, service: String, token: TokenConfig) -> Result<()> {
pub fn add_token_to_profile(
&mut self,
profile_name: &str,
service: String,
token: TokenConfig,
) -> Result<()> {
if !self.config.profiles.contains_key(profile_name) {
bail!("Profile '{}' does not exist", profile_name);
}
@@ -192,18 +199,26 @@ impl ConfigManager {
}
/// Store a PAT token in keyring for a profile
pub fn store_pat_for_profile(&self, profile_name: &str, service: &str, token_value: &str) -> Result<()> {
let profile = self.get_profile(profile_name)
pub fn store_pat_for_profile(
&self,
profile_name: &str,
service: &str,
token_value: &str,
) -> Result<()> {
let profile = self
.get_profile(profile_name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", profile_name))?;
let user_email = &profile.user_email;
self.keyring.store_pat(profile_name, user_email, service, token_value)
self.keyring
.store_pat(profile_name, user_email, service, token_value)
}
/// Get a PAT token from keyring for a profile
pub fn get_pat_for_profile(&self, profile_name: &str, service: &str) -> Result<Option<String>> {
let profile = self.get_profile(profile_name)
let profile = self
.get_profile(profile_name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", profile_name))?;
let user_email = &profile.user_email;
@@ -227,14 +242,33 @@ impl ConfigManager {
bail!("Profile '{}' does not exist", profile_name);
}
let user_email = self.config.profiles.get(profile_name).unwrap().user_email.clone();
let services: Vec<String> = self.config.profiles.get(profile_name).unwrap().tokens.keys().cloned().collect();
let user_email = self
.config
.profiles
.get(profile_name)
.unwrap()
.user_email
.clone();
let services: Vec<String> = self
.config
.profiles
.get(profile_name)
.unwrap()
.tokens
.keys()
.cloned()
.collect();
if !services.contains(&service.to_string()) {
bail!("Token for service '{}' not found in profile '{}'", service, profile_name);
bail!(
"Token for service '{}' not found in profile '{}'",
service,
profile_name
);
}
self.keyring.delete_pat(profile_name, &user_email, service)?;
self.keyring
.delete_pat(profile_name, &user_email, service)?;
if let Some(profile) = self.config.profiles.get_mut(profile_name) {
profile.remove_token(service);
@@ -250,7 +284,8 @@ impl ConfigManager {
let user_email = &profile.user_email;
let services: Vec<String> = profile.tokens.keys().cloned().collect();
self.keyring.delete_all_pats_for_profile(profile_name, user_email, &services)?;
self.keyring
.delete_all_pats_for_profile(profile_name, user_email, &services)?;
}
Ok(())
}
@@ -302,14 +337,24 @@ impl ConfigManager {
// }
/// Check and compare profile with git configuration
pub fn check_profile_config(&self, profile_name: &str, repo: &git2::Repository) -> Result<super::ProfileComparison> {
let profile = self.get_profile(profile_name)
pub fn check_profile_config(
&self,
profile_name: &str,
repo: &git2::Repository,
) -> Result<super::ProfileComparison> {
let profile = self
.get_profile(profile_name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' not found", profile_name))?;
profile.compare_with_git_config(repo)
}
/// Find a profile that matches the given user config (name, email, signing_key)
pub fn find_matching_profile(&self, user_name: &str, user_email: &str, signing_key: Option<&str>) -> Option<&GitProfile> {
pub fn find_matching_profile(
&self,
user_name: &str,
user_email: &str,
signing_key: Option<&str>,
) -> Option<&GitProfile> {
for profile in self.config.profiles.values() {
let name_match = profile.user_name == user_name;
let email_match = profile.user_email == user_email;
@@ -329,7 +374,9 @@ impl ConfigManager {
/// Find profiles that partially match (same name or same email)
pub fn find_partial_matches(&self, user_name: &str, user_email: &str) -> Vec<&GitProfile> {
self.config.profiles.values()
self.config
.profiles
.values()
.filter(|p| p.user_name == user_name || p.user_email == user_email)
.collect()
}
@@ -339,6 +386,22 @@ impl ConfigManager {
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
/// Get LLM provider
@@ -384,7 +447,11 @@ impl ConfigManager {
/// Get API key from configured storage method
pub fn get_api_key(&self) -> Option<String> {
// First try environment variables (always checked)
if let Some(key) = self.keyring.get_api_key(&self.config.llm.provider).unwrap_or(None) {
if let Some(key) = self
.keyring
.get_api_key(&self.config.llm.provider)
.unwrap_or(None)
{
return Some(key);
}
@@ -401,20 +468,29 @@ impl ConfigManager {
match self.config.llm.api_key_storage.as_str() {
"keyring" => {
if !self.keyring.is_available() {
bail!("Keyring is not available. Set QUICOMMIT_API_KEY environment variable instead or change api_key_storage to 'config'.");
bail!(
"Keyring is not available. Set QUICOMMIT_API_KEY environment variable instead or change api_key_storage to 'config'."
);
}
self.keyring
.store_api_key(&self.config.llm.provider, api_key)
}
self.keyring.store_api_key(&self.config.llm.provider, api_key)
},
"config" => {
// We can't modify self.config here since self is immutable
// This will be handled by the caller updating the config
Ok(())
},
}
"environment" => {
bail!("API key storage set to 'environment'. Please set QUICOMMIT_{}_API_KEY environment variable.", self.config.llm.provider.to_uppercase());
},
bail!(
"API key storage set to 'environment'. Please set QUICOMMIT_{}_API_KEY environment variable.",
self.config.llm.provider.to_uppercase()
);
}
_ => {
bail!("Invalid API key storage method: {}", self.config.llm.api_key_storage);
bail!(
"Invalid API key storage method: {}",
self.config.llm.api_key_storage
);
}
}
}
@@ -426,16 +502,19 @@ impl ConfigManager {
if self.keyring.is_available() {
self.keyring.delete_api_key(&self.config.llm.provider)?;
}
},
}
"config" => {
// We can't modify self.config here since self is immutable
// This will be handled by the caller updating the config
},
}
"environment" => {
// Environment variables are not managed by the app
},
}
_ => {
bail!("Invalid API key storage method: {}", self.config.llm.api_key_storage);
bail!(
"Invalid API key storage method: {}",
self.config.llm.api_key_storage
);
}
}
Ok(())
@@ -448,7 +527,12 @@ impl ConfigManager {
}
// Check environment variables
if self.keyring.get_api_key(&self.config.llm.provider).unwrap_or(None).is_some() {
if self
.keyring
.get_api_key(&self.config.llm.provider)
.unwrap_or(None)
.is_some()
{
return true;
}
@@ -576,14 +660,12 @@ impl ConfigManager {
/// Export configuration to TOML string
pub fn export(&self) -> Result<String> {
toml::to_string_pretty(&self.config)
.context("Failed to serialize config")
toml::to_string_pretty(&self.config).context("Failed to serialize config")
}
/// Import configuration from TOML string
pub fn import(&mut self, toml_str: &str) -> Result<()> {
self.config = toml::from_str(toml_str)
.context("Failed to parse config")?;
self.config = toml::from_str(toml_str).context("Failed to parse config")?;
self.modified = true;
Ok(())
}

View File

@@ -7,10 +7,7 @@ use std::path::{Path, PathBuf};
pub mod manager;
pub mod profile;
pub use profile::{
GitProfile, TokenConfig, TokenType,
ProfileComparison
};
pub use profile::{GitProfile, ProfileComparison, TokenConfig, TokenType};
/// Application configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -20,10 +17,11 @@ pub struct AppConfig {
pub version: String,
/// Default profile name
#[serde(skip_serializing_if = "Option::is_none")]
pub default_profile: Option<String>,
/// All configured profiles
#[serde(default)]
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub profiles: HashMap<String, GitProfile>,
/// LLM configuration
@@ -43,17 +41,9 @@ pub struct AppConfig {
pub changelog: ChangelogConfig,
/// Repository-specific profile mappings
#[serde(default)]
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
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
#[serde(default)]
pub language: LanguageConfig,
@@ -70,8 +60,6 @@ impl Default for AppConfig {
tag: TagConfig::default(),
changelog: ChangelogConfig::default(),
repo_profiles: HashMap::new(),
encrypt_sensitive: true,
theme: ThemeConfig::default(),
language: LanguageConfig::default(),
}
}
@@ -84,11 +72,12 @@ pub struct LlmConfig {
#[serde(default = "default_llm_provider")]
pub provider: String,
/// Model to use (stored in config, not in keyring)
/// Model to use
#[serde(default = "default_model")]
pub model: String,
/// API base URL (optional, will use provider default if not set)
#[serde(skip_serializing_if = "Option::is_none")]
pub base_url: Option<String>,
/// Maximum tokens for generation
@@ -107,9 +96,17 @@ pub struct LlmConfig {
#[serde(default = "default_api_key_storage")]
pub api_key_storage: String,
/// API key (stored in config for fallback, encrypted if encrypt_sensitive is true)
#[serde(default)]
/// API key (stored in config for fallback)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
/// Enable thinking/reasoning mode (deepseek, kimi, anthropic)
#[serde(default)]
pub thinking_enabled: bool,
/// Budget tokens for thinking mode (Anthropic Claude 4)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking_budget_tokens: Option<u32>,
}
fn default_api_key_storage() -> String {
@@ -127,6 +124,8 @@ impl Default for LlmConfig {
timeout: default_timeout(),
api_key_storage: default_api_key_storage(),
api_key: None,
thinking_enabled: false,
thinking_budget_tokens: None,
}
}
}
@@ -141,33 +140,6 @@ pub struct CommitConfig {
/// Enable AI generation by default
#[serde(default = "default_true")]
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 {
@@ -175,13 +147,6 @@ impl Default for CommitConfig {
Self {
format: default_commit_format(),
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(),
}
}
}
@@ -213,18 +178,6 @@ pub struct TagConfig {
/// Enable AI generation for tag messages
#[serde(default = "default_true")]
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 {
@@ -232,9 +185,6 @@ impl Default for TagConfig {
Self {
version_prefix: default_version_prefix(),
auto_generate: true,
gpg_sign: false,
include_changelog: true,
annotation_template: None,
}
}
}
@@ -249,26 +199,6 @@ pub struct ChangelogConfig {
/// Enable AI generation for changelog entries
#[serde(default = "default_true")]
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 {
@@ -276,56 +206,6 @@ impl Default for ChangelogConfig {
Self {
path: default_changelog_path(),
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(),
}
}
}
@@ -408,6 +288,7 @@ impl Language {
}
// Default value functions
fn default_version() -> String {
"1".to_string()
}
@@ -440,14 +321,6 @@ fn default_commit_format() -> CommitFormat {
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 {
"v".to_string()
}
@@ -456,14 +329,6 @@ fn default_changelog_path() -> 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 {
"en".to_string()
}
@@ -484,8 +349,7 @@ impl AppConfig {
/// Save configuration to file
pub fn save(&self, path: &Path) -> Result<()> {
let content = toml::to_string_pretty(self)
.context("Failed to serialize config")?;
let content = toml::to_string_pretty(self).context("Failed to serialize config")?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
@@ -500,25 +364,9 @@ impl AppConfig {
/// Get default config path
pub fn default_path() -> Result<PathBuf> {
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"))
}
// /// 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

View File

@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -120,11 +120,15 @@ impl GitProfile {
/// Get signing key (from GPG config or direct)
pub fn signing_key(&self) -> Option<&str> {
self.signing_key
.as_ref()
.map(|s| s.as_str())
.as_deref()
.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
pub fn add_token(&mut self, service: String, token: TokenConfig) {
self.tokens.insert(service, token);
@@ -160,76 +164,120 @@ impl GitProfile {
pub fn apply_to_repo(&self, repo: &git2::Repository) -> Result<()> {
let mut config = repo.config()?;
// Clean up old managed keys that the new profile won't set
if self.ssh.as_ref().and_then(|s| s.git_ssh_command()).is_none() {
let _ = config.remove("core.sshCommand");
}
if self.signing_key().is_none() {
let _ = config.remove("user.signingkey");
let _ = config.remove("commit.gpgsign");
let _ = config.remove("tag.gpgsign");
}
if self.gpg.is_none() {
let _ = config.remove("gpg.program");
}
// Apply new values; track whether we've written past name/email for rollback
let mut wrote_optional = false;
let result = (|| -> Result<()> {
config.set_str("user.name", &self.user_name)?;
config.set_str("user.email", &self.user_email)?;
if let Some(ref gpg) = self.gpg {
config.set_str("gpg.program", &gpg.program)?;
wrote_optional = true;
}
if let Some(key) = self.signing_key() {
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(ref key_path) = ssh.private_key_path {
let path_str = key_path.display().to_string();
#[cfg(target_os = "windows")]
{
config.set_str("core.sshCommand",
&format!("ssh -i \"{}\"", path_str.replace('\\', "/")))?;
}
#[cfg(not(target_os = "windows"))]
{
config.set_str("core.sshCommand",
&format!("ssh -i '{}'", path_str))?;
}
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");
}
result
}
/// Apply this profile globally
pub fn apply_global(&self) -> Result<()> {
let mut config = git2::Config::open_default()?;
// Clean up old managed keys that the new profile won't set
if self.ssh.as_ref().and_then(|s| s.git_ssh_command()).is_none() {
let _ = config.remove("core.sshCommand");
}
if self.signing_key().is_none() {
let _ = config.remove("user.signingkey");
let _ = config.remove("commit.gpgsign");
let _ = config.remove("tag.gpgsign");
}
if self.gpg.is_none() {
let _ = config.remove("gpg.program");
}
// Apply new values; track whether we've written past name/email for rollback
let mut wrote_optional = false;
let result = (|| -> Result<()> {
config.set_str("user.name", &self.user_name)?;
config.set_str("user.email", &self.user_email)?;
if let Some(ref gpg) = self.gpg {
config.set_str("gpg.program", &gpg.program)?;
wrote_optional = true;
}
if let Some(key) = self.signing_key() {
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(ref key_path) = ssh.private_key_path {
let path_str = key_path.display().to_string();
#[cfg(target_os = "windows")]
{
config.set_str("core.sshCommand",
&format!("ssh -i \"{}\"", path_str.replace('\\', "/")))?;
}
#[cfg(not(target_os = "windows"))]
{
config.set_str("core.sshCommand",
&format!("ssh -i '{}'", path_str))?;
}
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");
}
result
}
/// Compare with current git configuration
@@ -264,8 +312,9 @@ impl GitProfile {
});
}
if let Some(profile_key) = self.signing_key() {
if git_signing_key.as_deref() != Some(profile_key) {
if let Some(profile_key) = self.signing_key()
&& git_signing_key.as_deref() != Some(profile_key)
{
comparison.matches = false;
comparison.differences.push(ConfigDifference {
key: "user.signingkey".to_string(),
@@ -273,14 +322,13 @@ impl GitProfile {
git_value: git_signing_key.unwrap_or_else(|| "<not set>".to_string()),
});
}
}
Ok(comparison)
}
}
/// Profile settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProfileSettings {
/// Automatically sign commits
#[serde(default)]
@@ -307,19 +355,6 @@ pub struct ProfileSettings {
pub commit_template: Option<String>,
}
impl Default for ProfileSettings {
fn default() -> Self {
Self {
auto_sign_commits: false,
auto_sign_tags: false,
default_commit_format: None,
repo_patterns: vec![],
llm_provider: None,
commit_template: None,
}
}
}
/// SSH configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshConfig {
@@ -349,37 +384,84 @@ pub struct SshConfig {
impl SshConfig {
/// Validate SSH configuration
pub fn validate(&self) -> Result<()> {
if let Some(ref path) = self.private_key_path {
if !path.exists() {
if let Some(ref path) = self.private_key_path
&& !path.exists()
{
bail!("SSH private key does not exist: {:?}", path);
}
}
if let Some(ref path) = self.public_key_path {
if !path.exists() {
if let Some(ref path) = self.public_key_path
&& !path.exists()
{
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(())
}
/// 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> {
if let Some(ref cmd) = self.ssh_command {
Some(cmd.clone())
} else if let Some(ref key_path) = self.private_key_path {
return Some(cmd.clone());
}
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();
#[cfg(target_os = "windows")]
{
Some(format!("ssh -i \"{}\"", path_str.replace('\\', "/")))
parts.push(format!("-i \"{}\"", path_str.replace('\\', "/")));
}
#[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
} else {
Some(parts.join(" "))
}
}
}
@@ -495,7 +577,9 @@ impl TokenConfig {
/// Token type
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TokenType {
#[default]
None,
Personal,
OAuth,
@@ -503,12 +587,6 @@ pub enum TokenType {
App,
}
impl Default for TokenType {
fn default() -> Self {
Self::None
}
}
impl std::fmt::Display for TokenType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@@ -638,9 +716,15 @@ impl GitProfileBuilder {
}
pub fn build(self) -> Result<GitProfile> {
let name = self.name.ok_or_else(|| anyhow::anyhow!("Name is required"))?;
let user_name = self.user_name.ok_or_else(|| anyhow::anyhow!("User name is required"))?;
let user_email = self.user_email.ok_or_else(|| anyhow::anyhow!("User email is required"))?;
let name = self
.name
.ok_or_else(|| anyhow::anyhow!("Name is required"))?;
let user_name = self
.user_name
.ok_or_else(|| anyhow::anyhow!("User name is required"))?;
let user_email = self
.user_email
.ok_or_else(|| anyhow::anyhow!("User email is required"))?;
Ok(GitProfile {
name,

View File

@@ -1,5 +1,5 @@
use crate::config::{CommitFormat, Language};
use crate::config::manager::ConfigManager;
use crate::config::{CommitFormat, Language};
use crate::git::{CommitInfo, GitRepo};
use crate::llm::{GeneratedCommit, LlmClient};
use anyhow::{Context, Result};
@@ -7,18 +7,54 @@ use anyhow::{Context, Result};
/// Content generator using LLM
pub struct ContentGenerator {
llm_client: LlmClient,
template: Option<String>,
}
impl ContentGenerator {
/// Create new content generator
pub async fn new(manager: &ConfigManager) -> Result<Self> {
let llm_client = LlmClient::from_config(manager).await?;
Self::new_with_think(manager, false, None).await
}
/// Create new content generator with thinking override and optional commit template
pub async fn new_with_think(
manager: &ConfigManager,
think_override: bool,
template: Option<String>,
) -> Result<Self> {
let mut thinking_enabled = if think_override {
true
} else {
manager.config().llm.thinking_enabled
};
// Validate thinking support per provider
if thinking_enabled {
let provider = manager.llm_provider();
if !Self::supports_thinking(provider) {
eprintln!(
"Warning: Provider '{}' does not support thinking mode. \
Disabling thinking for this invocation.",
provider
);
thinking_enabled = false;
}
}
let llm_client = LlmClient::from_config_with_think(manager, thinking_enabled).await?;
if !llm_client.is_available().await {
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 {
matches!(provider, "deepseek" | "kimi" | "anthropic" | "openai")
}
/// Generate commit message from diff
@@ -37,7 +73,9 @@ impl ContentGenerator {
diff.to_string()
};
self.llm_client.generate_commit_message(&truncated_diff, format, language).await
self.llm_client
.generate_commit_message(&truncated_diff, format, language, self.template.as_deref())
.await
}
/// Generate commit message from repository changes
@@ -47,7 +85,8 @@ impl ContentGenerator {
format: CommitFormat,
language: Language,
) -> Result<GeneratedCommit> {
let diff = repo.get_staged_diff()
let diff = repo
.get_staged_diff_sorted()
.context("Failed to get staged diff")?;
if diff.is_empty() {
@@ -64,12 +103,12 @@ impl ContentGenerator {
commits: &[CommitInfo],
language: Language,
) -> Result<String> {
let commit_messages: Vec<String> = commits
.iter()
.map(|c| c.subject().to_string())
.collect();
let commit_messages: Vec<String> =
commits.iter().map(|c| c.subject().to_string()).collect();
self.llm_client.generate_tag_message(version, &commit_messages, language).await
self.llm_client
.generate_tag_message(version, &commit_messages, language)
.await
}
/// Generate changelog entry
@@ -87,7 +126,9 @@ impl ContentGenerator {
})
.collect();
self.llm_client.generate_changelog_entry(version, &typed_commits, language).await
self.llm_client
.generate_changelog_entry(version, &typed_commits, language)
.await
}
/// Generate changelog from repository
@@ -104,7 +145,8 @@ impl ContentGenerator {
repo.get_commits(50)?
};
self.generate_changelog_entry(version, &commits, language).await
self.generate_changelog_entry(version, &commits, language)
.await
}
/// Interactive commit generation with user feedback
@@ -116,7 +158,7 @@ impl ContentGenerator {
) -> Result<GeneratedCommit> {
use dialoguer::Select;
let diff = repo.get_staged_diff()?;
let diff = repo.get_staged_diff_sorted()?;
if diff.is_empty() {
anyhow::bail!("No staged changes");
@@ -131,7 +173,9 @@ impl ContentGenerator {
// Generate initial commit
println!("\nGenerating commit message...");
let mut generated = self.generate_commit_message(&diff, format, language).await?;
let mut generated = self
.generate_commit_message(&diff, format, language)
.await?;
loop {
println!("\n{}", "".repeat(60));
@@ -157,7 +201,9 @@ impl ContentGenerator {
0 => return Ok(generated),
1 => {
println!("Regenerating...");
generated = self.generate_commit_message(&diff, format, language).await?;
generated = self
.generate_commit_message(&diff, format, language)
.await?;
}
2 => {
let edited = crate::utils::editor::edit_content(&generated.to_conventional())?;
@@ -209,9 +255,13 @@ pub mod fallback {
f.ends_with(".rs") || f.ends_with(".py") || f.ends_with(".js") || f.ends_with(".ts")
});
let has_docs = files.iter().any(|f| f.ends_with(".md") || f.contains("README"));
let has_docs = files
.iter()
.any(|f| f.ends_with(".md") || f.contains("README"));
let has_tests = files.iter().any(|f| f.contains("test") || f.contains("spec"));
let has_tests = files
.iter()
.any(|f| f.contains("test") || f.contains("spec"));
if has_tests {
"test: update tests".to_string()

View File

@@ -95,9 +95,7 @@ impl ChangelogGenerator {
ChangelogFormat::GitHubReleases => {
self.generate_github_releases(version, date, commits)
}
ChangelogFormat::Custom => {
self.generate_custom(version, date, commits)
}
ChangelogFormat::Custom => self.generate_custom(version, date, commits),
}
}
@@ -159,7 +157,7 @@ impl ChangelogGenerator {
let mut output = format!("## [{}] - {}\n\n", version, date_str);
if self.group_by_type {
let grouped = self.group_commits(commits);
let _grouped = self.group_commits(commits);
// Standard categories
let categories = vec![
@@ -230,11 +228,11 @@ impl ChangelogGenerator {
fn generate_github_releases(
&self,
version: &str,
_version: &str,
_date: DateTime<Utc>,
commits: &[CommitInfo],
) -> Result<String> {
let mut output = format!("## What's Changed\n\n");
let mut output = "## What's Changed\n\n".to_string();
// Group by type
let mut features = vec![];
@@ -357,7 +355,12 @@ impl ChangelogGenerator {
}
fn format_commit_github(&self, commit: &CommitInfo) -> String {
format!("- {} by @{} in {}\n", commit.subject(), commit.author, &commit.short_id)
format!(
"- {} by @{} in {}\n",
commit.subject(),
commit.author,
&commit.short_id
)
}
fn group_commits<'a>(&self, commits: &'a [CommitInfo]) -> HashMap<String, Vec<&'a CommitInfo>> {
@@ -380,8 +383,7 @@ impl Default for ChangelogGenerator {
/// Read existing changelog
pub fn read_changelog(path: &Path) -> Result<String> {
fs::read_to_string(path)
.with_context(|| format!("Failed to read changelog: {:?}", path))
fs::read_to_string(path).with_context(|| format!("Failed to read changelog: {:?}", path))
}
/// Initialize new changelog file
@@ -407,17 +409,13 @@ pub fn generate_from_history(
if let Some(from) = from_tag {
repo.get_commits_between(from, to_ref)
} else {
// Get last 50 commits if no tag specified
repo.get_commits(50)
// Get all commits from the beginning (no from_tag = initial changelog)
repo.get_commits(usize::MAX)
}
}
/// Update version links in changelog
pub fn update_version_links(
changelog: &str,
version: &str,
compare_url: &str,
) -> String {
pub fn update_version_links(changelog: &str, version: &str, compare_url: &str) -> String {
// Add version link at the end of changelog
format!("{}\n[{}]: {}\n", changelog, version, compare_url)
}
@@ -427,20 +425,19 @@ pub fn parse_versions(changelog: &str) -> Vec<(String, String)> {
let mut versions = vec![];
for line in changelog.lines() {
if line.starts_with("## [") {
if let Some(start) = line.find('[') {
if let Some(end) = line.find(']') {
if line.starts_with("## [")
&& let Some(start) = line.find('[')
&& let Some(end) = line.find(']')
{
let version = &line[start + 1..end];
if version != "Unreleased" {
if let Some(date_start) = line.find(" - ") {
if version != "Unreleased"
&& let Some(date_start) = line.find(" - ")
{
let date = &line[date_start + 3..].trim();
versions.push((version.to_string(), date.to_string()));
}
}
}
}
}
}
versions
}
@@ -479,3 +476,137 @@ impl ChangelogEntry {
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");
}
}

View File

@@ -1,5 +1,5 @@
use super::GitRepo;
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use chrono::Local;
/// Commit builder for creating commits
@@ -119,10 +119,14 @@ impl CommitBuilder {
return Ok(msg.clone());
}
let commit_type = self.commit_type.as_ref()
let commit_type = self
.commit_type
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Commit type is required"))?;
let description = self.description.as_ref()
let description = self
.description
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Description is required"))?;
let message = match self.format {
@@ -194,7 +198,8 @@ impl CommitBuilder {
"GPG signing failed. Please check:\n\
1. GPG signing key is configured (git config --get user.signingkey)\n\
2. GPG agent is running\n\
3. You can sign commits manually (try: git commit --amend -S)".to_string()
3. You can sign commits manually (try: git commit --amend -S)"
.to_string()
} else {
stdout.to_string()
}
@@ -241,12 +246,19 @@ pub fn suggest_commit_type(diff: &str) -> Vec<&'static str> {
}
// Check for configuration files
if diff.contains("config") || diff.contains(".json") || diff.contains(".yaml") || diff.contains(".toml") {
if diff.contains("config")
|| diff.contains(".json")
|| diff.contains(".yaml")
|| diff.contains(".toml")
{
suggestions.push("chore");
}
// Check for dependencies
if diff.contains("Cargo.toml") || diff.contains("package.json") || diff.contains("requirements.txt") {
if diff.contains("Cargo.toml")
|| diff.contains("package.json")
|| diff.contains("requirements.txt")
{
suggestions.push("build");
}
@@ -303,11 +315,12 @@ pub fn parse_commit_message(message: &str) -> ParsedCommit {
continue;
}
if line.starts_with("BREAKING CHANGE:") ||
line.starts_with("Closes") ||
line.starts_with("Fixes") ||
line.starts_with("Refs") ||
line.starts_with("Co-authored-by:") {
if line.starts_with("BREAKING CHANGE:")
|| line.starts_with("Closes")
|| line.starts_with("Fixes")
|| line.starts_with("Refs")
|| line.starts_with("Co-authored-by:")
{
in_footer = true;
}
@@ -322,8 +335,16 @@ pub fn parse_commit_message(message: &str) -> ParsedCommit {
commit_type,
scope,
description: Some(description.to_string()),
body: if body_lines.is_empty() { None } else { Some(body_lines.join("\n")) },
footer: if footer_lines.is_empty() { None } else { Some(footer_lines.join("\n")) },
body: if body_lines.is_empty() {
None
} else {
Some(body_lines.join("\n"))
},
footer: if footer_lines.is_empty() {
None
} else {
Some(footer_lines.join("\n"))
},
breaking,
};
}

View File

@@ -1,33 +1,29 @@
use anyhow::{bail, Context, Result};
use git2::{Repository, Signature, StatusOptions, Config, Oid, ObjectType};
use std::path::{Path, PathBuf, Component};
use anyhow::{Context, Result, bail};
use git2::{Config, ObjectType, Oid, Repository, Signature, StatusOptions};
use std::collections::HashMap;
use tempfile;
use std::path::{Component, Path, PathBuf};
pub mod changelog;
pub mod commit;
pub mod tag;
#[cfg(target_os = "windows")]
use std::os::windows::ffi::OsStringExt;
fn normalize_path_for_git2(path: &Path) -> PathBuf {
let mut normalized = path.to_path_buf();
#[cfg(target_os = "windows")]
{
let path_str = path.to_string_lossy();
if path_str.starts_with(r"\\?\") {
if let Some(stripped) = path_str.strip_prefix(r"\\?\") {
if path_str.starts_with(r"\\?\")
&& let Some(stripped) = path_str.strip_prefix(r"\\?\")
{
normalized = PathBuf::from(stripped);
}
}
if path_str.starts_with(r"\\?\UNC\") {
if let Some(stripped) = path_str.strip_prefix(r"\\?\UNC\") {
if path_str.starts_with(r"\\?\UNC\")
&& let Some(stripped) = path_str.strip_prefix(r"\\?\UNC\")
{
normalized = PathBuf::from(format!(r"\\{}", stripped));
}
}
}
normalized
}
@@ -39,8 +35,7 @@ fn get_absolute_path<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
return Ok(normalize_path_for_git2(path));
}
let current_dir = std::env::current_dir()
.with_context(|| "Failed to get current directory")?;
let current_dir = std::env::current_dir().with_context(|| "Failed to get current directory")?;
let absolute = current_dir.join(path);
Ok(normalize_path_for_git2(&absolute))
@@ -77,7 +72,7 @@ fn try_open_repo_with_git2(path: &Path) -> Result<Repository> {
let discover_opts = git2::RepositoryOpenFlags::empty();
let ceiling_dirs: [&str; 0] = [];
let repo = Repository::open_ext(&normalized, discover_opts, &ceiling_dirs)
let repo = Repository::open_ext(&normalized, discover_opts, ceiling_dirs)
.or_else(|_| Repository::discover(&normalized))
.or_else(|_| Repository::open(&normalized));
@@ -86,7 +81,7 @@ fn try_open_repo_with_git2(path: &Path) -> Result<Repository> {
fn try_open_repo_with_git_cli(path: &Path) -> Result<Repository> {
let output = std::process::Command::new("git")
.args(&["rev-parse", "--show-toplevel"])
.args(["rev-parse", "--show-toplevel"])
.current_dir(path)
.output()
.context("Failed to execute git command")?;
@@ -181,10 +176,8 @@ impl GitRepo {
let absolute_path = get_absolute_path(path)?;
let resolved_path = resolve_path_without_canonicalize(&absolute_path);
let repo = try_open_repo_with_git2(&resolved_path)
.or_else(|git2_err| {
try_open_repo_with_git_cli(&resolved_path)
.map_err(|cli_err| {
let repo = try_open_repo_with_git2(&resolved_path).or_else(|git2_err| {
try_open_repo_with_git_cli(&resolved_path).map_err(|cli_err| {
let diagnosis = diagnose_repo_issue(&resolved_path);
anyhow::anyhow!(
"Failed to open git repository:\n\
@@ -200,12 +193,15 @@ impl GitRepo {
2. Run: git status (to verify git works)\n\
3. Run: git config --global --add safe.directory \"*\"\n\
4. Check file permissions",
git2_err, cli_err, diagnosis
git2_err,
cli_err,
diagnosis
)
})
})?;
let repo_path = repo.workdir()
let repo_path = repo
.workdir()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| resolved_path.clone());
@@ -251,7 +247,11 @@ impl GitRepo {
pub fn get_user_name(&self) -> Result<String> {
self.get_config("user.name")?
.or_else(|| std::env::var("GIT_AUTHOR_NAME").ok())
.ok_or_else(|| anyhow::anyhow!("User name not configured. Set it with: git config user.name \"Your Name\""))
.ok_or_else(|| {
anyhow::anyhow!(
"User name not configured. Set it with: git config user.name \"Your Name\""
)
})
}
/// Get the configured user email
@@ -263,7 +263,8 @@ impl GitRepo {
/// Get the configured GPG signing key
pub fn get_signing_key(&self) -> Result<Option<String>> {
Ok(self.get_config("user.signingkey")?
Ok(self
.get_config("user.signingkey")?
.or_else(|| std::env::var("GIT_SIGNING_KEY").ok()))
}
@@ -291,11 +292,7 @@ impl GitRepo {
return Ok(program);
}
let default_gpg = if cfg!(windows) {
"gpg.exe"
} else {
"gpg"
};
let default_gpg = if cfg!(windows) { "gpg.exe" } else { "gpg" };
Ok(default_gpg.to_string())
}
@@ -304,10 +301,13 @@ impl GitRepo {
pub fn create_signature(&self) -> Result<Signature<'_>> {
let name = self.get_user_name()?;
let email = self.get_user_email()?;
let time = git2::Time::new(std::time::SystemTime::now()
let time = git2::Time::new(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64, 0);
.as_secs() as i64,
0,
);
Signature::new(&name, &email, &time).map_err(Into::into)
}
@@ -332,7 +332,7 @@ impl GitRepo {
pub fn get_staged_diff(&self) -> Result<String> {
// Use git CLI to get staged diff for better compatibility
let output = std::process::Command::new("git")
.args(&["diff", "--cached"])
.args(["diff", "--cached"])
.current_dir(&self.path)
.output()
.with_context(|| "Failed to get staged diff with git command")?;
@@ -346,6 +346,128 @@ impl GitRepo {
Ok(diff_text)
}
/// Get staged diff with files sorted by importance
/// Important files (source code) come first, then config files like Cargo.toml,
/// then lock files like Cargo.lock
pub fn get_staged_diff_sorted(&self) -> Result<String> {
let diff = self.get_staged_diff()?;
if diff.is_empty() {
return Ok(diff);
}
let mut file_diffs = Vec::new();
let mut current_file_diff = String::new();
let mut current_file = String::new();
for line in diff.lines() {
if line.starts_with("diff --git") {
// Save previous file diff if any
if !current_file_diff.is_empty() && !current_file.is_empty() {
file_diffs.push((current_file.clone(), current_file_diff.clone()));
}
current_file = extract_file_from_diff_line(line);
current_file_diff = format!("{}\n", line);
} else {
current_file_diff.push_str(line);
current_file_diff.push('\n');
}
}
// Add the last file diff
if !current_file_diff.is_empty() && !current_file.is_empty() {
file_diffs.push((current_file, current_file_diff));
}
// Sort by file importance
file_diffs.sort_by(|a, b| {
let score_a = file_importance_score(&a.0);
let score_b = file_importance_score(&b.0);
score_b.cmp(&score_a) // Descending order
});
// Combine sorted diffs
let sorted_diff: String = file_diffs.into_iter().map(|(_, diff)| diff).collect();
Ok(sorted_diff)
}
}
/// Extract filename from diff --git line
fn extract_file_from_diff_line(line: &str) -> String {
// Format: "diff --git a/path/to/file b/path/to/file"
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 3 {
// Return the second path (after b/)
if let Some(path) = parts[2].strip_prefix("b/") {
return path.to_string();
}
// Fallback to first path (after a/)
if let Some(path) = parts[1].strip_prefix("a/") {
return path.to_string();
}
}
line.to_string()
}
/// Calculate file importance score
/// Higher score = more important
fn file_importance_score(filename: &str) -> i32 {
// Priority list for important file types
let important_extensions = [
".rs", ".py", ".js", ".ts", ".tsx", ".jsx", ".go", ".java", ".cpp", ".c", ".rust", ".vue",
".svelte", ".html", ".css", ".scss", ".sass", ".less",
];
// Config files that are important but less than source code
let config_files = [
"Cargo.toml",
"package.json",
"go.mod",
"go.sum",
"pom.xml",
"Makefile",
"CMakeLists.txt",
"build.gradle",
"gradle.properties",
];
// Lock files - lowest priority
let lock_files = [
"Cargo.lock",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"Gemfile.lock",
"composer.lock",
];
// Check lock files first (lowest priority)
for lock in lock_files.iter() {
if filename.ends_with(lock) {
return 1;
}
}
// Check config files (medium priority)
for config in config_files.iter() {
if filename.ends_with(config) {
return 2;
}
}
// Check important source files (highest priority)
for ext in important_extensions.iter() {
if filename.ends_with(ext) {
return 3;
}
}
// Default priority for other files
2
}
impl GitRepo {
/// Get unstaged diff
pub fn get_unstaged_diff(&self) -> Result<String> {
let diff = self.repo.diff_index_to_workdir(None, None)?;
@@ -390,48 +512,140 @@ impl GitRepo {
/// Get list of staged files
pub fn get_staged_files(&self) -> Result<Vec<String>> {
let statuses = self.repo.statuses(Some(
StatusOptions::new()
.include_untracked(false),
))?;
let statuses = self
.repo
.statuses(Some(StatusOptions::new().include_untracked(false)))?;
let mut files = vec![];
for entry in statuses.iter() {
let status = entry.status();
if status.is_index_new() || status.is_index_modified() || status.is_index_deleted() || status.is_index_renamed() || status.is_index_typechange() {
if let Some(path) = entry.path() {
if (status.is_index_new()
|| status.is_index_modified()
|| status.is_index_deleted()
|| status.is_index_renamed()
|| status.is_index_typechange())
&& let Some(path) = entry.path()
{
files.push(path.to_string());
}
}
}
Ok(files)
}
/// Stage files
pub fn stage_files<P: AsRef<Path>>(&self, paths: &[P]) -> Result<()> {
/// Stage files, skipping paths matched by .gitignore rules
/// 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 skipped = Vec::new();
for path in paths {
let path = path.as_ref();
if path.is_absolute() {
if let Ok(rel_path) = path.strip_prefix(&self.path) {
index.add_path(rel_path)?;
let rel_path = if path.is_absolute() {
match path.strip_prefix(&self.path) {
Ok(p) => p,
Err(_) => {
// Outside repo, skip
skipped.push(path.to_string_lossy().to_string());
continue;
}
}
} 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()?;
Ok(())
Ok(skipped)
}
/// Stage all changes including subdirectories
pub fn stage_all(&self) -> Result<()> {
/// Check if a path is ignored by .gitignore rules
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)
let output = std::process::Command::new("git")
.args(&["add", "-A"])
.args(["add", "-A"])
.current_dir(&self.path)
.output()
.with_context(|| "Failed to stage changes with git command")?;
@@ -444,7 +658,14 @@ impl GitRepo {
// Force refresh the git2 index to pick up changes from git CLI
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
@@ -515,7 +736,7 @@ impl GitRepo {
std::fs::write(temp_file.path(), message)?;
let output = std::process::Command::new("git")
.args(&["commit", "-S", "-F", temp_file.path().to_str().unwrap()])
.args(["commit", "-S", "-F", temp_file.path().to_str().unwrap()])
.current_dir(&self.path)
.output()?;
@@ -528,7 +749,8 @@ impl GitRepo {
"GPG signing failed. Please check:\n\
1. GPG signing key is configured (git config --get user.signingkey)\n\
2. GPG agent is running\n\
3. You can sign commits manually (try: git commit -S -m 'test')".to_string()
3. You can sign commits manually (try: git commit -S -m 'test')"
.to_string()
} else {
stdout.to_string()
}
@@ -548,7 +770,8 @@ impl GitRepo {
let head = self.repo.head()?;
if head.is_branch() {
let name = head.shorthand()
let name = head
.shorthand()
.ok_or_else(|| anyhow::anyhow!("Invalid branch name"))?;
Ok(name.to_string())
} else {
@@ -559,7 +782,8 @@ impl GitRepo {
/// Get current commit hash (short)
pub fn current_commit_short(&self) -> Result<String> {
let head = self.repo.head()?;
let oid = head.target()
let oid = head
.target()
.ok_or_else(|| anyhow::anyhow!("No target for HEAD"))?;
Ok(oid.to_string()[..8].to_string())
}
@@ -567,7 +791,8 @@ impl GitRepo {
/// Get current commit hash (full)
pub fn current_commit(&self) -> Result<String> {
let head = self.repo.head()?;
let oid = head.target()
let oid = head
.target()
.ok_or_else(|| anyhow::anyhow!("No target for HEAD"))?;
Ok(oid.to_string())
}
@@ -637,24 +862,34 @@ impl GitRepo {
let name = String::from_utf8_lossy(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
// (oid is a commit) and annotated (oid is a tag object) tags.
if let Ok(obj) = self.repo.find_object(oid, None) {
if let Ok(commit) = obj.peel_to_commit() {
tags.push(TagInfo {
name: name.to_string(),
target: oid.to_string(),
target: commit.id().to_string(),
message: commit.message().unwrap_or("").to_string(),
time: commit.time().seconds(),
});
}
}
true
})?;
// Sort tags by time (newest first)
tags.sort_by(|a, b| b.time.cmp(&a.time));
// Sort tags by semver (descending), then by time
crate::git::tag::sort_tags_by_semver(&mut 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
pub fn create_tag(&self, name: &str, message: Option<&str>, sign: bool) -> Result<()> {
let head = self.repo.head()?;
@@ -666,13 +901,7 @@ impl GitRepo {
if sign {
self.create_signed_tag_with_git2(name, msg, &sig, target.id())?;
} else {
self.repo.tag(
name,
target.as_object(),
&sig,
msg,
false,
)?;
self.repo.tag(name, target.as_object(), &sig, msg, false)?;
}
} else {
self.repo.tag(
@@ -688,9 +917,15 @@ impl GitRepo {
}
/// Create signed tag using git CLI
fn create_signed_tag_with_git2(&self, name: &str, message: &str, _signature: &Signature, _target_id: Oid) -> Result<()> {
fn create_signed_tag_with_git2(
&self,
name: &str,
message: &str,
_signature: &Signature,
_target_id: Oid,
) -> Result<()> {
let output = std::process::Command::new("git")
.args(&["tag", "-s", name, "-m", message])
.args(["tag", "-s", name, "-m", message])
.current_dir(&self.path)
.output()?;
@@ -703,7 +938,12 @@ impl GitRepo {
}
/// Create GPG signature for arbitrary content
fn create_gpg_signature_for_content(&self, _content: &str, _gpg_program: &str, _signing_key: &str) -> Result<String> {
fn create_gpg_signature_for_content(
&self,
_content: &str,
_gpg_program: &str,
_signing_key: &str,
) -> Result<String> {
Ok(String::new())
}
@@ -716,7 +956,7 @@ impl GitRepo {
/// Push to remote
pub fn push(&self, remote: &str, refspec: &str) -> Result<()> {
let output = std::process::Command::new("git")
.args(&["push", remote, refspec])
.args(["push", remote, refspec])
.current_dir(&self.path)
.output()?;
@@ -731,7 +971,8 @@ impl GitRepo {
/// Get remote URL
pub fn get_remote_url(&self, remote: &str) -> Result<String> {
let remote_obj = self.repo.find_remote(remote)?;
let url = remote_obj.url()
let url = remote_obj
.url()
.ok_or_else(|| anyhow::anyhow!("Remote has no URL"))?;
Ok(url.to_string())
}
@@ -745,7 +986,7 @@ impl GitRepo {
pub fn status_summary(&self) -> Result<StatusSummary> {
// Use git CLI for more reliable status detection
let output = std::process::Command::new("git")
.args(&["status", "--porcelain"])
.args(["status", "--porcelain"])
.current_dir(&self.path)
.output()
.with_context(|| "Failed to get status with git command")?;
@@ -782,9 +1023,10 @@ impl GitRepo {
}
// Conflicted files (both columns are U or DD, AA, etc.)
if (index_status == 'U' || worktree_status == 'U') ||
(index_status == 'A' && worktree_status == 'A') ||
(index_status == 'D' && worktree_status == 'D') {
if (index_status == 'U' || worktree_status == 'U')
|| (index_status == 'A' && worktree_status == 'A')
|| (index_status == 'D' && worktree_status == 'D')
{
conflicted += 1;
}
}
@@ -839,6 +1081,13 @@ pub struct TagInfo {
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
#[derive(Debug, Clone)]
pub struct StatusSummary {
@@ -904,20 +1153,19 @@ pub fn find_repo<P: AsRef<Path>>(start_path: P) -> Result<GitRepo> {
}
if let Ok(output) = std::process::Command::new("git")
.args(&["rev-parse", "--show-toplevel"])
.args(["rev-parse", "--show-toplevel"])
.current_dir(&resolved_start)
.output()
&& output.status.success()
{
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let git_root = stdout.trim();
if !git_root.is_empty() {
if let Ok(repo) = GitRepo::open(git_root) {
if !git_root.is_empty()
&& let Ok(repo) = GitRepo::open(git_root)
{
return Ok(repo);
}
}
}
}
let diagnosis = diagnose_repo_issue(&resolved_start);
@@ -1134,7 +1382,10 @@ impl MergedUserConfig {
}
pub fn has_local_overrides(&self) -> bool {
self.name.is_local() || self.email.is_local() || self.signing_key.is_local() || self.ssh_command.is_local()
self.name.is_local()
|| self.email.is_local()
|| self.signing_key.is_local()
|| self.ssh_command.is_local()
}
}
@@ -1161,23 +1412,38 @@ impl UserConfig {
diffs.push(ConfigDiff {
key: "user.name".to_string(),
left: self.name.clone().unwrap_or_else(|| "<not set>".to_string()),
right: other.name.clone().unwrap_or_else(|| "<not set>".to_string()),
right: other
.name
.clone()
.unwrap_or_else(|| "<not set>".to_string()),
});
}
if self.email != other.email {
diffs.push(ConfigDiff {
key: "user.email".to_string(),
left: self.email.clone().unwrap_or_else(|| "<not set>".to_string()),
right: other.email.clone().unwrap_or_else(|| "<not set>".to_string()),
left: self
.email
.clone()
.unwrap_or_else(|| "<not set>".to_string()),
right: other
.email
.clone()
.unwrap_or_else(|| "<not set>".to_string()),
});
}
if self.signing_key != other.signing_key {
diffs.push(ConfigDiff {
key: "user.signingkey".to_string(),
left: self.signing_key.clone().unwrap_or_else(|| "<not set>".to_string()),
right: other.signing_key.clone().unwrap_or_else(|| "<not set>".to_string()),
left: self
.signing_key
.clone()
.unwrap_or_else(|| "<not set>".to_string()),
right: other
.signing_key
.clone()
.unwrap_or_else(|| "<not set>".to_string()),
});
}
@@ -1192,3 +1458,126 @@ pub struct ConfigDiff {
pub left: 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"
);
}
}

View File

@@ -1,6 +1,7 @@
use super::GitRepo;
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use semver::Version;
use std::path::Path;
/// Tag builder for creating tags
pub struct TagBuilder {
@@ -69,9 +70,7 @@ impl TagBuilder {
/// Build tag message
pub fn build_message(&self) -> Result<String> {
let message = self.message.as_ref()
.cloned()
.unwrap_or_else(|| {
let message = self.message.as_ref().cloned().unwrap_or_else(|| {
let name = self.name.as_deref().unwrap_or("unknown");
format!("Release {}", name)
});
@@ -81,7 +80,9 @@ impl TagBuilder {
/// Execute tag creation
pub fn execute(&self, repo: &GitRepo) -> Result<()> {
let name = self.name.as_ref()
let name = self
.name
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Tag name is required"))?;
if !self.force {
@@ -136,7 +137,10 @@ impl VersionBump {
"minor" => Ok(Self::Minor),
"patch" => Ok(Self::Patch),
"prerelease" | "pre" => Ok(Self::Prerelease),
_ => bail!("Invalid version bump: {}. Use: major, minor, patch, prerelease", s),
_ => bail!(
"Invalid version bump: {}. Use: major, minor, patch, prerelease",
s
),
}
}
@@ -187,7 +191,10 @@ pub fn suggest_version_bump(commits: &[super::CommitInfo]) -> VersionBump {
for commit in commits {
let msg = commit.message.to_lowercase();
if msg.contains("breaking change") || msg.contains("breaking-change") || msg.contains("breaking_change") {
if msg.contains("breaking change")
|| msg.contains("breaking-change")
|| msg.contains("breaking_change")
{
has_breaking = true;
}
@@ -283,7 +290,7 @@ pub fn delete_tag(repo: &GitRepo, name: &str, remote: Option<&str>) -> Result<()
let refspec = format!(":refs/tags/{}", name);
let output = Command::new("git")
.args(&["push", remote, &refspec])
.args(["push", remote, &refspec])
.current_dir(repo.path())
.output()?;
@@ -321,3 +328,193 @@ pub fn list_tags(
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
}
});
}
/// Read the project version from Cargo.toml or pyproject.toml.
/// Returns None if no project config file is found or version cannot be read.
pub fn read_project_version(project_dir: &Path) -> Option<Version> {
// Try Cargo.toml first
let cargo_path = project_dir.join("Cargo.toml");
if cargo_path.exists() {
if let Ok(content) = std::fs::read_to_string(&cargo_path) {
if let Ok(value) = content.parse::<toml::Value>() {
if let Some(version) = value
.get("package")
.and_then(|p| p.get("version"))
.and_then(|v| v.as_str())
{
if let Ok(ver) = Version::parse(version) {
return Some(ver);
}
}
}
}
}
// Try pyproject.toml
let pyproject_path = project_dir.join("pyproject.toml");
if pyproject_path.exists() {
if let Ok(content) = std::fs::read_to_string(&pyproject_path) {
if let Ok(value) = content.parse::<toml::Value>() {
if let Some(version) = value
.get("project")
.and_then(|p| p.get("version"))
.and_then(|v| v.as_str())
{
if let Ok(ver) = Version::parse(version) {
return Some(ver);
}
}
}
}
}
None
}
#[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_project_version_from_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 version = read_project_version(dir.path());
assert_eq!(version, Some(Version::new(0, 3, 0)));
}
#[test]
fn test_read_project_version_from_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 version = read_project_version(dir.path());
assert_eq!(version, Some(Version::new(0, 2, 1)));
}
#[test]
fn test_read_project_version_no_config_files() {
let dir = tempfile::TempDir::new().unwrap();
let version = read_project_version(dir.path());
assert_eq!(version, None);
}
#[test]
fn test_read_project_version_cargo_takes_priority() {
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 version = read_project_version(dir.path());
assert_eq!(version, Some(Version::new(0, 3, 0)));
}
}

View File

@@ -267,7 +267,9 @@ impl Messages {
Language::Chinese => "没有可提交的更改。工作树是干净的。",
Language::Japanese => "コミットする変更がありません。作業ツリーはクリーンです。",
Language::Korean => "커밋할 변경 사항이 없습니다. 작업 트리가 깨끗합니다.",
Language::Spanish => "No hay cambios para hacer commit. El árbol de trabajo está limpio.",
Language::Spanish => {
"No hay cambios para hacer commit. El árbol de trabajo está limpio."
}
Language::French => "Aucun changement à commiter. L'arbre de travail est propre.",
Language::German => "Keine Änderungen zum Committen. Arbeitsbaum ist sauber.",
}
@@ -289,11 +291,19 @@ impl Messages {
match self.language {
Language::English => "No files staged. Auto-staging all changes...",
Language::Chinese => "没有暂存文件。自动暂存所有更改...",
Language::Japanese => "ステージされたファイルがありません。すべての変更を自動ステージ中...",
Language::Japanese => {
"ステージされたファイルがありません。すべての変更を自動ステージ中..."
}
Language::Korean => "스테이징된 파일이 없습니다. 모든 변경 사항을 자동 스테이징 중...",
Language::Spanish => "No hay archivos preparados. Preparando automáticamente todos los cambios...",
Language::French => "Aucun fichier indexé. Indexation automatique de tous les changements...",
Language::German => "Keine Dateien bereitgestellt. Alle Änderungen werden automatisch bereitgestellt...",
Language::Spanish => {
"No hay archivos preparados. Preparando automáticamente todos los cambios..."
}
Language::French => {
"Aucun fichier indexé. Indexation automatique de tous les changements..."
}
Language::German => {
"Keine Dateien bereitgestellt. Alle Änderungen werden automatisch bereitgestellt..."
}
}
}
@@ -359,12 +369,23 @@ impl Messages {
pub fn ai_generating_tag(&self, count: usize) -> String {
match self.language {
Language::English => format!("🤖 AI is generating tag message from {} commits...", count),
Language::English => {
format!("🤖 AI is generating tag message from {} commits...", count)
}
Language::Chinese => format!("🤖 AI 正在从 {} 个提交生成标签消息...", count),
Language::Japanese => format!("🤖 AIが{}個のコミットからタグメッセージを生成しています...", count),
Language::Japanese => format!(
"🤖 AIが{}個のコミットからタグメッセージを生成しています...",
count
),
Language::Korean => format!("🤖 AI가 {}개의 커밋에서 태그 메시지를 생성 중...", count),
Language::Spanish => format!("🤖 La IA está generando mensaje de etiqueta desde {} commits...", count),
Language::French => format!("🤖 L'IA génère le message dtiquette à partir de {} commits...", count),
Language::Spanish => format!(
"🤖 La IA está generando mensaje de etiqueta desde {} commits...",
count
),
Language::French => format!(
"🤖 L'IA génère le message d'étiquette à partir de {} commits...",
count
),
Language::German => format!("🤖 KI generiert Tag-Nachricht aus {} Commits...", count),
}
}

View File

@@ -7,7 +7,11 @@ pub struct Translator {
}
impl Translator {
pub fn new(language: Language, keep_types_english: bool, keep_changelog_types_english: bool) -> Self {
pub fn new(
language: Language,
keep_types_english: bool,
keep_changelog_types_english: bool,
) -> Self {
Self {
language,
keep_types_english,
@@ -227,7 +231,11 @@ pub fn translate_commit_type(commit_type: &str, language: Language, keep_english
translator.translate_commit_type(commit_type)
}
pub fn translate_changelog_category(category: &str, language: Language, keep_english: bool) -> String {
pub fn translate_changelog_category(
category: &str,
language: Language,
keep_english: bool,
) -> String {
let translator = Translator::new(language, true, keep_english);
translator.translate_changelog_category(category)
}

9
src/lib.rs Normal file
View 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;

View File

@@ -1,7 +1,9 @@
use super::{create_http_client, LlmProvider};
use anyhow::{bail, Context, Result};
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
@@ -9,6 +11,12 @@ 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)]
@@ -17,24 +25,59 @@ struct MessagesRequest {
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<String>,
system: Option<Vec<SystemContent>>,
#[serde(skip_serializing_if = "Option::is_none")]
thinking: Option<ThinkingConfig>,
stream: bool,
}
#[derive(Debug, Serialize, Deserialize)]
#[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: 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<ContentBlock>,
content: Vec<ResponseContentBlock>,
}
#[derive(Debug, Deserialize)]
struct ContentBlock {
struct ResponseContentBlock {
#[serde(rename = "type")]
content_type: String,
text: String,
@@ -52,8 +95,57 @@ struct AnthropicError {
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 {
/// Create new Anthropic client
pub fn new(api_key: &str, model: &str) -> Result<Self> {
let client = create_http_client(Duration::from_secs(60))?;
@@ -61,22 +153,54 @@ impl AnthropicClient {
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,
})
}
/// Set timeout
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
self.client = create_http_client(timeout)?;
Ok(self)
}
/// List available models
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>> {
// Anthropic doesn't have a models API endpoint, return predefined list
Ok(ANTHROPIC_MODELS.iter().map(|&m| m.to_string()).collect())
}
/// Validate API key
pub async fn validate_key(&self) -> Result<bool> {
let url = "https://api.anthropic.com/v1/messages";
@@ -84,14 +208,18 @@ impl AnthropicClient {
model: self.model.clone(),
max_tokens: 5,
temperature: Some(0.0),
top_p: None,
messages: vec![AnthropicMessage {
role: "user".to_string(),
content: "Hi".to_string(),
content: AnthropicContent::Text("Hi".to_string()),
}],
system: None,
thinking: None,
stream: false,
};
let response = self.client
let response = self
.client
.post(url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", "2023-06-01")
@@ -124,25 +252,28 @@ impl LlmProvider for AnthropicClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![AnthropicMessage {
role: "user".to_string(),
content: prompt.to_string(),
content: AnthropicContent::Text(prompt.to_string()),
}];
self.messages_request(messages, None).await
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: user.to_string(),
content: AnthropicContent::Text(user.to_string()),
}];
let system = if system.is_empty() {
None
} else {
Some(system.to_string())
Some(vec![SystemContent {
content_type: "text".to_string(),
text: system.to_string(),
}])
};
self.messages_request(messages, system).await
self.messages_request_with_retry(messages, system).await
}
async fn is_available(&self) -> bool {
@@ -155,22 +286,84 @@ impl LlmProvider for AnthropicClient {
}
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<String>,
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 request = MessagesRequest {
model: self.model.clone(),
max_tokens: 500,
temperature: Some(0.7),
messages,
system,
let temperature = if self.temperature == 0.0 {
None
} else {
Some(self.temperature)
};
let response = self.client
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")
@@ -185,9 +378,12 @@ impl AnthropicClient {
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!("Anthropic API error: {} ({})", error.error.message, error.error.error_type);
bail!(
"Anthropic API error: {} ({})",
error.error.message,
error.error.error_type
);
}
bail!("Anthropic API error: {} - {}", status, text);
@@ -198,16 +394,183 @@ impl AnthropicClient {
.await
.context("Failed to parse Anthropic response")?;
result.content
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;
}
}
_ => {}
}
}
}
}
}
/// Available Anthropic models
// 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",
@@ -216,7 +579,6 @@ pub const ANTHROPIC_MODELS: &[&str] = &[
"claude-instant-1.2",
];
/// Check if a model name is valid
pub fn is_valid_model(model: &str) -> bool {
ANTHROPIC_MODELS.contains(&model)
}
@@ -226,8 +588,68 @@ mod tests {
use super::*;
#[test]
fn test_model_validation() {
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""#));
}
}

View File

@@ -1,7 +1,9 @@
use super::{create_http_client, LlmProvider};
use anyhow::{bail, Context, Result};
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
@@ -10,6 +12,11 @@ pub struct DeepSeekClient {
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)]
@@ -20,13 +27,31 @@ struct ChatCompletionRequest {
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, Deserialize)]
#[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)]
@@ -37,6 +62,31 @@ struct ChatCompletionResponse {
#[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)]
@@ -52,41 +102,73 @@ struct ApiError {
}
impl DeepSeekClient {
/// Create new DeepSeek client
pub fn new(api_key: &str, model: &str) -> Result<Self> {
let client = create_http_client(Duration::from_secs(60))?;
let client = create_http_client(Duration::from_secs(300))?;
Ok(Self {
base_url: "https://api.deepseek.com/v1".to_string(),
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,
})
}
/// 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))?;
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,
})
}
/// Set timeout
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
self.client = create_http_client(timeout)?;
Ok(self)
}
/// List available models
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
let response = self
.client
.get(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.send()
@@ -101,11 +183,11 @@ impl DeepSeekClient {
#[derive(Deserialize)]
struct ModelsResponse {
data: Vec<Model>,
data: Vec<ModelId>,
}
#[derive(Deserialize)]
struct Model {
struct ModelId {
id: String,
}
@@ -117,7 +199,6 @@ impl DeepSeekClient {
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),
@@ -136,14 +217,13 @@ impl DeepSeekClient {
#[async_trait]
impl LlmProvider for DeepSeekClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![
Message {
let messages = vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
},
];
reasoning_content: None,
}];
self.chat_completion(messages).await
self.chat_completion_with_retry(messages).await
}
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
@@ -153,15 +233,17 @@ impl LlmProvider for DeepSeekClient {
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(messages).await
self.chat_completion_with_retry(messages).await
}
async fn is_available(&self) -> bool {
@@ -174,22 +256,102 @@ impl LlmProvider for DeepSeekClient {
}
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 request = ChatCompletionRequest {
model: self.model.clone(),
messages,
max_tokens: Some(500),
temperature: Some(0.7),
stream: false,
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 response = self.client
.post(&url)
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)
.json(request)
.send()
.await
.context("Failed to send request to DeepSeek")?;
@@ -199,9 +361,12 @@ impl DeepSeekClient {
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!("DeepSeek API error: {} ({})", error.error.message, error.error.error_type);
bail!(
"DeepSeek API error: {} ({})",
error.error.message,
error.error.error_type
);
}
bail!("DeepSeek API error: {} - {}", status, text);
@@ -212,21 +377,170 @@ impl DeepSeekClient {
.await
.context("Failed to parse DeepSeek response")?;
result.choices
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
);
}
/// Available DeepSeek models
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-coder",
"deepseek-reasoner",
];
/// Check if a model name is valid
pub fn is_valid_model(model: &str) -> bool {
DEEPSEEK_MODELS.contains(&model)
}
@@ -236,8 +550,73 @@ mod tests {
use super::*;
#[test]
fn test_model_validation() {
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()));
}
}

View File

@@ -1,7 +1,9 @@
use super::{create_http_client, LlmProvider};
use anyhow::{bail, Context, Result};
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)
@@ -10,6 +12,10 @@ pub struct KimiClient {
api_key: String,
model: String,
client: reqwest::Client,
thinking_enabled: bool,
max_tokens: u32,
temperature: f32,
thinking_state: Option<Arc<ThinkingStateManager>>,
}
#[derive(Debug, Serialize)]
@@ -21,12 +27,22 @@ struct ChatCompletionRequest {
#[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, Deserialize)]
#[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)]
@@ -37,6 +53,31 @@ struct ChatCompletionResponse {
#[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)]
@@ -52,41 +93,66 @@ struct ApiError {
}
impl KimiClient {
/// Create new Kimi client
pub fn new(api_key: &str, model: &str) -> Result<Self> {
let client = create_http_client(Duration::from_secs(60))?;
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,
})
}
/// 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))?;
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,
})
}
/// Set timeout
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
self.client = create_http_client(timeout)?;
Ok(self)
}
/// List available models
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
let response = self
.client
.get(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.send()
@@ -101,11 +167,11 @@ impl KimiClient {
#[derive(Deserialize)]
struct ModelsResponse {
data: Vec<Model>,
data: Vec<ModelId>,
}
#[derive(Deserialize)]
struct Model {
struct ModelId {
id: String,
}
@@ -117,7 +183,6 @@ impl KimiClient {
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),
@@ -136,14 +201,13 @@ impl KimiClient {
#[async_trait]
impl LlmProvider for KimiClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![
Message {
let messages = vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
},
];
reasoning_content: None,
}];
self.chat_completion(messages).await
self.chat_completion_with_retry(messages).await
}
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
@@ -153,15 +217,17 @@ impl LlmProvider for KimiClient {
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(messages).await
self.chat_completion_with_retry(messages).await
}
async fn is_available(&self) -> bool {
@@ -174,22 +240,84 @@ impl LlmProvider for KimiClient {
}
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 request = ChatCompletionRequest {
model: self.model.clone(),
messages,
max_tokens: Some(500),
temperature: Some(0.7),
stream: false,
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 response = self.client
.post(&url)
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)
.json(request)
.send()
.await
.context("Failed to send request to Kimi")?;
@@ -199,9 +327,12 @@ impl KimiClient {
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!("Kimi API error: {} ({})", error.error.message, error.error.error_type);
bail!(
"Kimi API error: {} ({})",
error.error.message,
error.error.error_type
);
}
bail!("Kimi API error: {} - {}", status, text);
@@ -212,22 +343,178 @@ impl KimiClient {
.await
.context("Failed to parse Kimi response")?;
result.choices
result
.choices
.into_iter()
.next()
.map(|c| c.message.content.trim().to_string())
.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(_) => {
// 忽略无法解析的行
}
}
}
}
/// Available Kimi models
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",
];
/// Check if a model name is valid
pub fn is_valid_model(model: &str) -> bool {
KIMI_MODELS.contains(&model)
}
@@ -237,8 +524,64 @@ mod tests {
use super::*;
#[test]
fn test_model_validation() {
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"));
}
}

View File

@@ -1,20 +1,21 @@
use anyhow::{bail, Context, Result};
use crate::config::Language;
use anyhow::{Context, Result, bail};
use async_trait::async_trait;
use std::time::Duration;
use crate::config::Language;
pub mod anthropic;
pub mod deepseek;
pub mod kimi;
pub mod ollama;
pub mod openai;
pub mod anthropic;
pub mod kimi;
pub mod deepseek;
pub mod openrouter;
pub mod thinking;
pub use anthropic::AnthropicClient;
pub use deepseek::DeepSeekClient;
pub use kimi::KimiClient;
pub use ollama::OllamaClient;
pub use openai::OpenAiClient;
pub use anthropic::AnthropicClient;
pub use kimi::KimiClient;
pub use deepseek::DeepSeekClient;
pub use openrouter::OpenRouterClient;
/// LLM provider trait
@@ -44,6 +45,7 @@ pub struct LlmClientConfig {
pub max_tokens: u32,
pub temperature: f32,
pub timeout: Duration,
pub thinking_enabled: bool,
}
impl Default for LlmClientConfig {
@@ -52,6 +54,7 @@ impl Default for LlmClientConfig {
max_tokens: 500,
temperature: 0.7,
timeout: Duration::from_secs(30),
thinking_enabled: false,
}
}
}
@@ -59,11 +62,20 @@ impl Default for LlmClientConfig {
impl LlmClient {
/// Create LLM client from configuration manager
pub async fn from_config(manager: &crate::config::manager::ConfigManager) -> Result<Self> {
Self::from_config_with_think(manager, manager.config().llm.thinking_enabled).await
}
/// Create LLM client from configuration with explicit thinking override
pub async fn from_config_with_think(
manager: &crate::config::manager::ConfigManager,
thinking_enabled: bool,
) -> Result<Self> {
let config = manager.config();
let client_config = LlmClientConfig {
max_tokens: config.llm.max_tokens,
temperature: config.llm.temperature,
timeout: Duration::from_secs(config.llm.timeout),
thinking_enabled,
};
let provider = config.llm.provider.as_str();
@@ -72,33 +84,99 @@ impl LlmClient {
let api_key = manager.get_api_key();
let provider: Box<dyn LlmProvider> = match provider {
"ollama" => {
Box::new(OllamaClient::new(&base_url, model))
}
"ollama" => Box::new(
OllamaClient::new(&base_url, model)
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature),
),
"openai" => {
let key = api_key.as_ref()
let key = api_key
.as_ref()
.ok_or_else(|| anyhow::anyhow!("OpenAI API key not configured"))?;
Box::new(OpenAiClient::new(&base_url, key, model)?)
let thinking_state = if thinking_enabled {
Some(thinking::create_console_thinking_state())
} else {
None
};
let mut client = OpenAiClient::new(&base_url, key, model)?
.with_thinking(thinking_enabled)
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature)
.with_timeout(client_config.timeout)?;
if let Some(state) = thinking_state {
client = client.with_thinking_state(state);
}
Box::new(client)
}
"anthropic" => {
let key = api_key.as_ref()
let key = api_key
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Anthropic API key not configured"))?;
Box::new(AnthropicClient::new(key, model)?)
let thinking_state = if thinking_enabled {
Some(thinking::create_console_thinking_state())
} else {
None
};
let budget = config.llm.thinking_budget_tokens.unwrap_or(1024);
let mut client = AnthropicClient::new(key, model)?
.with_thinking(thinking_enabled)
.with_thinking_budget_tokens(budget)
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature)
.with_timeout(client_config.timeout)?;
if let Some(state) = thinking_state {
client = client.with_thinking_state(state);
}
Box::new(client)
}
"kimi" => {
let key = api_key.as_ref()
let key = api_key
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Kimi API key not configured"))?;
Box::new(KimiClient::with_base_url(key, model, &base_url)?)
let thinking_state = if thinking_enabled {
Some(thinking::create_console_thinking_state())
} else {
None
};
let mut client = KimiClient::with_base_url(key, model, &base_url)?
.with_thinking(thinking_enabled)
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature)
.with_timeout(client_config.timeout)?;
if let Some(state) = thinking_state {
client = client.with_thinking_state(state);
}
Box::new(client)
}
"deepseek" => {
let key = api_key.as_ref()
let key = api_key
.as_ref()
.ok_or_else(|| anyhow::anyhow!("DeepSeek API key not configured"))?;
Box::new(DeepSeekClient::with_base_url(key, model, &base_url)?)
let thinking_state = if thinking_enabled {
Some(thinking::create_console_thinking_state())
} else {
None
};
let mut client = DeepSeekClient::with_base_url(key, model, &base_url)?
.with_thinking(thinking_enabled)
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature)
.with_timeout(client_config.timeout)?;
if let Some(state) = thinking_state {
client = client.with_thinking_state(state);
}
Box::new(client)
}
"openrouter" => {
let key = api_key.as_ref()
let key = api_key
.as_ref()
.ok_or_else(|| anyhow::anyhow!("OpenRouter API key not configured"))?;
Box::new(OpenRouterClient::with_base_url(key, model, &base_url)?)
Box::new(
OpenRouterClient::with_base_url(key, model, &base_url)?
.with_max_tokens(client_config.max_tokens)
.with_temperature(client_config.temperature)
.with_timeout(client_config.timeout)?,
)
}
_ => bail!("Unknown LLM provider: {}", provider),
};
@@ -123,8 +201,16 @@ impl LlmClient {
diff: &str,
format: crate::config::CommitFormat,
language: Language,
template: Option<&str>,
) -> Result<GeneratedCommit> {
let system_prompt = get_commit_system_prompt(format, language);
let mut system_prompt = get_commit_system_prompt(format, language).to_string();
if let Some(tmpl) = template {
system_prompt.push_str(&format!(
"\n\n## Commit Message Template\nFollow this template structure:\n{}",
tmpl
));
}
// Add language instruction to the prompt
let language_instruction = match language {
@@ -138,7 +224,10 @@ impl LlmClient {
};
let prompt = format!("{}{}", diff, language_instruction);
let response = self.provider.generate_with_system(system_prompt, &prompt).await?;
let response = self
.provider
.generate_with_system(&system_prompt, &prompt)
.await?;
self.parse_commit_response(&response, format)
}
@@ -164,9 +253,14 @@ impl LlmClient {
Language::English => "",
};
let prompt = format!("Version: {}\n\nCommits:\n{}{}", version, commits_text, language_instruction);
let prompt = format!(
"Version: {}\n\nCommits:\n{}{}",
version, commits_text, language_instruction
);
self.provider.generate_with_system(system_prompt, &prompt).await
self.provider
.generate_with_system(system_prompt, &prompt)
.await
}
/// Generate changelog entry
@@ -195,9 +289,14 @@ impl LlmClient {
Language::English => "",
};
let prompt = format!("Version: {}\n\nCommits:\n{}{}", version, commits_text, language_instruction);
let prompt = format!(
"Version: {}\n\nCommits:\n{}{}",
version, commits_text, language_instruction
);
self.provider.generate_with_system(system_prompt, &prompt).await
self.provider
.generate_with_system(system_prompt, &prompt)
.await
}
/// Check if provider is available
@@ -206,35 +305,115 @@ impl LlmClient {
}
/// Parse commit response from LLM
fn parse_commit_response(&self, response: &str, format: crate::config::CommitFormat) -> Result<GeneratedCommit> {
let lines: Vec<&str> = response.lines().collect();
fn parse_commit_response(
&self,
response: &str,
format: crate::config::CommitFormat,
) -> Result<GeneratedCommit> {
// Clean markdown code fences from the response
let cleaned = Self::strip_code_fences(response);
let lines: Vec<&str> = cleaned
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if lines.is_empty() {
bail!("Empty response from LLM");
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
);
}
let first_line = lines[0];
// Find the line most likely to be the commit subject
let first_line = Self::find_commit_subject_line(&lines, format);
// Parse based on format
match format {
crate::config::CommitFormat::Conventional => {
self.parse_conventional_commit(first_line, lines)
self.parse_conventional_commit(first_line, &lines, response)
}
crate::config::CommitFormat::Commitlint => {
self.parse_commitlint_commit(first_line, lines)
self.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(
&self,
first_line: &str,
lines: Vec<&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 {
bail!("Invalid conventional commit format: missing colon");
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];
@@ -257,7 +436,7 @@ impl LlmClient {
};
// Extract body and footer
let (body, footer) = self.extract_body_footer(&lines);
let (body, footer) = self.extract_body_footer(lines);
Ok(GeneratedCommit {
commit_type,
@@ -272,12 +451,21 @@ impl LlmClient {
fn parse_commitlint_commit(
&self,
first_line: &str,
lines: Vec<&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 {
bail!("Invalid commit format: missing colon");
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];
@@ -323,7 +511,13 @@ impl LlmClient {
}
// Look for footer markers
let footer_markers = ["BREAKING CHANGE:", "Closes", "Fixes", "Refs", "Co-authored-by:"];
let footer_markers = [
"BREAKING CHANGE:",
"Closes",
"Fixes",
"Refs",
"Co-authored-by:",
];
let mut body_lines = vec![];
let mut footer_lines = vec![];
@@ -403,17 +597,34 @@ pub(crate) fn create_http_client(timeout: Duration) -> Result<reqwest::Client> {
}
/// Get commit system prompt based on format and language
fn get_commit_system_prompt(format: crate::config::CommitFormat, language: Language) -> &'static str {
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, 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::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,
@@ -504,8 +715,7 @@ const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成符合 C
4. 不要大写首字母
5. 结尾不要句号
6. 如果更改特定于模块/组件,请包含作用域
仅输出提交消息,不要输出其他内容。
7. 仅输出提交消息,不要输出其他内容。
"#;
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_JA: &str = r#"あなたはConventional Commits仕様に従ったコミットメッセージを生成するアシスタントです。
@@ -534,8 +744,7 @@ const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_JA: &str = r#"あなたはConventional C
4. 先頭を大文字にしない
5. 最後にピリオドを付けない
6. 変更がモジュール/コンポーネントに固有の場合はスコープを含める
コミットメッセージのみを出力し、それ以外は出力しないでください。
7. コミットメッセージのみを出力し、それ以外は出力しないでください。
"#;
const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_KO: &str = r#"당신은 Conventional Commits 사양에 따른 커밋 메시지를 생성하는 도우미입니다.
@@ -564,8 +773,7 @@ const CONVENTIONAL_COMMIT_SYSTEM_PROMPT_KO: &str = r#"당신은 Conventional Com
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.
@@ -594,8 +802,7 @@ Reglas:
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
Genera SOLO el mensaje de commit, nada más.
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.
@@ -624,8 +831,7 @@ Règles:
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
Générez SEULEMENT le message de commit, rien d'autre.
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.
@@ -654,8 +860,7 @@ Regeln:
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
Geben Sie NUR die Commit-Nachricht aus, nichts anderes.
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.
@@ -672,8 +877,7 @@ Rules:
3. Subject should be 4-100 characters
4. Use imperative mood
5. Be concise but descriptive
Output ONLY the commit message, nothing else.
6. Output ONLY the commit message, nothing else.
"#;
const COMMITLINT_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成符合 @commitlint/config-conventional 规范的提交消息的助手。
@@ -690,8 +894,7 @@ const COMMITLINT_SYSTEM_PROMPT_ZH: &str = r#"你是一个生成符合 @commitlin
3. 主题应为 4-100 个字符
4. 使用祈使语气
5. 简洁但描述性强
仅输出提交消息,不要输出其他内容。
6. 仅输出提交消息,不要输出其他额外内容。
"#;
const COMMITLINT_SYSTEM_PROMPT_JA: &str = r#"あなたは@commitlint/config-conventionalに従ったコミットメッセージを生成するアシスタントです。
@@ -708,8 +911,7 @@ git diffを分析し、コミットメッセージを生成してください。
3. 件名は4-100文字である必要があります
4. 命令形を使用してください
5. 簡潔ですが説明的であること
コミットメッセージのみを出力し、それ以外は出力しないでください。
6. コミットメッセージのみを出力し、それ以外は出力しないでください。
"#;
const COMMITLINT_SYSTEM_PROMPT_KO: &str = r#"당신은 @commitlint/config-conventional에 따른 커밋 메시지를 생성하는 도우미입니다.
@@ -726,8 +928,7 @@ git diff를 분석하고 커밋 메시지를 생성하세요.
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.
@@ -744,8 +945,7 @@ Reglas:
3. El asunto debe tener 4-100 caracteres
4. Usa modo imperativo
5. Sé conciso pero descriptivo
Genera SOLO el mensaje de commit, nada más.
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.
@@ -762,8 +962,7 @@ Règles:
3. Le sujet doit avoir 4-100 caractères
4. Utilisez le mode impératif
5. Soyez concis mais descriptif
Générez SEULEMENT le message de commit, rien d'autre.
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.
@@ -780,8 +979,7 @@ Regeln:
3. Der Betreff sollte 4-100 Zeichen haben
4. Verwenden Sie den Imperativ
5. Seien Sie prägnant aber beschreibend
Geben Sie NUR die Commit-Nachricht aus, nichts anderes.
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.

View File

@@ -1,4 +1,4 @@
use super::{create_http_client, LlmProvider};
use super::{LlmProvider, create_http_client};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
@@ -9,6 +9,9 @@ pub struct OllamaClient {
base_url: String,
model: String,
client: reqwest::Client,
max_tokens: u32,
temperature: f32,
top_p: Option<f32>,
}
#[derive(Debug, Serialize)]
@@ -47,20 +50,37 @@ struct ModelInfo {
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");
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.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
}
@@ -68,7 +88,8 @@ impl OllamaClient {
pub async fn list_models(&self) -> Result<Vec<String>> {
let url = format!("{}/api/tags", self.base_url);
let response = self.client
let response = self
.client
.get(&url)
.send()
.await
@@ -97,7 +118,8 @@ impl OllamaClient {
"stream": false,
});
let response = self.client
let response = self
.client
.post(&url)
.json(&request)
.send()
@@ -143,12 +165,13 @@ impl LlmProvider for OllamaClient {
system,
stream: false,
options: GenerationOptions {
temperature: Some(0.7),
num_predict: Some(500),
temperature: Some(self.temperature),
num_predict: Some(self.max_tokens),
},
};
let response = self.client
let response = self
.client
.post(&url)
.json(&request)
.send()

View File

@@ -1,15 +1,23 @@
use super::{create_http_client, LlmProvider};
use anyhow::{bail, Context, Result};
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
/// 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)]
@@ -20,10 +28,14 @@ struct ChatCompletionRequest {
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)]
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Message {
role: String,
content: String,
@@ -39,6 +51,28 @@ 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,
@@ -61,20 +95,55 @@ impl OpenAiClient {
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,
})
}
/// Set timeout
pub fn with_timeout(mut self, timeout: Duration) -> Result<Self> {
self.client = create_http_client(timeout)?;
Ok(self)
}
/// List available models
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
let response = self
.client
.get(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.send()
@@ -105,7 +174,6 @@ impl OpenAiClient {
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),
@@ -124,14 +192,12 @@ impl OpenAiClient {
#[async_trait]
impl LlmProvider for OpenAiClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![
Message {
let messages = vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
},
];
}];
self.chat_completion(messages).await
self.chat_completion_with_retry(messages).await
}
async fn generate_with_system(&self, system: &str, user: &str) -> Result<String> {
@@ -149,7 +215,7 @@ impl LlmProvider for OpenAiClient {
content: user.to_string(),
});
self.chat_completion(messages).await
self.chat_completion_with_retry(messages).await
}
async fn is_available(&self) -> bool {
@@ -162,18 +228,63 @@ impl LlmProvider for OpenAiClient {
}
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(500),
temperature: Some(0.7),
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
let response = self
.client
.post(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.header("Content-Type", "application/json")
@@ -187,9 +298,12 @@ impl OpenAiClient {
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!("OpenAI API error: {} ({})", error.error.message, error.error.error_type);
bail!(
"OpenAI API error: {} ({})",
error.error.message,
error.error.error_type
);
}
bail!("OpenAI API error: {} - {}", status, text);
@@ -200,12 +314,144 @@ impl OpenAiClient {
.await
.context("Failed to parse OpenAI response")?;
result.choices
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)
@@ -215,16 +461,16 @@ pub struct AzureOpenAiClient {
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 {
/// Create new Azure OpenAI client
pub fn new(
endpoint: &str,
api_key: &str,
deployment: &str,
api_version: &str,
) -> Result<Self> {
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 {
@@ -233,6 +479,12 @@ impl AzureOpenAiClient {
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,
})
}
@@ -245,12 +497,15 @@ impl AzureOpenAiClient {
let request = ChatCompletionRequest {
model: self.deployment.clone(),
messages,
max_tokens: Some(500),
temperature: Some(0.7),
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
let response = self
.client
.post(&url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
@@ -270,10 +525,12 @@ impl AzureOpenAiClient {
.await
.context("Failed to parse Azure OpenAI response")?;
result.choices
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"))
}
}
@@ -281,12 +538,10 @@ impl AzureOpenAiClient {
#[async_trait]
impl LlmProvider for AzureOpenAiClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![
Message {
let messages = vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
},
];
}];
self.chat_completion(messages).await
}
@@ -310,7 +565,6 @@ impl LlmProvider for AzureOpenAiClient {
}
async fn is_available(&self) -> bool {
// Simple check - try to make a minimal request
let url = format!(
"{}/openai/deployments/{}/chat/completions?api-version={}",
self.endpoint, self.deployment, self.api_version
@@ -324,10 +578,13 @@ impl LlmProvider for AzureOpenAiClient {
}],
max_tokens: Some(5),
temperature: Some(0.0),
top_p: None,
reasoning_effort: None,
stream: false,
};
match self.client
match self
.client
.post(&url)
.header("api-key", &self.api_key)
.json(&request)
@@ -343,3 +600,60 @@ impl LlmProvider for AzureOpenAiClient {
"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());
}
}

View File

@@ -1,5 +1,5 @@
use super::{create_http_client, LlmProvider};
use anyhow::{bail, Context, Result};
use super::{LlmProvider, create_http_client};
use anyhow::{Context, Result, bail};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::time::Duration;
@@ -10,6 +10,9 @@ pub struct OpenRouterClient {
api_key: String,
model: String,
client: reqwest::Client,
max_tokens: u32,
temperature: f32,
top_p: Option<f32>,
}
#[derive(Debug, Serialize)]
@@ -61,6 +64,9 @@ impl OpenRouterClient {
api_key: api_key.to_string(),
model: model.to_string(),
client,
max_tokens: 500,
temperature: 0.7,
top_p: None,
})
}
@@ -73,6 +79,9 @@ impl OpenRouterClient {
api_key: api_key.to_string(),
model: model.to_string(),
client,
max_tokens: 500,
temperature: 0.7,
top_p: None,
})
}
@@ -82,11 +91,27 @@ impl OpenRouterClient {
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
let response = self
.client
.get(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.header("HTTP-Referer", "https://quicommit.dev")
@@ -138,12 +163,10 @@ impl OpenRouterClient {
#[async_trait]
impl LlmProvider for OpenRouterClient {
async fn generate(&self, prompt: &str) -> Result<String> {
let messages = vec![
Message {
let messages = vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
},
];
}];
self.chat_completion(messages).await
}
@@ -182,12 +205,13 @@ impl OpenRouterClient {
let request = ChatCompletionRequest {
model: self.model.clone(),
messages,
max_tokens: Some(500),
temperature: Some(0.7),
max_tokens: Some(self.max_tokens),
temperature: Some(self.temperature),
stream: false,
};
let response = self.client
let response = self
.client
.post(&url)
.header("Authorization", format!("Bearer {}", self.api_key))
.header("Content-Type", "application/json")
@@ -205,7 +229,11 @@ impl OpenRouterClient {
// 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: {} ({})",
error.error.message,
error.error.error_type
);
}
bail!("OpenRouter API error: {} - {}", status, text);
@@ -216,7 +244,8 @@ impl OpenRouterClient {
.await
.context("Failed to parse OpenRouter response")?;
result.choices
result
.choices
.into_iter()
.next()
.map(|c| c.message.content.trim().to_string())

151
src/llm/thinking.rs Normal file
View File

@@ -0,0 +1,151 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// 统一的思考状态管理器,用于管理模型思考状态的显示与隐藏
pub struct ThinkingStateManager {
is_thinking: AtomicBool,
on_start: Option<Box<dyn Fn() + Send + Sync>>,
on_end: Option<Box<dyn Fn() + Send + Sync>>,
}
impl ThinkingStateManager {
pub fn new() -> Self {
Self {
is_thinking: AtomicBool::new(false),
on_start: None,
on_end: None,
}
}
/// 设置思考开始回调
pub fn on_thinking_start<F: Fn() + Send + Sync + 'static>(mut self, callback: F) -> Self {
self.on_start = Some(Box::new(callback));
self
}
/// 设置思考结束回调
pub fn on_thinking_end<F: Fn() + Send + Sync + 'static>(mut self, callback: F) -> Self {
self.on_end = Some(Box::new(callback));
self
}
/// 开始思考状态
pub fn start_thinking(&self) {
if !self.is_thinking.load(Ordering::SeqCst) {
self.is_thinking.store(true, Ordering::SeqCst);
if let Some(ref cb) = self.on_start {
cb();
}
}
}
/// 结束思考状态
pub fn end_thinking(&self) {
if self.is_thinking.load(Ordering::SeqCst) {
self.is_thinking.store(false, Ordering::SeqCst);
if let Some(ref cb) = self.on_end {
cb();
}
}
}
/// 当前是否处于思考状态
pub fn is_thinking(&self) -> bool {
self.is_thinking.load(Ordering::SeqCst)
}
}
impl Default for ThinkingStateManager {
fn default() -> Self {
Self::new()
}
}
/// 线程安全的思考状态管理器引用
pub type SharedThinkingState = Arc<ThinkingStateManager>;
/// 创建带有默认控制台输出的思考状态管理器
/// 在思考开始时打印 "thinking...",在思考结束时清除该标识
pub fn create_console_thinking_state() -> SharedThinkingState {
Arc::new(
ThinkingStateManager::new()
.on_thinking_start(|| {
eprint!("\rthinking...");
})
.on_thinking_end(|| {
eprint!("\r \r");
}),
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[test]
fn test_thinking_state_transitions() {
let manager = ThinkingStateManager::new();
assert!(!manager.is_thinking());
manager.start_thinking();
assert!(manager.is_thinking());
manager.end_thinking();
assert!(!manager.is_thinking());
}
#[test]
fn test_thinking_idempotent_start() {
let manager = ThinkingStateManager::new();
manager.start_thinking();
manager.start_thinking(); // 重复调用不应触发回调两次
assert!(manager.is_thinking());
}
#[test]
fn test_thinking_idempotent_end() {
let manager = ThinkingStateManager::new();
manager.end_thinking(); // 未开始时结束不应触发问题
assert!(!manager.is_thinking());
}
#[test]
fn test_thinking_callbacks() {
let events: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let manager = ThinkingStateManager::new().on_thinking_start(move || {
events_clone.lock().unwrap().push("start".to_string());
});
let events_clone2 = events.clone();
let manager = manager.on_thinking_end(move || {
events_clone2.lock().unwrap().push("end".to_string());
});
manager.start_thinking();
manager.end_thinking();
let recorded = events.lock().unwrap();
assert_eq!(recorded.len(), 2);
assert_eq!(recorded[0], "start");
assert_eq!(recorded[1], "end");
}
#[test]
fn test_create_console_thinking_state() {
let state = create_console_thinking_state();
assert!(!state.is_thinking());
state.start_thinking();
assert!(state.is_thinking());
state.end_thinking();
assert!(!state.is_thinking());
}
#[test]
fn test_default() {
let manager = ThinkingStateManager::default();
assert!(!manager.is_thinking());
}
}

View File

@@ -1,19 +1,13 @@
#![allow(dead_code)]
use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use tracing::debug;
mod commands;
mod config;
mod generator;
mod git;
mod i18n;
mod llm;
mod utils;
use commands::{
use quicommit::commands::{
changelog::ChangelogCommand, commit::CommitCommand, config::ConfigCommand,
init::InitCommand, profile::ProfileCommand, tag::TagCommand,
credential::CredentialCommand, init::InitCommand, profile::ProfileCommand, tag::TagCommand,
};
/// QuiCommit - AI-powered Git assistant
@@ -69,6 +63,10 @@ enum Commands {
/// Manage configuration settings
#[command(alias = "cfg")]
Config(ConfigCommand),
/// Git credential helper (hidden, invoked by git)
#[command(hide = true)]
Credential(CredentialCommand),
}
#[tokio::main]
@@ -98,5 +96,6 @@ async fn main() -> Result<()> {
Commands::Changelog(cmd) => cmd.execute(config_path).await,
Commands::Profile(cmd) => cmd.execute(config_path).await,
Commands::Config(cmd) => cmd.execute(config_path).await,
Commands::Credential(cmd) => cmd.execute(config_path).await,
}
}

View File

@@ -1,9 +1,9 @@
use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Nonce,
aead::{Aead, KeyInit},
};
use anyhow::{Context, Result};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use rand::Rng;
use std::fs;
use std::path::Path;
@@ -20,8 +20,7 @@ pub fn encrypt(data: &[u8], password: &str) -> Result<String> {
rand::thread_rng().fill(&mut nonce_bytes);
let key = derive_key(password, &salt)?;
let cipher = Aes256Gcm::new_from_slice(&key)
.context("Failed to create cipher")?;
let cipher = Aes256Gcm::new_from_slice(&key).context("Failed to create cipher")?;
let nonce = Nonce::from_slice(&nonce_bytes);
let encrypted = cipher
@@ -39,7 +38,8 @@ pub fn encrypt(data: &[u8], password: &str) -> Result<String> {
/// Decrypt data with password
pub fn decrypt(encrypted_data: &str, password: &str) -> Result<Vec<u8>> {
let data = BASE64.decode(encrypted_data)
let data = BASE64
.decode(encrypted_data)
.context("Invalid base64 encoding")?;
if data.len() < SALT_LEN + NONCE_LEN {
@@ -51,8 +51,7 @@ pub fn decrypt(encrypted_data: &str, password: &str) -> Result<Vec<u8>> {
let encrypted = &data[SALT_LEN + NONCE_LEN..];
let key = derive_key(password, salt)?;
let cipher = Aes256Gcm::new_from_slice(&key)
.context("Failed to create cipher")?;
let cipher = Aes256Gcm::new_from_slice(&key).context("Failed to create cipher")?;
let nonce = Nonce::from_slice(nonce_bytes);
let decrypted = cipher
@@ -64,7 +63,7 @@ pub fn decrypt(encrypted_data: &str, password: &str) -> Result<Vec<u8>> {
/// Derive key from password using simple method
fn derive_key(password: &str, salt: &[u8]) -> Result<[u8; KEY_LEN]> {
use sha2::{Sha256, Digest};
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(salt);

View File

@@ -9,14 +9,11 @@ pub fn edit_content(initial_content: &str) -> Result<String> {
/// Edit file in user's default editor
pub fn edit_file(path: &Path) -> Result<String> {
let content = fs::read_to_string(path)
.unwrap_or_default();
let content = fs::read_to_string(path).unwrap_or_default();
let edited = edit::edit(&content)
.context("Failed to open editor")?;
let edited = edit::edit(&content).context("Failed to open editor")?;
fs::write(path, &edited)
.with_context(|| format!("Failed to write file: {:?}", path))?;
fs::write(path, &edited).with_context(|| format!("Failed to write file: {:?}", path))?;
Ok(edited)
}
@@ -29,8 +26,7 @@ pub fn edit_temp(initial_content: &str, extension: &str) -> Result<String> {
.context("Failed to create temp file")?;
let path = temp_file.path();
fs::write(path, initial_content)
.context("Failed to write temp file")?;
fs::write(path, initial_content).context("Failed to write temp file")?;
edit_file(path)
}
@@ -41,10 +37,10 @@ pub fn get_editor() -> String {
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| {
if cfg!(target_os = "windows") {
if let Ok(code) = which::which("code") {
if let Ok(_code) = which::which("code") {
return "code --wait".to_string();
}
if let Ok(notepad) = which::which("notepad") {
if let Ok(_notepad) = which::which("notepad") {
return "notepad".to_string();
}
"notepad".to_string()
@@ -65,7 +61,6 @@ pub fn get_editor() -> String {
/// Check if editor is available
pub fn check_editor() -> Result<()> {
let editor = get_editor();
which::which(&editor)
.with_context(|| format!("Editor '{}' not found in PATH", editor))?;
which::which(&editor).with_context(|| format!("Editor '{}' not found in PATH", editor))?;
Ok(())
}

View File

@@ -1,4 +1,4 @@
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result, bail};
use std::env;
const SERVICE_NAME: &str = "quicommit";
@@ -78,18 +78,19 @@ impl KeyringManager {
let entry = keyring::Entry::new(SERVICE_NAME, provider)
.context("Failed to create keyring entry")?;
entry.set_password(api_key)
entry
.set_password(api_key)
.context("Failed to store API key")?;
Ok(())
}
pub fn get_api_key(&self, provider: &str) -> Result<Option<String>> {
if let Ok(key) = env::var(ENV_API_KEY) {
if !key.is_empty() {
if let Ok(key) = env::var(ENV_API_KEY)
&& !key.is_empty()
{
return Ok(Some(key));
}
}
if !self.is_available() {
return Ok(None);
@@ -113,7 +114,8 @@ impl KeyringManager {
let entry = keyring::Entry::new(SERVICE_NAME, provider)
.context("Failed to create keyring entry")?;
entry.delete_credential()
entry
.delete_credential()
.context("Failed to delete API key")?;
Ok(())
@@ -127,7 +129,13 @@ impl KeyringManager {
format!("{}/{}", PAT_SERVICE_PREFIX, profile_name)
}
pub fn store_pat(&self, profile_name: &str, user_email: &str, service: &str, token: &str) -> Result<()> {
pub fn store_pat(
&self,
profile_name: &str,
user_email: &str,
service: &str,
token: &str,
) -> Result<()> {
if !self.is_available() {
bail!("Keyring is not available on this system");
}
@@ -138,15 +146,19 @@ impl KeyringManager {
let entry = keyring::Entry::new(&keyring_service, &keyring_user)
.context("Failed to create keyring entry for PAT")?;
entry.set_password(token)
entry
.set_password(token)
.context("Failed to store PAT in keyring")?;
eprintln!("[DEBUG] PAT stored in keyring: service={}, user={}", keyring_service, keyring_user);
Ok(())
}
pub fn get_pat(&self, profile_name: &str, user_email: &str, service: &str) -> Result<Option<String>> {
pub fn get_pat(
&self,
profile_name: &str,
user_email: &str,
service: &str,
) -> Result<Option<String>> {
if !self.is_available() {
return Ok(None);
}
@@ -158,14 +170,8 @@ impl KeyringManager {
.context("Failed to create keyring entry for PAT")?;
match entry.get_password() {
Ok(token) => {
eprintln!("[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)
}
Ok(token) => Ok(Some(token)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(e.into()),
}
}
@@ -181,23 +187,27 @@ impl KeyringManager {
let entry = keyring::Entry::new(&keyring_service, &keyring_user)
.context("Failed to create keyring entry for PAT")?;
entry.delete_credential()
entry
.delete_credential()
.context("Failed to delete PAT from keyring")?;
eprintln!("[DEBUG] PAT deleted from keyring: service={}, user={}", keyring_service, keyring_user);
Ok(())
}
pub fn has_pat(&self, profile_name: &str, user_email: &str, service: &str) -> bool {
self.get_pat(profile_name, user_email, service).unwrap_or(None).is_some()
self.get_pat(profile_name, user_email, service)
.unwrap_or(None)
.is_some()
}
pub fn delete_all_pats_for_profile(&self, profile_name: &str, user_email: &str, services: &[String]) -> Result<()> {
pub fn delete_all_pats_for_profile(
&self,
profile_name: &str,
user_email: &str,
services: &[String],
) -> Result<()> {
for service in services {
if let Err(e) = self.delete_pat(profile_name, user_email, service) {
eprintln!("[DEBUG] Failed to delete PAT for service '{}': {}", service, e);
}
let _ = self.delete_pat(profile_name, user_email, service);
}
Ok(())
}
@@ -251,8 +261,8 @@ pub fn get_default_model(provider: &str) -> &'static str {
match provider {
"openai" => "gpt-4",
"anthropic" => "claude-3-sonnet-20240229",
"kimi" => "moonshot-v1-8k",
"deepseek" => "deepseek-chat",
"kimi" => "kimi-k2.6",
"deepseek" => "deepseek-v4-flash",
"openrouter" => "openai/gpt-3.5-turbo",
"ollama" => "llama2",
_ => "",
@@ -260,7 +270,14 @@ pub fn get_default_model(provider: &str) -> &'static str {
}
pub fn get_supported_providers() -> &'static [&'static str] {
&["ollama", "openai", "anthropic", "kimi", "deepseek", "openrouter"]
&[
"ollama",
"openai",
"anthropic",
"kimi",
"deepseek",
"openrouter",
]
}
pub fn provider_needs_api_key(provider: &str) -> bool {
@@ -274,10 +291,19 @@ mod tests {
#[test]
fn test_get_default_base_url() {
assert_eq!(get_default_base_url("openai"), "https://api.openai.com/v1");
assert_eq!(get_default_base_url("anthropic"), "https://api.anthropic.com/v1");
assert_eq!(
get_default_base_url("anthropic"),
"https://api.anthropic.com/v1"
);
assert_eq!(get_default_base_url("kimi"), "https://api.moonshot.cn/v1");
assert_eq!(get_default_base_url("deepseek"), "https://api.deepseek.com/v1");
assert_eq!(get_default_base_url("openrouter"), "https://openrouter.ai/api/v1");
assert_eq!(
get_default_base_url("deepseek"),
"https://api.deepseek.com/v1"
);
assert_eq!(
get_default_base_url("openrouter"),
"https://openrouter.ai/api/v1"
);
assert_eq!(get_default_base_url("ollama"), "http://localhost:11434");
}

View File

@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use lazy_static::lazy_static;
use regex::Regex;
@@ -121,7 +121,12 @@ pub fn validate_commitlint_commit(message: &str) -> Result<()> {
bail!("Commit subject too long (max 100 characters)");
}
if subject.chars().next().map(|c| c.is_uppercase()).unwrap_or(false) {
if subject
.chars()
.next()
.map(|c| c.is_uppercase())
.unwrap_or(false)
{
bail!("Commit subject should not start with uppercase letter");
}
@@ -187,7 +192,10 @@ pub fn validate_profile_name(name: &str) -> Result<()> {
bail!("Profile name too long (max 50 characters)");
}
if !name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
if !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
bail!("Profile name can only contain letters, numbers, hyphens, and underscores");
}

View File

@@ -1,38 +1,11 @@
use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin_cmd;
use predicates::prelude::*;
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;
fn create_git_repo(dir: &PathBuf) -> std::process::Output {
std::process::Command::new("git")
.args(&["init"])
.current_dir(dir)
.output()
.expect("Failed to init git repo")
}
fn configure_git_user(dir: &PathBuf) {
std::process::Command::new("git")
.args(&["config", "user.name", "Test User"])
.current_dir(dir)
.output()
.expect("Failed to configure git user name");
std::process::Command::new("git")
.args(&["config", "user.email", "test@example.com"])
.current_dir(dir)
.output()
.expect("Failed to configure git user email");
}
fn setup_git_repo(dir: &PathBuf) {
create_git_repo(dir);
configure_git_user(dir);
}
fn init_quicommit(config_path: &PathBuf) {
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
}
@@ -46,8 +19,13 @@ mod config_export {
let config_path = temp_dir.path().join("config.toml");
init_quicommit(&config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "export", "--config", config_path.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"export",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert()
.success()
@@ -62,12 +40,16 @@ mod config_export {
let export_path = temp_dir.path().join("exported.toml");
init_quicommit(&config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", ""
"config",
"export",
"--config",
config_path.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
"",
]);
cmd.assert()
@@ -78,7 +60,10 @@ mod config_export {
let content = fs::read_to_string(&export_path).unwrap();
assert!(content.contains("version"), "Export should contain version");
assert!(content.contains("[llm]"), "Export should contain LLM config");
assert!(
content.contains("[llm]"),
"Export should contain LLM config"
);
}
#[test]
@@ -88,12 +73,16 @@ mod config_export {
let export_path = temp_dir.path().join("encrypted.toml");
init_quicommit(&config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", "test_password_123"
"config",
"export",
"--config",
config_path.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
"test_password_123",
]);
cmd.assert()
@@ -103,8 +92,14 @@ mod config_export {
assert!(export_path.exists(), "Export file should be created");
let content = fs::read_to_string(&export_path).unwrap();
assert!(content.starts_with("ENCRYPTED:"), "Encrypted file should start with ENCRYPTED:");
assert!(!content.contains("[llm]"), "Encrypted content should not be readable");
assert!(
content.starts_with("ENCRYPTED:"),
"Encrypted file should start with ENCRYPTED:"
);
assert!(
!content.contains("[llm]"),
"Encrypted content should not be readable"
);
}
}
@@ -131,31 +126,14 @@ api_key_storage = "keyring"
[commit]
format = "conventional"
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]
version_prefix = "v"
auto_generate = true
gpg_sign = false
include_changelog = true
[changelog]
path = "CHANGELOG.md"
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]
output_language = "en"
@@ -164,19 +142,28 @@ keep_changelog_types_english = true
"#;
fs::write(&import_path, plain_config).unwrap();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "import",
"--config", config_path.to_str().unwrap(),
"--file", import_path.to_str().unwrap()
"config",
"import",
"--config",
config_path.to_str().unwrap(),
"--file",
import_path.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("Configuration imported"));
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "get", "llm.provider", "--config", config_path.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"get",
"llm.provider",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("openai"));
@@ -191,35 +178,53 @@ keep_changelog_types_english = true
init_quicommit(&config_path1);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "set", "llm.provider", "anthropic",
"--config", config_path1.to_str().unwrap()
"config",
"set",
"llm.provider",
"anthropic",
"--config",
config_path1.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path1.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", "secure_password"
"config",
"export",
"--config",
config_path1.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
"secure_password",
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "import",
"--config", config_path2.to_str().unwrap(),
"--file", export_path.to_str().unwrap(),
"--password", "secure_password"
"config",
"import",
"--config",
config_path2.to_str().unwrap(),
"--file",
export_path.to_str().unwrap(),
"--password",
"secure_password",
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("Configuration imported"));
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "get", "llm.provider", "--config", config_path2.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"get",
"llm.provider",
"--config",
config_path2.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("anthropic"));
@@ -233,21 +238,29 @@ keep_changelog_types_english = true
init_quicommit(&config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", "correct_password"
"config",
"export",
"--config",
config_path.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
"correct_password",
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "import",
"--config", config_path.to_str().unwrap(),
"--file", export_path.to_str().unwrap(),
"--password", "wrong_password"
"config",
"import",
"--config",
config_path.to_str().unwrap(),
"--file",
export_path.to_str().unwrap(),
"--password",
"wrong_password",
]);
cmd.assert()
.failure()
@@ -267,32 +280,49 @@ mod config_export_import_roundtrip {
init_quicommit(&config_path1);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "set", "llm.model", "gpt-4-turbo",
"--config", config_path1.to_str().unwrap()
"config",
"set",
"llm.model",
"gpt-4-turbo",
"--config",
config_path1.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path1.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", ""
"config",
"export",
"--config",
config_path1.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
"",
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "import",
"--config", config_path2.to_str().unwrap(),
"--file", export_path.to_str().unwrap()
"config",
"import",
"--config",
config_path2.to_str().unwrap(),
"--file",
export_path.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "get", "llm.model", "--config", config_path2.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"get",
"llm.model",
"--config",
config_path2.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("gpt-4-turbo"));
@@ -308,26 +338,38 @@ mod config_export_import_roundtrip {
init_quicommit(&config_path1);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "set", "llm.provider", "deepseek",
"--config", config_path1.to_str().unwrap()
"config",
"set",
"llm.provider",
"deepseek",
"--config",
config_path1.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "set", "llm.model", "deepseek-chat",
"--config", config_path1.to_str().unwrap()
"config",
"set",
"llm.model",
"deepseek-chat",
"--config",
config_path1.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "export",
"--config", config_path1.to_str().unwrap(),
"--output", export_path.to_str().unwrap(),
"--password", password
"config",
"export",
"--config",
config_path1.to_str().unwrap(),
"--output",
export_path.to_str().unwrap(),
"--password",
password,
]);
cmd.assert().success();
@@ -335,23 +377,39 @@ mod config_export_import_roundtrip {
assert!(exported_content.starts_with("ENCRYPTED:"));
assert!(!exported_content.contains("deepseek"));
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config", "import",
"--config", config_path2.to_str().unwrap(),
"--file", export_path.to_str().unwrap(),
"--password", password
"config",
"import",
"--config",
config_path2.to_str().unwrap(),
"--file",
export_path.to_str().unwrap(),
"--password",
password,
]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "get", "llm.provider", "--config", config_path2.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"get",
"llm.provider",
"--config",
config_path2.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("deepseek"));
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "get", "llm.model", "--config", config_path2.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"get",
"llm.model",
"--config",
config_path2.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("deepseek-chat"));

1124
tests/credential_tests.rs Normal file

File diff suppressed because it is too large Load Diff

266
tests/gitignore_tests.rs Normal file
View 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
);
}

View File

@@ -1,4 +1,4 @@
use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin_cmd;
use predicates::prelude::*;
use std::fs;
use std::path::PathBuf;
@@ -59,7 +59,7 @@ fn setup_test_repo_with_file(dir: &PathBuf, file_name: &str, file_content: &str)
}
fn init_quicommit(dir: &PathBuf, config_path: &PathBuf) {
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()])
.current_dir(dir);
cmd.assert().success();
@@ -70,7 +70,7 @@ mod cli_basic {
#[test]
fn test_help() {
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.arg("--help");
cmd.assert()
.success()
@@ -83,7 +83,7 @@ mod cli_basic {
#[test]
fn test_version() {
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.arg("--version");
cmd.assert()
.success()
@@ -92,7 +92,7 @@ mod cli_basic {
#[test]
fn test_no_args_shows_help() {
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.assert()
.failure()
.stderr(predicate::str::contains("Usage:"));
@@ -106,8 +106,14 @@ mod cli_basic {
create_git_repo(&repo_path);
configure_git_user(&repo_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["-vv", "init", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"-vv",
"init",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
@@ -122,7 +128,7 @@ mod init_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -135,7 +141,7 @@ mod init_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
@@ -152,7 +158,7 @@ mod init_command {
let config_path = repo_path.join("test_config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()])
.current_dir(&repo_path);
@@ -164,12 +170,18 @@ mod init_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["init", "--yes", "--reset", "--config", config_path.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"init",
"--yes",
"--reset",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("initialized successfully"));
@@ -184,7 +196,7 @@ mod profile_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["profile", "list", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -197,11 +209,11 @@ mod profile_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["profile", "list", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -218,11 +230,11 @@ mod config_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["config", "show", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -235,11 +247,11 @@ mod config_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["config", "path", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -256,12 +268,18 @@ mod commit_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(temp_dir.path());
cmd.assert()
@@ -278,8 +296,17 @@ mod commit_command {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--manual", "-m", "test: empty", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: empty",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -296,8 +323,17 @@ mod commit_command {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--manual", "-m", "test: add test file", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: add test file",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -314,14 +350,47 @@ mod commit_command {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--date", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--date",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("Dry run"));
}
#[test]
fn test_commit_with_think_flag() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--think",
"--manual",
"-m",
"test: think flag",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
}
}
mod tag_command {
@@ -332,12 +401,18 @@ mod tag_command {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["tag", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(temp_dir.path());
cmd.assert()
@@ -358,14 +433,51 @@ mod tag_command {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["tag", "--name", "v0.1.0", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--name",
"v0.1.0",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("v0.1.0"));
}
#[test]
fn test_tag_with_think_flag() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
setup_git_repo(&repo_path);
create_test_file(&repo_path, "test.txt", "content");
stage_file(&repo_path, "test.txt");
create_commit(&repo_path, "feat: initial commit");
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--think",
"--name",
"v0.2.0",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
}
}
mod changelog_command {
@@ -382,8 +494,15 @@ mod changelog_command {
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["changelog", "--init", "--output", changelog_path.to_str().unwrap(), "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"changelog",
"--init",
"--output",
changelog_path.to_str().unwrap(),
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
@@ -404,12 +523,17 @@ mod changelog_command {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["changelog", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"changelog",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success();
cmd.assert().success();
}
}
@@ -421,7 +545,7 @@ mod cross_platform {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("subdir").join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
@@ -435,7 +559,7 @@ mod cross_platform {
fs::create_dir_all(&space_dir).unwrap();
let config_path = space_dir.join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
@@ -449,7 +573,7 @@ mod cross_platform {
fs::create_dir_all(&unicode_dir).unwrap();
let config_path = unicode_dir.join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
@@ -523,8 +647,17 @@ mod validators {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--manual", "-m", "invalid commit message without type", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"invalid commit message without type",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -541,8 +674,17 @@ mod validators {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--manual", "-m", "feat: add new feature", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"feat: add new feature",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -563,8 +705,17 @@ mod subcommands {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["c", "--manual", "-m", "fix: test", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"c",
"--manual",
"-m",
"fix: test",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -577,7 +728,7 @@ mod subcommands {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["i", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -590,11 +741,11 @@ mod subcommands {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["p", "list", "--config", config_path.to_str().unwrap()]);
cmd.assert()
@@ -611,8 +762,13 @@ mod edge_cases {
let temp_dir = TempDir::new().unwrap();
let non_existent_config = temp_dir.path().join("non_existent_config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["config", "show", "--config", non_existent_config.to_str().unwrap()]);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"show",
"--config",
non_existent_config.to_str().unwrap(),
]);
cmd.assert()
.success()
@@ -627,12 +783,18 @@ mod edge_cases {
let repo_path = temp_dir.path().to_path_buf();
let config_path = repo_path.join("config.toml");
let mut cmd = Command::cargo_bin("quicommit").unwrap();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
@@ -649,12 +811,21 @@ mod edge_cases {
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = Command::cargo_bin("quicommit").unwrap();
cmd.args(&["commit", "--manual", "-m", "", "--dry-run", "--yes", "--config", config_path.to_str().unwrap()])
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.failure()
.stderr(predicate::str::contains("Invalid conventional commit format"));
cmd.assert().failure().stderr(predicate::str::contains(
"Invalid conventional commit format",
));
}
}