9 Commits

Author SHA1 Message Date
7440523260 chore(release): 发布 0.9.0 版本并更新路线图 2026-10-09 10:19:08 +08:00
c2f914307d feat(ginit): 新增一键初始化本地 Git 仓库命令
`quicommit ginit`(别名 `gi`)离线完成仓库起步:用 git2 建库并确立初始分支、
写最简 README.md、按根目录标志文件装配 .gitignore、按 --add 添加远程,
`--profile` 可选套用已有 Git 配置。在已有仓库上重复执行只补齐缺失项:绝不覆盖
既有的 README.md/.gitignore、绝不改动已有 remote 的地址、不提供 --force、
不创建首个提交。边界取舍见 ADR 0006,命令命名见 ADR 0005。

实现落在新的 src/git/init.rs(9 个 git 层函数)与 src/commands/ginit.rs,
命令层不直接引用 git2,GitRepo 公开接口未改动,其余命令行为不变。
测试:src/git/init.rs 11 条单元测试、tests/ginit_tests.rs 18 条集成测试;
新增 35 个 ginit_* 消息覆盖 7 种语言。

另将 CONTEXT.md 与 docs/adr/ 纳入版本跟踪(.gitignore 放开 adr/ 与
CONTEXT.md 两条忽略规则);RAODMAP.md 除 ginit 条目外还包含此前未提交的
规划条目更新。
2026-10-09 09:36:04 +08:00
ef64e7d844 fix: 修正 DeepSeek 默认 base_url 去除多余 /v1 后缀 2026-09-21 17:28:50 +08:00
1dd98885da chore(release): 发布 v0.8.1 2026-08-31 14:47:23 +08:00
8ff7504d96 fix(cli): 未指定 --no-color 时恢复 colored 的 TTY 自动检测
set_override(!no_color) 在默认情况下无条件强制着色,导致管道/CI/
测试捕获的输出混入 ANSI 色码,违背 ADR-0003 "color keeps colored's
existing tty auto-detection" 的规定。改为仅在 --no-color 或 NO_COLOR
存在时强制关闭颜色,其余场景交给 colored 按 stdout 是否为 TTY 自动
判断:终端体验不变,管道输出恢复纯文本。
2026-08-31 14:37:10 +08:00
fac96021fb feat(commit,tag): 推送环节感知远程配置并支持多远程选择推送
- 仓库未配置任何远程时跳过推送询问并打印说明(--push 显式指定同样跳过)
- --remote 指定的目标不存在时回退到第一个可用远程(字母序)并明确提示
- 新增 --select-remote:多远程仓库弹出多选列表依次推送,失败即中止并汇总已推送/未尝试
- 优先级链:--yes > --select-remote > --push
- commit/tag 推送段收敛为 commands::run_push_flow 共享流程
- GitRepo 新增 list_remotes/resolve_push_target,i18n 新文案覆盖 7 种语言
2026-08-31 14:19:58 +08:00
b391bdabaf docs(changelog): 更新 0.7.0 版本发布说明 2026-08-21 14:43:38 +08:00
d6958dc41e chore: 升级版本至 0.7.0 并启用 regex unicode-perl 特性 2026-08-21 14:07:02 +08:00
a40c88c768 feat(changelog): 添加 --no-generate 标志以支持纯模板生成
- 新增 `--no-generate` 参数,强制使用模板生成而非 AI
- 调整 `--yes` 参数仅跳过交互提示,不改变生成行为
- 统一使用工具函数替代 println 输出
2026-08-21 13:57:25 +08:00
39 changed files with 10415 additions and 1551 deletions

2
.gitignore vendored
View File

@@ -26,6 +26,4 @@ config.toml
.qoder/
CLAUDE.md
**/agents/
adr/
.scratch/
CONTEXT.md

View File

@@ -5,9 +5,54 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.9.0] - 2026-10-09
暂无。
### ✨ 新功能
- 新增 `quicommit ginit`(别名 `gi`):一条命令完成本地 Git 仓库起步——建库、写最简 `README.md`、按根目录标志文件生成 `.gitignore`、确立初始分支、按 `--add` 添加远程,并可用 `--profile` 套用已有 Git 配置。命令全程离线,不创建首个提交,不覆盖已存在的 `README.md` 与 `.gitignore`;`--dry-run` 只预览,`--yes` 仅跳过确认
### 🐞 错误修复
- 修复 DeepSeek 默认 `base_url` 误带 `/v1` 后缀的问题:该后缀会使用于校验凭据的 `GET /user/balance` 被拼成 `/v1/user/balance` 而失败,并在生成前被笼统报为 `LLM provider 'deepseek' is not available`。默认地址改为 `https://api.deepseek.com`,与官方 API 路径一致;已有配置若显式写入过 `.../v1`,需用 `quicommit config set-llm deepseek` 重新选择或手动修改
### 📚 文档
- README(中/英文)DeepSeek 配置示例的 `--base-url` 同步去掉 `/v1`
- README(中/英文)命令参考新增 `quicommit ginit` 一行与 `ginit` 选项表
- 新增 ADR 0005(`init` 与 `ginit` 保持两个命令)与 ADR 0006(`ginit` 的产出边界);CONTEXT.md 补充 Repo init、Config init、Ecosystem marker、Initial branch 四个术语
- `.gitignore` 放开 `CONTEXT.md` 与 `adr/` 的忽略,使术语表与 ADR 进入版本跟踪
### 🔧 其他变更
- 新增 git 层 `src/git/init.rs`:`init_repo`、`apply_initial_branch`、`add_remote`、`open_repo_at`、`has_commits`、`is_bare`、`head_branch`、`configured_initial_branch`、`is_valid_remote_name`,全部走 git2 且不改动 `GitRepo` 的公开接口,命令层不直接引用 git2
- 新增 35 个 `ginit_*` 多语言消息,覆盖 7 种语言
- 新增 `tests/ginit_tests.rs` 的 18 个集成测试与 `src/git/init.rs` 的 11 个单元测试
## [0.8.1] - 2026-08-31
### ✨ 新功能
- `commit` 与 `tag` 命令新增 `--select-remote` 标志:仓库存在多个远程时,以多选形式交互式选择推送目标(可多选),与 `--push`、`--yes` 形成优先链(`--yes` > `--select-remote` > `--push`)
- 推送流程重构为共享的 `run_push_flow`,感知远程配置:请求的远程不存在时回退到按字母序首个可用远程并提示;多远程推送失败时输出已推送/未尝试清单
### 🐞 错误修复
- 修复未指定 `--no-color` 时对 `colored` 的强制颜色覆盖会破坏 TTY 自动检测的问题:现仅在明确禁用时才强制关闭颜色,管道输出保持无 ANSI 转义
### 📚 文档
- README(中/英文)同步补充 `--select-remote` 选项说明
### 🔧 其他变更
- 新增 `GitRepo::list_remotes()` 与 `GitRepo::resolve_push_target()` 辅助方法及单元测试
- 新增多语言推送消息(`push_skipped_no_remote`、`push_target_fallback`、`select_push_remotes`、`no_remotes_selected`、`push_multi_failed`),覆盖 7 种语言
- 新增 `tests/integration_tests.rs` 集成测试,覆盖远程解析与多远程推送流程
## [0.7.0] - 2026-08-21
### ✨ 新功能
- `changelog` 命令新增 `--no-generate` 标志:强制使用模板生成而非 AI 生成
- `tag` 命令支持从多个配置文件(`Cargo.toml` / `pyproject.toml`)读取版本并交互选择
### 🐞 错误修复
- 修复 `regex` 关闭默认 unicode 特性后 SEMVER 正则编译 panic:启用 `unicode-perl` 特性,恢复 `\d` 字符类可用性
### 🔧 其他变更
- `--yes` 参数行为调整:仅跳过交互提示,不再改变生成行为
- 统一使用工具函数替代 `println` 输出
## [0.6.1] - 2026-08-18

65
CONTEXT.md Normal file
View File

@@ -0,0 +1,65 @@
# QuiCommit
AI 辅助的 Git 提交、Tag 和 Changelog 管理 CLI 工具。
## Language
**Remote**:
Git 远程仓库配置名。QuiCommit 推送 commit/tag 的默认目标是 `origin`。仓库一个远程都没有时,创建后不询问推送、直接跳过并说明。`--select-remote` 开启后,在多远程仓库中弹出多选列表,可一次推送其中部分或全部远程。
_Avoid_: 远端、远程仓库地址
**Tag message**:
Tag 对象的注释消息。annotated tag 时写入,lightweight tag 时为空。QuiCommit 默认创建 annotated tag。
_Avoid_: Tag 消息、标签说明
**Changelog entry**:
一条版本发布记录,包含该版本所有变更按类别(Added / Changed / Fixed 等)分组。多个 entry 组成一个完整的 CHANGELOG.md 文件。
_Avoid_: 更新日志条目、发布说明
**Keep a Changelog**:
CHANGELOG.md 的标准格式。以 `# Changelog` 开头,版本章节按 `## [x.y.z] - YYYY-MM-DD` 排列,变更按 Added / Changed / Deprecated / Removed / Fixed / Security 分组。
_Avoid_: 标准 changelog
**Version bump**:
根据提交类型推断下一个版本号的操作。feat → Minor, fix → Patch, breaking change → Major。
_Avoid_: 版本升级、版本号递增
**--auto mode**:
从项目根目录的主流包管理器配置文件(Cargo.toml、package.json、pyproject.toml、pom.xml 等)中读取当前版本作为新 tag。若同时存在多个配置文件,列出所有发现的版本让用户选择。读取失败则回退到 commit 分析自动建议版本并提示用户确认。读取到的版本直接用作 tag name,不做自动 bump——假定用户已在配置文件中手动更新了版本号。
支持的项目配置文件:Cargo.toml、package.json、pyproject.toml、pom.xml、.gemspec、pubspec.yaml、build.sbt、project.clj、mix.exs、package.yaml(Haskell Stack)、Project.toml(Julia)、composer.json、.csproj、CMakeLists.txt、meson.build。
`go.mod` 存在时跳过配置文件读取,直接走 commit 分析——Go 项目约定以 git tag 为版本依据,go.mod 不含 version 字段。
_Avoid_: 自动模式
**Annotated tag**:
Git 中带有独立对象(包含 message、作者、时间戳)的 tag。`git tag -a` 或 `git2::Repository::tag()` 传入 message 时创建。
_Avoid_: 注释标签、带消息的 tag
**Lightweight tag**:
Git 中仅为一个 commit 指针的 tag,无独立对象。`git tag` 不带 `-a` 创建。
_Avoid_: 轻量标签
**Thinking mode**:
生成 commit/tag/changelog 内容时启用模型思考(reasoning)的生成模式,终端显示 "thinking..." 状态直到正文开始输出;仅部分 LLM provider 支持,不支持时自动降级为普通生成。通过 `--think/-t` 或配置 `thinking_enabled` 启用。
_Avoid_: 推理模式、reasoning mode
**Project config file**:
项目根目录下由包管理器/构建系统使用的配置文件,其中的 `version` 字段反映项目当前版本。结构化的(JSON/TOML/YAML/XML)用对应解析器读取,代码即配置的(.gemspec/build.sbt/project.clj/mix.exs)用正则提取。仅检查项目根目录,不递归子目录。解析失败静默跳过。
_Avoid_: 项目配置文件、版本文件
**Ecosystem marker**:
只凭「存在与否」就能判定目录属于哪个语言生态的根目录标志文件,不要求其内容可解析。与 Project config file 的区别是职责不同:后者要读出 version,前者只要认出生态,因此 versionless 的 package.json、workspace 继承版本的 Cargo.toml、go.mod 都是有效的 Ecosystem marker。仅检查项目根目录,不递归子目录。
_Avoid_: 语言检测文件、生态标志(口头可用,书面统一用 Ecosystem marker)
**Repo init**:
把一个普通目录变成 Git 仓库并备好起步内容的操作——建库、定 Initial branch、补 README 与忽略规则、按需挂 Remote。由 `ginit` 承担。
_Avoid_: 项目初始化、建仓、git 初始化
**Config init**:
创建或重置 QuiCommit 自身配置文件(LLM provider 与首个 Git Profile)的操作,由 `init` 承担。不创建 Git 仓库,也不写入工作目录任何文件。
_Avoid_: 初始化(单独使用时有歧义,必须区分 Config init 与 Repo init)
**Initial branch**:
新仓库里 HEAD 指向、尚无任何 commit 的第一个分支。QuiCommit 认定它是一次 Repo init 的产物,只能在尚不存在任何分支时确立,不得用于重命名已有仓库的当前分支。
_Avoid_: 默认分支、主分支、master 分支

View File

@@ -1,6 +1,6 @@
[package]
name = "quicommit"
version = "0.6.1"
version = "0.9.0"
edition = "2024"
authors = ["Sidney Zhang <zly@lyzhang.me>"]
description = "A powerful Git assistant tool with AI-powered commit/tag/changelog generation"
@@ -42,7 +42,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
# Utilities
chrono = { version = "0.4", features = ["serde"] }
regex = { version = "1.10", default-features = false, features = ["std", "perf"] }
regex = { version = "1.10", default-features = false, features = ["std", "perf", "unicode-perl"] }
roxmltree = "0.20"
colored = "2.1"
semver = "1.0"

View File

@@ -1,5 +1,8 @@
# QuiCommit Roadmap
> 本路线图按「已完成 / 进行中 / 计划中 / 长远规划」四档跟踪功能演进,并为"计划中"条目标注优先级(P0 = 核心必做,P1 = 重要增强,P2 = 探索性方向)。
> 更新约定:条目完成后请及时勾选并移入"已完成",避免已完成事项长期滞留在"计划中"栏目;新增条目请附带动机说明与优先级。
## 已完成 ✅
- [x] 基础 Git 操作(commit、tag、changelog)
@@ -14,98 +17,82 @@
- [x] 7 种语言国际化支持
- [x] 配置导出/导入(支持加密保护)
- [x] Profile Token 管理(PAT 等)
- [x] Git 凭证管理器(Credential Helper 协议、Windows/macOS/Linux 跨平台密钥环对接、PAT scope/有效期与过期提醒)
- [x] DeepSeek 最新模型支持(`deepseek-chat` / `deepseek-reasoner` / `deepseek-v4`)
- [x] 流式生成的 SSE(Server-Sent Events)基础接入
- [x] 一键初始化本地 Git 仓库(`quicommit ginit` / `gi`):建库、写最简 `README.md`、按根目录标志文件生成 `.gitignore`、确立初始分支、按 `--add` 添加远程,可用 `--profile` 套用已有 Git 配置;全程离线、不创建首个提交、不覆盖已有 `README.md` 与 `.gitignore`
---
## 进行中 🚧
暂无。
- (暂无)
---
## 计划中 📋
### 1. Git 凭证管理器
### 1. Agent Skills 技能包完善 `P0`(新增)
将 Git 凭证管理集成到 QuiCommit 中,统一管理 HTTPS 仓库的身份认证。
**动机**:`.claude/skills`、`skills/` 目录下现有内容零散,需要系统化沉淀为可复用的 QuiCommit Agent 技能,让编码助手(Claude、Qoder 等)能够开箱用地安装、调用 QuiCommit。
- [x] **Git Credential Helper 集成**
- 实现 `git credential-store` / `git-credential-libsecret` 等标准的 credential helper 协议
- 支持 `quicommit credential get|store|erase` 子命令
- 与系统密钥环无缝对接,复用已有的 `KeyringManager`
- [ ] **安装类技能:`install-quicommit`**
- 指导用户 / Agent 在 Windows / macOS / Linux 上安装 QuiCommit:Cargo 安装、预编译二进制、源码构建等途径
- 覆盖首次运行前的环境依赖检查(Git、系统密钥环服务等)
- [ ] **使用指导类技能:`use-quicommit`**
- 面向 Agent 的命令速查与调用范式:`commit` / `tag` / `changelog` / `config` / `profile` / `credential`,以及新增的 `ginit`
- 说明各命令的输入前提(如需要先 `quicommit init` 配置 LLM Provider)、典型输出与常见失败排查
- [ ] **技能内容规范**
- 统一采用 SKILL.md 结构(触发场景 / 使用方式 / 注意事项),与 `.claude/skills` 现有约定保持一致
- 技能内示例命令、参数需要与 `src/commands/` 的实际实现保持同步,避免文档漂移
- [ ] **发布与复用**
- 评估随 crate 发布(打包进 `skills/`)还是通过独立仓库 / 技能市场分发
- [x] **跨平台支持**
- Windows:集成 Windows Credential Manager
- macOS:集成 Keychain
- Linux:通过 Secret Service / D-Bus 对接 GNOME Keyring / KWallet
- [x] **安全增强**
- 支持 PAT(Personal Access Token)按 scope / 有效期管理
- 支持凭证过期检查和自动提醒
---
### 2. 新增模型支持
### 2. 新增模型支持 `P1`
扩展 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. 生成体验优化
### 3. 生成体验优化 `P1`
提升 AI 生成提交信息、标签说明和变更日志时的用户体验。
- [ ] **流式输出与实时反馈**
- [x] 支持 SSE(Server-Sent Events)流式生成
- [ ]终端打字机效果实时显示生成内容
- [ ]流式生成过程中支持 `Ctrl+C` 中断
- [ ] 终端打字机效果实时显示生成内容
- [ ] 流式生成过程中支持 `Ctrl+C` 中断
- [ ] **生成质量提升**
- 基于 commitlint 规则的后校验与自动修正
- 支持 Few-shot 示例引导(用户可自定义示例库)
- 生成结果的置信度评分与多候选方案
- [ ] **Diff 上下文增强**
- 智能 diff 摘要(大改动时自动压缩关键信息)
- 支持 `.gitattributes` 排除/包含规则
- 支持 `.gitattributes` 排除 / 包含规则
- 按文件类型分组生成更精准的提交描述
- [ ] **交互式编辑增强**
- 生成后支持内联编辑(类似 `git rebase -i` 体验)
- 支持重新生成指定部分(如 scope、description)
- 历史提交信息学习与风格适配
- [ ] **批量操作支持**
- 批量生成多个 commit(分组暂存区变更)
- `--dry-run` 预览模式(只生成本地查看,不写 Git)
- [ ] **性能优化**
- API 请求并发优化(多个模型同时生成候选)
- 本地缓存常用 prompt 模板

View File

@@ -15,6 +15,7 @@ A powerful AI-powered Git assistant for generating conventional commits, tags, a
## Features
- **Repository Initialization**: Bootstrap a local Git repository with `quicommit ginit` — create `.git`, write a minimal `README.md`, generate a `.gitignore` from detected ecosystems, set the initial branch, and add remotes. Runs fully offline and never creates the first commit
- **AI-Powered Generation**: Generate commits, tags, and changelogs using LLM APIs (Ollama, OpenAI, Anthropic, Kimi, DeepSeek, OpenRouter) or local models
- **Conventional Commits**: Full support for Conventional Commits and commitlint formats
- **Profile Management**: Manage multiple Git identities with SSH keys and GPG signing support
@@ -48,6 +49,28 @@ Requirements: Rust 1.70+, Git 2.0+
## Quick Start
### Initialize a Git Repository
```bash
# Bootstrap the current directory as a Git repository
quicommit ginit
# Specify the initial branch (default: init.defaultBranch, then main)
quicommit ginit -b dev
# Add remotes, repeatable: --add <URL> or --add <NAME>=<URL>
quicommit ginit --add https://github.com/user/repo.git
quicommit ginit --add upstream=git@github.com:user/repo.git
# Apply an existing Git profile to the new repository
quicommit ginit --profile work
# Preview only, write nothing
quicommit ginit --dry-run
```
`ginit` runs fully offline and is safe to re-run: it never creates the first commit and never overwrites an existing `README.md` or `.gitignore`.
### Initialize
```bash
@@ -236,6 +259,10 @@ quicommit profile token
quicommit config set-llm ollama
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
> ⚠️ **Security note**: passing your API key as a CLI argument puts it in your shell
> history and process list. Prefer running `quicommit config set-api-key` (or
> `config set-llm`) without the key to enter it via a hidden prompt instead.
# Configure OpenAI
quicommit config set-llm openai
quicommit config set-api-key YOUR_API_KEY
@@ -252,7 +279,7 @@ quicommit config set-llm kimi --base-url https://api.moonshot.cn/v1 --model moon
# Configure DeepSeek
quicommit config set-llm deepseek
quicommit config set-api-key YOUR_API_KEY
quicommit config set-llm deepseek --base-url https://api.deepseek.com/v1 --model deepseek-chat
quicommit config set-llm deepseek --base-url https://api.deepseek.com --model deepseek-chat
# Configure OpenRouter
quicommit config set-llm openrouter
@@ -303,6 +330,7 @@ quicommit config reset --force
| Command | Alias | Description |
|---------|-------|-------------|
| `quicommit init` | `i` | Initialize configuration |
| `quicommit ginit` | `gi` | Initialize a local Git repository |
| `quicommit commit` | `c` | Generate and create commit |
| `quicommit tag` | `t` | Generate and create tag |
| `quicommit changelog` | `cl` | Generate changelog |
@@ -310,6 +338,18 @@ quicommit config reset --force
| `quicommit config` | `cfg` | Manage settings |
| `quicommit credential` | — | Git credential helper (hidden, invoked by Git) |
### Ginit Options
| Option | Description |
|--------|-------------|
| `-b, --branch` | Initial branch name (default: global `init.defaultBranch`, then `main`) |
| `--add` | Add a remote: `--add <url>` (name defaults to `origin`) or `--add <name>=<url>`; repeatable |
| `--profile` | Apply an existing Git Profile to the new repository and record the directory mapping |
| `--dry-run` | Show the plan without creating anything |
| `-y, --yes` | Skip confirmation prompts only (output behavior unchanged) |
`ginit` runs fully offline: it never creates a remote repository on a hosting service, never checks remote reachability, never makes the first commit, and never overwrites an existing `README.md` or `.gitignore`.
### Commit Options
| Option | Description |
@@ -329,9 +369,10 @@ quicommit config reset --force
| `--commitlint` | Use commitlint format |
| `--no-verify` | Skip commit message verification |
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
| `-y, --yes` | Skip confirmation |
| `-y, --yes` | Skip confirmation prompts only (generation behavior unchanged) |
| `--push` | Push after committing |
| `--remote` | Specify remote repository (default: origin) |
| `--select-remote` | Interactively select push target(s) when the repo has multiple remotes |
### Tag Options
@@ -347,9 +388,10 @@ quicommit config reset --force
| `-f, --force` | Force overwrite existing tag |
| `-p, --push` | Push to remote |
| `-r, --remote` | Specify remote repository (default: origin) |
| `--select-remote` | Interactively select push target(s) when the repo has multiple remotes |
| `--dry-run` | Dry run |
| `-t, --think` | Enable LLM thinking/reasoning mode (overrides config) |
| `-y, --yes` | Skip confirmation |
| `-y, --yes` | Skip confirmation prompts only (generation behavior unchanged) |
### Changelog Options
@@ -366,10 +408,13 @@ quicommit config reset --force
| `--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 |
| `--no-generate` | Generate deterministically from template (no AI call) |
| `-y, --yes` | Skip confirmation prompts only (generation behavior unchanged) |
## Configuration File
> For a complete categorized reference — quick setup, every field, provider defaults, recipes, and troubleshooting — see [docs/configuration-guide.en.md](docs/configuration-guide.en.md).
Location:
- Linux: `~/.config/quicommit/config.toml`
- macOS: `~/Library/Application Support/quicommit/config.toml`
@@ -425,6 +470,9 @@ auto_generate = true
path = "CHANGELOG.md"
auto_generate = true
[output]
emoji = true
[repo_profiles]
"/path/to/work/project" = "work"
"/path/to/personal/project" = "personal"
@@ -436,7 +484,15 @@ auto_generate = true
|----------|-------------|
| `QUICOMMIT_CONFIG` | Configuration file path |
| `EDITOR` | Default editor |
| `NO_COLOR` | Disable colored output |
| `NO_COLOR` | Disable colored output and emoji decorations (any value) |
| `RUST_LOG` | Overrides `-v` log filtering (e.g. `debug`) |
## Global Options
- `-v, --verbose` (repeatable): `-v` shows info logs, `-vv` debug, `-vvv` trace.
- `--no-color`: disable colors **and** emoji decorations (highest priority).
- `--emoji` / `--no-emoji`: force emoji decorations on/off, overriding the `output.emoji` config value.
- Emoji decorations can also be configured via `config set output.emoji true|false`.
## Troubleshooting
@@ -453,7 +509,7 @@ quicommit config set llm.provider ollama
# Get configuration value
quicommit config get llm.provider
# Set API key (stored in system keyring)
# Set API key (stored in system keyring; omit the value for hidden prompt input)
quicommit config set-api-key YOUR_API_KEY
# Delete API key from keyring
@@ -533,6 +589,7 @@ src/
│ ├── changelog.rs
│ ├── profile.rs
│ ├── config.rs
│ ├── ginit.rs
│ └── init.rs
├── config/ # Configuration management
│ ├── manager.rs
@@ -541,7 +598,8 @@ src/
├── git/ # Git operations
│ ├── commit.rs
│ ├── tag.rs
│ └── changelog.rs
│ ├── changelog.rs
│ └── init.rs
├── llm/ # LLM integration (rig-core based)
│ ├── mod.rs
│ ├── prompts.rs

View File

@@ -0,0 +1,5 @@
# Multi-config version resolution for --auto mode
When `--auto` detects the project version, it reads from project config files (e.g. Cargo.toml, package.json). We extended this from 2 formats to 16. 11 formats are structured (JSON, TOML, XML), 5 are code-as-config (Ruby, Scala, Clojure, Elixir, CMake/Meson). We use structured parsers for the first group (adding only `roxmltree` for XML — YAML formats use regex to avoid a new dep) and regex for the second. When multiple config files coexist in the project root, we surface all found versions and let the user pick — rather than imposing a fixed priority order. A `go.mod` file causes an immediate skip to commit-analysis fallback (Go defines versions via git tags, not in go.mod). Only the project root is searched; subdirectories are not recursed.
**Considered Options**: A hardcoded priority list (e.g. Cargo.toml > package.json > …) was rejected because no ordering satisfies every polyglot project. Letting the user choose adds one interaction in the rare multi-config case and avoids surprising wrong picks.

View File

@@ -0,0 +1,7 @@
# LLM provider layer built on rig-core instead of hand-written clients
QuiCommit's LLM layer (commit/tag/changelog generation) moved from six hand-written HTTP clients to `rig-core` 0.41 (locked, `reqwest` + `rustls` features only, umbrella `rig` crate not used). Rationale: the hand-written layer accumulated duplicated SSE parsing, string-matching retry logic, inconsistent per-provider timeouts, and provider-specific bugs (Anthropic silently ignoring configured base_url, Ollama constructor panics); rig-core 0.41 natively supports all six providers and models reasoning/thinking as first-class typed content (streaming `Reasoning`/`ReasoningDelta` events), which matches QuiCommit's thinking-mode display feature. In exchange we accept rig's 0.x breaking-change velocity (upgrades require manual provider-diff review), no application-level retry on non-streaming requests, and the Ollama endpoint moving to `/api/chat`.
**Considered Options**: keep hand-writing (rejected — every new provider meant a full HTTP/SSE/retry suite; six near-duplicate implementations already); per-provider SDKs like async-openai plus hand-written rest (rejected — multiple API styles, no unified interface); rig-core (accepted — one dependency covers every current provider and normalizes reasoning content across them).
**Consequences**: user-visible behavior changes recorded in CHANGELOG for 0.6.0 (Ollama `/api/chat`, no non-streaming retry, credential-verify endpoint changes, Anthropic base_url now honored); rig-core upgrades must re-verify provider API changes before bumping the locked version.

View File

@@ -0,0 +1,7 @@
# Output channels, message prefixes, and the decoration switch
QuiCommit's user-facing output follows fixed conventions: stdout carries results and interactive content, stderr carries diagnostics; the hidden `credential` subcommand keeps stdout protocol-only (errors on stderr prefixed `[quicommit credential]`). Message text — `Messages` keys and inline command strings alike — never embeds emoji or status symbols; decoration prefixes (✓/✗/⚠/→, spinner frames) are applied only by the shared `utils` print helpers, so they can be toggled centrally. Decoration is configurable via `output.emoji` (bool, default on) with global `--emoji`/`--no-emoji` overrides (precedence: explicit flag > config > default); `--no-color`/`NO_COLOR` is highest priority and disables both color and decoration. When decorations are off, output is plain text with no severity labels — errors stay distinguishable via stderr and anyhow's `Error:` prefix. Emoji is not auto-disabled on non-tty (explicit control only), while color keeps `colored`'s existing tty auto-detection.
**Considered Options**: emoji embedded in message text per language (rejected — decoration duplicated across 7 languages, half-on states when toggling, and two competing styles already coexisted in the codebase); text severity labels (`Warning:`/`Error:`) substituted when decorations are off (rejected — 7-language label burden for marginal value; stream separation already distinguishes errors); auto-disabling emoji on non-tty (rejected — emoji is a content-level choice, not a terminal capability, and script authors get explicit control via `--no-emoji`).
**Consequences**: every future command author must route output through the helpers and keep message text decoration-free. Existing tests pinning English output stay valid because the default language is English. `--no-color` now also strips decorations — a behavior change from 0.6.x, where the flag was parsed but ignored (a review finding).

View File

@@ -0,0 +1,7 @@
# --yes only skips confirmation; explicit --no-generate for deterministic output
`--yes`/`-y` on commit, tag, and changelog now means only "skip interactive prompts" — generation behavior follows config and flags exactly as it would interactively. Previously `commit --yes` still AI-generated, while `tag --yes`/`changelog --yes` silently downgraded to a hardcoded `Release vX` message or template output when auto-generation was enabled — an undocumented three-way inconsistency. Deterministic non-AI output is now explicit: `tag --yes -m <message>` (the existing message flag) or `changelog --no-generate` (new flag, template-based). The tag message fallback (`Release {version}`) moves into `Messages` so it is localized.
**Considered Options**: keep the silent downgrade and only document it (rejected — a flag that claims to skip prompts must not also change what gets generated; it broke CI differently per command); make `--yes` always generate with no explicit opt-out (rejected — CI users need a deterministic, key-free path, which `--no-generate`/`-m` provide).
**Consequences**: users who relied on `tag --yes`/`changelog --yes` to avoid LLM calls must switch to `--no-generate` (changelog) or `-m` (tag). Help text and README update accordingly.

View File

@@ -0,0 +1,7 @@
# `init` and `ginit` stay two commands, one letter apart
QuiCommit's existing `init` bootstraps QuiCommit's own configuration (`config.toml`: LLM provider plus a first Git Profile), while the new `ginit` bootstraps a local Git repository in the current directory. The two names differ by a single character and appear next to each other in `quicommit --help`. We kept both rather than unifying them, because the CLI surface is public API: renaming `init` or folding repo creation into it would break existing users, existing alias tests, and ADR 0004's promise that `--yes` behaves identically per command. Disambiguation is carried by help text only — "Initialize quicommit configuration" versus "Initialize a local Git repository" — and by the CONTEXT.md pair **Config init** / **Repo init**.
**Considered Options**: rename the config flow to `config init` and hand `init` to repo creation (rejected — breaks existing users and their scripts, which is exactly the blast radius this release was scoped to avoid); nest it as `quicommit repo init` (rejected — would introduce a new top-level command group for a single command); pick a longer name like `gitinit` or `git-init` (rejected — no clearer than `ginit`, and less consistent with the existing terse alias set `i`/`c`/`t`/`cl`/`p`/`cfg`).
**Consequences**: `gi` is added as an alias, and every doc that lists commands must show the two help strings adjacent so the contrast is visible. Anyone later tempted to "clean up" this near-collision should read this ADR first: it is deliberate.

View File

@@ -0,0 +1,7 @@
# ginit prepares a repository and stops there
`quicommit ginit` writes `.git`, an Initial branch, `README.md`, `.gitignore` and Remote entries — and deliberately does not: create a first commit, apply a Git Profile unless `--profile` is passed, append anything to a pre-existing `README.md` or `.gitignore`, reuse QuiCommit's own root `.gitignore` as the template, contact a hosting API to create a remote repository, verify remote reachability, or set upstream tracking. Each of these was within reach and would have made the command look more capable, but all of them either destroy the property that makes `ginit` safe to run anywhere ("it only ever adds, never overwrites or deletes") or would silently pull the LLM pipeline, the network, and credential scopes into a command whose whole job is offline repo scaffolding. There is also no `--force`: `git init` is already idempotent on an existing repository, so the only thing `--force` could mean is deleting `.git`.
**Considered Options**: commit `README.md` + `.gitignore` as `chore: initial commit` (rejected — the user's week-old source files stay untracked, producing a repository that looks complete but is missing files, and it couples a local-only command to commit identity and message generation); apply `default_profile` automatically (rejected — it would rewrite signing keys and `core.sshCommand` in a repo the user did not ask us to configure, so the intent must be explicit); merge missing entries into an existing `.gitignore` (rejected — deciding whether `target/` is already covered means string-matching `/target`, `**/target/`, and directory rules, and a wrong match writes into a file the user maintains by hand); seed the template from the repository's own `.gitignore` (rejected — it carries QuiCommit-specific development artifacts: it ignores `Cargo.lock`, `config.toml`, `CONTEXT.md`, `adr/`, `.claude/`, plus `# OS` and `# IDE` sections that the roadmap entry explicitly rules out).
**Consequences**: after `ginit`, the first commit is still the user's action via `quicommit commit`, so `ginit` must print next-step guidance and must warn when no `user.name`/`user.email` can be resolved from either the repository or global config — otherwise the very next command fails with an error the user will blame on `ginit`. Users who want `.gitignore` entries added to an existing file must edit it themselves. Repo-creation capability lives in a new `src/git/init.rs` rather than on `GitRepo`, whose `open` diagnostic chain is built for repositories that already exist.

View File

@@ -0,0 +1,695 @@
# QuiCommit Configuration Guide
English | [简体中文](configuration-guide.md)
This guide is for readers who want a complete command of QuiCommit's configuration. It covers:
- **Quick setup**: get from "create a repo → configure an LLM → first commit" in three minutes
- **Detailed settings by category**: every field in the config file, its meaning, accepted values, and default
- **Command reference**: full tables for the `config` / `profile` subcommands
- **Environment variables and global options**
- **Common recipes** and **troubleshooting**
> For a feature overview, see [README.md](../README.md) (Chinese: [readme_zh.md](../readme_zh.md)).
> Definitions of configuration terms (Repo init, Config init, Initial branch, …) live in [CONTEXT.md](../CONTEXT.md).
---
## Table of Contents
1. [Quick Setup](#1-quick-setup)
2. [Config File Location and Precedence](#2-config-file-location-and-precedence)
3. [Detailed Settings by Category](#3-detailed-settings-by-category)
- [3.1 Application Metadata (version / default_profile)](#31-application-metadata-version--default_profile)
- [3.2 LLM and AI Generation ([llm])](#32-llm-and-ai-generation-llm)
- [3.3 Git Identities (profiles.*)](#33-git-identities-profiles)
- [3.4 Repository-to-Profile Mapping (repo_profiles)](#34-repository-to-profile-mapping-repo_profiles)
- [3.5 Commit Settings ([commit])](#35-commit-settings-commit)
- [3.6 Tag Settings ([tag])](#36-tag-settings-tag)
- [3.7 Changelog Settings ([changelog])](#37-changelog-settings-changelog)
- [3.8 Language Settings ([language])](#38-language-settings-language)
- [3.9 Output Settings ([output])](#39-output-settings-output)
4. [Config Command Reference (quicommit config)](#4-config-command-reference-quicommit-config)
5. [Profile Command Reference (quicommit profile)](#5-profile-command-reference-quicommit-profile)
6. [Tokens and Credentials](#6-tokens-and-credentials)
7. [Environment Variables](#7-environment-variables)
8. [Global Options](#8-global-options)
9. [Full Configuration Example](#9-full-configuration-example)
10. [Common Recipes](#10-common-recipes)
11. [Troubleshooting](#11-troubleshooting)
---
## 1. Quick Setup
### Prerequisites
| Requirement | Notes |
| --- | --- |
| Git | Any version works (repo initialization uses libgit2, so it does not rely on `git init -b`) |
| Rust / an installed `quicommit` | See the [README install section](../README.md#installation) |
| System keyring (recommended) | Windows Credential Manager / macOS Keychain / Linux Secret Service. Used to store API keys and PATs securely. Check with `quicommit config check-keyring` |
### Path A: Interactive wizard (recommended for first-time use)
```bash
quicommit init
```
The wizard asks, in order: output language → your first Git Profile (name / user name / email / description / work flag) → optional SSH → optional GPG → LLM provider → model → API key (hidden input, stored in the keyring). This is what CONTEXT.md calls **Config init** — it only creates QuiCommit's own config file and never touches a Git repository.
Skip every prompt and generate a minimal config from your local Git identity:
```bash
quicommit init --yes
```
### Path B: Bootstrap a repo + configure the LLM manually
```bash
# 1. Turn the current directory into a Git repository
# (creates .git, writes README, generates .gitignore, sets the initial branch)
quicommit ginit
# 2. Choose an LLM provider (interactive when no provider is given)
quicommit config set-llm deepseek
# 3. Set the API key (omit the value for hidden input; a literal value leaks into shell history)
quicommit config set-api-key
# 4. Verify connectivity
quicommit config test-llm
# 5. First commit
quicommit commit
```
### Verify the current configuration
```bash
quicommit config show # summarized view of all effective settings
quicommit config path # print the config file path
quicommit config get llm.provider
quicommit config check-keyring # check the keyring and related environment variables
```
---
## 2. Config File Location and Precedence
The configuration is a single TOML file whose default location is determined by the OS config directory:
| Platform | Default path |
| --- | --- |
| Linux | `~/.config/quicommit/config.toml` |
| macOS | `~/Library/Application Support/quicommit/config.toml` |
| Windows | `%APPDATA%\quicommit\config.toml` |
### Specifying a custom path
Precedence (highest to lowest):
1. The global CLI option `-c` / `--config <PATH>`
2. The environment variable `QUICOMMIT_CONFIG`
3. The platform default path above
```bash
quicommit -c ./my-config.toml config show
# or
QUICOMMIT_CONFIG=./my-config.toml quicommit config show
```
> This path is shared by every subcommand (`commit`, `tag`, `changelog`, `profile`, `ginit`, …).
> With a custom path, keyring entries are still keyed by provider / profile, independent of the config file path.
### Where each value comes from
| Setting | Precedence (high → low) |
| --- | --- |
| Config file path | `-c/--config` > `QUICOMMIT_CONFIG` > platform default |
| API key | Environment variable (`QUICOMMIT_API_KEY`, always first within a process) > keyring (default storage) > `llm.api_key` in the config file (only when `api_key_storage = "config"`) |
| Emoji decorations | `--no-color` (disables) > `--no-emoji` / `--emoji` > `output.emoji` config > on by default |
| Log level | `RUST_LOG` > number of `-v` flags |
| Initial branch (`ginit`) | `-b/--branch` > global `init.defaultBranch` > `main` |
---
## 3. Detailed Settings by Category
Each top-level table of the config file is documented field by field below. Every field lists **key / type / default**.
### 3.1 Application Metadata (version / default_profile)
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `version` | string | `"1"` | Config schema version, used for future migrations; normally left alone |
| `default_profile` | string (optional) | none | Default Git identity. Used when `profile apply` is called without a name and by `profile show` without a name |
### 3.2 LLM and AI Generation ([llm])
QuiCommit talks to six providers through [rig-core](https://github.com/0xPlaygrounds/rig): `ollama`, `openai`, `anthropic`, `kimi`, `deepseek`, `openrouter`.
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `provider` | string | `"ollama"` | Provider name, see the table below |
| `model` | string | `"llama2"` | Model name. When switching providers, if the current model is empty or still `llama2` it is replaced by that provider's default model |
| `base_url` | string (optional) | none (provider default) | Custom API base URL, for proxies, self-hosting, or regional endpoints |
| `max_tokens` | integer | `500` | Maximum output tokens per generation |
| `temperature` | float | `0.6` | Sampling temperature. Some providers override it (see "Temperature and thinking mode") |
| `timeout` | integer (seconds) | `30` | HTTP request timeout |
| `api_key_storage` | string | `"keyring"` | API key storage: `keyring` / `config` / `environment` |
| `api_key` | string (optional) | none | Only effective when `api_key_storage = "config"`; stored in plain text |
| `thinking_enabled` | bool | `false` | Whether thinking/reasoning mode is on by default (`--think` on `commit`/`tag`/`changelog` overrides it per run) |
| `thinking_budget_tokens` | integer (optional) | none (treated as `1024` at runtime) | Anthropic only: thinking budget in tokens |
#### Provider defaults at a glance
| provider | Default `base_url` | Default `model` | Needs an API key? |
| --- | --- | --- | --- |
| `ollama` | `http://localhost:11434` | `llama2` | No |
| `openai` | `https://api.openai.com/v1` | `gpt-4` | Yes |
| `anthropic` | `https://api.anthropic.com/v1` | `claude-3-sonnet-20240229` | Yes |
| `kimi` | `https://api.moonshot.cn/v1` | `kimi-k2.6` | Yes |
| `deepseek` | `https://api.deepseek.com` | `deepseek-v4-flash` | Yes |
| `openrouter` | `https://openrouter.ai/api/v1` | `openai/gpt-3.5-turbo` | Yes |
> `quicommit config list-models` prints a set of example model names for the current provider (for Ollama it tries to call the local `ollama list`).
#### The three API key storage modes
- `keyring` (default, recommended): stored in the system keyring; no plain text appears in `config.toml`. If the keyring is unavailable, `set-api-key` fails and suggests using an environment variable or `config`.
- `config`: written in plain text to `llm.api_key` in `config.toml`. Convenient but insecure; `set-api-key` prints a plain-text warning.
- `environment`: nothing is stored; you must set the environment variable yourself.
Setting and deleting:
```bash
# Option 1: interactively choose provider / model / base_url / API key
quicommit config set-llm deepseek
# Option 2: non-interactive, pass values directly
# (--api-key lands in shell history; prefer it only for CI)
quicommit config set-llm openai --model gpt-4o --base-url https://api.openai.com/v1
# Set/delete the API key on its own (omit the value for hidden input)
quicommit config set-api-key
quicommit config delete-api-key
```
#### Temperature and thinking mode
`--think` (or `thinking_enabled = true`) takes effect only on `deepseek`, `kimi`, `anthropic`, and `openai`; other providers silently fall back to normal generation. Per-provider parameter handling:
| provider | Normal mode | Thinking mode |
| --- | --- | --- |
| `ollama` | Uses `temperature` / `max_tokens` | Not supported, falls back |
| `deepseek` | Uses `temperature`; sends `thinking: disabled` explicitly | Omits temperature, streams |
| `kimi` | Forces `temperature = 0.6` (ignores config) | Forces `temperature = 1.0`, streams |
| `anthropic` | Uses `temperature` | Omits temperature; raises `max_tokens` to at least `thinking_budget_tokens + 100` (budget defaults to `1024`); streams |
| `openai` | Uses `temperature`; `o*` models explicitly disable reasoning | Omits temperature, streams |
| `openrouter` | Uses `temperature` / `max_tokens` | Not supported, falls back |
> CLI switches: `commit --think`, `tag --think`, `changelog --think`.
### 3.3 Git Identities (profiles.*)
Each profile is a set of Git identity + authentication settings you can switch on independently. Create them with `quicommit profile add` (interactive) or by editing the config file directly.
Top-level fields:
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | none | Profile name; must match the TOML table name. Letters, digits, `-`, `_` only, max 50 chars |
| `user_name` | string | none | Written to `user.name` |
| `user_email` | string | none | Written to `user.email`; must be a valid email address |
| `description` | string (optional) | none | Free-form note |
| `is_work` | bool | `false` | Whether this is a work identity (a display/filter flag only) |
| `organization` | string (optional) | none | Organization name (meaningful when `is_work = true`) |
| `signing_key` | string (optional) | none | Explicit signing key; falls back to `gpg.key_id` when unset |
#### `[profiles.<name>.settings]` — behavioral preferences
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `auto_sign_commits` | bool | `false` | When the profile is applied, write `commit.gpgsign = true` |
| `auto_sign_tags` | bool | `false` | When the profile is applied, write `tag.gpgsign = true` |
| `default_commit_format` | string (optional) | none | Preferred commit format for this profile: `conventional` / `commitlint` |
| `repo_patterns` | array of strings | `[]` | Path fragments used to match repositories to this profile |
| `llm_provider` | string (optional) | none | Preferred LLM provider for this profile (metadata, reserved) |
| `commit_template` | string (optional) | none | Custom commit message template |
#### `[profiles.<name>.ssh]` — SSH settings (optional)
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `private_key_path` | path (optional) | none | Path to the SSH private key (existence is validated) |
| `public_key_path` | path (optional) | none | Public key path; derived as `<key>.pub` from the private key when unset |
| `passphrase` | string (optional) | none | Key passphrase (stored encrypted) |
| `agent_forwarding` | bool | `false` | Whether to add `-A` |
| `ssh_command` | string (optional) | none | Fully custom SSH command; overrides the other fields when set |
| `known_hosts_file` | path (optional) | none | Adds `-o UserKnownHostsFile=<path>` |
Applying writes `core.sshCommand` into the local Git config. Command assembly: `ssh` + (`-A`) + (`-i <private key>`) + (`-o UserKnownHostsFile=<file>`); if `ssh_command` is set, it is used as-is.
#### `[profiles.<name>.gpg]` — GPG settings (optional)
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `key_id` | string | none | GPG Key ID, 16–40 uppercase hex characters |
| `program` | string | Windows: `gpg.exe`; otherwise: `gpg` | Written to `gpg.program` |
| `home_dir` | path (optional) | none | GPG home directory |
| `passphrase` | string (optional) | none | Passphrase (stored encrypted) |
| `use_agent` | bool | `true` | Whether to use gpg-agent |
Applying writes `gpg.program`, `user.signingkey`, and — per `settings.auto_sign_commits` / `settings.auto_sign_tags` — `commit.gpgsign` / `tag.gpgsign` into the local Git config.
#### Applying (writing to Git) and display
`profile apply` / `profile set-repo` / `profile switch` write the profile into Git config:
- Repo-level: `user.name`, `user.email`, plus the SSH / GPG keys noted above
- Global (`profile apply --global`): written into the global Git config
> Applying a profile first clears "managed" keys that the new profile will not set (`core.sshCommand`, `user.signingkey`, `commit.gpgsign`, `tag.gpgsign`, `gpg.program`) so stale identities do not linger.
### 3.4 Repository-to-Profile Mapping (repo_profiles)
Records "repository absolute path → profile name" so commands such as `profile show` can tell which identity a repository should use. It is written automatically by `profile set-repo` or `ginit --profile`; hand-editing is rarely needed.
```toml
[repo_profiles]
"/home/me/work/project" = "work"
"/home/me/personal/project" = "personal"
```
### 3.5 Commit Settings ([commit])
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `format` | string | `"conventional"` | Commit format: `conventional` or `commitlint` |
| `auto_generate` | bool | `true` | Whether to generate commit messages with AI by default (`commit --manual` turns it off per run) |
Format differences (see [validators.rs](../src/utils/validators.rs)):
- `conventional`: `<type>[scope][!]: <description>`, where type is one of 11 (feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert).
- `commitlint`: extends the conventional types (adds wip, init, update, remove, security) and additionally requires the subject not to start with an uppercase letter and not to end with a period.
```bash
quicommit config set commit.format conventional
quicommit config set-commit-format commitlint
quicommit config set commit.auto_generate false
```
### 3.6 Tag Settings ([tag])
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `version_prefix` | string | `"v"` | Tag version prefix, e.g. `v1.2.3` |
| `auto_generate` | bool | `true` | Whether to generate tag messages with AI by default |
```bash
quicommit config set tag.version_prefix v
quicommit config set-version-prefix v
```
### 3.7 Changelog Settings ([changelog])
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | string | `"CHANGELOG.md"` | Changelog file path |
| `auto_generate` | bool | `true` | Whether to generate changelogs with AI by default (`--no-generate` turns it off per run, using the template instead) |
```bash
quicommit config set changelog.path CHANGELOG.md
quicommit config set-changelog-path CHANGELOG.md
```
### 3.8 Language Settings ([language])
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `output_language` | string | `"en"` | Language for UI and generated text |
| `keep_types_english` | bool | `true` | Whether commit types (feat, fix, …) stay in English |
| `keep_changelog_types_english` | bool | `true` | Whether changelog categories (Added, Fixed, …) stay in English |
Supported language codes: `en`, `zh` (including `zh-cn` / `zh-tw`), `ja`, `ko`, `es`, `fr`, `de` (full names such as `english`, `chinese` are also accepted). An invalid code silently falls back to English.
```bash
quicommit config set-language zh # omit the argument for an interactive picker
quicommit config set language.output_language zh
quicommit config set-keep-types-english true
quicommit config set-keep-changelog-types-english true
```
### 3.9 Output Settings ([output])
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| `emoji` | bool | `true` | Whether to show decorations such as ✓ / ✗ / ⚠ / → |
```bash
quicommit config set output.emoji false
```
CLI overrides: `--no-color` disables colors and decorations together; `--emoji` / `--no-emoji` control decorations alone.
---
## 4. Config Command Reference (quicommit config)
Alias: `quicommit cfg`. With no subcommand it behaves like `config show`.
| Subcommand | Description |
| --- | --- |
| `config show` | Summarized view of current settings (general / LLM / commit / tag / language / changelog / security) |
| `config path` | Print the config file path |
| `config edit` | Open the config file in `$EDITOR` (or `$VISUAL`) |
| `config get <key>` | Read a single setting |
| `config set <key> <value>` | Write a single setting (see the key table below) |
| `config set-llm [provider]` | Configure the LLM interactively; accepts `--model` / `--base-url` / `--api-key` |
| `config set-api-key [key]` | Set the current provider's API key (hidden input when omitted) |
| `config delete-api-key` | Delete the API key from the current storage backend |
| `config set-commit-format <fmt>` | Set `conventional` / `commitlint` |
| `config set-version-prefix <prefix>` | Set the tag version prefix |
| `config set-changelog-path <path>` | Set the changelog path |
| `config set-language [code]` | Set the output language (interactive when omitted) |
| `config set-keep-types-english <bool>` | Keep commit types in English |
| `config set-keep-changelog-types-english <bool>` | Keep changelog categories in English |
| `config list-models` | List example/installed models for the current provider |
| `config test-llm` | Send a test request to verify provider connectivity |
| `config check-keyring` | Check keyring availability and related environment variables |
| `config export -o <file> [--password]` | Export the config (optionally encrypted) |
| `config import -i <file> [--password]` | Import a config |
| `config reset [--force]` | Reset to defaults |
### Keys accepted by `config set` / `config get`
| Key | Values |
| --- | --- |
| `llm.provider` | `ollama` / `openai` / `anthropic` / `kimi` / `deepseek` / `openrouter` |
| `llm.model` | any model name |
| `llm.base_url` | a URL |
| `llm.max_tokens` | integer |
| `llm.temperature` | float |
| `llm.timeout` | integer (seconds) |
| `llm.thinking_enabled` | `true` / `false` |
| `llm.thinking_budget_tokens` | integer |
| `llm.api_key_storage` | `keyring` / `config` / `environment` |
| `commit.format` | `conventional` / `commitlint` |
| `commit.auto_generate` | `true` / `false` |
| `tag.version_prefix` | string |
| `tag.auto_generate` | `true` / `false` |
| `changelog.path` | path string |
| `changelog.auto_generate` | `true` / `false` |
| `language.output_language` | language code |
| `language.keep_types_english` | `true` / `false` |
| `language.keep_changelog_types_english` | `true` / `false` |
| `output.emoji` | `true` / `false` |
> `config set` accepts only the keys above; anything else reports an "unknown config key" error.
> **The API key is not among them** — use `config set-api-key` / `config delete-api-key`.
> Boolean keys accept only the literals `true` / `false`.
---
## 5. Profile Command Reference (quicommit profile)
Alias: `quicommit p`. With no subcommand it behaves like `profile list`.
| Subcommand | Description |
| --- | --- |
| `profile add` | Create a profile interactively (name / user name / email / description / work flag / SSH / GPG / tokens) |
| `profile list` | List all profiles (the default is marked `●`) |
| `profile show [name]` | Show the current repo's Git config, the matched profile, and details |
| `profile edit <name>` | Edit interactively, with SSH / GPG / signing / tokens submenus |
| `profile copy <from> <to>` | Duplicate a profile (usage stats are not copied) |
| `profile remove <name>` | Delete a profile (also clears its keyring PATs) |
| `profile set-default <name>` | Set the default profile |
| `profile set-repo <name>` | Record the mapping for the current repo and apply it immediately |
| `profile switch` | Switch the default profile interactively, optionally applying it to the current repo |
| `profile apply [name] [--global]` | Apply a profile (defaults to `default`) to the current repo or the global Git config |
| `profile check [name]` | Compare a profile against the current repo's Git config |
| `profile stats [name]` | Show usage statistics |
| `profile token add <profile> <service>` | Add a service token (stored in the keyring) |
| `profile token remove <profile> <service>` | Remove a service token |
| `profile token list <profile>` | List tokens and their storage status |
---
## 6. Tokens and Credentials
### PAT (Personal Access Token)
PATs are used to push to private repositories on GitHub / GitLab and similar platforms. They are stored in the system keyring keyed by **profile + service name** (`config.toml` only records metadata such as type, description, and whether it is stored).
```bash
quicommit profile token add personal github
quicommit profile token list personal
quicommit profile token remove personal github
```
The service name is free-form (`github`, `gitlab`, `bitbucket`, …).
### Git Credential Helper
QuiCommit can act as a Git credential helper; once registered, Git asks it for the PAT during a push:
```bash
git config --global credential.helper quicommit
# or limit it to one host
git config --global credential.https://github.com.helper quicommit
```
`credential get|store|erase` is invoked automatically by Git and hidden from `--help`. To delete a stored credential:
```bash
echo "protocol=https
host=github.com" | git credential reject
```
### Import, export, and backup
```bash
# Plain-text export (PATs in the keyring are not included)
quicommit config export -o config-backup.toml
# Encrypted export (profile PATs are encrypted and bundled too)
quicommit config export -o config-backup.enc --password
# Import
quicommit config import -i config-backup.toml
quicommit config import -i config-backup.enc --password
```
> The encrypted export uses AES-GCM + Argon2; the file is prefixed with `ENCRYPTED:`. If a target config holds PATs but encryption is not enabled, import/export prints a plain-text warning.
---
## 7. Environment Variables
| Variable | Description |
| --- | --- |
| `QUICOMMIT_CONFIG` | Config file path (equivalent to `-c/--config`) |
| `QUICOMMIT_API_KEY` | API key for any provider; **always first within the process**, ahead of the keyring and the config file |
| `QUICOMMIT_<PROVIDER>_API_KEY` | Provider-specific API key (e.g. `QUICOMMIT_OPENAI_API_KEY`). Detected by the interactive `init` and shown by `config check-keyring` |
| `EDITOR` / `VISUAL` | Editor used by `config edit` (`EDITOR` wins) |
| `NO_COLOR` | Setting any value disables colors and emoji decorations |
| `RUST_LOG` | Overrides `-v` log filtering, e.g. `RUST_LOG=debug` |
> Note: the key resolution path used for real generation requests is `QUICOMMIT_API_KEY` → keyring → (when `api_key_storage = "config"`) the config file.
> The provider-specific `QUICOMMIT_<PROVIDER>_API_KEY` is currently used only by `init`'s detection and the `config check-keyring` display; to have it feed generation, set `QUICOMMIT_API_KEY` instead.
---
## 8. Global Options
All subcommands share these global options:
| Option | Description |
| --- | --- |
| `-v, --verbose` (repeatable) | `-v` info, `-vv` debug, `-vvv` trace |
| `-c, --config <PATH>` | Config file path |
| `--no-color` | Disable colors **and** emoji decorations (highest priority) |
| `--emoji` / `--no-emoji` | Force emoji decorations on/off, overriding `output.emoji` |
---
## 9. Full Configuration Example
```toml
version = "1"
default_profile = "personal"
# -- LLM ------------------------------------------------------------
[llm]
provider = "deepseek"
model = "deepseek-v4-flash"
# base_url = "https://api.deepseek.com" # omit to use the provider default
max_tokens = 500
temperature = 0.6
timeout = 30
api_key_storage = "keyring"
thinking_enabled = false
# thinking_budget_tokens = 1024 # Anthropic only
# -- Commit / tag / changelog --------------------------------------
[commit]
format = "conventional"
auto_generate = true
[tag]
version_prefix = "v"
auto_generate = true
[changelog]
path = "CHANGELOG.md"
auto_generate = true
# -- Language and output -------------------------------------------
[language]
output_language = "en"
keep_types_english = true
keep_changelog_types_english = true
[output]
emoji = true
# -- Personal identity ---------------------------------------------
[profiles.personal]
name = "personal"
user_name = "Your Name"
user_email = "you@example.com"
description = "Personal projects"
is_work = false
[profiles.personal.settings]
auto_sign_commits = false
auto_sign_tags = false
repo_patterns = []
# -- Work identity (with SSH + GPG) --------------------------------
[profiles.work]
name = "work"
user_name = "Your Name"
user_email = "you@company.com"
description = "Work projects"
is_work = true
organization = "Your Company"
[profiles.work.settings]
auto_sign_commits = true
auto_sign_tags = true
default_commit_format = "conventional"
repo_patterns = ["/work/"]
[profiles.work.ssh]
private_key_path = "/home/user/.ssh/id_ed25519_work"
agent_forwarding = true
[profiles.work.gpg]
key_id = "0123456789ABCDEF"
program = "gpg"
use_agent = true
# -- Repo -> identity mapping --------------------------------------
[repo_profiles]
"/home/user/work/project" = "work"
"/home/user/personal/project" = "personal"
```
---
## 10. Common Recipes
### Local Ollama (no API key)
```bash
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
quicommit config test-llm
```
### DeepSeek
```bash
quicommit config set-llm deepseek --model deepseek-v4-flash
quicommit config set-api-key # hidden input
# or in one shot: quicommit config set-llm deepseek --api-key <KEY>
```
### Dual work / personal identities
```bash
quicommit profile add # create "personal"
quicommit profile add # create "work" (optionally with SSH/GPG)
quicommit profile set-default personal
cd ~/work/project
quicommit profile set-repo work # record the mapping and apply it immediately
quicommit profile check work # verify it matches the repo's Git config
```
### In CI (no keyring)
```bash
export QUICOMMIT_API_KEY=<KEY> # the environment variable always wins
export QUICOMMIT_CONFIG=./ci-config.toml
quicommit commit --yes
```
### Enabling thinking mode
```bash
# Just this commit
quicommit commit --think
# On by default (takes effect for deepseek/kimi/anthropic/openai)
quicommit config set llm.thinking_enabled true
```
### Headless Linux (no Secret Service)
```bash
# Option 1: use an environment variable
export QUICOMMIT_API_KEY=<KEY>
# Option 2: store it in the config file (plain text; mind the file permissions)
quicommit config set llm.api_key_storage config
quicommit config set-api-key
```
---
## 11. Troubleshooting
### Corrupted config or an incompatible upgrade
```bash
quicommit config reset --force # reset to defaults
quicommit init # reconfigure
```
### API key errors
```bash
quicommit config check-keyring # is the keyring available, are env vars picked up?
quicommit config show # confirm provider and key mask status
quicommit config test-llm # end-to-end connectivity
```
- "keyring is not available": the system has no Secret Service (common on headless Linux). Use an environment variable or `api_key_storage = config`.
- "API key not configured": `set-api-key` did not take effect, or the environment variable is unset.
- A provider reports "not available": usually a `base_url` or credential problem. DeepSeek's default URL is `https://api.deepseek.com` (**without** `/v1`); if a legacy config explicitly wrote `/v1` and validation now fails, re-run `quicommit config set-llm deepseek`.
### Changes do not take effect
- Confirm you edited the effective config file: `quicommit config path` (remember `-c` / `QUICOMMIT_CONFIG` may change the path).
- Check whether a global option overrides the config: `--emoji`, `--no-emoji`, `--think`.
- Check environment-variable precedence: `QUICOMMIT_API_KEY`, `RUST_LOG`.
### Opening the config file
```bash
quicommit config edit # uses $EDITOR / $VISUAL
quicommit config show # read-only view
```

693
docs/configuration-guide.md Normal file
View File

@@ -0,0 +1,693 @@
# QuiCommit 配置指南
[English](configuration-guide.en.md) | 简体中文
本指南面向希望完整掌握 QuiCommit 配置的读者,覆盖:
- **快速设置**:三分钟跑通「建仓库 → 配 LLM → 第一次提交」
- **分类详细设置**:逐项说明配置文件里每个字段的含义、取值与默认值
- **命令参考**:`config` / `profile` 子命令全表
- **环境变量与全局选项**
- **常见场景配方**与**故障排除**
> 想先看功能全貌,请阅读 [README](../README.md)(中文版 [readme_zh.md](../readme_zh.md))。
> 配置术语(Repo init、Config init、Initial branch 等)的定义见 [CONTEXT.md](../CONTEXT.md)。
---
## 目录
1. [快速设置](#1-快速设置)
2. [配置文件位置与优先级](#2-配置文件位置与优先级)
3. [分类详细设置](#3-分类详细设置)
- [3.1 应用元信息(version / default_profile)](#31-应用元信息version--default_profile)
- [3.2 LLM 与 AI 生成(`[llm]`)](#32-llm-与-ai-生成llm)
- [3.3 Git 身份配置(`[profiles.*]`)](#33-git-身份配置profiles)
- [3.4 仓库到身份映射(`[repo_profiles]`)](#34-仓库到身份映射repo_profiles)
- [3.5 提交配置(`[commit]`)](#35-提交配置commit)
- [3.6 标签配置(`[tag]`)](#36-标签配置tag)
- [3.7 变更日志配置(`[changelog]`)](#37-变更日志配置changelog)
- [3.8 语言配置(`[language]`)](#38-语言配置language)
- [3.9 输出配置(`[output]`)](#39-输出配置output)
4. [配置命令参考(`quicommit config`)](#4-配置命令参考quicommit-config)
5. [身份配置命令参考(`quicommit profile`)](#5-身份配置命令参考quicommit-profile)
6. [令牌与凭据](#6-令牌与凭据)
7. [环境变量](#7-环境变量)
8. [全局选项](#8-全局选项)
9. [完整配置示例](#9-完整配置示例)
10. [常见场景配方](#10-常见场景配方)
11. [故障排除](#11-故障排除)
---
## 1. 快速设置
### 前置条件
| 依赖 | 说明 |
| --- | --- |
| Git | 任意版本均可(仓库初始化走 libgit2,不依赖 `git init -b`) |
| Rust / 已安装的 `quicommit` | 见 [README 安装章节](../README.md#installation) |
| 系统密钥环(推荐) | Windows 凭据管理器 / macOS Keychain / Linux Secret Service。用于安全存放 API Key 与 PAT。用 `quicommit config check-keyring` 检查 |
### 路线 A:交互式向导(推荐首次使用)
```bash
quicommit init
```
向导依次询问:输出语言 → 第一个 Git Profile(名称 / 用户名 / 邮箱 / 描述 / 是否工作身份)→ 可选 SSH → 可选 GPG → LLM provider → 模型 → API Key(隐藏输入,存入密钥环)。这与 CONTEXT.md 所说的 **Config init** 对应——只创建 QuiCommit 自己的配置文件,不碰 Git 仓库。
跳过所有提问、使用本机 Git 身份生成一份最小配置:
```bash
quicommit init --yes
```
### 路线 B:仓库起步 + 手动配 LLM
```bash
# ① 把当前目录变成 Git 仓库(建库、写 README、生成 .gitignore、定初始分支)
quicommit ginit
# ② 选择 LLM provider(无参数时进入交互选择)
quicommit config set-llm deepseek
# ③ 设置 API Key(省略值可隐藏输入;已带值时注意 shell 历史泄露)
quicommit config set-api-key
# ④ 验证连通性
quicommit config test-llm
# ⑤ 第一次提交
quicommit commit
```
### 验证当前配置
```bash
quicommit config show # 汇总展示所有生效配置
quicommit config path # 打印配置文件路径
quicommit config get llm.provider
quicommit config check-keyring # 检查密钥环与相关环境变量
```
---
## 2. 配置文件位置与优先级
配置文件是单个 TOML 文件,默认位置由操作系统的配置目录决定:
| 平台 | 默认路径 |
| --- | --- |
| Linux | `~/.config/quicommit/config.toml` |
| macOS | `~/Library/Application Support/quicommit/config.toml` |
| Windows | `%APPDATA%\quicommit\config.toml` |
### 指定自定义路径
优先级(从高到低):
1. 命令行全局选项 `-c` / `--config <PATH>`
2. 环境变量 `QUICOMMIT_CONFIG`
3. 上述平台默认路径
```bash
quicommit -c ./my-config.toml config show
# 或
QUICOMMIT_CONFIG=./my-config.toml quicommit config show
```
> 该路径会被所有子命令共享(`commit`、`tag`、`changelog`、`profile`、`ginit` 等)。
> 用自定义路径时,密钥环条目仍按 provider / profile 维度存取,与配置文件路径无关。
### 配置来源优先级汇总
| 配置项 | 优先级(高 → 低) |
| --- | --- |
| 配置文件路径 | `-c/--config` > `QUICOMMIT_CONFIG` > 平台默认 |
| API Key | 环境变量(`QUICOMMIT_API_KEY`,进程内始终优先) > 密钥环(默认存储方式) > 配置文件内 `llm.api_key`(仅当 `api_key_storage = "config"`) |
| Emoji 装饰 | `--no-color`(关闭) > `--no-emoji` / `--emoji` > 配置 `output.emoji` > 默认开启 |
| 日志级别 | `RUST_LOG` > `-v` 次数 |
| Initial branch(`ginit`) | `-b/--branch` > 全局 `init.defaultBranch` > `main` |
---
## 3. 分类详细设置
下面按配置文件的顶层表(table)逐项说明。每个字段都给出 **键名 / 类型 / 默认值**。
### 3.1 应用元信息(version / default_profile)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `version` | string | `"1"` | 配置结构版本,用于未来迁移,一般不手动改动 |
| `default_profile` | string(可省略) | 无 | 默认 Git 身份名。`profile apply` 不带参数、`profile show` 不带参数时使用它 |
### 3.2 LLM 与 AI 生成(`[llm]`)
QuiCommit 通过 [rig-core](https://github.com/0xPlaygrounds/rig) 统一对接六家 provider:`ollama`、`openai`、`anthropic`、`kimi`、`deepseek`、`openrouter`。
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `provider` | string | `"ollama"` | provider 名称,见下表 |
| `model` | string | `"llama2"` | 模型名。切换 provider 时若当前模型为空或仍是 `llama2`,会自动替换为该 provider 的默认模型 |
| `base_url` | string(可省略) | 无(用 provider 默认) | 自定义 API 地址,用于代理、私有部署或国内镜像 |
| `max_tokens` | 整数 | `500` | 单次生成的最大输出 token 数 |
| `temperature` | 浮点 | `0.6` | 采样温度。部分 provider 会覆盖它(见「温度与思考模式」) |
| `timeout` | 整数(秒) | `30` | HTTP 请求超时 |
| `api_key_storage` | string | `"keyring"` | API Key 存储方式:`keyring` / `config` / `environment` |
| `api_key` | string(可省略) | 无 | 仅当 `api_key_storage = "config"` 时生效,明文存于配置文件 |
| `thinking_enabled` | 布尔 | `false` | 默认是否启用思考/推理模式(`commit`/`tag`/`changelog` 的 `--think` 可临时覆盖) |
| `thinking_budget_tokens` | 整数(可省略) | 无(运行期按 `1024` 处理) | 仅 Anthropic 使用:思考预算 token |
#### Provider 默认值速查
| provider | 默认 `base_url` | 默认 `model` | 是否需要 API Key |
| --- | --- | --- | --- |
| `ollama` | `http://localhost:11434` | `llama2` | 否 |
| `openai` | `https://api.openai.com/v1` | `gpt-4` | 是 |
| `anthropic` | `https://api.anthropic.com/v1` | `claude-3-sonnet-20240229` | 是 |
| `kimi` | `https://api.moonshot.cn/v1` | `kimi-k2.6` | 是 |
| `deepseek` | `https://api.deepseek.com` | `deepseek-v4-flash` | 是 |
| `openrouter` | `https://openrouter.ai/api/v1` | `openai/gpt-3.5-turbo` | 是 |
> `quicommit config list-models` 会按当前 provider 打印一批示例模型名(Ollama 会尝试直接调用本机 `ollama list`)。
#### API Key 的三种存储方式
- `keyring`(默认,推荐):存入系统密钥环,`config.toml` 中不出现明文。密钥环不可用时 `set-api-key` 会报错并提示改用环境变量或 `config`。
- `config`:明文写入 `config.toml` 的 `llm.api_key`。方便但不安全,`set-api-key` 会给出明文告警。
- `environment`:不存储,要求你自行设置环境变量。
设置与删除:
```bash
# 方式一:交互式选择 provider / 模型 / base_url / API Key
quicommit config set-llm deepseek
# 方式二:非交互,直接给出参数(--api-key 会进入 shell 历史,建议仅用于 CI)
quicommit config set-llm openai --model gpt-4o --base-url https://api.openai.com/v1
# 单独设置/删除 API Key(省略值则隐藏输入)
quicommit config set-api-key
quicommit config delete-api-key
```
#### 温度与思考模式
`--think`(或配置 `thinking_enabled = true`)只在 `deepseek`、`kimi`、`anthropic`、`openai` 上生效;其余 provider 会自动降级为普通生成。各 provider 的参数处理如下:
| provider | 普通模式 | 思考模式 |
| --- | --- | --- |
| `ollama` | 使用 `temperature` / `max_tokens` | 不支持,降级 |
| `deepseek` | 使用 `temperature`;显式传 `thinking: disabled` | 省略 temperature,走流式 |
| `kimi` | 强制 `temperature = 0.6`(忽略配置) | 强制 `temperature = 1.0`,走流式 |
| `anthropic` | 使用 `temperature` | 省略 temperature;`max_tokens` 提升到至少 `thinking_budget_tokens + 100`,预算缺省 `1024`;走流式 |
| `openai` | 使用 `temperature`;`o*` 系列模型显式关闭推理 | 省略 temperature,走流式 |
| `openrouter` | 使用 `temperature` / `max_tokens` | 不支持,降级 |
> 命令层开关:`commit --think`、`tag --think`、`changelog --think`。
### 3.3 Git 身份配置(`[profiles.*]`)
每个 profile 是一组可独立启用的 Git 身份 + 认证设置。用 `quicommit profile add`(交互式)创建,或直接编辑配置文件。
顶层字段:
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `name` | string | 无 | profile 名,须与 TOML 表名一致。只允许字母、数字、`-`、`_`,最长 50 字符 |
| `user_name` | string | 无 | 写入 `user.name` |
| `user_email` | string | 无 | 写入 `user.email`,须符合邮箱格式 |
| `description` | string(可省略) | 无 | 备注 |
| `is_work` | 布尔 | `false` | 是否工作身份(仅作展示/筛选标记) |
| `organization` | string(可省略) | 无 | 组织名(`is_work = true` 时有意义) |
| `signing_key` | string(可省略) | 无 | 直接指定签名 key;未设置时回退到 `gpg.key_id` |
#### `[profiles.<name>.settings]` — 行为偏好
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `auto_sign_commits` | 布尔 | `false` | 应用该 profile 时是否写入 `commit.gpgsign = true` |
| `auto_sign_tags` | 布尔 | `false` | 应用该 profile 时是否写入 `tag.gpgsign = true` |
| `default_commit_format` | string(可省略) | 无 | 该 profile 偏好的提交格式:`conventional` / `commitlint` |
| `repo_patterns` | 字符串数组 | `[]` | 用于把仓库路径匹配到该 profile 的路径片段 |
| `llm_provider` | string(可省略) | 无 | 该 profile 偏好的 LLM provider(元数据,供未来使用) |
| `commit_template` | string(可省略) | 无 | 自定义提交信息模板 |
#### `[profiles.<name>.ssh]` — SSH 配置(可选)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `private_key_path` | 路径(可省略) | 无 | SSH 私钥路径(校验存在性) |
| `public_key_path` | 路径(可省略) | 无 | 公钥路径;未设置时按私钥推导 `<key>.pub` |
| `passphrase` | string(可省略) | 无 | 私钥口令(加密存储) |
| `agent_forwarding` | 布尔 | `false` | 是否加 `-A` |
| `ssh_command` | string(可省略) | 无 | 完全自定义的 SSH 命令;设置后覆盖其他字段 |
| `known_hosts_file` | 路径(可省略) | 无 | 追加 `-o UserKnownHostsFile=<path>` |
应用时写入 Git 本地配置 `core.sshCommand`。命令拼接规则:`ssh` +(`-A`)+(`-i <私钥>`)+(`-o UserKnownHostsFile=<文件>`);若 `ssh_command` 有值则直接使用它。
#### `[profiles.<name>.gpg]` — GPG 配置(可选)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `key_id` | string | 无 | GPG Key ID,须为 16–40 位十六进制大写字符 |
| `program` | string | Windows:`gpg.exe`;其他:`gpg` | 写入 `gpg.program` |
| `home_dir` | 路径(可省略) | 无 | GPG home 目录 |
| `passphrase` | string(可省略) | 无 | 口令(加密存储) |
| `use_agent` | 布尔 | `true` | 是否使用 gpg-agent |
应用时写入 Git 本地配置 `gpg.program`、`user.signingkey`,并按 `settings.auto_sign_commits` / `auto_sign_tags` 写入 `commit.gpgsign` / `tag.gpgsign`。
#### 应用(写出到 Git)与展示
`profile apply` / `profile set-repo` / `profile switch` 会把 profile 写入 Git 配置:
- 仓库级:`user.name`、`user.email`,以及上面提到的 SSH / GPG 相关键
- 全局(`profile apply --global`):写入全局 Git 配置
> 应用 profile 时会先清理「新 profile 不再设置」的受管键(`core.sshCommand`、`user.signingkey`、`commit.gpgsign`、`tag.gpgsign`、`gpg.program`),避免残留旧身份。
### 3.4 仓库到身份映射(`[repo_profiles]`)
把「仓库绝对路径 → profile 名」记录下来,供 `profile show` 等命令识别当前仓库应使用哪个身份。由 `profile set-repo` 或 `ginit --profile` 自动写入,一般无需手改。
```toml
[repo_profiles]
"/home/me/work/project" = "work"
"/home/me/personal/project" = "personal"
```
### 3.5 提交配置(`[commit]`)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `format` | string | `"conventional"` | 提交格式:`conventional` 或 `commitlint` |
| `auto_generate` | 布尔 | `true` | 是否默认用 AI 生成提交信息(`commit --manual` 可临时关闭) |
格式差异(见 [validators.rs](../src/utils/validators.rs)):
- `conventional`:`<type>[scope][!]: <description>`,type 取自 11 种(feat、fix、docs、style、refactor、perf、test、build、ci、chore、revert)。
- `commitlint`:在 conventional 基础上扩展 type(额外支持 wip、init、update、remove、security),并额外校验主题不以大写字母开头、不以句点结尾。
```bash
quicommit config set commit.format conventional
quicommit config set-commit-format commitlint
quicommit config set commit.auto_generate false
```
### 3.6 标签配置(`[tag]`)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `version_prefix` | string | `"v"` | tag 版本前缀,如 `v1.2.3` |
| `auto_generate` | 布尔 | `true` | 是否默认用 AI 生成 tag message |
```bash
quicommit config set tag.version_prefix v
quicommit config set-version-prefix v
```
### 3.7 变更日志配置(`[changelog]`)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `path` | string | `"CHANGELOG.md"` | 变更日志文件路径 |
| `auto_generate` | 布尔 | `true` | 是否默认用 AI 生成变更日志(`--no-generate` 可临时关闭,改用模版) |
```bash
quicommit config set changelog.path CHANGELOG.md
quicommit config set-changelog-path CHANGELOG.md
```
### 3.8 语言配置(`[language]`)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `output_language` | string | `"en"` | 界面/生成文案语言 |
| `keep_types_english` | 布尔 | `true` | 提交类型(feat、fix…)是否保持英文 |
| `keep_changelog_types_english` | 布尔 | `true` | 变更日志分类(Added、Fixed…)是否保持英文 |
支持的语言代码:`en`、`zh`(含 `zh-cn` / `zh-tw`)、`ja`、`ko`、`es`、`fr`、`de`(也接受 `english`、`chinese` 等全称)。无效代码会静默回退为英文。
```bash
quicommit config set-language zh # 省略参数则交互式选择
quicommit config set language.output_language zh
quicommit config set-keep-types-english true
quicommit config set-keep-changelog-types-english true
```
### 3.9 输出配置(`[output]`)
| 键 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `emoji` | 布尔 | `true` | 是否显示 ✓ / ✗ / ⚠ / → 等装饰符号 |
```bash
quicommit config set output.emoji false
```
命令行覆盖:`--no-color` 会同时关闭颜色与装饰;`--emoji` / `--no-emoji` 单独控制装饰。
---
## 4. 配置命令参考(`quicommit config`)
别名:`quicommit cfg`。不带子命令时等价于 `config show`。
| 子命令 | 说明 |
| --- | --- |
| `config show` | 汇总展示当前配置(通用 / LLM / 提交 / 标签 / 语言 / 变更日志 / 安全) |
| `config path` | 打印配置文件路径 |
| `config edit` | 用 `$EDITOR`(或 `$VISUAL`)打开配置文件 |
| `config get <key>` | 读取单个配置项 |
| `config set <key> <value>` | 写入单个配置项(见下方键表) |
| `config set-llm [provider]` | 交互式配置 LLM;可带 `--model` / `--base-url` / `--api-key` |
| `config set-api-key [key]` | 设置当前 provider 的 API Key(省略则隐藏输入) |
| `config delete-api-key` | 从当前存储方式中删除 API Key |
| `config set-commit-format <fmt>` | 设置 `conventional` / `commitlint` |
| `config set-version-prefix <prefix>` | 设置 tag 版本前缀 |
| `config set-changelog-path <path>` | 设置变更日志路径 |
| `config set-language [code]` | 设置输出语言(省略则交互式选择) |
| `config set-keep-types-english <bool>` | 提交类型是否保持英文 |
| `config set-keep-changelog-types-english <bool>` | 变更日志分类是否保持英文 |
| `config list-models` | 按当前 provider 列出示例/已安装模型 |
| `config test-llm` | 发送一次测试请求,验证 provider 连通性 |
| `config check-keyring` | 检查密钥环可用性与相关环境变量 |
| `config export -o <file> [--password]` | 导出配置(可选加密) |
| `config import -i <file> [--password]` | 导入配置 |
| `config reset [--force]` | 重置为默认配置 |
### `config set` / `config get` 支持的键
| 键 | 取值 |
| --- | --- |
| `llm.provider` | `ollama` / `openai` / `anthropic` / `kimi` / `deepseek` / `openrouter` |
| `llm.model` | 任意模型名 |
| `llm.base_url` | URL |
| `llm.max_tokens` | 整数 |
| `llm.temperature` | 浮点 |
| `llm.timeout` | 整数(秒) |
| `llm.thinking_enabled` | `true` / `false` |
| `llm.thinking_budget_tokens` | 整数 |
| `llm.api_key_storage` | `keyring` / `config` / `environment` |
| `commit.format` | `conventional` / `commitlint` |
| `commit.auto_generate` | `true` / `false` |
| `tag.version_prefix` | 字符串 |
| `tag.auto_generate` | `true` / `false` |
| `changelog.path` | 路径字符串 |
| `changelog.auto_generate` | `true` / `false` |
| `language.output_language` | 语言代码 |
| `language.keep_types_english` | `true` / `false` |
| `language.keep_changelog_types_english` | `true` / `false` |
| `output.emoji` | `true` / `false` |
> `config set` 只接受上表键名,其他键会报「未知配置键」。
> **API Key 不在其中**——请用 `config set-api-key` / `config delete-api-key`。
> 布尔键只接受字面 `true` / `false`。
---
## 5. 身份配置命令参考(`quicommit profile`)
别名:`quicommit p`。不带子命令时等价于 `profile list`。
| 子命令 | 说明 |
| --- | --- |
| `profile add` | 交互式新建 profile(名称 / 用户名 / 邮箱 / 描述 / 工作标记 / SSH / GPG / 令牌) |
| `profile list` | 列出所有 profile(默认项标 `●`) |
| `profile show [name]` | 展示当前仓库 Git 配置、匹配到的 profile 及详情 |
| `profile edit <name>` | 交互式编辑,含 SSH / GPG / 签名偏好 / 令牌子菜单 |
| `profile copy <from> <to>` | 复制 profile(不复制使用统计) |
| `profile remove <name>` | 删除 profile(同时清理其密钥环 PAT) |
| `profile set-default <name>` | 设置默认 profile |
| `profile set-repo <name>` | 为当前仓库记录映射并立即应用 |
| `profile switch` | 交互式切换默认 profile,可选是否应用到当前仓库 |
| `profile apply [name] [--global]` | 把 profile(默认取 default)应用到当前仓库或全局 Git 配置 |
| `profile check [name]` | 对比 profile 与当前仓库 Git 配置的差异 |
| `profile stats [name]` | 查看使用统计 |
| `profile token add <profile> <service>` | 添加服务令牌(存入密钥环) |
| `profile token remove <profile> <service>` | 移除服务令牌 |
| `profile token list <profile>` | 列出令牌及其存储状态 |
---
## 6. 令牌与凭据
### PAT(Personal Access Token)
PAT 用于把私有仓库推送到 GitHub / GitLab 等平台,按 **profile + 服务名** 维度存入系统密钥环(`config.toml` 中只记录元信息如类型、描述、是否已存储)。
```bash
quicommit profile token add personal github
quicommit profile token list personal
quicommit profile token remove personal github
```
服务名可自由填写(`github`、`gitlab`、`bitbucket` 等)。
### Git Credential Helper
QuiCommit 可作为 Git 凭据助手,注册后 Git 推送时会自动向它索取 PAT:
```bash
git config --global credential.helper quicommit
# 或限定主机
git config --global credential.https://github.com.helper quicommit
```
`credential get|store|erase` 由 Git 自动调用,命令隐藏在 `--help` 之外。删除已存凭据:
```bash
echo "protocol=https
host=github.com" | git credential reject
```
### 导入导出与备份
```bash
# 明文导出(不含密钥环中的 PAT)
quicommit config export -o config-backup.toml
# 加密导出(把 profile 的 PAT 一并加密打包)
quicommit config export -o config-backup.enc --password
# 导入
quicommit config import -i config-backup.toml
quicommit config import -i config-backup.enc --password
```
> 加密导出使用 AES-GCM + Argon2;导出文件以 `ENCRYPTED:` 前缀标识。若目标配置含有 PAT 却未启用加密,导入/导出会给出明文告警。
---
## 7. 环境变量
| 变量 | 说明 |
| --- | --- |
| `QUICOMMIT_CONFIG` | 配置文件路径(等价于 `-c/--config`) |
| `QUICOMMIT_API_KEY` | 任意 provider 的 API Key,**进程内始终优先**于密钥环与配置文件 |
| `QUICOMMIT_<PROVIDER>_API_KEY` | provider 专属 API Key(如 `QUICOMMIT_OPENAI_API_KEY`)。交互式 `init` 会检测它,`config check-keyring` 会展示它 |
| `EDITOR` / `VISUAL` | `config edit` 使用的编辑器(`EDITOR` 优先) |
| `NO_COLOR` | 设置任意值即关闭彩色与 Emoji 装饰 |
| `RUST_LOG` | 覆盖 `-v` 的日志过滤,如 `RUST_LOG=debug` |
> 注意:真正参与生成请求的 Key 解析路径是 `QUICOMMIT_API_KEY` → 密钥环 →(`api_key_storage = "config"` 时)配置文件。
> provider 专属的 `QUICOMMIT_<PROVIDER>_API_KEY` 目前仅用于 `init` 的检测与 `config check-keyring` 的展示;若要让它生效参与生成,请改设 `QUICOMMIT_API_KEY`。
---
## 8. 全局选项
所有子命令共享以下全局选项:
| 选项 | 说明 |
| --- | --- |
| `-v, --verbose`(可叠加) | `-v` info、`-vv` debug、`-vvv` trace |
| `-c, --config <PATH>` | 配置文件路径 |
| `--no-color` | 关闭颜色**与** Emoji 装饰(最高优先级) |
| `--emoji` / `--no-emoji` | 强制开启/关闭 Emoji 装饰,覆盖 `output.emoji` |
---
## 9. 完整配置示例
```toml
version = "1"
default_profile = "personal"
# ── LLM ─────────────────────────────────────────────────────────────
[llm]
provider = "deepseek"
model = "deepseek-v4-flash"
# base_url = "https://api.deepseek.com" # 省略则用 provider 默认
max_tokens = 500
temperature = 0.6
timeout = 30
api_key_storage = "keyring"
thinking_enabled = false
# thinking_budget_tokens = 1024 # 仅 Anthropic 使用
# ── 提交 / 标签 / 变更日志 ──────────────────────────────────────────
[commit]
format = "conventional"
auto_generate = true
[tag]
version_prefix = "v"
auto_generate = true
[changelog]
path = "CHANGELOG.md"
auto_generate = true
# ── 语言与输出 ──────────────────────────────────────────────────────
[language]
output_language = "zh"
keep_types_english = true
keep_changelog_types_english = true
[output]
emoji = true
# ── 个人身份 ────────────────────────────────────────────────────────
[profiles.personal]
name = "personal"
user_name = "Your Name"
user_email = "you@example.com"
description = "个人项目"
is_work = false
[profiles.personal.settings]
auto_sign_commits = false
auto_sign_tags = false
repo_patterns = []
# ── 工作身份(含 SSH + GPG) ───────────────────────────────────────
[profiles.work]
name = "work"
user_name = "Your Name"
user_email = "you@company.com"
description = "工作项目"
is_work = true
organization = "Your Company"
[profiles.work.settings]
auto_sign_commits = true
auto_sign_tags = true
default_commit_format = "conventional"
repo_patterns = ["/work/"]
[profiles.work.ssh]
private_key_path = "/home/user/.ssh/id_ed25519_work"
agent_forwarding = true
[profiles.work.gpg]
key_id = "0123456789ABCDEF"
program = "gpg"
use_agent = true
# ── 仓库 → 身份映射 ────────────────────────────────────────────────
[repo_profiles]
"/home/user/work/project" = "work"
"/home/user/personal/project" = "personal"
```
---
## 10. 常见场景配方
### 用本地 Ollama(无需 API Key)
```bash
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
quicommit config test-llm
```
### 用 DeepSeek
```bash
quicommit config set-llm deepseek --model deepseek-v4-flash
quicommit config set-api-key # 隐藏输入
# 或一次性:quicommit config set-llm deepseek --api-key <KEY>
```
### 工作 / 个人双身份
```bash
quicommit profile add # 建 personal
quicommit profile add # 再建 work(可配 SSH/GPG)
quicommit profile set-default personal
cd ~/work/project
quicommit profile set-repo work # 记录映射并立即应用到本仓库
quicommit profile check work # 校验是否与仓库 Git 配置一致
```
### 在 CI 中使用(无密钥环)
```bash
export QUICOMMIT_API_KEY=<KEY> # 环境变量始终优先
export QUICOMMIT_CONFIG=./ci-config.toml
quicommit commit --yes
```
### 启用思考模式
```bash
# 仅本次提交
quicommit commit --think
# 全局默认开启(对 deepseek/kimi/anthropic/openai 生效)
quicommit config set llm.thinking_enabled true
```
### Linux 无桌面环境(无 Secret Service)
```bash
# 方案一:改用环境变量
export QUICOMMIT_API_KEY=<KEY>
# 方案二:改存配置文件(明文,注意权限)
quicommit config set llm.api_key_storage config
quicommit config set-api-key
```
---
## 11. 故障排除
### 配置损坏或旧版本不兼容
```bash
quicommit config reset --force # 重置为默认
quicommit init # 重新配置
```
### API Key 相关报错
```bash
quicommit config check-keyring # 确认密钥环是否可用、环境变量是否被识别
quicommit config show # 确认 provider 与 Key 掩码状态
quicommit config test-llm # 端到端连通性
```
- 「keyring is not available」:系统无 Secret Service(常见于无桌面的 Linux)。改用环境变量或 `api_key_storage = config`。
- 「API key not configured」:`set-api-key` 未生效或环境变量未设置。
- provider 报「not available」:多为 `base_url` 或凭据问题。DeepSeek 的默认地址是 `https://api.deepseek.com`(**不带** `/v1`);若历史配置里显式写过 `/v1` 导致校验失败,请重新执行 `quicommit config set-llm deepseek`。
### 改了配置但行为没变
- 确认改的是生效的配置文件:`quicommit config path`(注意 `-c` / `QUICOMMIT_CONFIG` 可能改变了路径)。
- 检查全局选项是否覆盖了配置:`--emoji`、`--no-emoji`、`--think`。
- 检查环境变量优先级:`QUICOMMIT_API_KEY`、`RUST_LOG`。
### 打开配置文件
```bash
quicommit config edit # 使用 $EDITOR / $VISUAL
quicommit config show # 只读查看
```

View File

@@ -14,6 +14,7 @@
## 主要功能
- **仓库初始化**:用 `quicommit ginit` 一键起步本地 Git 仓库——建库、写最简 `README.md`、按识别出的生态生成 `.gitignore`、确立初始分支、添加远程。全程离线,不创建首个提交
- **AI智能生成**:使用LLM API(Ollama本地、OpenAI、Anthropic Claude、Kimi、DeepSeek、OpenRouter)生成提交信息、标签和变更日志
- **规范化提交**:支持Conventional Commits和commitlint格式规范
- **多配置管理**:为不同场景管理多个Git身份,支持SSH密钥和GPG签名配置
@@ -47,6 +48,28 @@ cargo install --path .
## 快速开始
### 初始化 Git 仓库
```bash
# 把当前目录初始化为 Git 仓库
quicommit ginit
# 指定初始分支(默认取全局 init.defaultBranch,缺省为 main)
quicommit ginit -b dev
# 添加远程,可重复传入:--add <URL> 或 --add <名称>=<URL>
quicommit ginit --add https://github.com/user/repo.git
quicommit ginit --add upstream=git@github.com:user/repo.git
# 把已有 Git 配置套用到新仓库
quicommit ginit --profile work
# 只预览,不写任何内容
quicommit ginit --dry-run
```
`ginit` 全程离线且可重复执行:不创建首个提交,也不覆盖已存在的 `README.md` 与 `.gitignore`。
### 初始化配置
```bash
@@ -230,6 +253,10 @@ quicommit profile token
quicommit config set-llm ollama
quicommit config set-llm ollama --base-url http://localhost:11434 --model llama2
> ⚠️ **安全提示**:把 API 密钥作为命令行参数传入会留在 shell history 与进程列表中。
> 建议直接运行 `quicommit config set-api-key`(或 `config set-llm`)不携带密钥,
> 以隐藏方式输入。
# 配置OpenAI
quicommit config set-llm openai
quicommit config set-api-key YOUR_API_KEY
@@ -246,7 +273,7 @@ quicommit config set-llm kimi --base-url https://api.moonshot.cn/v1 --model moon
# 配置DeepSeek
quicommit config set-llm deepseek
quicommit config set-api-key YOUR_API_KEY
quicommit config set-llm deepseek --base-url https://api.deepseek.com/v1 --model deepseek-chat
quicommit config set-llm deepseek --base-url https://api.deepseek.com --model deepseek-chat
# 配置OpenRouter
quicommit config set-llm openrouter
@@ -297,6 +324,7 @@ quicommit config reset --force
| 命令 | 别名 | 说明 |
|------|------|------|
| `quicommit init` | `i` | 初始化配置 |
| `quicommit ginit` | `gi` | 初始化本地 Git 仓库 |
| `quicommit commit` | `c` | 生成并执行提交 |
| `quicommit tag` | `t` | 生成并创建标签 |
| `quicommit changelog` | `cl` | 生成变更日志 |
@@ -304,6 +332,18 @@ quicommit config reset --force
| `quicommit config` | `cfg` | 管理应用配置 |
| `quicommit credential` | — | Git凭据助手(隐藏,由Git调用) |
### ginit命令选项
| 选项 | 说明 |
|------|------|
| `-b, --branch` | 初始分支名(默认取全局 `init.defaultBranch`,缺省时为 `main`) |
| `--add` | 添加远程:`--add <url>`(远程名默认 `origin`)或 `--add <name>=<url>`;可重复传入 |
| `--profile` | 把已有的 Git 配置应用到新仓库,并记录该目录到配置文件的映射 |
| `--dry-run` | 只展示计划,不实际创建任何内容 |
| `-y, --yes` | 仅跳过交互确认(产出内容不变) |
`ginit` 全程离线:不向托管平台创建远程仓库、不验证远程可达性、不创建首个提交,也不会覆盖已存在的 `README.md` 与 `.gitignore`。
### commit命令选项
| 选项 | 说明 |
@@ -323,9 +363,10 @@ quicommit config reset --force
| `--commitlint` | 使用commitlint格式 |
| `--no-verify` | 不验证提交信息 |
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
| `-y, --yes` | 仅跳过确认提示(生成行为不变) |
| `--push` | 提交后推送到远程 |
| `--remote` | 指定远程仓库(默认:origin) |
| `--select-remote` | 多远程仓库时交互式选择推送目标(可多选) |
### tag命令选项
@@ -341,9 +382,10 @@ quicommit config reset --force
| `-f, --force` | 强制覆盖已存在的标签 |
| `-p, --push` | 推送到远程 |
| `-r, --remote` | 指定远程仓库(默认:origin) |
| `--select-remote` | 多远程仓库时交互式选择推送目标(可多选) |
| `--dry-run` | 试运行 |
| `-t, --think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
| `-y, --yes` | 仅跳过确认提示(生成行为不变) |
### changelog命令选项
@@ -360,10 +402,13 @@ quicommit config reset --force
| `--format` | 格式(keep-a-changelog、github-releases) |
| `--dry-run` | 试运行(输出到stdout) |
| `--think` | 启用 LLM 思考/推理模式(覆盖配置) |
| `-y, --yes` | 跳过确认提示 |
| `--no-generate` | 使用模板确定性生成(不调用 AI) |
| `-y, --yes` | 仅跳过确认提示(生成行为不变) |
## 配置文件
> 完整的分类配置说明(快速设置、逐字段详解、provider 默认值、常见配方与故障排除)见 [docs/configuration-guide.md](docs/configuration-guide.md)。
配置文件位置:
- Linux: `~/.config/quicommit/config.toml`
- macOS: `~/Library/Application Support/quicommit/config.toml`
@@ -419,6 +464,9 @@ auto_generate = true
path = "CHANGELOG.md"
auto_generate = true
[output]
emoji = true
[repo_profiles]
"/path/to/work/project" = "work"
"/path/to/personal/project" = "personal"
@@ -430,7 +478,15 @@ auto_generate = true
|--------|------|
| `QUICOMMIT_CONFIG` | 配置文件路径 |
| `EDITOR` | 默认编辑器 |
| `NO_COLOR` | 禁用彩色输出 |
| `NO_COLOR` | 禁用彩色与 Emoji 装饰输出(任意值即生效) |
| `RUST_LOG` | 覆盖 `-v` 的日志过滤(例如 `debug`) |
## 全局选项
- `-v, --verbose`(可叠加):`-v` 显示 info 日志、`-vv` debug、`-vvv` trace。
- `--no-color`:禁用彩色**与** Emoji 装饰(最高优先级)。
- `--emoji` / `--no-emoji`:强制开启/关闭 Emoji 装饰,覆盖 `output.emoji` 配置。
- Emoji 装饰也可通过 `quicommit config set output.emoji true|false` 配置。
## 故障排除
@@ -447,7 +503,7 @@ quicommit config set llm.provider ollama
# 获取配置值
quicommit config get llm.provider
# 设置API密钥(存储在系统密钥环中)
# 设置API密钥(存储在系统密钥环中;省略密钥值可通过隐藏提示输入)
quicommit config set-api-key YOUR_API_KEY
# 从密钥环删除API密钥
@@ -527,6 +583,7 @@ src/
│ ├── changelog.rs
│ ├── profile.rs
│ ├── config.rs
│ ├── ginit.rs
│ └── init.rs
├── config/ # 配置管理
│ ├── manager.rs
@@ -535,7 +592,8 @@ src/
├── git/ # Git操作封装
│ ├── commit.rs
│ ├── tag.rs
│ └── changelog.rs
│ ├── changelog.rs
│ └── init.rs
├── llm/ # LLM 集成(基于 rig-core)
│ ├── mod.rs
│ ├── prompts.rs

View File

@@ -11,6 +11,7 @@ use crate::git::GitRepo;
use crate::git::find_repo;
use crate::git::{CommitInfo, changelog::*};
use crate::i18n::{Messages, translate_changelog_category};
use crate::utils::{print_progress, print_success, print_warning};
/// Generate changelog
#[derive(Parser)]
@@ -60,7 +61,11 @@ pub struct ChangelogCommand {
#[arg(long)]
think: bool,
/// Skip interactive prompts
/// Generate deterministically from template (no AI call)
#[arg(long, conflicts_with = "generate")]
no_generate: bool,
/// Skip interactive prompts only (generation behavior unchanged)
#[arg(short = 'y', long)]
yes: bool,
}
@@ -85,7 +90,7 @@ impl ChangelogCommand {
.unwrap_or_else(|| PathBuf::from(&config.changelog.path));
init_changelog(&path)?;
println!("{}", messages.initialized_changelog(&format!("{:?}", path)));
print_success(&messages.initialized_changelog(&path.display().to_string()));
return Ok(());
}
@@ -101,10 +106,7 @@ 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!("{}", messages.unknown_changelog_format(f)),
};
// Get version
@@ -120,7 +122,7 @@ impl ChangelogCommand {
};
// Get commits
println!("{}", messages.fetching_commits());
print_progress(messages.fetching_commits());
// Determine from_tag: use explicit --from, or auto-detect from changelog
let from_tag = self.resolve_from_tag(&repo, &output_path, &messages);
@@ -130,10 +132,10 @@ impl ChangelogCommand {
bail!("{}", messages.no_commits_found());
}
println!("{}", messages.found_commits(commits.len()));
print_success(&messages.found_commits(commits.len()));
// Generate changelog
let changelog = if self.generate || (config.changelog.auto_generate && !self.yes) {
let changelog = if self.generate || (config.changelog.auto_generate && !self.no_generate) {
self.generate_with_ai(&version, &commits, &messages).await?
} else {
self.generate_with_template(format, &version, &commits, language)?
@@ -161,12 +163,12 @@ impl ChangelogCommand {
println!("{}", "─".repeat(60));
let confirm = Confirm::new()
.with_prompt(messages.write_to_file(&format!("{:?}", output_path)))
.with_prompt(messages.write_to_file(&output_path.display().to_string()))
.default(true)
.interact()?;
if !confirm {
println!("{}", messages.cancelled().yellow());
print_warning(messages.cancelled());
return Ok(());
}
}
@@ -185,7 +187,11 @@ impl ChangelogCommand {
std::fs::write(&output_path, content)?;
}
println!("{} {:?}", messages.changelog_written(), output_path);
print_success(&format!(
"{} {}",
messages.changelog_written(),
output_path.display()
));
Ok(())
}
@@ -221,12 +227,13 @@ impl ChangelogCommand {
let manager = ConfigManager::new()?;
let language = manager.get_language().unwrap_or(Language::English);
println!("{}", messages.ai_generating_changelog());
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
generator
let spinner = crate::utils::Spinner::start(messages.ai_generating_changelog());
let result = generator
.generate_changelog_entry(version, commits, language)
.await
.await;
spinner.finish_clear();
result
}
fn generate_with_template(

View File

@@ -11,6 +11,7 @@ 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;
use crate::utils::{print_success, print_warning};
/// Generate and execute conventional commits
#[derive(Parser)]
@@ -75,7 +76,7 @@ pub struct CommitCommand {
#[arg(short = 't', long)]
think: bool,
/// Skip interactive prompts
/// Skip interactive prompts only (generation behavior unchanged)
#[arg(short = 'y', long)]
yes: bool,
@@ -86,6 +87,10 @@ pub struct CommitCommand {
/// Remote to push to
#[arg(long, default_value = "origin")]
remote: String,
/// Interactively select push target(s) when the repo has multiple remotes
#[arg(long)]
select_remote: bool,
}
impl CommitCommand {
@@ -121,13 +126,13 @@ 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());
let removed = repo.stage_all()?;
let removed = repo.stage_all(&messages)?;
println!("{}", messages.staged_all().green());
if !removed.is_empty() {
println!(
"{}",
format!("Removed {} ignored files from staging:", removed.len()).yellow()
);
print_warning(&format!(
"Removed {} ignored files from staging:",
removed.len()
));
for file in &removed {
println!(" • {}", file);
}
@@ -136,19 +141,19 @@ impl CommitCommand {
// Re-check status after staging to ensure changes are detected
let new_status = repo.status_summary()?;
if new_status.staged == 0 {
bail!("Failed to stage changes. Please try running 'git add -A' manually.");
bail!("{}", messages.failed_to_stage());
}
}
// Stage all if requested
if self.all {
let removed = repo.stage_all()?;
let removed = repo.stage_all(&messages)?;
println!("{}", messages.staged_all().green());
if !removed.is_empty() {
println!(
"{}",
format!("Removed {} ignored files from staging:", removed.len()).yellow()
);
print_warning(&format!(
"Removed {} ignored files from staging:",
removed.len()
));
for file in &removed {
println!(" • {}", file);
}
@@ -194,29 +199,21 @@ impl CommitCommand {
.interact()?;
if !confirm {
println!("{}", messages.commit_cancelled().yellow());
print_warning(messages.commit_cancelled());
return Ok(());
}
}
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()
@@ -226,34 +223,32 @@ impl CommitCommand {
};
if let Some(commit_oid) = result {
println!(
print_success(&format!(
"{} {}",
messages.commit_created().green().bold(),
commit_oid.to_string()[..8].to_string().cyan()
);
));
} else {
println!("{} successfully", messages.commit_amended().green().bold());
print_success(messages.commit_amended_successfully());
}
// Push after commit if requested or ask user
if self.push {
println!("\n{}", messages.pushing_commit(&self.remote));
repo.push(&self.remote, "HEAD")?;
println!("{}", messages.pushed_commit(&self.remote));
} else if !self.yes && !self.dry_run {
let should_push = Confirm::new()
.with_prompt(messages.push_after_commit())
.default(false)
.interact()?;
let branch = repo
.current_branch()
.unwrap_or_else(|_| "HEAD (detached)".to_string());
if should_push {
println!("\n{}", messages.pushing_commit(&self.remote));
repo.push(&self.remote, "HEAD")?;
println!("{}", messages.pushed_commit(&self.remote));
}
}
Ok(())
super::run_push_flow(
&repo,
&self.remote,
self.select_remote,
self.push,
self.yes,
&messages,
&messages.push_after_commit(&branch),
"HEAD",
|r| messages.pushing_commit(r, &branch),
|r| messages.pushed_commit(r, &branch),
)
}
fn create_date_commit(&self) -> String {
@@ -306,21 +301,22 @@ impl CommitCommand {
.await
.context("Failed to initialize LLM. Use --manual for manual commit.")?;
println!("{}", messages.ai_analyzing());
let spinner = crate::utils::Spinner::start(messages.ai_analyzing());
let language = manager.get_language().unwrap_or(Language::English);
let generated = if self.yes {
generator
.generate_commit_from_repo(repo, format, language)
.await?
.await
} else {
generator
.generate_commit_interactive(repo, format, language)
.await?
.generate_commit_interactive(repo, format, language, messages)
.await
};
spinner.finish_clear();
Ok(generated.to_conventional())
Ok(generated?.to_conventional())
}
async fn create_interactive_commit(

File diff suppressed because it is too large Load Diff

View File

@@ -1,458 +1,457 @@
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());
}
}
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().cloned().collect();
for name in &profile_names {
let registered = manager
.get_profile(name)
.map(|p| p.tokens.contains_key(&service))
.unwrap_or(false);
if registered {
if let Err(e) = manager.remove_token_from_profile(name, &service) {
eprintln!(
"[quicommit credential] failed to erase PAT for '{}': {}",
name, e
);
}
} else if let Ok(true) = manager.delete_orphan_pat(name, &service) {
// Keyring PAT without a config token entry (issue 24).
eprintln!(
"[quicommit credential] erased unregistered PAT for '{}' (service {}) from keyring",
name, service
);
}
}
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());
}
}

756
src/commands/ginit.rs Normal file
View File

@@ -0,0 +1,756 @@
use anyhow::{Result, anyhow, bail};
use clap::Parser;
use colored::Colorize;
use dialoguer::Confirm;
use std::fs;
use std::path::{Path, PathBuf};
use crate::config::Language;
use crate::config::manager::ConfigManager;
use crate::git::GitRepo;
use crate::git::init::{
add_remote, apply_initial_branch, configured_initial_branch, has_commits, head_branch,
init_repo, is_bare, is_valid_remote_name, open_repo_at,
};
use crate::i18n::Messages;
use crate::utils::{print_error, print_success, print_warning};
/// Initialize a local Git repository
#[derive(Parser)]
pub struct GinitCommand {
/// Name of the initial branch
#[arg(short = 'b', long, value_name = "NAME")]
branch: Option<String>,
/// Add a remote, repeatable: --add <URL> or --add <NAME>=<URL>
#[arg(long = "add", value_name = "NAME=URL")]
add: Vec<String>,
/// Apply a configured profile to the repository
#[arg(long, value_name = "NAME")]
profile: Option<String>,
/// Preview only, write nothing
#[arg(long)]
dry_run: bool,
/// Skip interactive prompts only (output unchanged)
#[arg(short = 'y', long)]
yes: bool,
}
#[derive(Clone, Copy)]
enum BranchSource {
Flag,
GitConfig,
Default,
Current,
KeptCommits,
}
impl BranchSource {
/// Why the preview shows the branch it shows.
fn reason(self, messages: &Messages) -> &str {
match self {
BranchSource::Flag => messages.ginit_branch_from_flag(),
BranchSource::GitConfig => messages.ginit_branch_from_git_config(),
BranchSource::Default => messages.ginit_branch_from_default(),
BranchSource::Current => messages.ginit_branch_unchanged(),
BranchSource::KeptCommits => messages.ginit_branch_kept_commits(),
}
}
}
struct Plan {
cwd: PathBuf,
dir_name: Option<String>,
create_repo: bool,
bare: bool,
branch: String,
branch_source: BranchSource,
apply_branch: bool,
readme_exists: bool,
gitignore_exists: bool,
ecosystems: Vec<&'static str>,
ignore_sections: Vec<&'static str>,
remotes: Vec<(String, String)>,
profile_name: Option<String>,
entries: usize,
}
impl GinitCommand {
pub async fn execute(&self, config_path: Option<PathBuf>) -> Result<()> {
let mut manager = match config_path.as_deref() {
Some(path) => ConfigManager::with_path(path)?,
None => ConfigManager::new()?,
};
let messages = Messages::new(manager.get_language().unwrap_or(Language::English));
let cwd = std::env::current_dir()?;
let existing = detect_repository(&cwd, &messages)?;
let plan = self.build_plan(&cwd, existing.as_ref(), &manager, &messages)?;
print_preview(&plan, &messages);
if self.dry_run {
println!("\n{}", messages.ginit_dry_run_note().yellow());
return Ok(());
}
if !self.yes {
let confirmed = Confirm::new()
.with_prompt(messages.ginit_confirm_prompt())
.default(true)
.interact()?;
if !confirmed {
print_warning(messages.cancelled());
return Ok(());
}
}
self.apply(&mut manager, existing, &plan, &messages)
}
fn build_plan(
&self,
cwd: &Path,
existing: Option<&GitRepo>,
manager: &ConfigManager,
messages: &Messages,
) -> Result<Plan> {
let create_repo = existing.is_none();
let bare = existing.is_some_and(is_bare);
let committed = existing.is_some_and(has_commits);
let computed = match self.branch.as_deref() {
Some(name) => (name.to_string(), BranchSource::Flag),
None => match configured_initial_branch() {
Some(name) => (name, BranchSource::GitConfig),
None => ("main".to_string(), BranchSource::Default),
},
};
// On an existing repository ginit only retargets an unborn HEAD: a
// branch that already carries commits is renamed by the user with
// `git branch -m`, and without `-b` the current branch is left alone.
let (branch, branch_source, apply_branch) = match existing {
None => (computed.0, computed.1, false),
Some(repo) if self.branch.is_none() => (
head_branch(repo).unwrap_or(computed.0),
BranchSource::Current,
false,
),
Some(repo) if committed => (
head_branch(repo).unwrap_or(computed.0),
BranchSource::KeptCommits,
false,
),
Some(_) => (computed.0, BranchSource::Flag, true),
};
let gitignore_exists = cwd.join(".gitignore").exists();
let sections = if bare || gitignore_exists {
Vec::new()
} else {
assemble_sections(cwd)
};
let profile_name = match self.profile.as_deref() {
Some(name) => {
if !manager.has_profile(name) {
bail!(
"{}\n{}",
messages.profile_not_found(name),
messages.ginit_profile_hint()
);
}
Some(name.to_string())
}
None => None,
};
Ok(Plan {
cwd: cwd.to_path_buf(),
dir_name: directory_name(cwd),
create_repo,
bare,
branch,
branch_source,
apply_branch,
readme_exists: cwd.join("README.md").exists(),
gitignore_exists,
ecosystems: detected_ecosystems(cwd),
ignore_sections: sections.iter().map(|(title, _)| *title).collect(),
remotes: parse_remotes(&self.add, messages)?,
profile_name,
entries: fs::read_dir(cwd)
.map(|read| read.filter_map(Result::ok).count())
.unwrap_or(0),
})
}
fn apply(
&self,
manager: &mut ConfigManager,
existing: Option<GitRepo>,
plan: &Plan,
messages: &Messages,
) -> Result<()> {
let mut results: Vec<(String, String)> = Vec::new();
let mut failures: Vec<String> = Vec::new();
// A repository is the foundation of every later step, so its failure
// ends the run instead of joining the summary of soft failures.
let repo = match existing {
Some(repo) => {
results.push((
messages.ginit_repository_label().to_string(),
messages.ginit_status_exists().to_string(),
));
repo
}
None => {
results.push((
messages.ginit_repository_label().to_string(),
messages.ginit_status_created().to_string(),
));
init_repo(&plan.cwd, &plan.branch)?
}
};
if plan.apply_branch {
if let Err(e) = apply_initial_branch(&repo, &plan.branch) {
failures.push(e.to_string());
} else {
results.push((
messages.ginit_branch_label().to_string(),
plan.branch.clone(),
));
}
}
for (file, exists, content) in [
(
"README.md",
plan.readme_exists,
plan.dir_name.as_ref().map(|name| format!("# {name}\n")),
),
(
".gitignore",
plan.gitignore_exists,
Some(gitignore_contents(&plan.cwd)),
),
] {
let status = write_start_file(&plan.cwd, plan.bare, file, exists, content, messages);
match status {
Ok(status) => results.push((file.to_string(), status)),
Err(e) => failures.push(format!("{file}: {e}")),
}
}
for (name, url) in &plan.remotes {
if repo.get_remote_url(name).is_ok() {
failures.push(messages.ginit_remote_exists(name));
} else if let Err(e) = add_remote(&repo, name, url) {
failures.push(e.to_string());
} else {
results.push((name.clone(), messages.ginit_status_added().to_string()));
}
}
if let Some(name) = &plan.profile_name {
match apply_profile(manager, &repo, name, messages) {
Ok(()) => results.push((
messages.profile_label().to_string(),
messages.ginit_status_applied().to_string(),
)),
Err(e) => failures.push(e.to_string()),
}
}
println!();
for (label, value) in &results {
println!(" {}: {}", label, value);
}
for failure in &failures {
print_error(failure);
}
// Completed steps are kept: ginit cannot tell its own output apart
// from content the user already had, so rolling back would delete work.
if !failures.is_empty() {
bail!("{}", messages.ginit_failed(failures.len()));
}
print_success(messages.ginit_success());
print_next_steps(&repo, messages);
Ok(())
}
}
/// The repository rooted exactly at `cwd`, or a refusal when `cwd` is merely
/// inside one: a nested run would add remotes to the outer repository.
fn detect_repository(cwd: &Path, messages: &Messages) -> Result<Option<GitRepo>> {
match open_repo_at(cwd) {
Ok(repo) => Ok(Some(repo)),
Err(_) => match enclosing_repo_path(cwd) {
Some(outer) => bail!(
"{}",
messages.ginit_nested_repo(&outer.display().to_string())
),
None => Ok(None),
},
}
}
fn enclosing_repo_path(cwd: &Path) -> Option<PathBuf> {
let mut dir = cwd.parent()?;
loop {
if dir.join(".git").exists() {
return Some(dir.to_path_buf());
}
dir = dir.parent()?;
}
}
fn directory_name(cwd: &Path) -> Option<String> {
let name = cwd.file_name()?.to_string_lossy().trim().to_string();
(!name.is_empty() && name != "." && name != "..").then_some(name)
}
/// Write one starter file, returning the status to report. Skipping a bare
/// repository, an existing file and an unusable directory name are decisions,
/// not failures, so they come back as `Ok`.
fn write_start_file(
cwd: &Path,
bare: bool,
file: &str,
exists: bool,
content: Option<String>,
messages: &Messages,
) -> Result<String> {
if bare {
return Ok(messages.ginit_status_skipped_bare().to_string());
}
if exists {
return Ok(messages.ginit_status_exists().to_string());
}
match content {
Some(content) => {
fs::write(cwd.join(file), content)?;
Ok(messages.ginit_status_created().to_string())
}
// Only README.md can lack a usable directory name.
None => Ok(messages.ginit_readme_no_name().to_string()),
}
}
fn parse_remotes(specs: &[String], messages: &Messages) -> Result<Vec<(String, String)>> {
let mut remotes: Vec<(String, String)> = Vec::new();
for spec in specs {
// A leading `NAME=` only counts as a name when git accepts it; that
// keeps URLs containing `=` on the URL side of the split.
let (name, url) = match spec.split_once('=') {
Some((name, url)) if is_valid_remote_name(name.trim()) => (name.trim(), url.trim()),
_ => ("origin", spec.trim()),
};
// A value with neither a path separator nor a scheme separator is a
// bare word, and a bare word means the user forgot the URL —
// `--add origin` would otherwise register a remote named origin
// pointing at a path called "origin".
let looks_like_address = url.contains('/') || url.contains(':');
let has_whitespace = url.chars().any(char::is_whitespace);
if name.is_empty() || !looks_like_address || has_whitespace {
bail!("{}", messages.ginit_remote_missing_url(spec));
}
if !is_valid_remote_name(name) {
bail!("{}", messages.ginit_remote_invalid_name(name));
}
if remotes.iter().any(|(given, _)| given == name) {
bail!("{}", messages.ginit_remote_duplicate(name));
}
remotes.push((name.to_string(), url.to_string()));
}
Ok(remotes)
}
fn apply_profile(
manager: &mut ConfigManager,
repo: &GitRepo,
name: &str,
messages: &Messages,
) -> Result<()> {
let profile = manager
.get_profile(name)
.ok_or_else(|| anyhow!("{}", messages.profile_not_found(name)))?;
profile.apply_to_repo(repo.inner())?;
manager.set_repo_profile(repo.path().to_string_lossy().to_string(), name.to_string())?;
manager.save()?;
Ok(())
}
fn print_preview(plan: &Plan, messages: &Messages) {
let rule = "─".repeat(60);
println!("\n{rule}");
println!("{}", messages.ginit_title().bold());
println!("{rule}");
println!(
" {}: {}",
messages.ginit_directory_label(),
plan.cwd.display()
);
if plan.entries > 0 {
println!(" {}", messages.ginit_files_present(plan.entries));
}
let repository = if plan.create_repo {
messages.ginit_repository_action_create()
} else {
messages.ginit_repository_action_keep()
};
println!(" {}: {}", messages.ginit_repository_label(), repository);
println!(
" {}: {} ({})",
messages.ginit_branch_label(),
plan.branch,
plan.branch_source.reason(messages)
);
let readme = if plan.bare {
messages.ginit_status_skipped_bare()
} else if plan.readme_exists {
messages.ginit_status_exists()
} else if plan.dir_name.is_none() {
messages.ginit_readme_no_name()
} else {
messages.ginit_status_will_create()
};
println!(" README.md: {readme}");
let gitignore = if plan.bare {
messages.ginit_status_skipped_bare()
} else if plan.gitignore_exists {
messages.ginit_status_exists()
} else {
messages.ginit_status_will_create()
};
println!(" .gitignore: {gitignore}");
if !plan.bare {
let ecosystems = if plan.ecosystems.is_empty() {
messages.none_value().to_string()
} else {
plan.ecosystems.join(", ")
};
println!(" {}: {}", messages.ginit_ecosystems_label(), ecosystems);
}
if !plan.ignore_sections.is_empty() {
println!(
" {}: {}",
messages.ginit_sections_label(),
plan.ignore_sections.join(", ")
);
}
if !plan.remotes.is_empty() {
println!(" {}:", messages.ginit_remotes_label());
for (name, url) in &plan.remotes {
println!(" {} {}", name.cyan(), url);
}
}
if let Some(name) = &plan.profile_name {
println!(" {}: {}", messages.profile_label(), name.cyan());
}
println!("{rule}");
}
fn print_next_steps(repo: &GitRepo, messages: &Messages) {
let mut steps: Vec<&str> = Vec::new();
if repo.get_user_name().is_err() || repo.get_user_email().is_err() {
steps.push(messages.ginit_next_identity());
}
if !has_commits(repo) {
steps.push(messages.ginit_next_commit());
if repo.list_remotes().is_ok_and(|remotes| !remotes.is_empty()) {
steps.push(messages.ginit_next_push());
}
}
if steps.is_empty() {
return;
}
println!("\n{}", messages.next_steps());
for (index, step) in steps.iter().enumerate() {
println!(" {}. {step}", index + 1);
}
}
/// Written whatever the directory contains. `.env` is here on purpose: an
/// unignored secrets file is the costliest mistake a starter template makes.
const BASELINE_SECTIONS: &[(&str, &[&str])] = &[
("# Build output", &["build/", "dist/"]),
("# Logs", &["*.log"]),
("# Temporary files", &["tmp/"]),
("# Environment files", &[".env", ".env.*"]),
];
/// Ecosystem markers → section title → entries. Table order is output order,
/// and only root-level exact file names count as markers.
const ECOSYSTEM_MARKERS: &[(&[&str], &str, &[&str])] = &[
(
&["Cargo.toml"],
"# Rust",
&["target/", "**/*.rs.bk", "*.pdb"],
),
(
&["package.json"],
"# Node",
&[
"node_modules/",
"npm-debug.log*",
"yarn-error.log",
"pnpm-debug.log*",
],
),
(
&["pyproject.toml", "requirements.txt", "setup.py"],
"# Python",
&["__pycache__/", "*.pyc", ".venv/", "venv/", ".pytest_cache/"],
),
(&["go.mod"], "# Go", &["vendor/", "*.out"]),
(&["pom.xml"], "# Maven", &["target/"]),
(
&["build.gradle", "build.gradle.kts"],
"# Gradle",
&[".gradle/"],
),
(&["Gemfile"], "# Ruby", &[".bundle/", "*.gem"]),
(&["composer.json"], "# PHP", &["vendor/"]),
(&["pubspec.yaml"], "# Flutter", &[".dart_tool/"]),
(
&["CMakeLists.txt"],
"# C/C++",
&["CMakeCache.txt", "CMakeFiles/"],
),
];
/// Markers present in the root of `dir`, in table order.
fn detected_ecosystems(dir: &Path) -> Vec<&'static str> {
ECOSYSTEM_MARKERS
.iter()
.flat_map(|(markers, ..)| markers.iter().copied())
.filter(|marker| dir.join(marker).exists())
.collect()
}
/// The sections a generated `.gitignore` carries, in output order: the baseline
/// plus every section whose markers are present, each entry kept only at its
/// first occurrence, and any section left with no entries dropped.
fn assemble_sections(dir: &Path) -> Vec<(&'static str, Vec<&'static str>)> {
let mut sections: Vec<(&'static str, Vec<&'static str>)> = Vec::new();
let mut seen: Vec<&'static str> = Vec::new();
for &(title, entries) in BASELINE_SECTIONS {
push_section(&mut sections, &mut seen, title, entries);
}
for &(markers, title, entries) in ECOSYSTEM_MARKERS {
if markers.iter().any(|marker| dir.join(marker).exists()) {
push_section(&mut sections, &mut seen, title, entries);
}
}
sections
}
/// Contents of a generated `.gitignore`.
fn gitignore_contents(dir: &Path) -> String {
assemble_sections(dir)
.into_iter()
.map(|(title, entries)| format!("{title}\n{}", entries.join("\n")))
.collect::<Vec<_>>()
.join("\n\n")
+ "\n"
}
fn push_section(
sections: &mut Vec<(&'static str, Vec<&'static str>)>,
seen: &mut Vec<&'static str>,
title: &'static str,
entries: &'static [&'static str],
) {
let kept: Vec<&'static str> = entries
.iter()
.copied()
.filter(|entry| !seen.contains(entry))
.collect();
if kept.is_empty() {
return;
}
seen.extend(kept.iter().copied());
sections.push((title, kept));
}
#[cfg(test)]
mod tests {
use crate::commands::ginit::{detected_ecosystems, gitignore_contents};
use std::fs;
use tempfile::TempDir;
const BASELINE_IGNORE: &str = r#"# Build output
build/
dist/
# Logs
*.log
# Temporary files
tmp/
# Environment files
.env
.env.*
"#;
fn dir_with(markers: &[&str]) -> TempDir {
let dir = TempDir::new().unwrap();
for marker in markers {
fs::write(dir.path().join(marker), "").unwrap();
}
dir
}
#[test]
fn test_gitignore_without_any_marker_is_the_baseline_only() {
let dir = dir_with(&[]);
let content = gitignore_contents(dir.path());
assert_eq!(content, BASELINE_IGNORE);
assert!(
content.contains(".env\n"),
"the baseline must ignore .env so secrets never reach the first commit"
);
}
#[test]
fn test_gitignore_adds_the_rust_section_after_the_baseline() {
let dir = dir_with(&["Cargo.toml"]);
let content = gitignore_contents(dir.path());
assert_eq!(
content,
format!("{BASELINE_IGNORE}\n# Rust\ntarget/\n**/*.rs.bk\n*.pdb\n")
);
assert!(
!content.contains("Cargo.lock"),
"Cargo.lock stays under version control so builds stay reproducible"
);
}
#[test]
fn test_gitignore_unions_two_ecosystems_and_keeps_duplicates_once() {
let dir = dir_with(&["Cargo.toml", "package.json"]);
let content = gitignore_contents(dir.path());
assert!(content.contains("# Rust\n"));
assert!(content.contains("# Node\nnode_modules/\n"));
assert_eq!(
content.matches("dist/").count(),
1,
"an entry owned by the baseline must not reappear in an ecosystem section"
);
assert_eq!(content.matches("target/").count(), 1);
}
#[test]
fn test_gitignore_omits_a_section_whose_entries_are_all_duplicates() {
let alone = dir_with(&["pom.xml"]);
assert_eq!(
gitignore_contents(alone.path()),
format!("{BASELINE_IGNORE}\n# Maven\ntarget/\n")
);
let with_rust = dir_with(&["Cargo.toml", "pom.xml"]);
let content = gitignore_contents(with_rust.path());
assert!(
!content.contains("# Maven"),
"a section left with no entries should disappear entirely, got: {content}"
);
}
#[test]
fn test_gitignore_hands_vendor_to_the_first_matching_ecosystem_only() {
let dir = dir_with(&["go.mod", "composer.json"]);
let content = gitignore_contents(dir.path());
assert!(content.contains("# Go\nvendor/\n*.out\n"));
assert!(
!content.contains("# PHP"),
"PHP has nothing left to contribute once Go owns vendor/, got: {content}"
);
}
#[test]
fn test_gitignore_content_is_lf_only_with_a_single_trailing_newline() {
let dir = dir_with(&["pyproject.toml"]);
let content = gitignore_contents(dir.path());
assert!(
!content.contains('\r'),
"generated files should use LF endings"
);
assert!(
!content.starts_with('\u{feff}'),
"generated files must not carry a BOM"
);
assert!(content.ends_with(".pytest_cache/\n"));
assert!(!content.ends_with("\n\n"));
}
#[test]
fn test_detected_ecosystems_lists_markers_in_the_directory_root() {
let dir = dir_with(&["package.json"]);
fs::create_dir(dir.path().join("sub")).unwrap();
fs::write(dir.path().join("sub").join("Cargo.toml"), "").unwrap();
let detected = detected_ecosystems(dir.path());
assert_eq!(detected, vec!["package.json"]);
}
}

View File

@@ -10,6 +10,7 @@ use crate::config::{GitProfile, Language};
use crate::i18n::Messages;
use crate::utils::keyring::{get_default_model, get_supported_providers, provider_needs_api_key};
use crate::utils::validators::validate_email;
use crate::utils::{print_success, print_warning};
/// Initialize quicommit configuration
#[derive(Parser)]
@@ -34,19 +35,16 @@ impl InitCommand {
if config_path.exists() && !self.reset {
if !self.yes {
let overwrite = Confirm::new()
.with_prompt("Configuration already exists. Overwrite?")
.with_prompt(messages.config_exists_overwrite())
.default(false)
.interact()?;
if !overwrite {
println!("{}", "Initialization cancelled.".yellow());
print_warning(messages.init_cancelled());
return Ok(());
}
} else {
println!(
"{}",
"Configuration already exists. Use --reset to overwrite.".yellow()
);
print_warning(messages.config_exists_use_reset());
return Ok(());
}
}
@@ -59,7 +57,7 @@ impl InitCommand {
let mut manager = ConfigManager::with_path_fresh(&config_path)?;
if self.yes {
self.quick_setup(&mut manager).await?;
self.quick_setup(&mut manager, &messages).await?;
} else {
self.interactive_setup(&mut manager).await?;
}
@@ -69,27 +67,52 @@ impl InitCommand {
let language = manager.get_language().unwrap_or(Language::English);
let messages = Messages::new(language);
println!("{}", messages.init_success().bold().green());
print_success(messages.init_success());
println!("\n{}: {}", messages.config_file(), config_path.display());
println!("\n{}:", messages.next_steps());
println!(" 1. Create a profile: {}", "quicommit profile add".cyan());
println!(" 2. Configure LLM: {}", "quicommit config set-llm".cyan());
println!(" 3. Start committing: {}", "quicommit commit".cyan());
println!(
" 1. {}: {}",
messages.next_steps_create_profile(),
"quicommit profile add".cyan()
);
println!(
" 2. {}: {}",
messages.next_steps_configure_llm(),
"quicommit config set-llm".cyan()
);
println!(
" 3. {}: {}",
messages.next_steps_start_committing(),
"quicommit commit".cyan()
);
Ok(())
}
async fn quick_setup(&self, manager: &mut ConfigManager) -> Result<()> {
async fn quick_setup(&self, manager: &mut ConfigManager, messages: &Messages) -> 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 name_result = git_config.get_string("user.name");
let email_result = git_config.get_string("user.email");
let name_missing = name_result.is_err();
let email_missing = email_result.is_err();
let user_name = name_result.unwrap_or_else(|_| "User".to_string());
let user_email = email_result.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.clone(), user_email.clone());
println!("\n{}", messages.quick_setup_summary().bold());
println!(" {}: {}", messages.profile_label(), "default".cyan());
println!(
" {}: {} <{}>",
messages.identity_label(),
user_name,
user_email
);
if name_missing || email_missing {
print_warning(messages.identity_placeholder_warning());
}
println!(" {}: {}", messages.llm_provider_label(), "ollama".cyan());
manager.add_profile("default".to_string(), profile)?;
manager.set_default_profile(Some("default".to_string()))?;
@@ -231,11 +254,8 @@ impl InitCommand {
let keyring_available = keyring.is_available();
if !keyring_available {
println!(
"\n{}",
"⚠ Keyring is not available on this system.".yellow()
);
println!("{}", keyring.get_status_message().yellow());
print_warning(messages.keyring_unavailable());
print_warning(&keyring.get_status_message());
}
let api_key = if provider_needs_api_key(&provider) {
@@ -246,11 +266,7 @@ impl InitCommand {
.ok();
if let Some(_key) = env_key {
println!(
"\n{} {}",
"✓".green(),
"Found API key in environment variable.".green()
);
print_success(messages.api_key_found_env());
None
} else if keyring_available {
let prompt = match provider.as_str() {
@@ -259,16 +275,13 @@ impl InitCommand {
"kimi" => messages.kimi_api_key(),
"deepseek" => messages.deepseek_api_key(),
"openrouter" => messages.openrouter_api_key(),
_ => "API Key",
_ => messages.api_key_prompt_other(),
};
let key: String = Input::new().with_prompt(prompt).interact_text()?;
let key: String = crate::utils::password_input(prompt)?;
Some(key)
} else {
println!(
"\n{}",
"Please set the QUICOMMIT_API_KEY environment variable.".yellow()
);
print_warning(messages.please_set_api_key_env());
None
}
} else {
@@ -277,24 +290,26 @@ impl InitCommand {
let default_model = get_default_model(&provider);
let model: String = Input::new()
.with_prompt("Model name")
.with_prompt(messages.model_name())
.default(default_model.to_string())
.interact_text()?;
let base_url: Option<String> = if provider == "ollama" {
let url: String = Input::new()
.with_prompt("Ollama server URL")
.with_prompt(messages.ollama_server_url())
.default("http://localhost:11434".to_string())
.interact_text()?;
Some(url)
} else {
let use_custom_url = Confirm::new()
.with_prompt("Use custom API base URL?")
.with_prompt(messages.use_custom_base_url())
.default(false)
.interact()?;
if use_custom_url {
let url: String = Input::new().with_prompt("Base URL").interact_text()?;
let url: String = Input::new()
.with_prompt(messages.base_url_plain())
.interact_text()?;
Some(url)
} else {
None
@@ -309,11 +324,7 @@ impl InitCommand {
&& provider_needs_api_key(&provider)
{
manager.set_api_key(&key)?;
println!(
"\n{} {}",
"✓".green(),
"API key stored securely in system keyring.".green()
);
print_success(messages.api_key_stored_keyring());
}
Ok(())
@@ -332,7 +343,7 @@ impl InitCommand {
.interact_text()?;
let pub_key_path: String = Input::new()
.with_prompt("SSH public key path (optional, leave empty to auto-detect)")
.with_prompt(messages.ssh_public_key_path())
.default(ssh_dir.join("id_rsa.pub").display().to_string())
.allow_empty(true)
.interact_text()?;
@@ -354,12 +365,12 @@ impl InitCommand {
};
let agent_forwarding = Confirm::new()
.with_prompt("Enable SSH agent forwarding (-A)?")
.with_prompt(messages.ssh_agent_forwarding())
.default(false)
.interact()?;
let known_hosts: String = Input::new()
.with_prompt("Custom known_hosts file path (optional)")
.with_prompt(messages.known_hosts_path())
.allow_empty(true)
.interact_text()?;
let known_hosts_file = if known_hosts.is_empty() {
@@ -369,7 +380,7 @@ impl InitCommand {
};
let custom_cmd: String = Input::new()
.with_prompt("Custom SSH command (optional, overrides all other SSH settings)")
.with_prompt(messages.custom_ssh_command())
.allow_empty(true)
.interact_text()?;
let ssh_command = if custom_cmd.is_empty() {

View File

@@ -2,6 +2,105 @@ pub mod changelog;
pub mod commit;
pub mod config;
pub mod credential;
pub mod ginit;
pub mod init;
pub mod profile;
pub mod tag;
use anyhow::{Result, bail};
use dialoguer::{Confirm, MultiSelect};
use crate::git::GitRepo;
use crate::i18n::Messages;
use crate::utils::{print_progress, print_success, print_warning};
/// Shared push flow for commit and tag: resolve the push target, honor the
/// `--yes` > `--select-remote` > `--push` priority chain, then push to the
/// chosen target(s). `progress_msg`/`success_msg` render the per-remote
/// status lines; `refspec` is "HEAD" for commit, the tag ref for tag.
pub(crate) fn run_push_flow(
repo: &GitRepo,
requested_remote: &str,
select_remote: bool,
push: bool,
yes: bool,
messages: &Messages,
confirm_prompt: &str,
refspec: &str,
progress_msg: impl Fn(&str) -> String,
success_msg: impl Fn(&str) -> String,
) -> Result<()> {
let Some((target, fell_back)) = repo.resolve_push_target(requested_remote)? else {
print_warning(&messages.push_skipped_no_remote());
return Ok(());
};
if fell_back && (push || !yes) {
print_warning(&messages.push_target_fallback(requested_remote, &target));
}
let remotes = if select_remote && !yes {
Some(repo.list_remotes()?)
} else {
None
};
let use_multi_select = remotes.as_ref().is_some_and(|r| r.len() > 1);
let targets: Vec<String> = if use_multi_select {
let remotes = remotes.unwrap();
let items: Vec<(&String, bool)> = remotes.iter().map(|r| (r, *r == target)).collect();
let selected = MultiSelect::new()
.with_prompt(messages.select_push_remotes())
.items_checked(&items)
.interact()?;
if selected.is_empty() {
print_warning(&messages.no_remotes_selected());
return Ok(());
}
selected.iter().map(|&i| remotes[i].clone()).collect()
} else if push {
vec![target]
} else if !yes {
if Confirm::new()
.with_prompt(confirm_prompt)
.default(false)
.interact()?
{
vec![target]
} else {
Vec::new()
}
} else {
Vec::new()
};
if targets.len() == 1 {
print_progress(&progress_msg(&targets[0]));
repo.push(&targets[0], refspec)?;
print_success(&success_msg(&targets[0]));
} else if targets.len() > 1 {
let fmt_list = |items: &[String]| {
if items.is_empty() {
"-".to_string()
} else {
items.join(", ")
}
};
for (i, remote_name) in targets.iter().enumerate() {
print_progress(&progress_msg(remote_name));
if let Err(e) = repo.push(remote_name, refspec) {
bail!(
"{}\n{}",
messages.push_multi_failed(
remote_name,
&fmt_list(&targets[..i]),
&fmt_list(&targets[i + 1..])
),
e
);
}
print_success(&success_msg(remote_name));
}
}
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,6 +13,7 @@ use crate::git::tag::{
};
use crate::git::{GitRepo, find_repo};
use crate::i18n::Messages;
use crate::utils::{print_success, print_warning};
/// Generate and create Git tags
#[derive(Parser)]
@@ -53,6 +54,10 @@ pub struct TagCommand {
#[arg(short, long, default_value = "origin")]
remote: String,
/// Interactively select push target(s) when the repo has multiple remotes
#[arg(long)]
select_remote: bool,
/// Dry run
#[arg(long)]
dry_run: bool,
@@ -61,7 +66,7 @@ pub struct TagCommand {
#[arg(short = 't', long)]
think: bool,
/// Skip interactive prompts
/// Skip interactive prompts only (generation behavior unchanged)
#[arg(short = 'y', long)]
yes: bool,
@@ -115,11 +120,11 @@ impl TagCommand {
{
let version_str = tag_name.trim_start_matches('v');
if let Err(e) = crate::utils::validators::validate_semver(version_str) {
println!("{}: {}", "Warning".yellow(), e);
print_warning(&format!("{}: {}", messages.warning(), e));
if !self.yes {
let proceed = Confirm::new()
.with_prompt("Proceed with this tag name anyway?")
.with_prompt(messages.proceed_invalid_tag_name())
.default(true)
.interact()?;
@@ -135,7 +140,7 @@ impl TagCommand {
None
} else if let Some(msg) = &self.message {
Some(msg.clone())
} else if self.generate || (config.tag.auto_generate && !self.yes) {
} else if self.generate || config.tag.auto_generate {
Some(
self.generate_tag_message(&repo, &tag_name, &messages)
.await?,
@@ -143,7 +148,7 @@ impl TagCommand {
} else if !self.yes {
Some(self.input_message_interactive(&tag_name, &messages)?)
} else {
Some(format!("Release {}", tag_name))
Some(messages.release_default(&tag_name))
};
// Show preview
@@ -165,13 +170,13 @@ impl TagCommand {
.interact()?;
if !confirm {
println!("{}", messages.tag_cancelled().yellow());
print_warning(messages.tag_cancelled());
return Ok(());
}
}
if self.dry_run {
println!("\n{} {}", messages.dry_run(), "- tag not created.".yellow());
println!("\n{}", messages.dry_run_tag_not_created().yellow());
return Ok(());
}
@@ -184,27 +189,21 @@ impl TagCommand {
builder.execute(&repo)?;
println!("{} {}", messages.tag_created().green(), tag_name.cyan());
print_success(&format!("{} {}", messages.tag_created(), tag_name.cyan()));
// Push if requested or ask user
if self.push {
println!("{}", messages.pushing_tag(&self.remote));
repo.push(&self.remote, &format!("refs/tags/{}", tag_name))?;
println!("{}", messages.pushed_tag(&self.remote));
} else if !self.yes && !self.dry_run {
let should_push = Confirm::new()
.with_prompt(messages.push_after_tag())
.default(false)
.interact()?;
if should_push {
println!("{}", messages.pushing_tag(&self.remote));
repo.push(&self.remote, &format!("refs/tags/{}", tag_name))?;
println!("{}", messages.pushed_tag(&self.remote));
}
}
Ok(())
super::run_push_flow(
&repo,
&self.remote,
self.select_remote,
self.push,
self.yes,
&messages,
messages.push_after_tag(),
&format!("refs/tags/{}", tag_name),
|r| messages.pushing_tag(r),
|r| messages.pushed_tag(r),
)
}
async fn select_version_interactive(
@@ -323,15 +322,16 @@ impl TagCommand {
};
if commits.is_empty() {
return Ok(format!("Release {}", version));
return Ok(messages.release_default(version));
}
println!("{}", messages.ai_generating_tag(commits.len()));
let generator = ContentGenerator::new_with_think(&manager, self.think, None).await?;
generator
let spinner = crate::utils::Spinner::start(&messages.ai_generating_tag(commits.len()));
let result = generator
.generate_tag_message(version, &commits, language)
.await
.await;
spinner.finish_clear();
result
}
async fn auto_detect_version(
@@ -418,7 +418,7 @@ impl TagCommand {
}
fn input_message_interactive(&self, version: &str, messages: &Messages) -> Result<String> {
let default_msg = format!("Release {}", version);
let default_msg = messages.release_default(version);
let use_editor = Confirm::new()
.with_prompt(messages.open_editor())

View File

@@ -278,6 +278,22 @@ impl ConfigManager {
Ok(())
}
/// Delete a PAT from the keyring even when no config token entry exists.
/// Returns true if a keyring entry was deleted (issue 24).
pub fn delete_orphan_pat(&self, profile_name: &str, service: &str) -> Result<bool> {
if let Some(profile) = self.get_profile(profile_name) {
let user_email = &profile.user_email;
if self.keyring.has_pat(profile_name, user_email, service) {
self.keyring.delete_pat(profile_name, user_email, service)?;
Ok(true)
} else {
Ok(false)
}
} else {
Ok(false)
}
}
/// Delete all PAT tokens for a profile (used when removing a profile)
pub fn delete_all_pats_for_profile(&self, profile_name: &str) -> Result<()> {
if let Some(profile) = self.get_profile(profile_name) {
@@ -658,6 +674,17 @@ impl ConfigManager {
self.modified = true;
}
/// Check if emoji decorations are enabled
pub fn emoji_enabled(&self) -> bool {
self.config.output.emoji
}
/// Set emoji decorations flag
pub fn set_emoji_enabled(&mut self, enabled: bool) {
self.config.output.emoji = enabled;
self.modified = true;
}
/// Export configuration to TOML string
pub fn export(&self) -> Result<String> {
toml::to_string_pretty(&self.config).context("Failed to serialize config")

View File

@@ -47,6 +47,10 @@ pub struct AppConfig {
/// Language settings
#[serde(default)]
pub language: LanguageConfig,
/// Output settings
#[serde(default)]
pub output: OutputConfig,
}
impl Default for AppConfig {
@@ -61,6 +65,7 @@ impl Default for AppConfig {
changelog: ChangelogConfig::default(),
repo_profiles: HashMap::new(),
language: LanguageConfig::default(),
output: OutputConfig::default(),
}
}
}
@@ -236,6 +241,20 @@ impl Default for LanguageConfig {
}
}
/// Output configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
/// Show emoji/symbol decorations (✓/✗/⚠/→)
#[serde(default = "default_true")]
pub emoji: bool,
}
impl Default for OutputConfig {
fn default() -> Self {
Self { emoji: true }
}
}
/// Supported languages
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {

View File

@@ -1,8 +1,10 @@
use crate::config::manager::ConfigManager;
use crate::config::{CommitFormat, Language};
use crate::git::{CommitInfo, GitRepo};
use crate::i18n::Messages;
use crate::llm::parsing::GeneratedCommit;
use crate::llm::rig::LlmClient;
use crate::utils::{eprint_warning, success_prefix};
use anyhow::{Context, Result};
/// Content generator using LLM
@@ -33,11 +35,9 @@ impl ContentGenerator {
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
);
let language = manager.get_language().unwrap_or(Language::English);
let messages = Messages::new(language);
eprint_warning(&messages.thinking_unsupported(provider));
thinking_enabled = false;
}
}
@@ -156,6 +156,7 @@ impl ContentGenerator {
repo: &GitRepo,
format: CommitFormat,
language: Language,
messages: &Messages,
) -> Result<GeneratedCommit> {
use dialoguer::Select;
@@ -167,33 +168,33 @@ impl ContentGenerator {
// Show diff summary
let files = repo.get_staged_files()?;
println!("\nStaged files ({}):", files.len());
println!("\n{}", messages.staged_files(files.len()));
for file in &files {
println!(" • {}", file);
}
// Generate initial commit
println!("\nGenerating commit message...");
println!("\n{}", messages.generating_commit_message());
let mut generated = self
.generate_commit_message(&diff, format, language)
.await?;
loop {
println!("\n{}", "─".repeat(60));
println!("Generated commit message:");
println!("{}", messages.generated_commit_message());
println!("{}", "─".repeat(60));
println!("{}", generated.to_conventional());
println!("{}", "─".repeat(60));
let options = vec![
"✓ Accept and commit",
"🔄 Regenerate",
"✏️ Edit",
"❌ Cancel",
format!("{} {}", success_prefix(), messages.accept_and_commit()),
messages.regenerate().to_string(),
messages.edit().to_string(),
messages.cancel().to_string(),
];
let selection = Select::new()
.with_prompt("What would you like to do?")
.with_prompt(messages.what_would_you_like_to_do())
.items(&options)
.default(0)
.interact()?;
@@ -201,7 +202,7 @@ impl ContentGenerator {
match selection {
0 => return Ok(generated),
1 => {
println!("Regenerating...");
println!("{}", messages.regenerating());
generated = self
.generate_commit_message(&diff, format, language)
.await?;
@@ -210,7 +211,7 @@ impl ContentGenerator {
let edited = crate::utils::editor::edit_content(&generated.to_conventional())?;
generated = self.parse_edited_commit(&edited, format)?;
}
3 => anyhow::bail!("Cancelled by user"),
3 => anyhow::bail!("{}", messages.cancelled_by_user()),
_ => {}
}
}

306
src/git/init.rs Normal file
View File

@@ -0,0 +1,306 @@
//! Repository creation primitives used by `quicommit ginit`.
//!
//! These live next to [`GitRepo`] rather than on it: opening an existing
//! repository and creating a new one share nothing but the handle they return.
use anyhow::{Context, Result, bail};
use git2::{Reference, Remote, Repository, RepositoryInitOptions};
use std::path::Path;
use super::GitRepo;
/// Create a repository at `path` with HEAD already attached to `initial_branch`.
pub fn init_repo<P: AsRef<Path>>(path: P, initial_branch: &str) -> Result<GitRepo> {
let path = path.as_ref();
ensure_valid_branch_name(initial_branch)?;
let mut opts = RepositoryInitOptions::new();
opts.initial_head(initial_branch);
Repository::init_opts(path, &opts).with_context(|| {
format!(
"Failed to create git repository at {} (initial branch: {})",
path.display(),
initial_branch
)
})?;
GitRepo::open(path)
.with_context(|| format!("Failed to open {} after creating it", path.display()))
}
/// Retarget HEAD to `branch`. Only meaningful while no commit exists yet.
pub fn apply_initial_branch(repo: &GitRepo, branch: &str) -> Result<()> {
ensure_valid_branch_name(branch)?;
repo.inner()
.set_head(&format!("refs/heads/{branch}"))
.with_context(|| format!("Failed to set the initial branch to {branch}"))
}
pub fn is_valid_remote_name(name: &str) -> bool {
// libgit2 accepts a leading '-', which would make the remote unusable as a
// command line argument (`git push --delete -lead-dash`).
!name.starts_with('-') && Remote::is_valid_name(name)
}
/// Register a remote. An existing name is refused rather than overwritten:
/// repointing a remote is the user's call, made with `git remote set-url`.
///
/// No name or existence pre-check lives here: `git_remote_create` errors on an
/// existing name, and the caller validates names before it gets this far.
pub fn add_remote(repo: &GitRepo, name: &str, url: &str) -> Result<()> {
repo.inner()
.remote(name, url)
.with_context(|| format!("Failed to add remote '{name}' pointing to {url}"))?;
Ok(())
}
fn ensure_valid_branch_name(branch: &str) -> Result<()> {
if Reference::is_valid_name(&format!("refs/heads/{branch}")) {
return Ok(());
}
bail!("Invalid branch name: {branch}")
}
/// Whether the repository already contains a commit.
///
/// `Repository::is_empty` is unusable here: it only reports empty when HEAD
/// matches `init.defaultbranch`, so a repository created on a custom initial
/// branch looks non-empty to it.
pub fn has_commits(repo: &GitRepo) -> bool {
repo.inner().head().is_ok()
}
/// The branch the repository is on, including one with no commit yet.
///
/// `GitRepo::current_branch` reads `Repository::head`, which fails on an unborn
/// branch even though HEAD still names the branch the repository starts on.
pub fn head_branch(repo: &GitRepo) -> Option<String> {
if let Ok(head) = repo.inner().head() {
return head.shorthand().map(str::to_string);
}
repo.inner()
.find_reference("HEAD")
.ok()?
.symbolic_target()
.and_then(|target| target.strip_prefix("refs/heads/"))
.map(str::to_string)
}
/// Open the repository rooted exactly at `path`, without searching upwards.
///
/// `GitRepo::open` discovers an enclosing repository, which is wrong here: a
/// plain subdirectory of a repository must read as "not a repository yet".
pub fn open_repo_at(path: &Path) -> Result<GitRepo> {
let repo = Repository::open(path)
.with_context(|| format!("No git repository rooted at {}", path.display()))?;
let workdir = repo
.workdir()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| path.to_path_buf());
let config = repo.config().ok();
Ok(GitRepo {
repo,
path: super::normalize_path_for_git2(&workdir),
config,
})
}
pub fn is_bare(repo: &GitRepo) -> bool {
repo.inner().is_bare()
}
/// The branch git would start a new repository on: `init.defaultBranch`, when
/// the user has set it to something non-empty.
pub fn configured_initial_branch() -> Option<String> {
git2::Config::open_default()
.ok()?
.get_string("init.defaultBranch")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
#[cfg(test)]
mod tests {
use crate::git::init::{
add_remote, apply_initial_branch, has_commits, head_branch, init_repo, is_bare,
is_valid_remote_name, open_repo_at,
};
use std::fs;
use tempfile::TempDir;
#[test]
fn test_init_repo_attaches_head_to_requested_initial_branch() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "dev").unwrap();
let head = repo.inner().find_reference("HEAD").unwrap();
assert_eq!(
head.symbolic_target(),
Some("refs/heads/dev"),
"HEAD should be attached to the requested Initial branch"
);
assert!(
!has_commits(&repo),
"a freshly created repository has no commits yet"
);
assert!(
dir.path().join(".git").exists(),
"the repository should be created at the requested path"
);
}
#[test]
fn test_init_repo_reports_branch_name_when_branch_is_invalid() {
let dir = TempDir::new().unwrap();
let err = init_repo(dir.path(), "bad branch")
.err()
.expect("an invalid branch name should be refused")
.to_string();
assert!(
err.contains("bad branch"),
"error should name the offending branch so the user knows what to fix, got: {err}"
);
}
#[test]
fn test_apply_initial_branch_moves_unborn_head_only() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "main").unwrap();
apply_initial_branch(&repo, "topic").unwrap();
let head = repo.inner().find_reference("HEAD").unwrap();
assert_eq!(head.symbolic_target(), Some("refs/heads/topic"));
}
#[test]
fn test_add_remote_records_name_and_url() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "main").unwrap();
add_remote(&repo, "origin", "https://example.com/origin.git").unwrap();
assert_eq!(
repo.get_remote_url("origin").unwrap(),
"https://example.com/origin.git"
);
}
#[test]
fn test_add_remote_rejects_a_name_that_already_exists() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "main").unwrap();
add_remote(&repo, "origin", "https://example.com/first.git").unwrap();
let err = add_remote(&repo, "origin", "https://example.com/second.git")
.unwrap_err()
.to_string();
assert!(
err.contains("origin"),
"error should name the conflicting remote, got: {err}"
);
assert_eq!(
repo.get_remote_url("origin").unwrap(),
"https://example.com/first.git",
"an existing remote URL must never be overwritten"
);
}
#[test]
fn test_has_commits_detects_the_first_commit() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "main").unwrap();
let sig = git2::Signature::now("Test User", "test@example.com").unwrap();
let tree = {
let tree_id = repo.inner().index().unwrap().write_tree().unwrap();
repo.inner().find_tree(tree_id).unwrap()
};
assert!(!has_commits(&repo));
repo.inner()
.commit(Some("HEAD"), &sig, &sig, "first commit", &tree, &[])
.unwrap();
assert!(has_commits(&repo));
}
#[test]
fn test_head_branch_reads_an_unborn_branch() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "dev").unwrap();
let sig = git2::Signature::now("Test User", "test@example.com").unwrap();
let tree = {
let tree_id = repo.inner().index().unwrap().write_tree().unwrap();
repo.inner().find_tree(tree_id).unwrap()
};
assert_eq!(head_branch(&repo).as_deref(), Some("dev"));
assert!(
repo.current_branch().is_err(),
"current_branch reads HEAD's commit, which an unborn branch does not have yet"
);
repo.inner()
.commit(Some("HEAD"), &sig, &sig, "first commit", &tree, &[])
.unwrap();
assert_eq!(head_branch(&repo).as_deref(), Some("dev"));
}
#[test]
fn test_open_repo_at_opens_the_repository_at_that_exact_path() {
let dir = TempDir::new().unwrap();
let repo = init_repo(dir.path(), "main").unwrap();
let reopened = open_repo_at(dir.path()).unwrap();
assert!(!is_bare(&reopened));
assert!(!has_commits(&reopened));
assert_eq!(reopened.path(), repo.path());
}
#[test]
fn test_open_repo_at_refuses_to_walk_up_to_a_parent_repository() {
let dir = TempDir::new().unwrap();
init_repo(dir.path(), "main").unwrap();
let nested = dir.path().join("sub");
fs::create_dir(&nested).unwrap();
assert!(
open_repo_at(&nested).is_err(),
"a plain subdirectory is not a repository of its own"
);
}
#[test]
fn test_is_bare_flags_a_repository_without_working_directory() {
let dir = TempDir::new().unwrap();
git2::Repository::init_bare(dir.path()).unwrap();
let repo = open_repo_at(dir.path()).unwrap();
assert!(is_bare(&repo));
}
#[test]
fn test_is_valid_remote_name_accepts_plain_names_and_rejects_unusable_ones() {
assert!(is_valid_remote_name("origin"));
assert!(is_valid_remote_name("upstream"));
assert!(!is_valid_remote_name(""));
assert!(!is_valid_remote_name("not allowed"));
assert!(!is_valid_remote_name("-lead-dash"));
}
}

View File

@@ -5,6 +5,7 @@ use std::path::{Component, Path, PathBuf};
pub mod changelog;
pub mod commit;
pub mod init;
pub mod tag;
fn normalize_path_for_git2(path: &Path) -> PathBuf {
@@ -76,7 +77,7 @@ fn try_open_repo_with_git2(path: &Path) -> Result<Repository> {
.or_else(|_| Repository::discover(&normalized))
.or_else(|_| Repository::open(&normalized));
repo.map_err(|e| anyhow::anyhow!("git2 failed: {}", e))
repo.map_err(|e| anyhow::anyhow!("Failed to open repository: {}", e))
}
fn try_open_repo_with_git_cli(path: &Path) -> Result<Repository> {
@@ -642,7 +643,7 @@ impl GitRepo {
}
/// Stage all changes including subdirectories, then remove ignored tracked files
pub fn stage_all(&self) -> Result<Vec<String>> {
pub fn stage_all(&self, messages: &crate::i18n::Messages) -> Result<Vec<String>> {
// Use git command for reliable staging (handles all edge cases)
let output = std::process::Command::new("git")
.args(["add", "-A"])
@@ -662,7 +663,11 @@ impl GitRepo {
match self.remove_ignored_from_index() {
Ok(removed) => Ok(removed),
Err(e) => {
eprintln!("Warning: failed to clean ignored files from index: {}", e);
crate::utils::eprint_warning(&format!(
"{}: {}",
messages.failed_clean_ignored(),
e
));
Ok(Vec::new())
}
}
@@ -937,16 +942,6 @@ impl GitRepo {
Ok(())
}
/// Create GPG signature for arbitrary content
fn create_gpg_signature_for_content(
&self,
_content: &str,
_gpg_program: &str,
_signing_key: &str,
) -> Result<String> {
Ok(String::new())
}
/// Delete a tag
pub fn delete_tag(&self, name: &str) -> Result<()> {
self.repo.tag_delete(name)?;
@@ -977,6 +972,29 @@ impl GitRepo {
Ok(url.to_string())
}
/// List all configured remote names, sorted alphabetically
pub fn list_remotes(&self) -> Result<Vec<String>> {
let names = self.repo.remotes()?;
let mut remotes: Vec<String> = names.iter().flatten().map(|s| s.to_string()).collect();
remotes.sort();
Ok(remotes)
}
/// Resolve the push target for a requested remote name.
/// Returns `None` when the repository has no remotes configured.
/// The flag marks that the requested remote was missing and the first
/// available remote (alphabetically) was used instead.
pub fn resolve_push_target(&self, requested: &str) -> Result<Option<(String, bool)>> {
let remotes = self.list_remotes()?;
if remotes.iter().any(|r| r == requested) {
return Ok(Some((requested.to_string(), false)));
}
match remotes.first() {
Some(first) => Ok(Some((first.clone(), true))),
None => Ok(None),
}
}
/// Check if working directory is clean
pub fn is_clean(&self) -> Result<bool> {
Ok(!self.has_changes()?)
@@ -1515,7 +1533,14 @@ mod tests {
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)
repo.repo
.tag(
"v0.1.0",
head.as_object(),
&repo.repo.signature().unwrap(),
"",
false,
)
.unwrap();
let tags = repo.get_tags().unwrap();
@@ -1541,7 +1566,13 @@ mod tests {
// Create lightweight tag
repo.repo
.tag("v0.1.0", head.as_object(), &repo.repo.signature().unwrap(), "", false)
.tag(
"v0.1.0",
head.as_object(),
&repo.repo.signature().unwrap(),
"",
false,
)
.unwrap();
let tags = repo.get_tags().unwrap();
@@ -1580,4 +1611,79 @@ mod tests {
"tag.target should be the commit OID, not the tag object OID"
);
}
#[test]
fn test_list_remotes_empty_when_no_remote_configured() {
let (_dir, repo) = init_test_repo();
let remotes = repo.list_remotes().unwrap();
assert!(remotes.is_empty(), "fresh repo should have no remotes");
}
#[test]
fn test_list_remotes_returns_all_names_sorted() {
let (_dir, repo) = init_test_repo();
repo.repo
.remote("upstream", "https://example.com/upstream.git")
.unwrap();
repo.repo
.remote("origin", "https://example.com/origin.git")
.unwrap();
let remotes = repo.list_remotes().unwrap();
assert_eq!(remotes, vec!["origin".to_string(), "upstream".to_string()]);
}
#[test]
fn test_resolve_push_target_none_when_no_remotes() {
let (_dir, repo) = init_test_repo();
assert_eq!(repo.resolve_push_target("origin").unwrap(), None);
}
#[test]
fn test_resolve_push_target_returns_requested_when_it_exists() {
let (_dir, repo) = init_test_repo();
repo.repo
.remote("upstream", "https://example.com/upstream.git")
.unwrap();
repo.repo
.remote("origin", "https://example.com/origin.git")
.unwrap();
assert_eq!(
repo.resolve_push_target("origin").unwrap(),
Some(("origin".to_string(), false))
);
}
#[test]
fn test_resolve_push_target_falls_back_to_first_available() {
let (_dir, repo) = init_test_repo();
repo.repo
.remote("upstream", "https://example.com/upstream.git")
.unwrap();
repo.repo
.remote("bitbucket", "https://example.com/bitbucket.git")
.unwrap();
// "origin" is missing; alphabetically first available remote wins
assert_eq!(
repo.resolve_push_target("origin").unwrap(),
Some(("bitbucket".to_string(), true))
);
}
#[test]
fn test_resolve_push_target_single_non_requested_remote_falls_back() {
let (_dir, repo) = init_test_repo();
repo.repo
.remote("upstream", "https://example.com/upstream.git")
.unwrap();
assert_eq!(
repo.resolve_push_target("origin").unwrap(),
Some(("upstream".to_string(), true))
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
pub mod commands;
pub mod config;
pub mod generator;

View File

@@ -4,7 +4,7 @@
//! 全部 provider 接入并切换后,旧实现将被删除。
use crate::config::manager::ConfigManager;
use crate::llm::thinking::{create_console_thinking_state, ThinkingStateManager};
use crate::llm::thinking::{ThinkingStateManager, create_console_thinking_state};
use anyhow::{Context, Result, bail};
use rig_core::{
client::{CompletionClient, Nothing, VerifyClient},
@@ -154,7 +154,8 @@ fn required_api_key(provider: &str, key: Option<String>) -> Result<String> {
}
impl<H> LlmClient<H> {
/// 内部与测试构造入口。
/// 内部与测试构造入口(仅测试使用)。
#[cfg(test)]
pub(crate) fn new(
backend: Backend<H>,
model: impl Into<String>,
@@ -332,7 +333,9 @@ where
let language_instruction = match language {
crate::config::Language::Chinese => "\n\n请用中文生成提交消息。",
crate::config::Language::Japanese => "\n\n日本語でコミットメッセージを生成してください。",
crate::config::Language::Japanese => {
"\n\n日本語でコミットメッセージを生成してください。"
}
crate::config::Language::Korean => "\n\n한국어로 커밋 메시지를 생성하세요.",
crate::config::Language::Spanish => {
"\n\nPor favor, genera el mensaje de commit en español."
@@ -465,7 +468,8 @@ where
let event = event.map_err(|e| map_completion_error(&self.provider, e))?;
match event {
StreamedAssistantContent::Text(chunk) => {
if has_reasoning && !has_content
if has_reasoning
&& !has_content
&& let Some(state) = state
{
state.end_thinking();
@@ -474,7 +478,9 @@ where
text.push_str(&chunk.text);
}
StreamedAssistantContent::Reasoning(_)
| StreamedAssistantContent::ReasoningDelta { .. } if !has_reasoning => {
| StreamedAssistantContent::ReasoningDelta { .. }
if !has_reasoning =>
{
has_reasoning = true;
if let Some(state) = state {
state.start_thinking();
@@ -519,7 +525,11 @@ fn build_ollama_client(base_url: &str, http: ReqwestClient) -> Result<ollama::Cl
}
/// 构建 DeepSeek 客户端(OpenAI 兼容 API)。
fn build_deepseek_client(key: &str, base_url: &str, http: ReqwestClient) -> Result<deepseek::Client> {
fn build_deepseek_client(
key: &str,
base_url: &str,
http: ReqwestClient,
) -> Result<deepseek::Client> {
deepseek::Client::builder()
.api_key(key)
.base_url(base_url)
@@ -539,7 +549,11 @@ fn build_kimi_client(key: &str, base_url: &str, http: ReqwestClient) -> Result<m
}
/// 构建 Anthropic 客户端(rig 会自动规范化 base_url 的 /v1 等后缀)。
fn build_anthropic_client(key: &str, base_url: &str, http: ReqwestClient) -> Result<anthropic::Client> {
fn build_anthropic_client(
key: &str,
base_url: &str,
http: ReqwestClient,
) -> Result<anthropic::Client> {
anthropic::Client::builder()
.api_key(key)
.base_url(base_url)
@@ -564,7 +578,11 @@ fn build_openai_client(
}
/// 构建 OpenRouter 客户端(携带 QuiCommit 应用标识头)。
fn build_openrouter_client(key: &str, base_url: &str, http: ReqwestClient) -> Result<openrouter::Client> {
fn build_openrouter_client(
key: &str,
base_url: &str,
http: ReqwestClient,
) -> Result<openrouter::Client> {
openrouter::Client::builder()
.api_key(key)
.base_url(base_url)
@@ -708,13 +726,19 @@ mod tests {
let backend = Backend::DeepSeek(
deepseek::Client::builder()
.api_key("sk-test")
.base_url("https://api.deepseek.com/v1")
.base_url("https://api.deepseek.com")
.http_client(recorder.clone())
.build()
.expect("build deepseek client with mock backend"),
);
let client =
LlmClient::new(backend, "deepseek-v4-flash", "deepseek", test_config(), thinking, None);
let client = LlmClient::new(
backend,
"deepseek-v4-flash",
"deepseek",
test_config(),
thinking,
None,
);
(client, recorder)
}
@@ -817,7 +841,10 @@ mod tests {
assert_eq!(text, "hello from deepseek");
let captured = recorder.requests();
assert_eq!(captured[0].uri, "https://api.deepseek.com/v1/chat/completions");
assert_eq!(
captured[0].uri,
"https://api.deepseek.com/chat/completions"
);
let body: serde_json::Value = serde_json::from_slice(&captured[0].body).unwrap();
assert_eq!(body["model"], "deepseek-v4-flash");
// 非流式请求省略 stream 字段(API 默认 false)
@@ -843,7 +870,10 @@ mod tests {
client.generate(None, "hi").await.unwrap();
let captured = recorder.requests();
assert_eq!(captured[0].uri, "https://api.moonshot.cn/v1/chat/completions");
assert_eq!(
captured[0].uri,
"https://api.moonshot.cn/v1/chat/completions"
);
let body: serde_json::Value = serde_json::from_slice(&captured[0].body).unwrap();
assert_eq!(body["temperature"], 0.6);
assert_eq!(body["thinking"]["type"], "disabled");
@@ -881,8 +911,10 @@ mod tests {
let backend = Backend::DeepSeek(
deepseek::Client::builder()
.api_key("sk-test")
.base_url("https://api.deepseek.com/v1")
.http_client(MockStreamingClient { sse_bytes: sse.to_string().into() })
.base_url("https://api.deepseek.com")
.http_client(MockStreamingClient {
sse_bytes: sse.to_string().into(),
})
.build()
.expect("build deepseek client with streaming mock"),
);
@@ -962,9 +994,10 @@ mod tests {
#[test]
fn map_error_without_body_keeps_provider_prefix() {
let err = map_completion_error("DeepSeek", CompletionError::ProviderError("boom".into()));
assert!(err
.to_string()
.contains("DeepSeek API request failed: ProviderError: boom"));
assert!(
err.to_string()
.contains("DeepSeek API request failed: ProviderError: boom")
);
}
#[test]
@@ -980,10 +1013,16 @@ mod tests {
#[test]
fn supports_thinking_whitelist_matches_legacy() {
for provider in ["deepseek", "kimi", "anthropic", "openai"] {
assert!(supports_thinking(provider), "{provider} should support thinking");
assert!(
supports_thinking(provider),
"{provider} should support thinking"
);
}
for provider in ["ollama", "openrouter"] {
assert!(!supports_thinking(provider), "{provider} should not support thinking");
assert!(
!supports_thinking(provider),
"{provider} should not support thinking"
);
}
}
@@ -1015,7 +1054,14 @@ mod tests {
);
let mut config = test_config();
config.thinking_budget_tokens = budget;
let client = LlmClient::new(backend, "claude-sonnet-4-6", "anthropic", config, thinking, None);
let client = LlmClient::new(
backend,
"claude-sonnet-4-6",
"anthropic",
config,
thinking,
None,
);
(client, recorder)
}
@@ -1111,7 +1157,9 @@ mod tests {
anthropic::Client::builder()
.api_key("sk-ant-test")
.base_url("https://api.anthropic.com/v1")
.http_client(MockStreamingClient { sse_bytes: sse.to_string().into() })
.http_client(MockStreamingClient {
sse_bytes: sse.to_string().into(),
})
.build()
.expect("build anthropic client with streaming mock"),
);
@@ -1186,12 +1234,18 @@ mod tests {
assert_eq!(text, "hello from openai");
let captured = recorder.requests();
assert_eq!(captured[0].uri, "https://api.openai.com/v1/chat/completions");
assert_eq!(
captured[0].uri,
"https://api.openai.com/v1/chat/completions"
);
let body: serde_json::Value = serde_json::from_slice(&captured[0].body).unwrap();
assert_eq!(body["model"], "gpt-4o");
assert_eq!(body["temperature"], 0.5);
assert_eq!(body["max_tokens"], 123);
assert!(body.get("reasoning_effort").is_none(), "非 o 系列不应传 reasoning_effort");
assert!(
body.get("reasoning_effort").is_none(),
"非 o 系列不应传 reasoning_effort"
);
}
#[test]
@@ -1200,7 +1254,9 @@ mod tests {
let (client, _) = openai_client(recorder, "o3", false);
let options = client.request_options();
let params = options.additional_params.expect("o 系列应传 reasoning_effort");
let params = options
.additional_params
.expect("o 系列应传 reasoning_effort");
assert_eq!(params["reasoning_effort"], "none");
assert!(!options.stream);
}
@@ -1328,7 +1384,10 @@ mod tests {
let captured = recorder.requests();
let body: serde_json::Value = serde_json::from_slice(&captured[0].body).unwrap();
let system = body["messages"][0]["content"].as_str().unwrap();
assert!(system.contains("Conventional Commits"), "system prompt 应包含规范说明");
assert!(
system.contains("Conventional Commits"),
"system prompt 应包含规范说明"
);
let user = body["messages"][1]["content"].as_str().unwrap();
assert!(user.contains("diff --git"), "user prompt 应包含 diff");
assert!(user.contains("请用中文生成提交消息"), "应包含语言指令");
@@ -1336,12 +1395,15 @@ mod tests {
// ---- 实网冒烟(#[ignore],需真实服务/API key)----
fn smoke_client(
backend: Backend,
model: &str,
provider: &str,
) -> LlmClient {
LlmClient::new(backend, model, provider, LlmClientConfig::default(), false, None)
fn smoke_client(backend: Backend, model: &str, provider: &str) -> LlmClient {
LlmClient::new(
backend,
model,
provider,
LlmClientConfig::default(),
false,
None,
)
}
fn smoke_http() -> ReqwestClient {
@@ -1370,11 +1432,13 @@ mod tests {
#[ignore = "requires QUICOMMIT_API_KEY with a valid DeepSeek key"]
#[tokio::test]
async fn live_smoke_deepseek() {
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else { return };
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else {
return;
};
let backend = Backend::DeepSeek(
deepseek::Client::builder()
.api_key(&key)
.base_url("https://api.deepseek.com/v1")
.base_url("https://api.deepseek.com")
.http_client(smoke_http())
.build()
.expect("build deepseek client"),
@@ -1387,7 +1451,9 @@ mod tests {
#[ignore = "requires QUICOMMIT_API_KEY with a valid Moonshot key"]
#[tokio::test]
async fn live_smoke_kimi() {
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else { return };
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else {
return;
};
let backend = Backend::Kimi(
moonshot::Client::builder()
.api_key(&key)
@@ -1404,7 +1470,9 @@ mod tests {
#[ignore = "requires QUICOMMIT_API_KEY with a valid Anthropic key"]
#[tokio::test]
async fn live_smoke_anthropic() {
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else { return };
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else {
return;
};
let backend = Backend::Anthropic(
anthropic::Client::builder()
.api_key(&key)
@@ -1421,7 +1489,9 @@ mod tests {
#[ignore = "requires QUICOMMIT_API_KEY with a valid OpenAI key"]
#[tokio::test]
async fn live_smoke_openai() {
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else { return };
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else {
return;
};
let backend = Backend::OpenAi(
openai::Client::builder()
.api_key(&key)
@@ -1439,7 +1509,9 @@ mod tests {
#[ignore = "requires QUICOMMIT_API_KEY with a valid OpenRouter key"]
#[tokio::test]
async fn live_smoke_openrouter() {
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else { return };
let Ok(key) = std::env::var("QUICOMMIT_API_KEY") else {
return;
};
let backend = Backend::OpenRouter(
openrouter::Client::builder()
.api_key(&key)
@@ -1453,4 +1525,4 @@ mod tests {
let text = client.generate(None, "Say 'Hello, World!'").await.unwrap();
assert!(!text.is_empty());
}
}
}

View File

@@ -64,18 +64,10 @@ impl Default for ThinkingStateManager {
/// 线程安全的思考状态管理器引用
pub type SharedThinkingState = Arc<ThinkingStateManager>;
/// 创建带有默认控制台输出的思考状态管理器
/// 在思考开始时打印 "thinking...",在思考结束时清除该标识
/// 创建 LLM 流式使用的共享思考状态。
/// 进度显示由 AI 生成 spinner 负责(issue 21),此处不再附加控制台输出。
pub fn create_console_thinking_state() -> SharedThinkingState {
Arc::new(
ThinkingStateManager::new()
.on_thinking_start(|| {
eprint!("\rthinking...");
})
.on_thinking_end(|| {
eprint!("\r \r");
}),
)
Arc::new(ThinkingStateManager::new())
}
#[cfg(test)]

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
@@ -7,7 +5,8 @@ use tracing::debug;
use quicommit::commands::{
changelog::ChangelogCommand, commit::CommitCommand, config::ConfigCommand,
credential::CredentialCommand, init::InitCommand, profile::ProfileCommand, tag::TagCommand,
credential::CredentialCommand, ginit::GinitCommand, init::InitCommand, profile::ProfileCommand,
tag::TagCommand,
};
/// QuiCommit - AI-powered Git assistant
@@ -22,7 +21,7 @@ use quicommit::commands::{
#[command(propagate_version = true)]
#[command(arg_required_else_help = true)]
struct Cli {
/// Enable verbose output
/// Increase verbosity (-v: info, -vv: debug, -vvv: trace)
#[arg(short, long, global = true, action = clap::ArgAction::Count)]
verbose: u8,
@@ -31,9 +30,17 @@ struct Cli {
config: Option<String>,
/// Disable colored output
#[arg(long, global = true, env = "NO_COLOR")]
#[arg(long, global = true)]
no_color: bool,
/// Force emoji decorations on (overrides config)
#[arg(long, global = true, conflicts_with = "no_emoji")]
emoji: bool,
/// Disable emoji/symbol decorations
#[arg(long, global = true)]
no_emoji: bool,
#[command(subcommand)]
command: Commands,
}
@@ -44,6 +51,10 @@ enum Commands {
#[command(alias = "i")]
Init(InitCommand),
/// Initialize a local Git repository
#[command(alias = "gi")]
Ginit(GinitCommand),
/// Generate and execute conventional commits
#[command(alias = "c")]
Commit(CommitCommand),
@@ -73,6 +84,35 @@ enum Commands {
async fn main() -> Result<()> {
let cli = Cli::parse();
// Apply the global color decision before any output is produced.
// --no-color disables colors; NO_COLOR follows the no-color.org spec
// (any presence, regardless of value, disables color). Without them,
// color keeps colored's tty auto-detection (ADR-0003): piped output
// stays ANSI-free.
let no_color = cli.no_color || std::env::var_os("NO_COLOR").is_some();
if no_color {
colored::control::set_override(false);
}
// Resolve the decoration switch (issue 14): explicit flag > config >
// default; --no-color disables decorations too (ADR-0003).
let emoji_from_config = cli
.config
.as_deref()
.map(PathBuf::from)
.or_else(|| quicommit::config::AppConfig::default_path().ok())
.and_then(|path| quicommit::config::AppConfig::load(&path).ok())
.map(|config| config.output.emoji)
.unwrap_or(true);
let emoji_enabled = if no_color || cli.no_emoji {
false
} else if cli.emoji {
true
} else {
emoji_from_config
};
quicommit::utils::set_emoji_enabled(emoji_enabled);
let log_level = match cli.verbose {
0 => "warn",
1 => "info",
@@ -80,8 +120,11 @@ async fn main() -> Result<()> {
_ => "trace",
};
// RUST_LOG takes precedence when set; otherwise -v decides (issue 23).
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level));
tracing_subscriber::fmt()
.with_env_filter(log_level)
.with_env_filter(filter)
.with_target(false)
.init();
@@ -91,6 +134,7 @@ async fn main() -> Result<()> {
match cli.command {
Commands::Init(cmd) => cmd.execute(config_path).await,
Commands::Ginit(cmd) => cmd.execute(config_path).await,
Commands::Commit(cmd) => cmd.execute(config_path).await,
Commands::Tag(cmd) => cmd.execute(config_path).await,
Commands::Changelog(cmd) => cmd.execute(config_path).await,

View File

@@ -232,9 +232,7 @@ impl KeyringManager {
"Keyring is available".to_string()
}
}
KeyringStatus::Unavailable => {
"Keyring is not available. Set QUICOMMIT_API_KEY environment variable.".to_string()
}
KeyringStatus::Unavailable => "Keyring is not available on this system.".to_string(),
}
}
}
@@ -250,7 +248,7 @@ pub fn get_default_base_url(provider: &str) -> &'static str {
"openai" => "https://api.openai.com/v1",
"anthropic" => "https://api.anthropic.com/v1",
"kimi" => "https://api.moonshot.cn/v1",
"deepseek" => "https://api.deepseek.com/v1",
"deepseek" => "https://api.deepseek.com",
"openrouter" => "https://openrouter.ai/api/v1",
"ollama" => "http://localhost:11434",
_ => "",
@@ -296,10 +294,7 @@ mod tests {
"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("deepseek"), "https://api.deepseek.com");
assert_eq!(
get_default_base_url("openrouter"),
"https://openrouter.ai/api/v1"

View File

@@ -6,48 +6,144 @@ pub mod validators;
use anyhow::{Context, Result};
use colored::Colorize;
use std::io::{self, Write};
use std::io;
use std::sync::OnceLock;
use std::time::Duration;
/// Process-global decoration switch (issue 14).
static EMOJI_ENABLED: OnceLock<bool> = OnceLock::new();
/// Set whether emoji/symbol decorations are shown. Called once from `main`
/// after resolving config + flags.
pub fn set_emoji_enabled(enabled: bool) {
let _ = EMOJI_ENABLED.set(enabled);
}
/// Whether emoji/symbol decorations are shown.
pub fn emoji_enabled() -> bool {
*EMOJI_ENABLED.get_or_init(|| true)
}
/// Styled decoration prefix for status lines; empty when decorations are off
/// (ADR-0003: message text never embeds decorations).
pub fn success_prefix() -> colored::ColoredString {
if emoji_enabled() {
"✓".green().bold()
} else {
"".normal()
}
}
pub fn error_prefix() -> colored::ColoredString {
if emoji_enabled() {
"✗".red().bold()
} else {
"".normal()
}
}
pub fn warning_prefix() -> colored::ColoredString {
if emoji_enabled() {
"⚠".yellow().bold()
} else {
"".normal()
}
}
pub fn info_prefix() -> colored::ColoredString {
if emoji_enabled() {
"ℹ".blue().bold()
} else {
"".normal()
}
}
pub fn progress_prefix() -> colored::ColoredString {
if emoji_enabled() {
"→".cyan()
} else {
"".normal()
}
}
fn print_decorated(prefix: colored::ColoredString, msg: &str, to_stderr: bool) {
if emoji_enabled() {
if to_stderr {
eprintln!("{} {}", prefix, msg);
} else {
println!("{} {}", prefix, msg);
}
} else if to_stderr {
eprintln!("{}", msg);
} else {
println!("{}", msg);
}
}
/// Print success message
pub fn print_success(msg: &str) {
println!("{} {}", "✓".green().bold(), msg);
print_decorated(success_prefix(), msg, false);
}
/// Print error message
/// Print error message to stderr
pub fn print_error(msg: &str) {
eprintln!("{} {}", "✗".red().bold(), msg);
print_decorated(error_prefix(), msg, true);
}
/// Print warning message
pub fn print_warning(msg: &str) {
println!("{} {}", "⚠".yellow().bold(), msg);
print_decorated(warning_prefix(), msg, false);
}
/// Print warning message to stderr (stdout must stay clean, e.g. exports)
pub fn eprint_warning(msg: &str) {
print_decorated(warning_prefix(), msg, true);
}
/// Print info message
pub fn print_info(msg: &str) {
println!("{} {}", "ℹ".blue().bold(), msg);
print_decorated(info_prefix(), msg, false);
}
/// Confirm action with user
pub fn confirm(prompt: &str) -> Result<bool> {
print!("{} [y/N] ", prompt);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_lowercase().starts_with('y'))
/// Print progress/status message (→ prefix when decorations are on)
pub fn print_progress(msg: &str) {
print_decorated(progress_prefix(), msg, false);
}
/// Get user input
pub fn input(prompt: &str) -> Result<String> {
print!("{}: ", prompt);
io::stdout().flush()?;
/// Progress spinner for long-running operations (issue 21).
/// Degrades to a static line when stdout is not a terminal or when
/// decorations are disabled.
pub struct Spinner {
bar: Option<indicatif::ProgressBar>,
}
let mut input = String::new();
io::stdin().read_line(&mut input)?;
impl Spinner {
pub fn start(msg: &str) -> Self {
if emoji_enabled() && std::io::IsTerminal::is_terminal(&io::stdout()) {
let bar = indicatif::ProgressBar::new_spinner();
bar.set_message(msg.to_string());
bar.enable_steady_tick(Duration::from_millis(100));
Self { bar: Some(bar) }
} else {
println!("{}", msg);
Self { bar: None }
}
}
Ok(input.trim().to_string())
/// Stop the spinner, erasing it from the terminal (no completion line).
pub fn finish_clear(&self) {
if let Some(bar) = &self.bar {
bar.finish_and_clear();
}
}
/// Stop the spinner and print a completion line.
pub fn finish_with(&self, msg: &str) {
if let Some(bar) = &self.bar {
bar.finish_and_clear();
}
println!("{}", msg);
}
}
/// Get password input (hidden)
@@ -59,19 +155,3 @@ pub fn password_input(prompt: &str) -> Result<String> {
.interact()
.context("Failed to read password")
}
/// Check if running in a terminal
pub fn is_terminal() -> bool {
std::io::IsTerminal::is_terminal(&io::stdout())
}
/// Format duration in human-readable format
pub fn format_duration(secs: u64) -> String {
if secs < 60 {
format!("{}s", secs)
} else if secs < 3600 {
format!("{}m {}s", secs / 60, secs % 60)
} else {
format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
}
}

560
tests/ginit_tests.rs Normal file
View File

@@ -0,0 +1,560 @@
use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin_cmd;
use predicates::prelude::*;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
/// A ginit run isolated from the machine it happens on: `init.defaultBranch`,
/// `user.name`/`user.email` and QuiCommit's own config all come from throwaway
/// locations, so expectations hold both on a developer box and in CI.
struct Scenario {
work: TempDir,
home: TempDir,
config: PathBuf,
}
impl Scenario {
fn new() -> Scenario {
let work = TempDir::new().unwrap();
let home = TempDir::new().unwrap();
let config = home.path().join("config.toml");
Scenario { work, home, config }
}
fn dir(&self) -> &Path {
self.work.path()
}
fn command_in(&self, dir: &Path, args: &[&str]) -> Command {
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.current_dir(dir)
.env("HOME", self.home.path())
.env("USERPROFILE", self.home.path())
.env("XDG_CONFIG_HOME", self.home.path())
.arg("--config")
.arg(&self.config)
.args(args);
cmd
}
fn command(&self, args: &[&str]) -> Command {
self.command_in(self.dir(), args)
}
/// `--yes` is the non-interactive side of ADR-0004; every case uses it
/// because dialoguer refuses to answer without a terminal.
fn ginit(&self, args: &[&str]) -> Command {
let mut args: Vec<&str> = args.to_vec();
args.push("--yes");
self.command(&args)
}
fn git(&self, args: &[&str]) -> String {
self.git_in(self.dir(), args)
}
fn git_in(&self, dir: &Path, args: &[&str]) -> String {
let output = std::process::Command::new("git")
.args(args)
.current_dir(dir)
.env("HOME", self.home.path())
.env("USERPROFILE", self.home.path())
.env("XDG_CONFIG_HOME", self.home.path())
.output()
.expect("git should be available");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
fn read(&self, name: &str) -> String {
fs::read_to_string(self.dir().join(name)).unwrap_or_else(|e| panic!("{name}: {e}"))
}
/// QuiCommit's config is written by hand rather than produced by
/// `init --yes`, because on Windows libgit2 resolves the global git
/// config from the user profile folder and ignores `HOME`, so a profile
/// created by `init` would inherit this machine's real identity.
fn write_config(&self, contents: &str) {
fs::write(&self.config, contents).unwrap();
}
}
#[test]
fn test_ginit_creates_repository_readme_and_gitignore() {
let scenario = Scenario::new();
scenario
.ginit(&["ginit"])
.assert()
.success()
.stdout(predicate::str::contains("Repository initialized"));
assert!(scenario.dir().join(".git").exists());
assert_eq!(
scenario.git(&["symbolic-ref", "--short", "HEAD"]),
"main",
"with no init.defaultBranch configured, ginit starts on main"
);
let workdir = scenario.dir();
let name = workdir.file_name().unwrap().to_string_lossy().to_string();
assert_eq!(scenario.read("README.md"), format!("# {name}\n"));
let gitignore = scenario.read(".gitignore");
assert!(
gitignore.contains(".env\n"),
"the baseline must ignore .env, got: {gitignore}"
);
assert!(gitignore.contains("# Build output"));
}
#[test]
fn test_ginit_on_an_existing_repository_skips_creation_and_fills_gaps() {
let scenario = Scenario::new();
scenario.git(&["init"]);
fs::write(scenario.dir().join("README.md"), "# mine\n").unwrap();
// A repository whose HEAD has no commit yet still has a branch, and that
// branch is what ginit must report as untouched.
scenario.git(&["symbolic-ref", "HEAD", "refs/heads/trunk"]);
scenario
.ginit(&["ginit"])
.assert()
.success()
// The branch line must name the branch that exists, not the default it
// would have used for a fresh repository.
.stdout(predicate::str::contains(
"trunk (existing repository, branch untouched)",
));
assert_eq!(scenario.read("README.md"), "# mine\n");
assert!(
scenario.dir().join(".gitignore").exists(),
"the missing .gitignore should have been added"
);
}
#[test]
fn test_ginit_never_touches_existing_start_files() {
let scenario = Scenario::new();
fs::write(scenario.dir().join("README.md"), "# mine\n").unwrap();
fs::write(scenario.dir().join(".gitignore"), "keep-me/\n").unwrap();
scenario
.ginit(&["ginit"])
.assert()
.success()
.stdout(predicate::str::contains(".gitignore sections").not());
assert_eq!(scenario.read("README.md"), "# mine\n");
assert_eq!(
scenario.read(".gitignore"),
"keep-me/\n",
"ginit must not append to a maintained .gitignore"
);
}
#[test]
fn test_ginit_branch_flag_sets_the_initial_branch() {
let scenario = Scenario::new();
scenario.ginit(&["ginit", "-b", "dev"]).assert().success();
assert_eq!(scenario.git(&["symbolic-ref", "--short", "HEAD"]), "dev");
}
#[test]
fn test_ginit_refuses_to_rename_a_branch_that_has_commits() {
let scenario = Scenario::new();
scenario.git(&["init"]);
scenario.git(&["config", "user.name", "Test User"]);
scenario.git(&["config", "user.email", "test@example.com"]);
scenario.git(&["config", "commit.gpgsign", "false"]);
scenario.git(&["commit", "--allow-empty", "-m", "first"]);
let branch = scenario.git(&["symbolic-ref", "--short", "HEAD"]);
scenario
.ginit(&["ginit", "-b", "experiment"])
.assert()
.success()
.stdout(predicate::str::contains(
"already has commits, branch unchanged",
));
assert_eq!(scenario.git(&["symbolic-ref", "--short", "HEAD"]), branch);
}
#[test]
fn test_ginit_rejects_a_directory_inside_another_repository() {
let scenario = Scenario::new();
scenario.git(&["init"]);
let nested = scenario.dir().join("inner");
fs::create_dir(&nested).unwrap();
scenario
.command_in(&nested, &["ginit", "--yes"])
.assert()
.failure()
.stderr(predicate::str::contains("inside the repository"));
assert!(
!nested.join(".git").exists(),
"the nested directory must not become a repository"
);
assert!(
!nested.join("README.md").exists(),
"a refused run must write nothing at all"
);
}
#[test]
fn test_ginit_add_names_the_new_remote_origin() {
let scenario = Scenario::new();
scenario
.ginit(&["ginit", "--add", "https://example.com/origin.git"])
.assert()
.success();
let remotes = scenario.git(&["remote", "-v"]);
assert!(
remotes.starts_with("origin"),
"a bare URL should become origin, got: {remotes}"
);
assert!(remotes.contains("https://example.com/origin.git"));
}
#[test]
fn test_ginit_add_accepts_named_remotes_and_repeats() {
let scenario = Scenario::new();
scenario
.ginit(&[
"ginit",
"--add",
"upstream=https://example.com/upstream.git",
"--add",
"origin=https://example.com/origin.git",
])
.assert()
.success();
let remotes = scenario.git(&["remote", "-v"]);
assert!(remotes.contains("upstream"), "got: {remotes}");
assert!(remotes.contains("origin"), "got: {remotes}");
}
#[test]
fn test_ginit_refuses_to_rewrite_an_existing_remote_url() {
let scenario = Scenario::new();
scenario
.ginit(&["ginit", "--add", "https://example.com/first.git"])
.assert()
.success();
scenario
.ginit(&["ginit", "--add", "https://example.com/second.git"])
.assert()
.failure()
.stderr(predicate::str::contains("set-url"));
let remotes = scenario.git(&["remote", "-v"]);
assert!(
remotes.contains("https://example.com/first.git"),
"the existing URL must survive, got: {remotes}"
);
assert!(!remotes.contains("second.git"), "got: {remotes}");
}
#[test]
fn test_ginit_rejects_an_add_value_without_a_url() {
let scenario = Scenario::new();
scenario
.ginit(&["ginit", "--add", "origin"])
.assert()
.failure()
.stderr(predicate::str::contains("--add 'origin' has no URL"));
assert!(
!scenario.dir().join(".git").exists(),
"a rejected flag must stop the whole run"
);
}
#[test]
fn test_ginit_gitignore_sections_follow_the_markers_in_the_directory() {
struct Expected {
markers: &'static [&'static str],
present: &'static [&'static str],
absent: &'static [&'static str],
}
let cases = [
Expected {
markers: &[],
present: &["# Build output", "tmp/", ".env"],
absent: &["# Rust", "# Node"],
},
Expected {
markers: &["Cargo.toml"],
present: &["# Rust", "target/"],
absent: &["Cargo.lock", "# Node"],
},
Expected {
markers: &["Cargo.toml", "package.json"],
present: &["# Rust", "# Node", "node_modules/"],
absent: &[],
},
Expected {
markers: &["pyproject.toml"],
present: &["# Python", "__pycache__/"],
absent: &["# Ruby"],
},
Expected {
markers: &["go.mod", "composer.json"],
present: &["# Go", "vendor/"],
absent: &["# PHP"],
},
Expected {
markers: &["Cargo.toml", "pom.xml"],
present: &["# Rust"],
absent: &["# Maven"],
},
];
for case in cases {
let scenario = Scenario::new();
for marker in case.markers {
fs::write(scenario.dir().join(marker), "").unwrap();
}
let assertion = scenario.ginit(&["ginit"]).assert().success();
let stdout = String::from_utf8_lossy(&assertion.get_output().stdout).to_string();
let gitignore = scenario.read(".gitignore");
for expected in case.present {
assert!(
gitignore.contains(expected),
"{:?} should contain {expected}, got: {gitignore}",
case.markers
);
}
for unexpected in case.absent {
assert!(
!gitignore.contains(unexpected),
"{:?} should not contain {unexpected}, got: {gitignore}",
case.markers
);
}
// The preview promises exactly what the file delivers: a section the
// cross-section dedupe dropped (PHP behind Go, Maven behind Rust) may
// not be listed as if it were going to be written.
assert!(
stdout.contains(".gitignore sections:"),
"the preview should list the sections, got: {stdout}"
);
for title in case.present.iter().filter(|line| line.starts_with('#')) {
assert!(
stdout.contains(title),
"the preview should promise {title}, got: {stdout}"
);
}
for title in case.absent.iter().filter(|line| line.starts_with('#')) {
assert!(
!stdout.contains(title),
"the preview must not promise the dropped {title}, got: {stdout}"
);
}
assert_eq!(
gitignore.matches("dist/").count(),
1,
"entries shared with the baseline appear once, got: {gitignore}"
);
assert!(
!gitignore.contains("\n\n\n"),
"empty sections must be omitted, got: {gitignore}"
);
}
}
#[test]
fn test_ginit_dry_run_writes_nothing() {
let scenario = Scenario::new();
scenario
.ginit(&[
"ginit",
"--dry-run",
"-b",
"dev",
"--add",
"https://example.com/origin.git",
])
.assert()
.success()
.stdout(predicate::str::contains("Dry run"))
.stdout(predicate::str::contains("dev"));
assert!(
!scenario.dir().join(".git").exists(),
"a dry run must not even create the repository"
);
assert!(!scenario.dir().join("README.md").exists());
assert!(!scenario.dir().join(".gitignore").exists());
}
#[test]
fn test_ginit_yes_keeps_every_planned_line_of_the_output() {
let scenario = Scenario::new();
fs::write(scenario.dir().join("Cargo.toml"), "").unwrap();
let output = scenario
.ginit(&["ginit", "--add", "https://example.com/origin.git"])
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
// ADR-0004: --yes only removes the question, so the same artifacts the
// preview promised are still reported and still on disk.
for expected in ["README.md", ".gitignore", "origin", "Initial branch"] {
assert!(stdout.contains(expected), "stdout was: {stdout}");
}
assert!(
!stdout.contains("Create these now?"),
"--yes must not prompt, stdout was: {stdout}"
);
assert!(scenario.read(".gitignore").contains("# Rust"));
assert!(scenario.git(&["remote", "-v"]).contains("origin"));
}
#[test]
fn test_ginit_readme_title_survives_spaces_and_unicode() {
for name in ["my project", "中文 项目", "Ünïcödé-ß"] {
let scenario = Scenario::new();
let titled = scenario.dir().join(name);
fs::create_dir(&titled).unwrap();
scenario
.command_in(&titled, &["ginit", "--yes"])
.assert()
.success();
let readme = fs::read_to_string(titled.join("README.md")).unwrap();
assert_eq!(readme, format!("# {name}\n"));
}
}
#[test]
fn test_ginit_profile_applies_identity_and_records_the_mapping() {
let scenario = Scenario::new();
scenario.write_config(
r#"version = "1"
[profiles.work]
name = "work"
user_name = "Work User"
user_email = "work@example.com"
"#,
);
scenario
.ginit(&["ginit", "--profile", "work"])
.assert()
.success();
assert_eq!(
scenario.git(&["config", "--local", "user.email"]),
"work@example.com"
);
let config = fs::read_to_string(&scenario.config).unwrap();
assert!(
config.contains("[repo_profiles]"),
"the directory should be mapped to the profile, got: {config}"
);
}
#[test]
fn test_ginit_missing_profile_fails_without_writing_config() {
let scenario = Scenario::new();
scenario.write_config(
r#"version = "1"
[profiles.work]
name = "work"
user_name = "Work User"
user_email = "work@example.com"
"#,
);
let config_before = fs::read_to_string(&scenario.config).unwrap();
scenario
.ginit(&["ginit", "--profile", "nope"])
.assert()
.failure()
.stderr(predicate::str::contains("profile add"));
assert_eq!(
fs::read_to_string(&scenario.config).unwrap(),
config_before,
"a rejected profile must leave the config untouched"
);
}
#[test]
fn test_ginit_hints_at_pushing_after_the_first_commit() {
let scenario = Scenario::new();
scenario
.ginit(&["ginit", "--add", "https://example.com/origin.git"])
.assert()
.success()
// The label already ends in a colon; matching the newline guards the
// doubled colon that `println!("{}:", …)` would produce.
.stdout(predicate::str::contains("Next steps:\n"))
.stdout(predicate::str::contains("quicommit commit --push"));
}
#[test]
fn test_ginit_on_a_bare_repository_skips_files_and_still_adds_the_remote() {
let scenario = Scenario::new();
scenario.git(&["init", "--bare"]);
scenario
.ginit(&["ginit", "--add", "https://example.com/mirror.git"])
.assert()
.success();
assert!(!scenario.dir().join("README.md").exists());
assert!(!scenario.dir().join(".gitignore").exists());
assert!(
scenario
.git(&["config", "--local", "remote.origin.url"])
.contains("https://example.com/mirror.git")
);
}

View File

@@ -115,7 +115,8 @@ fn test_stage_all_removes_ignored_tracked_files() {
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");
let messages = quicommit::i18n::Messages::new(quicommit::config::Language::English);
let removed = repo.stage_all(&messages).expect("stage_all should succeed");
assert!(
removed.iter().any(|f| f == "__pycache__/foo.pyc"),
@@ -142,7 +143,8 @@ fn test_stage_all_no_ignored_files_returns_empty() {
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");
let messages = quicommit::i18n::Messages::new(quicommit::config::Language::English);
let removed = repo.stage_all(&messages).expect("stage_all should succeed");
assert!(
removed.is_empty(),

View File

@@ -258,6 +258,190 @@ mod config_command {
.success()
.stdout(predicate::str::contains("config.toml"));
}
#[test]
fn test_no_color_disables_ansi() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"config",
"show",
"--no-color",
"--config",
config_path.to_str().unwrap(),
]);
let output = cmd.output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
!stdout.contains("\x1b["),
"ANSI color codes present despite --no-color"
);
}
#[test]
fn test_emoji_switch_precedence() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let set_format = |extra: &[&str], cfg: &std::path::Path| {
let mut c = cargo_bin_cmd!("quicommit");
c.env_remove("NO_COLOR");
c.args(&["config", "set", "commit.format", "conventional"])
.args(extra)
.args(&["--config", cfg.to_str().unwrap()]);
c.output().unwrap()
};
// Default (config true): decorations shown
let out = set_format(&[], &config_path);
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("✓"));
// Config output.emoji=false: no decorations
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&[
"config",
"set",
"output.emoji",
"false",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert().success();
let out = set_format(&[], &config_path);
assert!(out.status.success());
assert!(!String::from_utf8_lossy(&out.stdout).contains("✓"));
// Explicit --emoji overrides config false
let out = set_format(&["--emoji"], &config_path);
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("✓"));
// Config back to true, then --no-emoji overrides
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&[
"config",
"set",
"output.emoji",
"true",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert().success();
let out = set_format(&["--no-emoji"], &config_path);
assert!(out.status.success());
assert!(!String::from_utf8_lossy(&out.stdout).contains("✓"));
}
#[test]
fn test_chinese_output_smoke() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
setup_test_repo_with_file(&repo_path, "test.txt", "content");
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&[
"config",
"set",
"language.output_language",
"zh",
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert().success();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&[
"commit",
"--manual",
"-m",
"feat: 中文冒烟",
"--dry-run",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("试运行"));
}
#[test]
fn test_rust_log_env() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.env("RUST_LOG", "debug");
cmd.args(&["config", "path", "--config", config_path.to_str().unwrap()]);
cmd.assert()
.success()
.stdout(predicate::str::contains("Starting quicommit"));
}
#[test]
fn test_auto_generate_defaults_true() {
// Documents the unified --yes semantics (issue 05): with default
// config, --yes still AI-generates; deterministic output needs
// --no-generate (changelog) or -m (tag).
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&["init", "--yes", "--config", config_path.to_str().unwrap()]);
cmd.assert().success();
for key in [
"commit.auto_generate",
"tag.auto_generate",
"changelog.auto_generate",
] {
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.env_remove("NO_COLOR");
cmd.args(&[
"config",
"get",
key,
"--config",
config_path.to_str().unwrap(),
]);
cmd.assert()
.success()
.stdout(predicate::str::contains("true"));
}
}
}
mod commit_command {
@@ -438,6 +622,8 @@ mod tag_command {
"tag",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--dry-run",
"--yes",
"--config",
@@ -469,6 +655,8 @@ mod tag_command {
"--think",
"--name",
"v0.2.0",
"-m",
"Release v0.2.0",
"--dry-run",
"--yes",
"--config",
@@ -528,6 +716,7 @@ mod changelog_command {
"changelog",
"--dry-run",
"--yes",
"--no-generate",
"--config",
config_path.to_str().unwrap(),
])
@@ -829,3 +1018,581 @@ mod edge_cases {
));
}
}
fn create_bare_remote(path: &std::path::Path) {
std::fs::create_dir(path).expect("Failed to create remote directory");
std::process::Command::new("git")
.args(["init", "--bare"])
.current_dir(path)
.output()
.expect("Failed to init bare remote");
}
fn add_remote(dir: &PathBuf, name: &str, url: &str) {
std::process::Command::new("git")
.args(["remote", "add", name, url])
.current_dir(dir)
.output()
.expect("Failed to add remote");
}
fn bare_head_commit(bare_path: &std::path::Path) -> Option<String> {
let output = std::process::Command::new("git")
.arg("--git-dir")
.arg(bare_path)
.args(["rev-parse", "HEAD"])
.output()
.expect("Failed to read bare repo HEAD");
if !output.status.success() {
return None;
}
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn bare_tag_exists(bare_path: &std::path::Path, tag: &str) -> bool {
std::process::Command::new("git")
.arg("--git-dir")
.arg(bare_path)
.args(["rev-parse", &format!("refs/tags/{}", tag)])
.output()
.expect("Failed to read remote tag")
.status
.success()
}
fn repo_head_commit(dir: &PathBuf) -> String {
let output = std::process::Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(dir)
.output()
.expect("Failed to read repo HEAD");
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
mod remote_aware_push {
use super::*;
#[test]
fn test_commit_no_remote_skips_push_prompt() {
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",
"--manual",
"-m",
"test: no remote",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("No remote configured, skipping push."));
}
#[test]
fn test_commit_no_remote_with_push_flag_skips_instead_of_failing() {
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",
"--manual",
"-m",
"test: no remote with push",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("No remote configured, skipping push."))
.stdout(predicate::str::contains("Push failed").not());
}
#[test]
fn test_commit_with_remote_still_pushes_to_origin() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let remote_path = temp_dir.path().join("remote.git");
create_bare_remote(&remote_path);
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "origin", remote_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: push to origin",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("Pushed branch"));
assert_eq!(
bare_head_commit(&remote_path),
Some(repo_head_commit(&repo_path)),
"bare remote should contain the pushed commit"
);
}
#[test]
fn test_tag_no_remote_skips_push_prompt() {
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",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("No remote configured, skipping push."));
}
#[test]
fn test_tag_with_remote_still_pushes_to_origin() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let remote_path = temp_dir.path().join("remote.git");
create_bare_remote(&remote_path);
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");
add_remote(&repo_path, "origin", remote_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("Pushed tag"));
assert!(
bare_tag_exists(&remote_path, "v0.1.0"),
"remote should contain the pushed tag"
);
}
#[test]
fn test_commit_falls_back_to_first_available_remote() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let remote_path = temp_dir.path().join("upstream.git");
create_bare_remote(&remote_path);
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "upstream", remote_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: fallback push",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains(
"Remote 'origin' not found, pushing to 'upstream' instead.",
))
.stdout(predicate::str::contains("Pushed branch"));
assert_eq!(
bare_head_commit(&remote_path),
Some(repo_head_commit(&repo_path)),
"fallback remote should contain the pushed commit"
);
}
#[test]
fn test_commit_falls_back_when_custom_remote_missing() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let remote_path = temp_dir.path().join("origin.git");
create_bare_remote(&remote_path);
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "origin", remote_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: custom remote missing",
"--yes",
"--push",
"--remote",
"nonexistent",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains(
"Remote 'nonexistent' not found, pushing to 'origin' instead.",
))
.stdout(predicate::str::contains("Pushed branch"));
}
#[test]
fn test_tag_falls_back_to_first_available_remote() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let remote_path = temp_dir.path().join("upstream.git");
create_bare_remote(&remote_path);
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");
add_remote(&repo_path, "upstream", remote_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains(
"Remote 'origin' not found, pushing to 'upstream' instead.",
))
.stdout(predicate::str::contains("Pushed tag"));
assert!(
bare_tag_exists(&remote_path, "v0.1.0"),
"fallback remote should contain the pushed tag"
);
}
#[test]
fn test_commit_select_remote_yes_pushes_only_remote_target() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let origin_path = temp_dir.path().join("origin.git");
let upstream_path = temp_dir.path().join("upstream.git");
create_bare_remote(&origin_path);
create_bare_remote(&upstream_path);
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "origin", origin_path.to_str().unwrap());
add_remote(&repo_path, "upstream", upstream_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
// --yes outranks --select-remote: no interaction, push only --remote target
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: select remote with yes",
"--yes",
"--push",
"--select-remote",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
assert_eq!(
bare_head_commit(&origin_path),
Some(repo_head_commit(&repo_path)),
"origin should receive the push"
);
assert_eq!(
bare_head_commit(&upstream_path),
None,
"upstream should not receive the push under --yes"
);
}
#[test]
fn test_commit_select_remote_no_remote_skips_push() {
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",
"--manual",
"-m",
"test: select remote without remotes",
"--yes",
"--select-remote",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("No remote configured, skipping push."));
}
#[test]
fn test_commit_select_remote_single_remote_with_yes_pushes_directly() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let origin_path = temp_dir.path().join("origin.git");
create_bare_remote(&origin_path);
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "origin", origin_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: single remote select",
"--yes",
"--push",
"--select-remote",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("Pushed branch"));
assert_eq!(
bare_head_commit(&origin_path),
Some(repo_head_commit(&repo_path))
);
}
#[test]
fn test_commit_push_failure_reports_error() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
// Remote points to a path that is not a git repository
let broken_path = temp_dir.path().join("not-a-repo");
std::fs::create_dir(&broken_path).unwrap();
setup_test_repo_with_file(&repo_path, "test.txt", "Hello, World!");
add_remote(&repo_path, "origin", broken_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"commit",
"--manual",
"-m",
"test: push failure",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.failure()
.stderr(predicate::str::contains("Push failed"));
}
#[test]
fn test_tag_select_remote_yes_pushes_only_remote_target() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
let origin_path = temp_dir.path().join("origin.git");
let upstream_path = temp_dir.path().join("upstream.git");
create_bare_remote(&origin_path);
create_bare_remote(&upstream_path);
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");
add_remote(&repo_path, "origin", origin_path.to_str().unwrap());
add_remote(&repo_path, "upstream", upstream_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--push",
"--select-remote",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert().success();
assert!(
bare_tag_exists(&origin_path, "v0.1.0"),
"origin should have the tag"
);
assert!(
!bare_tag_exists(&upstream_path, "v0.1.0"),
"upstream should not receive the tag under --yes"
);
}
#[test]
fn test_tag_no_remote_with_push_flag_skips_instead_of_failing() {
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",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.success()
.stdout(predicate::str::contains("No remote configured, skipping push."));
}
#[test]
fn test_tag_push_failure_reports_error() {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_path_buf();
// Remote points to a path that is not a git repository
let broken_path = temp_dir.path().join("not-a-repo");
std::fs::create_dir(&broken_path).unwrap();
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");
add_remote(&repo_path, "origin", broken_path.to_str().unwrap());
let config_path = repo_path.join("config.toml");
init_quicommit(&repo_path, &config_path);
let mut cmd = cargo_bin_cmd!("quicommit");
cmd.args(&[
"tag",
"--name",
"v0.1.0",
"-m",
"Release v0.1.0",
"--yes",
"--push",
"--config",
config_path.to_str().unwrap(),
])
.current_dir(&repo_path);
cmd.assert()
.failure()
.stderr(predicate::str::contains("Push failed"));
}
}