From 2bcc692271e6a89104a8fd4ddb031b5d4d3b8ada Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 2 Mar 2026 19:00:14 -0500 Subject: [PATCH 01/40] 0.5.1 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3dc36b2..1505a40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 692dd17..8c42ff7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.5.0" +version = "0.5.1" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From b7c40c53dddaa2654f92b4d94ddee9b055fcd67d Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 6 Mar 2026 13:34:48 -0500 Subject: [PATCH 02/40] Simplified GitHub Actions and CLI * Updated release ooo in Taskfile.yaml * Improved CLI flags by removing default version display and adding `--version` * Introduced option to print version number when running with --version flag in main.rs * Changed summary format in prompts.rs to bullet points --- Taskfile.yaml | 5 ++--- src/cli_args.rs | 6 +++++- src/llm/prompts.rs | 8 ++++---- src/main.rs | 6 ++++++ 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index a896d4f..d4ed679 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -95,11 +95,10 @@ tasks: cmds: - task: test - sh devops/release.sh {{.VERSION}} - - task: install - task: publish:dry - task: publish - - cd ../homebrew-tap && \ - TAG=$(commitbot --version | awk '{print $2}') && \ + - TAG=$(commitbot --version) && \ + cd ../homebrew-tap && \ gh workflow run update-formula.yml -f formula=commitbot -f repo=mikegarde/commitbot -f tag=$TAG publish:dry: diff --git a/src/cli_args.rs b/src/cli_args.rs index 399be8a..9c47fb4 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -4,7 +4,7 @@ use clap::{Parser, Subcommand, ArgAction}; #[derive(Parser, Debug)] #[command( name = "commitbot", - version, + disable_version_flag = true, about = "LLM-assisted Git commit message generator" )] pub struct Cli { @@ -60,6 +60,10 @@ pub struct Cli { /// Subcommand (e.g. 'pr') #[command(subcommand)] pub command: Option, + + /// Print only the version number (e.g. "0.5.1"). This replaces clap's auto --version output. + #[arg(long, global = true, action = ArgAction::SetTrue)] + pub version: bool, } /// Subcommands, e.g. `commitbot pr develop` diff --git a/src/llm/prompts.rs b/src/llm/prompts.rs index 40c09e5..e99ab4d 100644 --- a/src/llm/prompts.rs +++ b/src/llm/prompts.rs @@ -2,14 +2,14 @@ pub const SYSTEM_INSTRUCTIONS: &str = r#"You are a Git commit message assistant Produce the shortest accurate commit message that fully conveys intent. Mode A — single line: -- 3–12 words, no body. +- Line 1: 3–12 words summary. +- Line 2: 5-15 words of context if needed. - ONLY for fixes, corrections, typos, or single-line mechanical changes. -Mode B — summary + short paragraph (preferred for most changes): +Mode B — summary + bullet points (preferred for most changes): - First line under 50 characters. -- Follow with 1–3 sentences of plain prose describing what was added, changed, or why. +- Follow with a few bullet points of plain prose describing what was added, changed, or why. - Use when the change has a single clear purpose but involves multiple files or non-trivial scope. -- Do not use bullets. Mode C — summary + grouped bullets: - First line under 50 characters. diff --git a/src/main.rs b/src/main.rs index d521c94..0e76a64 100644 --- a/src/main.rs +++ b/src/main.rs @@ -661,6 +661,12 @@ fn main() -> Result<()> { // CLI + config let cli = Cli::parse(); + // Handle custom --version early so we print just the version number. + if cli.version { + println!("{}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + // Initialize logging logging::init_logger(cli.verbose); From 0406ceeb5432d95bed6601afcab06556701c122f Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 6 Mar 2026 13:37:41 -0500 Subject: [PATCH 03/40] 0.5.2 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1505a40..6b42d47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 8c42ff7..1f3d747 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.5.1" +version = "0.5.2" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From c2fe28a26542967a62d8ce4344e20224e4da1cf6 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 27 Mar 2026 14:39:04 -0400 Subject: [PATCH 04/40] Improve prompts and add model validation across LLM providers - Enhanced prompt clarity and consistency across commit message, file summary, and PR description templates - Added model validation to ensure configured LLM models are reachable/known before use - Implemented structured Git remote repository handling with support for multiple providers - Improved error handling and reporting for LLM API calls - Refactored prompt building and message generation for better readability and maintainability - Added comprehensive test coverage for Git URL parsing, commit link generation, and model validation - Updated CLI argument parsing and configuration handling for improved consistency - Streamlined LLM client setup with early model validation checks - Enhanced external diff support with clearer messaging and stdin handling - Improved logging output formatting and test suite reliability --- README.md | 6 +- Taskfile.yaml | 1 + src/cli_args.rs | 2 +- src/config.rs | 26 +++- src/git.rs | 274 +++++++++++++++++++++++++++++++++----- src/llm/mod.rs | 9 +- src/llm/ollama.rs | 124 +++++++++++++++-- src/llm/openai.rs | 109 +++++++++++++-- src/llm/prompt_builder.rs | 44 +++--- src/llm/prompts.rs | 15 ++- src/logging.rs | 11 +- src/main.rs | 75 ++++++----- src/setup.rs | 14 +- tests/cli_basics.rs | 4 +- tests/prompt_live.rs | 137 ++++++++++++------- 15 files changed, 650 insertions(+), 201 deletions(-) diff --git a/README.md b/README.md index b912003..6d8fcf1 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,10 @@ A Rust-powered CLI that writes meaningful, structured Git commit messages using LLMs. -[![Version](https://img.shields.io/github/v/release/MikeGarde/commitbot?color=brightgreen&label=release)](https://github.com/MikeGarde/commitbot/releases) -[![Version](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](https://github.com/MikeGarde/commitbot/blob/main/LICENSE) +[![Version](https://img.shields.io/github/v/release/MikeGarde/commitbot?color=blue&label=release)](https://github.com/MikeGarde/commitbot/releases) +[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](https://github.com/MikeGarde/commitbot/blob/main/LICENSE) +[![Downloads](https://img.shields.io/github/downloads/MikeGarde/commitbot/total.svg?color=blue)](https://GitHub.com/MikeGarde/commitbot/releases/) + --- diff --git a/Taskfile.yaml b/Taskfile.yaml index d4ed679..5a0d255 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -97,6 +97,7 @@ tasks: - sh devops/release.sh {{.VERSION}} - task: publish:dry - task: publish + - task: install - TAG=$(commitbot --version) && \ cd ../homebrew-tap && \ gh workflow run update-formula.yml -f formula=commitbot -f repo=mikegarde/commitbot -f tag=$TAG diff --git a/src/cli_args.rs b/src/cli_args.rs index 9c47fb4..47bdbc4 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -1,4 +1,4 @@ -use clap::{Parser, Subcommand, ArgAction}; +use clap::{ArgAction, Parser, Subcommand}; /// CLI options #[derive(Parser, Debug)] diff --git a/src/config.rs b/src/config.rs index 498b2fe..f240dca 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -use crate::{git, Cli}; +use crate::{Cli, git}; use git::detect_repo_id; use serde::Deserialize; use std::collections::HashMap; @@ -48,7 +48,9 @@ impl Config { let base_url = base_url.map(|s| s.trim_matches('"').to_string()); if provider == "openai" && openai_api_key.is_none() { - panic!("OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai"); + panic!( + "OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai" + ); } Config { @@ -161,7 +163,11 @@ impl<'a> ConfigResolver<'a> { // ---- FILE SOURCES ---- fn file_string(&self, key: &str, repo: bool) -> Option { - let cfg = if repo { &self.file_repo } else { &self.file_default }; + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; match key { "provider" => cfg.provider.clone(), "model" => cfg.model.clone(), @@ -172,7 +178,11 @@ impl<'a> ConfigResolver<'a> { } fn file_usize(&self, key: &str, repo: bool) -> Option { - let cfg = if repo { &self.file_repo } else { &self.file_default }; + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; match key { "max_concurrent_requests" => cfg.max_concurrent_requests, _ => None, @@ -180,7 +190,11 @@ impl<'a> ConfigResolver<'a> { } fn file_bool(&self, key: &str, repo: bool) -> Option { - let cfg = if repo { &self.file_repo } else { &self.file_default }; + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; match key { "stream" => cfg.stream, _ => None, @@ -434,4 +448,4 @@ fn load_file_config_from_path(path: &Path) -> FileConfigRoot { FileConfigRoot::default() } } -} \ No newline at end of file +} diff --git a/src/git.rs b/src/git.rs index 9787a66..f006fb3 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result, anyhow}; use std::process::Command as GitCommand; /// How we want to summarize a PR. @@ -26,6 +26,56 @@ pub struct PrItem { pub pr_number: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] +struct RemoteRepo { + path: String, + web_base_url: String, + provider: GitProvider, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GitProvider { + GitHub, + GitLab, + Bitbucket, + AzureDevOps, + Unknown, +} + +impl RemoteRepo { + fn repo_id(&self) -> Option { + if self.provider == GitProvider::AzureDevOps { + let segments: Vec<&str> = self.path.split('/').filter(|s| !s.is_empty()).collect(); + if segments.len() >= 4 && segments[2] == "_git" { + return Some(format!("{}/{}", segments[1], segments[3])); + } + } + + let segments: Vec<&str> = self.path.split('/').filter(|s| !s.is_empty()).collect(); + if segments.len() >= 2 { + let owner = segments[segments.len() - 2]; + let repo = segments[segments.len() - 1]; + Some(format!("{owner}/{repo}")) + } else { + None + } + } + + fn commit_url(&self, commit_hash: &str) -> Option { + match self.provider { + GitProvider::GitHub => Some(format!("{}/commit/{}", self.web_base_url, commit_hash)), + GitProvider::GitLab => Some(format!("{}/-/commit/{}", self.web_base_url, commit_hash)), + GitProvider::Bitbucket => { + Some(format!("{}/commits/{}", self.web_base_url, commit_hash)) + } + GitProvider::AzureDevOps => { + Some(format!("{}/commit/{}", self.web_base_url, commit_hash)) + } + GitProvider::Unknown => None, + } + } +} + /// Run a git command and capture stdout as String. pub fn git_output(args: &[&str]) -> Result { let output = GitCommand::new("git") @@ -44,6 +94,22 @@ pub fn git_output(args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } +fn remote_origin_url() -> Option { + let output = GitCommand::new("git") + .args(["config", "--get", "remote.origin.url"]) + .output() + .ok()?; + + if !output.status.success() { + return None; + } + + String::from_utf8(output.stdout) + .ok() + .map(|url| url.trim().to_string()) + .filter(|url| !url.is_empty()) +} + /// Get the current branch name. pub fn current_branch() -> Result { let name = git_output(&["rev-parse", "--abbrev-ref", "HEAD"])? @@ -85,9 +151,7 @@ fn find_first_pr_number(text: &str) -> Option { let b = bytes[j]; if b.is_ascii_digit() { found_digit = true; - value = value - .saturating_mul(10) - .saturating_add((b - b'0') as u32); + value = value.saturating_mul(10).saturating_add((b - b'0') as u32); j += 1; } else { break; @@ -195,42 +259,190 @@ pub fn stage_all() -> Result<()> { /// Try to derive a repo identifier like "owner/repo" from `git remote.origin.url`. pub fn detect_repo_id() -> Option { - use std::process::Command; + let remote = remote_origin_url()?; + parse_remote_repo(&remote)?.repo_id() +} - let output = Command::new("git") - .args(["config", "--get", "remote.origin.url"]) - .output() - .ok()?; +pub fn format_pr_commit_appendix(items: &[PrItem]) -> String { + if items.is_empty() { + return String::new(); + } - if !output.status.success() { - return None; + let remote = remote_origin_url().and_then(|url| parse_remote_repo(&url)); + format_pr_commit_appendix_with_remote(items, remote.as_ref()) +} + +fn format_pr_commit_appendix_with_remote(items: &[PrItem], remote: Option<&RemoteRepo>) -> String { + let mut out = String::from("Commits in this PR:\n"); + for item in items { + let short = short_commit_hash(&item.commit_hash); + let title = item.title.trim(); + + match remote.and_then(|repo| repo.commit_url(&item.commit_hash)) { + Some(url) => { + out.push_str(&format!("- [`{short}`]({url}) {title}\n")); + } + None => { + out.push_str(&format!("- `{short}` {title}\n")); + } + } } - let url = String::from_utf8(output.stdout).ok()?; + out.trim_end().to_string() +} + +fn short_commit_hash(hash: &str) -> String { + hash.chars().take(7).collect() +} + +fn parse_remote_repo(url: &str) -> Option { let trimmed = url.trim().trim_end_matches(".git"); + if trimmed.is_empty() { + return None; + } - // For SSH: git@github.com:owner/repo - // For HTTPS: https://github.com/owner/repo - let path = if let Some(idx) = trimmed.find("://") { - // Strip scheme and host, keep "owner/repo" - let rest = &trimmed[idx + 3..]; - match rest.find('/') { - Some(slash) => &rest[slash + 1..], - None => rest, + if let Some(rest) = trimmed.strip_prefix("git@ssh.dev.azure.com:v3/") { + let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect(); + if parts.len() >= 3 { + let org = parts[0]; + let project = parts[1]; + let repo = parts[2]; + return Some(RemoteRepo { + path: format!("{org}/{project}/_git/{repo}"), + web_base_url: format!("https://dev.azure.com/{org}/{project}/_git/{repo}"), + provider: GitProvider::AzureDevOps, + }); } - } else if let Some(idx) = trimmed.find(':') { - // SSH-style: after ':' is "owner/repo" - &trimmed[idx + 1..] + } + + if let Some(rest) = trimmed.strip_prefix("ssh://") { + return parse_remote_repo_from_authority_path(rest); + } + + if let Some((host_part, path_part)) = trimmed.split_once("://") { + let _scheme = host_part; + return parse_remote_repo_from_authority_path(path_part); + } + + if let Some((user_host, path)) = trimmed.split_once(':') { + let host = user_host.rsplit('@').next()?.to_string(); + return build_remote_repo(host, path.trim_start_matches('/')); + } + + None +} + +fn parse_remote_repo_from_authority_path(input: &str) -> Option { + let without_user = input.rsplit('@').next().unwrap_or(input); + let (host, path) = without_user.split_once('/')?; + build_remote_repo(host.to_string(), path) +} + +fn build_remote_repo(host: String, path: &str) -> Option { + let clean_path = path.trim_matches('/').to_string(); + if clean_path.is_empty() { + return None; + } + + let provider = if host.contains("github") { + GitProvider::GitHub + } else if host.contains("gitlab") { + GitProvider::GitLab + } else if host.contains("bitbucket") { + GitProvider::Bitbucket + } else if host.contains("azure") + || host == "dev.azure.com" + || host.ends_with(".visualstudio.com") + { + GitProvider::AzureDevOps } else { - trimmed + GitProvider::Unknown + }; + + let web_base_url = match provider { + GitProvider::AzureDevOps => normalize_azure_web_base(&host, &clean_path)?, + _ => format!("https://{host}/{clean_path}"), }; + Some(RemoteRepo { + path: clean_path, + web_base_url, + provider, + }) +} + +fn normalize_azure_web_base(host: &str, path: &str) -> Option { let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); - if segments.len() >= 2 { - let owner = segments[segments.len() - 2]; - let repo = segments[segments.len() - 1]; - Some(format!("{}/{}", owner, repo)) - } else { - None + + if host == "dev.azure.com" && segments.len() >= 4 && segments[2] == "_git" { + return Some(format!( + "https://dev.azure.com/{}/{}/_git/{}", + segments[0], segments[1], segments[3] + )); } -} \ No newline at end of file + + if host.ends_with(".visualstudio.com") { + let org = host.trim_end_matches(".visualstudio.com"); + if segments.len() >= 3 && segments[1] == "_git" { + return Some(format!( + "https://{}.visualstudio.com/{}/_git/{}", + org, segments[0], segments[2] + )); + } + } + + None +} + +#[cfg(test)] +mod tests { + use super::{GitProvider, PrItem, parse_remote_repo}; + + #[test] + fn parses_github_ssh_remote() { + let remote = parse_remote_repo("git@github.com:owner/repo.git").unwrap(); + assert_eq!(remote.provider, GitProvider::GitHub); + assert_eq!(remote.repo_id().as_deref(), Some("owner/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://github.com/owner/repo/commit/abcdef123456") + ); + } + + #[test] + fn parses_gitlab_https_remote() { + let remote = + parse_remote_repo("https://gitlab.example.com/group/subgroup/repo.git").unwrap(); + assert_eq!(remote.provider, GitProvider::GitLab); + assert_eq!(remote.repo_id().as_deref(), Some("subgroup/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://gitlab.example.com/group/subgroup/repo/-/commit/abcdef123456") + ); + } + + #[test] + fn parses_azure_ssh_remote() { + let remote = parse_remote_repo("git@ssh.dev.azure.com:v3/org/project/repo").unwrap(); + assert_eq!(remote.provider, GitProvider::AzureDevOps); + assert_eq!(remote.repo_id().as_deref(), Some("project/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://dev.azure.com/org/project/_git/repo/commit/abcdef123456") + ); + } + + #[test] + fn appendix_falls_back_to_hash_only_when_no_remote() { + let items = vec![PrItem { + commit_hash: "abcdef123456".to_string(), + title: "Refine PR footer rendering".to_string(), + body: String::new(), + pr_number: None, + }]; + + let appendix = super::format_pr_commit_appendix_with_remote(&items, None); + assert!(appendix.contains("Commits in this PR:")); + assert!(appendix.contains("- `abcdef1` Refine PR footer rendering")); + } +} diff --git a/src/llm/mod.rs b/src/llm/mod.rs index a7e5cf3..fd3fe0d 100644 --- a/src/llm/mod.rs +++ b/src/llm/mod.rs @@ -1,15 +1,18 @@ -pub mod openai; pub mod ollama; -mod prompts; +pub mod openai; mod prompt_builder; +mod prompts; mod stream; -use crate::git::{PrItem, PrSummaryMode}; use crate::FileChange; +use crate::git::{PrItem, PrSummaryMode}; use anyhow::Result; /// Trait for talking to an LLM (real backend). pub trait LlmClient: Send + Sync { + /// Confirm the configured model is reachable/known by the upstream provider. + fn validate_model(&self) -> Result<()>; + /// Generate a per-file summary based on diff + metadata. fn summarize_file( &self, diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index d21f32b..7da2b67 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -1,15 +1,16 @@ -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use log; -use musli::{Encode, Decode}; use musli::json; +use musli::{Decode, Encode}; +use reqwest::StatusCode; use reqwest::blocking::Client; use std::io::BufReader; use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; -use super::{prompt_builder, LlmClient}; use super::stream::read_stream_to_string; +use super::{LlmClient, prompt_builder}; #[derive(Debug, Encode, Decode)] struct OllamaMessage { @@ -28,6 +29,16 @@ struct OllamaStreamResponse { done: Option, } +#[derive(Debug, Decode)] +struct OllamaTagModel { + name: String, +} + +#[derive(Debug, Decode)] +struct OllamaTagsResponse { + models: Vec, +} + /// Synchronous Ollama client using /api/chat. pub struct OllamaClient { http: Client, @@ -114,6 +125,9 @@ impl OllamaClient { Ok(parsed.message.content.trim().to_string()) } + fn tags_url(&self) -> String { + format!("{}/api/tags", self.base_url) + } } fn parse_stream_line(line: &str) -> Result> { @@ -124,14 +138,65 @@ fn parse_stream_line(line: &str) -> Result> { return Ok(None); } - let content = parsed - .message - .and_then(|m| if m.content.is_empty() { None } else { Some(m.content) }); + let content = parsed.message.and_then(|m| { + if m.content.is_empty() { + None + } else { + Some(m.content) + } + }); Ok(content) } impl LlmClient for OllamaClient { + fn validate_model(&self) -> Result<()> { + let url = self.tags_url(); + let resp = self + .http + .get(&url) + .send() + .map_err(|e| anyhow!("Error calling Ollama at {url}: {e}"))?; + + if resp.status() != StatusCode::OK { + let status = resp.status(); + let body = resp.text().unwrap_or_default(); + return Err(anyhow!( + "Ollama model validation failed at {url}: HTTP {} - {}", + status.as_u16(), + body + )); + } + + let body = resp + .text() + .map_err(|e| anyhow!("Failed to read Ollama tags response from {url}: {e}"))?; + let parsed: OllamaTagsResponse = json::from_str(&body) + .map_err(|e| anyhow!("Failed to decode Ollama tags response from {url}: {e}"))?; + + if parsed.models.iter().any(|model| model.name == self.model) { + return Ok(()); + } + + let available = parsed + .models + .iter() + .map(|model| model.name.as_str()) + .collect::>() + .join(", "); + + Err(anyhow!( + "Model {:?} was not found at {}. Available models: {}", + self.model, + url, + if available.is_empty() { + "" + } else { + &available + } + )) + } + fn summarize_file( &self, branch: &str, @@ -140,7 +205,13 @@ impl LlmClient for OllamaClient { total_files: usize, ticket_summary: Option<&str>, ) -> Result { - let prompts = prompt_builder::file_summary_prompt(branch, file, file_index, total_files, ticket_summary); + let prompts = prompt_builder::file_summary_prompt( + branch, + file, + file_index, + total_files, + ticket_summary, + ); self.chat(prompts.system, prompts.user, false) } @@ -162,8 +233,43 @@ impl LlmClient for OllamaClient { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result { - let prompts = - prompt_builder::pr_message_prompt(base_branch, from_branch, mode, items, ticket_summary); + let prompts = prompt_builder::pr_message_prompt( + base_branch, + from_branch, + mode, + items, + ticket_summary, + ); self.chat(prompts.system, prompts.user, self.stream) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trims_trailing_slash_in_tags_url() { + let client = OllamaClient::new("http://localhost:11434/", "qwen3-coder:30b", false); + assert_eq!(client.tags_url(), "http://localhost:11434/api/tags"); + } + + #[test] + fn decodes_ollama_tags_payload() { + let body = r#"{"models":[{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#; + let parsed: OllamaTagsResponse = json::from_str(body).expect("valid tags payload"); + + assert!( + parsed + .models + .iter() + .any(|model| model.name == "qwen3-coder:30b") + ); + assert!( + !parsed + .models + .iter() + .any(|model| model.name == "missing:model") + ); + } +} diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 162b541..ed55e4a 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -1,13 +1,14 @@ use super::LlmClient; +use super::prompt_builder; use super::stream::read_stream_to_string; -use crate::{FileChange}; +use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result, anyhow}; +use reqwest::StatusCode; use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::time::Duration; -use super::prompt_builder; /// Minimal request/response structs for OpenAI Chat Completions API. #[derive(Serialize)] @@ -94,6 +95,14 @@ impl OpenAiClient { } } + fn model_url(&self) -> String { + if self.api_base_url.ends_with("/v1") { + format!("{}/models/{}", self.api_base_url, self.model) + } else { + format!("{}/v1/models/{}", self.api_base_url, self.model) + } + } + fn call_chat(&self, req: &ChatRequest) -> Result { if req.stream { return self.call_chat_streaming(req); @@ -129,8 +138,11 @@ impl OpenAiClient { .ok_or_else(|| anyhow!("no choices returned from OpenAI"))?; if let Some(usage) = &chat_resp.usage { - log::warn!("Token usage: prompt={}, completion={}, total={}", - usage.prompt_tokens, usage.completion_tokens, usage.total_tokens + log::warn!( + "Token usage: prompt={}, completion={}, total={}", + usage.prompt_tokens, + usage.completion_tokens, + usage.total_tokens ); } @@ -178,15 +190,36 @@ fn parse_stream_line(line: &str) -> Result> { let chunk: StreamResponse = serde_json::from_str(data).context("failed to parse OpenAI streaming chunk")?; - let content = chunk - .choices - .first() - .and_then(|c| c.delta.content.clone()); + let content = chunk.choices.first().and_then(|c| c.delta.content.clone()); Ok(content) } impl LlmClient for OpenAiClient { + fn validate_model(&self) -> Result<()> { + let url = self.model_url(); + let resp = self + .client + .get(&url) + .bearer_auth(&self.api_key) + .send() + .context("failed to send model validation request to OpenAI")?; + + if resp.status() == StatusCode::OK { + return Ok(()); + } + + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + Err(anyhow!( + "OpenAI model validation failed for {:?} at {}: HTTP {} - {}", + self.model, + url, + status.as_u16(), + text + )) + } + fn summarize_file( &self, branch: &str, @@ -195,7 +228,13 @@ impl LlmClient for OpenAiClient { total_files: usize, ticket_summary: Option<&str>, ) -> Result { - let prompts = prompt_builder::file_summary_prompt(branch, file, file_index, total_files, ticket_summary); + let prompts = prompt_builder::file_summary_prompt( + branch, + file, + file_index, + total_files, + ticket_summary, + ); log::info!( "Per-file summarize prompt for {} ({:?}) [truncated]:\n{}", @@ -275,8 +314,13 @@ impl LlmClient for OpenAiClient { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result { - let prompts = - prompt_builder::pr_message_prompt(base_branch, from_branch, mode, items, ticket_summary); + let prompts = prompt_builder::pr_message_prompt( + base_branch, + from_branch, + mode, + items, + ticket_summary, + ); log::info!( "PR description prompt [truncated]:\n{}", @@ -313,6 +357,45 @@ fn truncate(s: &str, max_len: usize) -> String { if s.len() <= max_len { s.to_string() } else { - format!("{}...\n[truncated {} chars]", &s[..max_len], s.len() - max_len) + format!( + "{}...\n[truncated {} chars]", + &s[..max_len], + s.len() - max_len + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn builds_model_url_from_root_base() { + let client = OpenAiClient::new( + "test-key".into(), + "gpt-5-nano".into(), + "https://api.openai.com".into(), + false, + ); + + assert_eq!( + client.model_url(), + "https://api.openai.com/v1/models/gpt-5-nano" + ); + } + + #[test] + fn builds_model_url_from_v1_base() { + let client = OpenAiClient::new( + "test-key".into(), + "gpt-5-nano".into(), + "https://api.openai.com/v1".into(), + false, + ); + + assert_eq!( + client.model_url(), + "https://api.openai.com/v1/models/gpt-5-nano" + ); } } diff --git a/src/llm/prompt_builder.rs b/src/llm/prompt_builder.rs index 212a190..e203886 100644 --- a/src/llm/prompt_builder.rs +++ b/src/llm/prompt_builder.rs @@ -1,8 +1,8 @@ use std::collections::BTreeMap; +use crate::git::{PrItem, PrSummaryMode}; use crate::llm::prompts; use crate::{FileCategory, FileChange}; -use crate::git::{PrItem, PrSummaryMode}; pub struct PromptPair { pub system: String, @@ -51,9 +51,11 @@ pub fn commit_message_prompt( } let per_file = render_per_file_summaries(files); + let file_count = files.len(); let user = format!( - "Branch: {branch}\n\nPer-file summaries:\n\n{per_file}", + "Branch: {branch}\n\nFiles Changed: {file_count}\n\nPer-file summaries:\n\n{per_file}", branch = branch, + file_count = file_count + 1, per_file = per_file ); @@ -114,31 +116,18 @@ pub fn pr_message_prompt( } } - user.push_str( - "Pull requests contributing to this branch (oldest commits first):\n", - ); + user.push_str("Pull requests contributing to this branch (oldest commits first):\n"); for (num, group) in grouped { - let short = group[0] - .commit_hash - .chars() - .take(7) - .collect::(); + let short = group[0].commit_hash.chars().take(7).collect::(); let title = group[0].title.trim(); user.push_str(&format!("\nPR #{num}: {title} [{short}]\n")); if group.len() > 1 { user.push_str("Additional commits in this PR:\n"); for item in group.iter().skip(1) { - let sh = item - .commit_hash - .chars() - .take(7) - .collect::(); - user.push_str(&format!( - "- {sh}: {title}\n", - title = item.title.trim() - )); + let sh = item.commit_hash.chars().take(7).collect::(); + user.push_str(&format!("- {sh}: {title}\n", title = item.title.trim())); } } } @@ -148,15 +137,8 @@ pub fn pr_message_prompt( "\nCommits without associated PR numbers (may be small fixes or direct pushes):\n", ); for item in no_pr { - let short = item - .commit_hash - .chars() - .take(7) - .collect::(); - user.push_str(&format!( - "- {short}: {title}\n", - title = item.title.trim() - )); + let short = item.commit_hash.chars().take(7).collect::(); + user.push_str(&format!("- {short}: {title}\n", title = item.title.trim())); } } } @@ -168,7 +150,11 @@ pub fn pr_message_prompt( fn render_per_file_summaries(files: &[FileChange]) -> String { let total_files = files.len(); let mut out = String::new(); - for (idx, file) in files.iter().enumerate().filter(|(_, f)| !matches!(f.category, FileCategory::Ignored)) { + for (idx, file) in files + .iter() + .enumerate() + .filter(|(_, f)| !matches!(f.category, FileCategory::Ignored)) + { out.push_str(&format!( "File {file_num} of {total_files}: {path}\nCategory: {category}\nSummary:\n{summary}\n\n", file_num = idx + 1, diff --git a/src/llm/prompts.rs b/src/llm/prompts.rs index e99ab4d..4a94724 100644 --- a/src/llm/prompts.rs +++ b/src/llm/prompts.rs @@ -25,20 +25,23 @@ Rules: - No filler ("various", "multiple", "across modules"). - Precise verbs over vague ones ("Extract", "Wire up", "Expose" vs "Update", "Improve"). - Backticks only in modes B and C. -- Output only the commit message."#; +- Use dashes '-' for bullet points, never use '*' or '•'. +- Output only the commit message. +- Do not add commentary or decession reasoning."#; pub const FILE_SUMMARY: &str = r#"Summarize the intent of changes to this file into as few bullets as possible. - Focus on WHY, not WHAT (the reader has the diff). - Skip mechanical, formatting, or metadata-only changes — just label them as such. - No code, no speculation, no narration. -- Output only the bullet list."#; +- Output only the bullet list. +- Use dashes '-' for bullet points, never use '*' or '•'."#; pub const PR_INSTRUCTIONS: &str = r#"You are a GitHub Pull Request description assistant. Summarize the *story* and *intent* of the branch, not the diff. Rules: -- Start with a concise PR title (<= 72 characters, no formatting). +- Start with a concise PR title (<= 72 characters and no formatting). - Then include sections such as: ## Overview ## Changes @@ -48,5 +51,7 @@ Rules: - Treat the PR as a unit of work, not a list of commits. - De-emphasize mechanical, formatting-only, or metadata-only changes. - If many small changes exist, summarize them collectively. -- Reference PR numbers if provided. -- Avoid generic phrases like "misc changes" or "small fixes"."#; +- Reference commit hashes when appropriate. +- Avoid generic phrases like "misc changes" or "small fixes". +- Use dashes '-' for bullet points, never use '*' or '•'. +- Do not add commentary or decession reasoning."#; diff --git a/src/logging.rs b/src/logging.rs index ee2614c..8dc793e 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -20,18 +20,13 @@ pub fn init_logger(verbosity: u8) { let level_label = match level { Level::Error => "ERROR".red().bold(), - Level::Warn => "WARN ".yellow().bold(), - Level::Info => "INFO ".white().bold(), + Level::Warn => "WARN ".yellow().bold(), + Level::Info => "INFO ".white().bold(), Level::Debug => "DEBUG".bright_black(), Level::Trace => "TRACE".bright_black(), }; - writeln!( - buf, - "{} {}", - level_label, - record.args() - ) + writeln!(buf, "{} {}", level_label, record.args()) }); builder.init(); diff --git a/src/main.rs b/src/main.rs index 0e76a64..6e5abbf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ mod llm; mod logging; mod setup; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use clap::Parser; use config::Config; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; @@ -18,8 +18,8 @@ use std::time::Duration; use crate::cli_args::{Cli, Command}; use crate::git::{ - collect_pr_items, current_branch, split_diff_by_file, staged_diff_for_file, staged_files, - stage_all, PrSummaryMode, + PrSummaryMode, collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, + stage_all, staged_diff_for_file, staged_files, }; use crate::llm::LlmClient; @@ -228,8 +228,7 @@ fn summarize_files_concurrently( for &file_idx in chunk { let results = Arc::clone(&results); let pb = pb.clone(); - let file_line = file_lines - .and_then(|lines| lines.get(file_idx)).cloned(); + let file_line = file_lines.and_then(|lines| lines.get(file_idx)).cloned(); if let Some(line) = &file_line { line.set_message("summarizing..."); @@ -443,18 +442,11 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if cfg.stream { - let _msg = llm.generate_commit_message( - &branch, - &file_changes, - ticket_summary.as_deref(), - )?; + let _msg = + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; println!(); } else { - let msg = llm.generate_commit_message( - &branch, - &file_changes, - ticket_summary.as_deref(), - )?; + let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; println!("{msg}"); } @@ -464,7 +456,9 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { /// Auto mode (default): per-file LLM summaries then final commit message — no human classification. /// When `--diff` is supplied the combined diff is split by file; otherwise staged files are used. fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { - let (branch, file_pairs): (String, Vec<(String, String)>) = if let Some(ref diff_arg) = cli.diff { + let using_external_diff = cli.diff.is_some(); + let (branch, file_pairs): (String, Vec<(String, String)>) = if let Some(ref diff_arg) = cli.diff + { // Read the combined diff from file or stdin. let combined = if diff_arg == "-" { use std::io::Read; @@ -517,6 +511,10 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); println!("Asking {}...", cfg.model); + if let Some(ref diff_arg) = cli.diff { + let diff_source = if diff_arg == "-" { "stdin" } else { diff_arg }; + println!("Using external diff: {diff_source}"); + } let total = file_changes.len(); let mp = MultiProgress::new(); @@ -528,7 +526,12 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { ProgressStyle::with_template("{spinner:.cyan} {prefix:.bold}: {msg}") .expect("progress style template"), ); - line.set_prefix(fc.path.clone()); + let prefix = if using_external_diff { + format!("[diff] {}", fc.path) + } else { + fc.path.clone() + }; + line.set_prefix(prefix); line.enable_steady_tick(Duration::from_millis(120)); line.set_message("waiting"); file_lines.push(line); @@ -569,7 +572,8 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if cfg.stream { - let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; + let _msg = + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; println!(); } else { let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; @@ -631,29 +635,25 @@ fn run_pr( let ticket_summary = resolved_ticket_summary(cli); let _pr_message = if cfg.stream { println!(); - let msg = llm.generate_pr_message( - base, - &from_branch, - mode, - &items, - ticket_summary.as_deref(), - )?; + let msg = + llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; println!(); msg } else { println!(); - let msg = llm.generate_pr_message( - base, - &from_branch, - mode, - &items, - ticket_summary.as_deref(), - )?; + let msg = + llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; println!("{msg}"); msg }; + let appendix = format_pr_commit_appendix(&items); + if !appendix.is_empty() { + println!(); + println!("{appendix}"); + } + Ok(()) } @@ -686,14 +686,15 @@ fn main() -> Result<()> { // LLM client setup let boxed_client = setup::build_llm_client(&cfg); + boxed_client.validate_model()?; match &cli.command { Some(Command::Pr { - base, - from, - pr_mode, - commit_mode, - }) => run_pr( + base, + from, + pr_mode, + commit_mode, + }) => run_pr( &cli, &cfg, boxed_client.as_ref(), diff --git a/src/setup.rs b/src/setup.rs index e6cec2d..a584185 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1,7 +1,7 @@ use crate::config::Config; use crate::llm::LlmClient; -use crate::llm::openai::OpenAiClient; use crate::llm::ollama::OllamaClient; +use crate::llm::openai::OpenAiClient; /// Build the LLM client based on CLI + config. pub fn build_llm_client(cfg: &Config) -> Box { @@ -18,7 +18,8 @@ pub fn build_llm_client(cfg: &Config) -> Box { log::debug!( "Using OpenAiClient with model: {} (stream={})", - cfg.model, cfg.stream + cfg.model, + cfg.stream ); Box::new(OpenAiClient::new( @@ -36,14 +37,11 @@ pub fn build_llm_client(cfg: &Config) -> Box { log::debug!( "Using OllamaClient with model: {} (stream={})", - cfg.model, cfg.stream + cfg.model, + cfg.stream ); - Box::new(OllamaClient::new( - base_url, - cfg.model.clone(), - cfg.stream, - )) + Box::new(OllamaClient::new(base_url, cfg.model.clone(), cfg.stream)) } other => panic!("Unknown provider: {}", other), } diff --git a/tests/cli_basics.rs b/tests/cli_basics.rs index 48abfe6..8d0eb88 100644 --- a/tests/cli_basics.rs +++ b/tests/cli_basics.rs @@ -1,4 +1,4 @@ -use assert_cmd::{cargo}; +use assert_cmd::cargo; #[test] fn prints_help() { @@ -18,4 +18,4 @@ fn prints_version() { .assert() .success() .stdout(predicates::str::contains(env!("CARGO_PKG_VERSION"))); -} \ No newline at end of file +} diff --git a/tests/prompt_live.rs b/tests/prompt_live.rs index 4d7538b..a47b18a 100644 --- a/tests/prompt_live.rs +++ b/tests/prompt_live.rs @@ -62,15 +62,25 @@ impl TestResult { } fn print_summary(&self) { - let status = if self.passed() { "✅ PASS" } else { "❌ FAIL" }; + let status = if self.passed() { + "✅ PASS" + } else { + "❌ FAIL" + }; println!("\n{} {} ({})", status, self.name, self.language); println!(" Output: \"{}\"", self.output.lines().next().unwrap_or("")); - println!(" Metrics: {} lines, {} words, {} chars, summary={} chars", - self.metrics.lines, self.metrics.words, - self.metrics.characters, self.metrics.summary_length); - println!(" Keywords: {}/{} found", + println!( + " Metrics: {} lines, {} words, {} chars, summary={} chars", + self.metrics.lines, + self.metrics.words, + self.metrics.characters, + self.metrics.summary_length + ); + println!( + " Keywords: {}/{} found", self.keywords_found.len(), - self.keywords_found.len() + self.keywords_missing.len()); + self.keywords_found.len() + self.keywords_missing.len() + ); if !self.keywords_missing.is_empty() { println!(" Missing keywords: {:?}", self.keywords_missing); @@ -85,6 +95,12 @@ impl TestResult { } } +fn print_llm_output(label: &str, output: &str) { + println!("\n--- LLM Output: {label} ---"); + println!("{}", output.trim()); + println!("--- End LLM Output ---"); +} + fn get_test_diffs_dir() -> PathBuf { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("tests"); @@ -102,10 +118,10 @@ fn run_commitbot_with_diff(diff_file: &str, branch: &str) -> Result TestResult { failures.push(format!("lines {} > max {}", metrics.lines, test.max_lines)); } if metrics.summary_length > test.max_summary_length { - failures.push(format!("summary {} > max {}", metrics.summary_length, test.max_summary_length)); + failures.push(format!( + "summary {} > max {}", + metrics.summary_length, test.max_summary_length + )); } TestResult { @@ -166,7 +185,7 @@ fn all_test_cases() -> Vec { diff_file: "rust_auth_feature.diff", expected_keywords: vec!["auth", "token", "validate"], min_words: 15, - max_words: 45, + max_words: 60, max_lines: 10, max_summary_length: 72, }, @@ -176,8 +195,8 @@ fn all_test_cases() -> Vec { diff_file: "rust_fix_panic.diff", expected_keywords: vec!["fix", "error", "panic"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 55, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -186,8 +205,8 @@ fn all_test_cases() -> Vec { diff_file: "python_rate_limit.diff", expected_keywords: vec!["rate", "limit", "decorator"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 75, + max_lines: 11, max_summary_length: 72, }, TestCase { @@ -196,8 +215,8 @@ fn all_test_cases() -> Vec { diff_file: "js_debounce_hook.diff", expected_keywords: vec!["debounce", "hook"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 80, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -206,8 +225,8 @@ fn all_test_cases() -> Vec { diff_file: "ts_api_types.diff", expected_keywords: vec!["type", "interface", "api"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 65, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -216,8 +235,8 @@ fn all_test_cases() -> Vec { diff_file: "go_logging_middleware.diff", expected_keywords: vec!["logging", "middleware", "http"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 65, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -226,8 +245,8 @@ fn all_test_cases() -> Vec { diff_file: "java_email_service.diff", expected_keywords: vec!["email", "service"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 65, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -236,8 +255,8 @@ fn all_test_cases() -> Vec { diff_file: "php_phone_validation.diff", expected_keywords: vec!["validation", "phone"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 65, + max_lines: 10, max_summary_length: 72, }, TestCase { @@ -246,8 +265,8 @@ fn all_test_cases() -> Vec { diff_file: "csharp_repository.diff", expected_keywords: vec!["repository"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 100, + max_lines: 15, max_summary_length: 72, }, TestCase { @@ -256,8 +275,8 @@ fn all_test_cases() -> Vec { diff_file: "ruby_soft_delete.diff", expected_keywords: vec!["soft", "delete"], min_words: 3, - max_words: 15, - max_lines: 1, + max_words: 60, + max_lines: 10, max_summary_length: 72, }, ] @@ -273,17 +292,26 @@ fn test_all_diff_files_exist() { for test in all_test_cases() { let path = diffs_dir.join(test.diff_file); - assert!(path.exists(), "Missing diff file: {} ({:?})", test.name, path); + assert!( + path.exists(), + "Missing diff file: {} ({:?})", + test.name, + path + ); let content = fs::read_to_string(&path).expect("Failed to read diff file"); assert!(!content.is_empty(), "Empty diff file: {}", test.name); assert!( content.contains("diff --git") || content.contains("---"), - "Invalid diff format in {}", test.name + "Invalid diff format in {}", + test.name ); } - println!("✅ All {} diff files exist and are valid", all_test_cases().len()); + println!( + "✅ All {} diff files exist and are valid", + all_test_cases().len() + ); } #[test] @@ -294,8 +322,10 @@ fn test_list_available_fixtures() { println!("📁 {} ({})", test.name, test.language); println!(" File: {}", test.diff_file); println!(" Expected keywords: {:?}", test.expected_keywords); - println!(" Constraints: {}-{} words, max {} lines, summary <= {} chars", - test.min_words, test.max_words, test.max_lines, test.max_summary_length); + println!( + " Constraints: {}-{} words, max {} lines, summary <= {} chars", + test.min_words, test.max_words, test.max_lines, test.max_summary_length + ); println!(); } } @@ -310,8 +340,12 @@ fn live_test_all_languages() { for test in all_test_cases() { print!("Testing {} ({})... ", test.name, test.language); - match run_commitbot_with_diff(test.diff_file, &format!("feature/{}", test.language.to_lowercase())) { + match run_commitbot_with_diff( + test.diff_file, + &format!("feature/{}", test.language.to_lowercase()), + ) { Ok(output) => { + print_llm_output(test.name, &output); let result = validate_output(&test, &output); if result.passed() { println!("✅"); @@ -342,7 +376,8 @@ fn live_test_all_languages() { println!("\n=== CSV Report ==="); println!("name,language,lines,words,chars,summary_len,keywords_found,keywords_missing,passed"); for result in &results { - println!("{},{},{},{},{},{},{},{},{}", + println!( + "{},{},{},{},{},{},{},{},{}", result.name, result.language, result.metrics.lines, @@ -369,9 +404,7 @@ fn live_test_single_rust() { result.print_summary(); // For manual inspection during prompt tuning - println!("\n--- Full Output ---"); - println!("{}", output); - println!("--- End Output ---"); + print_llm_output(test.name, &output); } Err(e) => { println!("Error: {}", e); @@ -390,6 +423,7 @@ fn live_test_word_count_distribution() { for test in all_test_cases() { if let Ok(output) = run_commitbot_with_diff(test.diff_file, "feature/test") { + print_llm_output(test.name, &output); let metrics = OutputMetrics::from_output(&output); word_counts.push((test.name, test.language, metrics.words)); } @@ -404,7 +438,8 @@ fn live_test_word_count_distribution() { } if !word_counts.is_empty() { - let avg: f64 = word_counts.iter().map(|x| x.2 as f64).sum::() / word_counts.len() as f64; + let avg: f64 = + word_counts.iter().map(|x| x.2 as f64).sum::() / word_counts.len() as f64; let min = word_counts.first().map(|x| x.2).unwrap_or(0); let max = word_counts.last().map(|x| x.2).unwrap_or(0); @@ -423,6 +458,7 @@ fn live_test_keyword_hit_rate() { for test in all_test_cases() { if let Ok(output) = run_commitbot_with_diff(test.diff_file, "feature/test") { + print_llm_output(test.name, &output); let result = validate_output(&test, &output); let expected = result.keywords_found.len() + result.keywords_missing.len(); let found = result.keywords_found.len(); @@ -430,16 +466,23 @@ fn live_test_keyword_hit_rate() { total_expected += expected; total_found += found; - let rate = if expected > 0 { (found as f64 / expected as f64) * 100.0 } else { 0.0 }; - println!("{:20} | {}/{} ({:.0}%) | Found: {:?}", - test.name, found, expected, rate, result.keywords_found); + let rate = if expected > 0 { + (found as f64 / expected as f64) * 100.0 + } else { + 0.0 + }; + println!( + "{:20} | {}/{} ({:.0}%) | Found: {:?}", + test.name, found, expected, rate, result.keywords_found + ); } } if total_expected > 0 { let overall_rate = (total_found as f64 / total_expected as f64) * 100.0; - println!("\nOverall keyword hit rate: {}/{} ({:.1}%)", - total_found, total_expected, overall_rate); + println!( + "\nOverall keyword hit rate: {}/{} ({:.1}%)", + total_found, total_expected, overall_rate + ); } } - From 2bbdc03d1a8c109d0bf642e80c145f4e2ec86061 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 27 Mar 2026 14:54:52 -0400 Subject: [PATCH 05/40] Switch to faster release process by using targeted tests and removing automated testing step - Updated Taskfile.yaml to add `test:simple` task for faster unit test execution with nocapture - Modified release process to use `test:simple` instead of full test suite - Removed automated testing from devops/release.sh to reduce release runtime --- Taskfile.yaml | 8 +++++++- devops/release.sh | 3 --- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index 5a0d255..cb4bb52 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -17,6 +17,12 @@ tasks: - cargo clippy --all-targets --all-features -- -D warnings - cargo test --all-features + test:simple: + desc: "Run simple unit tests" + cmds: + - cargo clippy --all-targets --all-features -- -D warnings + - cargo test --test cli_basics -- --nocapture + test:prompts: desc: "Run prompt tests" cmds: @@ -93,7 +99,7 @@ tasks: VERSION: '{{index .MATCH 0}}' interactive: true cmds: - - task: test + - task: test:simple - sh devops/release.sh {{.VERSION}} - task: publish:dry - task: publish diff --git a/devops/release.sh b/devops/release.sh index d4ea765..dbb0256 100644 --- a/devops/release.sh +++ b/devops/release.sh @@ -126,9 +126,6 @@ perl -pi -e 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"/version = "'"$NEW_VERSION"'"/ echo "Running task setup..." task setup -echo "Running task test..." -task test - echo "Running task build:release:all..." task "build:release:${NEW_VERSION}" From 067501e68501e78102a84605dd7d4fb8de9bcd24 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 27 Mar 2026 14:57:23 -0400 Subject: [PATCH 06/40] 0.6.0 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6b42d47..53d6d07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.5.2" +version = "0.6.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 1f3d747..6f4a4f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.5.2" +version = "0.6.0" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From df091d7a122c04ed05adc711aabb76f9a68a66da Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 27 Mar 2026 20:20:27 -0400 Subject: [PATCH 07/40] Refactor CLI and config handling, improve error propagation, and enhance test coverage - Replaced specific test file name with --ignored flag to run all tests - Made branch field optional in CLI args with dynamic derivation from current branch - Introduced anyhow::Result for better config loading error handling - Exposed helper functions and made struct/enum fields public in git module - Refactored main module imports and error handling with explicit ? operators - Moved LLM client setup to setup module for better organization - Added comprehensive tests for CLI parsing, config loading, Git operations, and core types - Marked live LLM tests as ignored to prevent execution without actual LLM access - Corrected spelling in prompt rules and reformatted assertions for readability --- Taskfile.yaml | 4 +- src/cli_args.rs | 12 ++- src/config.rs | 17 ++-- src/git.rs | 83 +++++------------- src/lib.rs | 51 ++++++++++++ src/llm/ollama.rs | 20 ++--- src/llm/prompts.rs | 4 +- src/main.rs | 194 ++++++++++++++----------------------------- src/setup.rs | 17 ++-- tests/cli_basics.rs | 12 +++ tests/config.rs | 135 ++++++++++++++++++++++++++++++ tests/git.rs | 143 +++++++++++++++++++++++++++++++ tests/lib_types.rs | 25 ++++++ tests/prompt_live.rs | 4 + 14 files changed, 497 insertions(+), 224 deletions(-) create mode 100644 src/lib.rs create mode 100644 tests/config.rs create mode 100644 tests/git.rs create mode 100644 tests/lib_types.rs diff --git a/Taskfile.yaml b/Taskfile.yaml index cb4bb52..d1b6290 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -21,12 +21,12 @@ tasks: desc: "Run simple unit tests" cmds: - cargo clippy --all-targets --all-features -- -D warnings - - cargo test --test cli_basics -- --nocapture + - cargo test -- --nocapture test:prompts: desc: "Run prompt tests" cmds: - - cargo test --test prompt_live -- --nocapture + - cargo test --test prompt_live -- --ignored --nocapture run:simple: desc: "Run commitbot in simple mode (no model, debug) using cargo run" diff --git a/src/cli_args.rs b/src/cli_args.rs index 47bdbc4..da0fda4 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -42,8 +42,9 @@ pub struct Cli { pub diff: Option, /// Branch name to use in the commit message context (used with --diff). - #[arg(long, global = true, default_value = "feature/test-branch")] - pub branch: String, + /// If not specified with --diff, defaults to the current branch. + #[arg(long, global = true)] + pub branch: Option, /// Disable streaming responses (streaming is on by default) #[arg(long, global = true)] @@ -70,6 +71,10 @@ pub struct Cli { #[derive(Subcommand, Debug)] pub enum Command { /// Generate a Pull Request description by summarizing commit or PR messages + /// + /// This command analyzes a commit range and generates a PR summary. + /// Example: + /// commitbot pr --base main --from feature-branch Pr { /// Base branch to compare against (e.g. main or develop) base: String, @@ -87,6 +92,9 @@ pub enum Command { }, /// Freeform summary provided at the end of the command. + /// + /// Example: + /// commitbot summary "fix: correct typo in documentation" #[command(external_subcommand)] Summary(Vec), } diff --git a/src/config.rs b/src/config.rs index f240dca..9b642e0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,5 @@ use crate::{Cli, git}; +use anyhow::{anyhow, Result}; use git::detect_repo_id; use serde::Deserialize; use std::collections::HashMap; @@ -9,11 +10,17 @@ use std::path::{Path, PathBuf}; /// Final resolved configuration for commitbot. #[derive(Debug, Clone)] pub struct Config { + /// LLM provider (openai, ollama) pub provider: String, + /// OpenAI API key for authentication pub openai_api_key: Option, + /// Base URL for the LLM provider pub base_url: Option, + /// Model name to use for LLM calls pub model: String, + /// Maximum concurrent requests to the LLM API pub max_concurrent_requests: usize, + /// Whether to stream responses from the LLM pub stream: bool, } @@ -26,7 +33,7 @@ impl Config { /// 3. Per-repo table in config file (e.g. ["mikegarde/commitbot"]) /// 4. [default] table in config file /// 5. Hardcoded defaults - pub fn from_sources(cli: &Cli) -> Self { + pub fn from_sources(cli: &Cli) -> Result { let r = ConfigResolver::new(cli); let provider = r.get_string("provider", "openai").to_lowercase(); @@ -48,19 +55,19 @@ impl Config { let base_url = base_url.map(|s| s.trim_matches('"').to_string()); if provider == "openai" && openai_api_key.is_none() { - panic!( + return Err(anyhow!( "OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai" - ); + )); } - Config { + Ok(Config { provider, model, openai_api_key, base_url, max_concurrent_requests, stream, - } + }) } } diff --git a/src/git.rs b/src/git.rs index f006fb3..20f3879 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,14 +1,17 @@ -use anyhow::{Context, Result, anyhow}; +use anyhow::{anyhow, Context, Result}; use std::process::Command as GitCommand; /// How we want to summarize a PR. #[derive(Debug, Clone, Copy)] pub enum PrSummaryMode { + /// Summarize by commits ByCommits, + /// Summarize by PR numbers ByPrs, } impl PrSummaryMode { + /// Convert the mode to a string representation. pub fn as_str(&self) -> &'static str { match self { PrSummaryMode::ByCommits => "commits", @@ -20,21 +23,25 @@ impl PrSummaryMode { /// A commit involved in the PR range, plus any detected PR number. #[derive(Debug, Clone)] pub struct PrItem { + /// Git commit hash pub commit_hash: String, + /// Commit title/message pub title: String, + /// Commit body/description pub body: String, + /// Detected PR number from commit message pub pr_number: Option, } #[derive(Debug, Clone, PartialEq, Eq)] -struct RemoteRepo { +pub struct RemoteRepo { path: String, web_base_url: String, - provider: GitProvider, + pub provider: GitProvider, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum GitProvider { +pub enum GitProvider { GitHub, GitLab, Bitbucket, @@ -43,7 +50,7 @@ enum GitProvider { } impl RemoteRepo { - fn repo_id(&self) -> Option { + pub fn repo_id(&self) -> Option { if self.provider == GitProvider::AzureDevOps { let segments: Vec<&str> = self.path.split('/').filter(|s| !s.is_empty()).collect(); if segments.len() >= 4 && segments[2] == "_git" { @@ -61,7 +68,7 @@ impl RemoteRepo { } } - fn commit_url(&self, commit_hash: &str) -> Option { + pub fn commit_url(&self, commit_hash: &str) -> Option { match self.provider { GitProvider::GitHub => Some(format!("{}/commit/{}", self.web_base_url, commit_hash)), GitProvider::GitLab => Some(format!("{}/-/commit/{}", self.web_base_url, commit_hash)), @@ -136,7 +143,7 @@ pub fn staged_diff_for_file(path: &str) -> Result { } /// Find the first PR number in a string, based on '#123' pattern. -fn find_first_pr_number(text: &str) -> Option { +pub fn find_first_pr_number(text: &str) -> Option { let bytes = text.as_bytes(); let len = bytes.len(); let mut i = 0; @@ -272,7 +279,10 @@ pub fn format_pr_commit_appendix(items: &[PrItem]) -> String { format_pr_commit_appendix_with_remote(items, remote.as_ref()) } -fn format_pr_commit_appendix_with_remote(items: &[PrItem], remote: Option<&RemoteRepo>) -> String { +pub fn format_pr_commit_appendix_with_remote( + items: &[PrItem], + remote: Option<&RemoteRepo>, +) -> String { let mut out = String::from("Commits in this PR:\n"); for item in items { let short = short_commit_hash(&item.commit_hash); @@ -291,11 +301,11 @@ fn format_pr_commit_appendix_with_remote(items: &[PrItem], remote: Option<&Remot out.trim_end().to_string() } -fn short_commit_hash(hash: &str) -> String { +pub fn short_commit_hash(hash: &str) -> String { hash.chars().take(7).collect() } -fn parse_remote_repo(url: &str) -> Option { +pub fn parse_remote_repo(url: &str) -> Option { let trimmed = url.trim().trim_end_matches(".git"); if trimmed.is_empty() { return None; @@ -393,56 +403,3 @@ fn normalize_azure_web_base(host: &str, path: &str) -> Option { None } - -#[cfg(test)] -mod tests { - use super::{GitProvider, PrItem, parse_remote_repo}; - - #[test] - fn parses_github_ssh_remote() { - let remote = parse_remote_repo("git@github.com:owner/repo.git").unwrap(); - assert_eq!(remote.provider, GitProvider::GitHub); - assert_eq!(remote.repo_id().as_deref(), Some("owner/repo")); - assert_eq!( - remote.commit_url("abcdef123456").as_deref(), - Some("https://github.com/owner/repo/commit/abcdef123456") - ); - } - - #[test] - fn parses_gitlab_https_remote() { - let remote = - parse_remote_repo("https://gitlab.example.com/group/subgroup/repo.git").unwrap(); - assert_eq!(remote.provider, GitProvider::GitLab); - assert_eq!(remote.repo_id().as_deref(), Some("subgroup/repo")); - assert_eq!( - remote.commit_url("abcdef123456").as_deref(), - Some("https://gitlab.example.com/group/subgroup/repo/-/commit/abcdef123456") - ); - } - - #[test] - fn parses_azure_ssh_remote() { - let remote = parse_remote_repo("git@ssh.dev.azure.com:v3/org/project/repo").unwrap(); - assert_eq!(remote.provider, GitProvider::AzureDevOps); - assert_eq!(remote.repo_id().as_deref(), Some("project/repo")); - assert_eq!( - remote.commit_url("abcdef123456").as_deref(), - Some("https://dev.azure.com/org/project/_git/repo/commit/abcdef123456") - ); - } - - #[test] - fn appendix_falls_back_to_hash_only_when_no_remote() { - let items = vec![PrItem { - commit_hash: "abcdef123456".to_string(), - title: "Refine PR footer rendering".to_string(), - body: String::new(), - pr_number: None, - }]; - - let appendix = super::format_pr_commit_appendix_with_remote(&items, None); - assert!(appendix.contains("Commits in this PR:")); - assert!(appendix.contains("- `abcdef1` Refine PR footer rendering")); - } -} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..bcbf502 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,51 @@ +//! Core types and shared functionality for commitbot. +//! +//! This module contains shared types and functions used across the application. + +pub mod cli_args; +pub mod config; +pub mod git; +pub mod llm; +pub mod logging; +pub mod setup; + +pub use cli_args::{Cli, Command}; +pub use git::{ + collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, stage_all, + staged_diff_for_file, staged_files, PrSummaryMode, +}; +pub use llm::LlmClient; + +/// How the user categorizes each file in interactive mode. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +pub enum FileCategory { + Main, // 1 + Supporting, // 2 + Consequence, // 3 + Ignored, // 4 +} + +impl FileCategory { + /// Convert the category to a string representation. + pub fn as_str(&self) -> &'static str { + match self { + FileCategory::Main => "main", + FileCategory::Supporting => "supporting", + FileCategory::Consequence => "consequence", + FileCategory::Ignored => "ignored", + } + } +} + +/// Represents a single staged file's change and metadata. +#[derive(Debug, Clone)] +pub struct FileChange { + /// Path to the file + pub path: String, + /// User-defined category for this file + pub category: FileCategory, + /// Git diff for this file + pub diff: String, + /// LLM-generated summary for this file + pub summary: Option, +} diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 7da2b67..d24d97a 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -259,17 +259,13 @@ mod tests { let body = r#"{"models":[{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#; let parsed: OllamaTagsResponse = json::from_str(body).expect("valid tags payload"); - assert!( - parsed - .models - .iter() - .any(|model| model.name == "qwen3-coder:30b") - ); - assert!( - !parsed - .models - .iter() - .any(|model| model.name == "missing:model") - ); + assert!(parsed + .models + .iter() + .any(|model| model.name == "qwen3-coder:30b")); + assert!(!parsed + .models + .iter() + .any(|model| model.name == "missing:model")); } } diff --git a/src/llm/prompts.rs b/src/llm/prompts.rs index 4a94724..1f416b5 100644 --- a/src/llm/prompts.rs +++ b/src/llm/prompts.rs @@ -27,7 +27,7 @@ Rules: - Backticks only in modes B and C. - Use dashes '-' for bullet points, never use '*' or '•'. - Output only the commit message. -- Do not add commentary or decession reasoning."#; +- Do not add commentary or decision reasoning."#; pub const FILE_SUMMARY: &str = r#"Summarize the intent of changes to this file into as few bullets as possible. @@ -54,4 +54,4 @@ Rules: - Reference commit hashes when appropriate. - Avoid generic phrases like "misc changes" or "small fixes". - Use dashes '-' for bullet points, never use '*' or '•'. -- Do not add commentary or decession reasoning."#; +- Do not add commentary or decision reasoning."#; diff --git a/src/main.rs b/src/main.rs index 6e5abbf..6f59632 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,28 +1,12 @@ -mod cli_args; -mod config; -mod git; -mod llm; -mod logging; -mod setup; - -use anyhow::{Result, anyhow}; +use anyhow::{anyhow, Result}; use clap::Parser; -use config::Config; -use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; - -use std::collections::HashSet; -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; - -use crate::cli_args::{Cli, Command}; -use crate::git::{ - PrSummaryMode, collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, - stage_all, staged_diff_for_file, staged_files, +use commitbot::config::Config; +use commitbot::git::{ + collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, + staged_diff_for_file, staged_files, PrSummaryMode, }; -use crate::llm::LlmClient; - +use commitbot::llm::LlmClient; +use commitbot::{Cli, Command, FileCategory, FileChange}; use crossterm::{ cursor, event::{self, Event, KeyCode}, @@ -30,40 +14,14 @@ use crossterm::{ style::{self, Color}, terminal::{self, Clear, ClearType}, }; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; -/// Re-export for modules like `config` that might refer to `crate::Cli` / `crate::Command`. -pub use cli_args::{Cli as RootCli, Command as RootCommand}; - -/// How the user categorizes each file in interactive mode. -#[derive(Debug, Clone, Copy, serde::Serialize)] -pub enum FileCategory { - Main, // 1 - Supporting, // 2 - Consequence, // 3 - Ignored, // 4 -} - -impl FileCategory { - pub fn as_str(&self) -> &'static str { - match self { - FileCategory::Main => "main", - FileCategory::Supporting => "supporting", - FileCategory::Consequence => "consequence", - FileCategory::Ignored => "ignored", - } - } -} - -/// Represents a single staged file's change and metadata. -#[derive(Debug, Clone)] -pub struct FileChange { - pub path: String, - pub category: FileCategory, - pub diff: String, - pub summary: Option, // Filled by per-file model call (or dummy) -} +use std::collections::HashSet; +use std::io::{self, Read, Write}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; -/// Ask the user a question and return a trimmed input line. fn prompt_input(prompt: &str) -> Result { print!("{prompt}"); io::stdout().flush()?; @@ -80,7 +38,6 @@ fn resolved_ticket_summary(cli: &Cli) -> Option { } } -/// Helper: write a line in raw mode so we also reset the cursor to column 0. fn tprintln(out: &mut W, s: &str) -> io::Result<()> { write!(out, "{}\r\n", s) } @@ -100,11 +57,13 @@ fn dimmed(text: &str) -> String { format!("\x1b[2m{text}\x1b[0m") } -/// Arrow-key UI for choosing a FileCategory (no diff preview). fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { use FileCategory::*; let mut stdout = io::stdout(); + std::io::stderr() + .flush() + .map_err(|e| anyhow!("failed to flush stderr: {e}"))?; terminal::enable_raw_mode().map_err(|e| anyhow!("failed to enable raw mode: {e}"))?; let res = (|| -> Result { @@ -148,7 +107,6 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { if selected_index == 0 { selected_index = labels.len() - 1; @@ -159,14 +117,10 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { selected_index = (selected_index + 1) % labels.len(); } - - // Numeric shortcuts KeyCode::Char('1') => return Ok(Main), KeyCode::Char('2') => return Ok(Supporting), KeyCode::Char('3') => return Ok(Consequence), KeyCode::Char('4') => return Ok(Ignored), - - // Enter = accept current selection KeyCode::Enter => { let cat = match selected_index { 0 => Main, @@ -177,12 +131,9 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { return Err(anyhow!("aborted by user")); } - _ => {} } } @@ -203,7 +154,6 @@ struct SummarizeContext<'a> { max_concurrent_requests: usize, } -/// Run per-file summaries concurrently, honoring `max_concurrent_requests`. fn summarize_files_concurrently( file_changes: &mut [FileChange], indices: &[usize], @@ -216,13 +166,10 @@ fn summarize_files_concurrently( } let max_concurrent = ctx.max_concurrent_requests.max(1); + let total_files = file_changes.len(); - // Store (file_index, result) for all summarizations. let results: SummarizeResults = Arc::new(Mutex::new(Vec::new())); - // Process in chunks of `max_concurrent` so we never have more than that many - // in-flight LLM calls at once. - let total_files = file_changes.len(); for chunk in indices.chunks(max_concurrent) { thread::scope(|scope| { for &file_idx in chunk { @@ -234,7 +181,6 @@ fn summarize_files_concurrently( line.set_message("summarizing..."); } - // Clone just the data we need from this file so we don't share &mut across threads. let path = file_changes[file_idx].path.clone(); let diff = file_changes[file_idx].diff.clone(); let category = file_changes[file_idx].category; @@ -260,7 +206,6 @@ fn summarize_files_concurrently( Ok(summary) })(); - // Always advance the progress bar for this file, even if it errors. pb.inc(1); if let Some(line) = &file_line { @@ -282,7 +227,6 @@ fn summarize_files_concurrently( }); } - // Unwrap Arc and Mutex and apply results back onto file_changes. let results = Arc::try_unwrap(results) .expect("results Arc still has multiple owners") .into_inner() @@ -310,13 +254,9 @@ fn summarize_files_concurrently( Ok(()) } -/// Interactive mode: classify files, then do all LLM calls afterward (batched with concurrency). -/// Supports --diff for prompt testing (splits combined diff into per-file entries). fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { - // Build (branch, file_pairs) — works with both staged git and --diff. let (branch, file_pairs) = if let Some(ref diff_arg) = cli.diff { let combined = if diff_arg == "-" { - use std::io::Read; let mut buf = String::new(); io::stdin().read_to_string(&mut buf)?; buf @@ -332,7 +272,11 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { if per_file.is_empty() { per_file = vec![("(diff)".to_string(), combined)]; } - (cli.branch.clone(), per_file) + let branch = cli + .branch + .clone() + .unwrap_or_else(|| current_branch().unwrap_or_else(|_| "unknown-branch".to_string())); + (branch, per_file) } else { let branch = current_branch()?; let files = staged_files()?; @@ -358,7 +302,6 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let mut file_changes: Vec = Vec::new(); - // Phase 1: Interactive classification let total_files = file_pairs.len(); for (idx, (path, diff)) in file_pairs.into_iter().enumerate() { let category = categorize_file_interactive(idx, total_files, &path)?; @@ -370,7 +313,6 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { }); } - // Phase 2: LLM calls println!(); println!("Asking {}...", cfg.model); @@ -400,7 +342,6 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { .unwrap_or_else(|_| ProgressStyle::default_bar()), ); - // Pre-increment for ignored files and collect indices that actually need summarization. let mut indices_to_summarize = Vec::new(); let mut ignored_count = 0usize; @@ -438,7 +379,6 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { pb.inc(1); pb.finish_with_message("Done"); - // Final commit message println!(); if cfg.stream { @@ -453,52 +393,49 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { Ok(()) } -/// Auto mode (default): per-file LLM summaries then final commit message — no human classification. -/// When `--diff` is supplied the combined diff is split by file; otherwise staged files are used. fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let using_external_diff = cli.diff.is_some(); - let (branch, file_pairs): (String, Vec<(String, String)>) = if let Some(ref diff_arg) = cli.diff - { - // Read the combined diff from file or stdin. - let combined = if diff_arg == "-" { - use std::io::Read; - let mut buf = String::new(); - io::stdin().read_to_string(&mut buf)?; - buf - } else { - std::fs::read_to_string(diff_arg) - .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e))? - }; + let (branch, file_pairs): (String, Vec<(String, String)>) = + if let Some(ref diff_arg) = cli.diff { + let combined = if diff_arg == "-" { + let mut buf = String::new(); + io::stdin().read_to_string(&mut buf)?; + buf + } else { + std::fs::read_to_string(diff_arg) + .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e))? + }; - if combined.trim().is_empty() { - println!("No diff content found."); - return Ok(()); - } + if combined.trim().is_empty() { + println!("No diff content found."); + return Ok(()); + } - let mut per_file = split_diff_by_file(&combined); - if per_file.is_empty() { - per_file = vec![("(diff)".to_string(), combined)]; - } - (cli.branch.clone(), per_file) - } else { - // Normal git mode: get per-file staged diffs. - let branch = current_branch()?; - let files = staged_files()?; - if files.is_empty() { - println!("No staged changes found."); - return Ok(()); - } - let mut pairs = Vec::new(); - for path in files { - let diff = staged_diff_for_file(&path)?; - pairs.push((path, diff)); - } - (branch, pairs) - }; + let mut per_file = split_diff_by_file(&combined); + if per_file.is_empty() { + per_file = vec![("(diff)".to_string(), combined)]; + } + let branch = cli.branch.clone().unwrap_or_else(|| { + current_branch().unwrap_or_else(|_| "unknown-branch".to_string()) + }); + (branch, per_file) + } else { + let branch = current_branch()?; + let files = staged_files()?; + if files.is_empty() { + println!("No staged changes found."); + return Ok(()); + } + let mut pairs = Vec::new(); + for path in files { + let diff = staged_diff_for_file(&path)?; + pairs.push((path, diff)); + } + (branch, pairs) + }; let ticket_summary = resolved_ticket_summary(cli); - // Build FileChange list — all files are categorized as Main automatically. let mut file_changes: Vec = file_pairs .into_iter() .map(|(path, diff)| FileChange { @@ -583,7 +520,6 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { Ok(()) } -/// PR mode: summarize commits/PRs between base..from into a PR description. fn run_pr( cli: &Cli, cfg: &Config, @@ -604,13 +540,11 @@ fn run_pr( return Ok(()); } - // Determine mode let mode = if pr_flag { PrSummaryMode::ByPrs } else if commit_flag { PrSummaryMode::ByCommits } else { - // Auto-detect: if multiple distinct PR numbers are present, use PR mode. let mut distinct_prs: HashSet = HashSet::new(); for item in &items { if let Some(n) = item.pr_number { @@ -658,7 +592,6 @@ fn run_pr( } fn main() -> Result<()> { - // CLI + config let cli = Cli::parse(); // Handle custom --version early so we print just the version number. @@ -667,8 +600,7 @@ fn main() -> Result<()> { return Ok(()); } - // Initialize logging - logging::init_logger(cli.verbose); + commitbot::logging::init_logger(cli.verbose); if cli.diff.is_some() && matches!(&cli.command, Some(Command::Pr { .. })) { return Err(anyhow!( @@ -677,15 +609,13 @@ fn main() -> Result<()> { )); } - let cfg = Config::from_sources(&cli); + let cfg = Config::from_sources(&cli)?; - // Pre-Work Items if cli.stage { - stage_all()?; + commitbot::git::stage_all()?; } - // LLM client setup - let boxed_client = setup::build_llm_client(&cfg); + let boxed_client = commitbot::setup::build_llm_client(&cfg)?; boxed_client.validate_model()?; match &cli.command { diff --git a/src/setup.rs b/src/setup.rs index a584185..3e2bd3b 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1,16 +1,17 @@ +use anyhow::{anyhow, Result}; use crate::config::Config; use crate::llm::LlmClient; use crate::llm::ollama::OllamaClient; use crate::llm::openai::OpenAiClient; /// Build the LLM client based on CLI + config. -pub fn build_llm_client(cfg: &Config) -> Box { +pub fn build_llm_client(cfg: &Config) -> Result> { match cfg.provider.as_str() { "openai" => { let key = cfg .openai_api_key .clone() - .expect("OPENAI_API_KEY must be set for provider=openai"); + .ok_or_else(|| anyhow!("OPENAI_API_KEY must be set for provider=openai"))?; let base_url = cfg .base_url .clone() @@ -22,12 +23,12 @@ pub fn build_llm_client(cfg: &Config) -> Box { cfg.stream ); - Box::new(OpenAiClient::new( + Ok(Box::new(OpenAiClient::new( key, cfg.model.clone(), base_url, cfg.stream, - )) + ))) } "ollama" => { let base_url = cfg @@ -41,8 +42,12 @@ pub fn build_llm_client(cfg: &Config) -> Box { cfg.stream ); - Box::new(OllamaClient::new(base_url, cfg.model.clone(), cfg.stream)) + Ok(Box::new(OllamaClient::new( + base_url, + cfg.model.clone(), + cfg.stream, + ))) } - other => panic!("Unknown provider: {}", other), + other => Err(anyhow!("Unknown provider: {}", other)), } } diff --git a/tests/cli_basics.rs b/tests/cli_basics.rs index 8d0eb88..f10a597 100644 --- a/tests/cli_basics.rs +++ b/tests/cli_basics.rs @@ -1,4 +1,6 @@ use assert_cmd::cargo; +use clap::Parser; +use commitbot::{Cli, Command}; #[test] fn prints_help() { @@ -19,3 +21,13 @@ fn prints_version() { .success() .stdout(predicates::str::contains(env!("CARGO_PKG_VERSION"))); } + +#[test] +fn cli_parsing() { + let cli = Cli::parse_from(["commitbot", "summary"]); + + match cli.command { + Some(Command::Summary(words)) => assert_eq!(words, vec!["summary"]), + other => panic!("expected summary command, got {:?}", other), + } +} diff --git a/tests/config.rs b/tests/config.rs new file mode 100644 index 0000000..3a9420e --- /dev/null +++ b/tests/config.rs @@ -0,0 +1,135 @@ +use clap::Parser; +use commitbot::config::Config; +use commitbot::Cli; +use std::fs; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn unique_config_path(name: &str) -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system time before unix epoch") + .as_nanos(); + std::env::temp_dir().join(format!("commitbot_{name}_{nanos}.toml")) +} + +fn write_temp_config(name: &str, contents: &str) -> PathBuf { + let path = unique_config_path(name); + fs::write(&path, contents).expect("write temp config"); + path +} + +#[test] +fn missing_config_uses_cli_values() { + let missing_path = unique_config_path("missing"); + let cli = Cli::parse_from([ + "commitbot", + "--config", + missing_path.to_str().expect("utf-8 path"), + "--provider", + "ollama", + "--model", + "qwen3-coder:30b", + "--url", + "http://localhost:11434", + ]); + + let cfg = Config::from_sources(&cli).expect("config should resolve from cli"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "qwen3-coder:30b"); + assert_eq!(cfg.base_url.as_deref(), Some("http://localhost:11434")); + assert!(cfg.stream); +} + +#[test] +fn reads_values_from_default_config_table() { + let config_path = write_temp_config( + "default_table", + r#" +[default] +provider = "ollama" +model = "llama3.1:8b-instruct-q5_K_M" +url = "http://gpu.trigapi.com:11434" +max_concurrent_requests = 2 +stream = false +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("config should load default table"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "llama3.1:8b-instruct-q5_K_M"); + assert_eq!(cfg.base_url.as_deref(), Some("http://gpu.trigapi.com:11434")); + assert_eq!(cfg.max_concurrent_requests, 2); + assert!(!cfg.stream); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn cli_overrides_file_values() { + let config_path = write_temp_config( + "cli_override", + r#" +[default] +provider = "ollama" +model = "qwen3-coder:30b" +url = "http://gpu.trigapi.com:11434" +max_concurrent_requests = 1 +stream = true +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + "--model", + "gpt-oss:20b", + "--url", + "http://localhost:11434", + "--max", + "4", + "--no-stream", + ]); + + let cfg = Config::from_sources(&cli).expect("cli values should override file"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "gpt-oss:20b"); + assert_eq!(cfg.base_url.as_deref(), Some("http://localhost:11434")); + assert_eq!(cfg.max_concurrent_requests, 4); + assert!(!cfg.stream); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn invalid_openai_config_returns_error() { + let config_path = write_temp_config( + "invalid_openai", + r#" +[default] +provider = "openai" +model = "gpt-5-nano" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let err = Config::from_sources(&cli).expect_err("openai config should require an api key"); + assert!( + err.to_string() + .contains("OPENAI_API_KEY must be set via CLI, env var, or config file") + ); + + fs::remove_file(config_path).ok(); +} diff --git a/tests/git.rs b/tests/git.rs new file mode 100644 index 0000000..2589c68 --- /dev/null +++ b/tests/git.rs @@ -0,0 +1,143 @@ +use commitbot::git::{ + find_first_pr_number, format_pr_commit_appendix_with_remote, parse_remote_repo, + short_commit_hash, split_diff_by_file, PrItem, PrSummaryMode, +}; + +#[test] +fn parses_github_ssh_remote() { + let remote = parse_remote_repo("git@github.com:owner/repo.git").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::GitHub); + assert_eq!(remote.repo_id().as_deref(), Some("owner/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://github.com/owner/repo/commit/abcdef123456") + ); +} + +#[test] +fn parses_gitlab_https_remote() { + let remote = parse_remote_repo("https://gitlab.example.com/group/subgroup/repo.git").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::GitLab); + assert_eq!(remote.repo_id().as_deref(), Some("subgroup/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://gitlab.example.com/group/subgroup/repo/-/commit/abcdef123456") + ); +} + +#[test] +fn parses_azure_ssh_remote() { + let remote = parse_remote_repo("git@ssh.dev.azure.com:v3/org/project/repo").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::AzureDevOps); + assert_eq!(remote.repo_id().as_deref(), Some("project/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://dev.azure.com/org/project/_git/repo/commit/abcdef123456") + ); +} + +#[test] +fn appendix_falls_back_to_hash_only_when_no_remote() { + let items = vec![PrItem { + commit_hash: "abcdef123456".to_string(), + title: "Refine PR footer rendering".to_string(), + body: String::new(), + pr_number: None, + }]; + + let appendix = format_pr_commit_appendix_with_remote(&items, None); + assert!(appendix.contains("Commits in this PR:")); + assert!(appendix.contains("- `abcdef1` Refine PR footer rendering")); +} + +#[test] +fn find_first_pr_number_in_title() { + let result = find_first_pr_number("Fix bug in #123"); + assert_eq!(result, Some(123)); +} + +#[test] +fn find_first_pr_number_in_body() { + let result = find_first_pr_number("Closes #456"); + assert_eq!(result, Some(456)); +} + +#[test] +fn find_first_pr_number_multiple_hashes() { + let result = find_first_pr_number("Related to #100, fixes #200"); + assert_eq!(result, Some(100)); +} + +#[test] +fn find_first_pr_number_no_hash() { + let result = find_first_pr_number("No PR here"); + assert_eq!(result, None); +} + +#[test] +fn find_first_pr_number_empty() { + let result = find_first_pr_number(""); + assert_eq!(result, None); +} + +#[test] +fn split_diff_by_file_single_file() { + let diff = r#"diff --git a/src/main.rs b/src/main.rs +index 1234567..89abcdef 100644 +--- a/src/main.rs ++++ b/src/main.rs +@@ -1,3 +1,4 @@ ++use std::io; + fn main() { + println!("Hello"); + }"#; + let result = split_diff_by_file(diff); + assert_eq!(result.len(), 1); + assert_eq!(result[0].0, "src/main.rs"); + assert!(result[0].1.contains("diff --git")); +} + +#[test] +fn split_diff_by_file_multiple_files() { + let diff = r#"diff --git a/src/main.rs b/src/main.rs +index 1234567..89abcdef 100644 +--- a/src/main.rs ++++ b/src/main.rs +@@ -1,3 +1,4 @@ ++use std::io; +diff --git a/src/lib.rs b/src/lib.rs +index abcdefg..1234567 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -1,2 +1,3 @@ ++pub fn helper() {} + pub fn other() {}"#; + let result = split_diff_by_file(diff); + assert_eq!(result.len(), 2); + assert_eq!(result[0].0, "src/main.rs"); + assert_eq!(result[1].0, "src/lib.rs"); +} + +#[test] +fn split_diff_by_file_empty() { + let result = split_diff_by_file(""); + assert!(result.is_empty()); +} + +#[test] +fn short_commit_hash_works() { + let result = short_commit_hash("abcdef123456"); + assert_eq!(result, "abcdef1"); +} + +#[test] +fn short_commit_hash_short_input() { + let result = short_commit_hash("abc"); + assert_eq!(result, "abc"); +} + +#[test] +fn pr_summary_mode_as_str() { + assert_eq!(PrSummaryMode::ByCommits.as_str(), "commits"); + assert_eq!(PrSummaryMode::ByPrs.as_str(), "prs"); +} diff --git a/tests/lib_types.rs b/tests/lib_types.rs new file mode 100644 index 0000000..ec4b102 --- /dev/null +++ b/tests/lib_types.rs @@ -0,0 +1,25 @@ +//! Tests for core types and functionality in lib.rs + +use commitbot::{FileCategory, FileChange}; + +#[test] +fn file_category_str_representation() { + assert_eq!(FileCategory::Main.as_str(), "main"); + assert_eq!(FileCategory::Supporting.as_str(), "supporting"); + assert_eq!(FileCategory::Consequence.as_str(), "consequence"); + assert_eq!(FileCategory::Ignored.as_str(), "ignored"); +} + +#[test] +fn file_change_creation() { + let file_change = FileChange { + path: "src/main.rs".to_string(), + category: FileCategory::Main, + diff: "diff --git a/src/main.rs b/src/main.rs\n--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,3 @@\n-println!(\"Hello world\");\n+println!(\"Hello commitbot\");\n".to_string(), + summary: Some("Update hello message".to_string()), + }; + + assert_eq!(file_change.path, "src/main.rs"); + assert_eq!(file_change.category, FileCategory::Main); + assert_eq!(file_change.summary.as_deref(), Some("Update hello message")); +} diff --git a/tests/prompt_live.rs b/tests/prompt_live.rs index a47b18a..fd00755 100644 --- a/tests/prompt_live.rs +++ b/tests/prompt_live.rs @@ -332,6 +332,7 @@ fn test_list_available_fixtures() { #[test] #[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] fn live_test_all_languages() { let mut total_passed = 0; let mut total_failed = 0; @@ -393,6 +394,7 @@ fn live_test_all_languages() { #[test] #[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] fn live_test_single_rust() { let test = &all_test_cases()[0]; // Rust Auth Feature @@ -418,6 +420,7 @@ fn live_test_single_rust() { #[test] #[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] fn live_test_word_count_distribution() { let mut word_counts = Vec::new(); @@ -452,6 +455,7 @@ fn live_test_word_count_distribution() { #[test] #[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] fn live_test_keyword_hit_rate() { let mut total_expected = 0; let mut total_found = 0; From d0a0596612fbbf792ddcf78aaa3c0de18c038dd8 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 8 Apr 2026 22:10:56 -0400 Subject: [PATCH 08/40] Redact sensitive keys from logs across the app * Add `commitbot_macros` dependency for redacting keys * Improve log security by removing sensitive field keys * Redact keys from logs in Ollama and OpenAI clients * Track token usage and logging in LLM clients --- Cargo.lock | 10 ++++++ Cargo.toml | 1 + Taskfile.yaml | 10 +++++- commitbot-macros/Cargo.toml | 13 +++++++ commitbot-macros/src/lib.rs | 46 +++++++++++++++++++++++++ src/config.rs | 39 ++++++++++++++++++--- src/llm/ollama.rs | 67 ++++++++++++++++++++++++++++++++++--- src/llm/openai.rs | 43 +++++++++++++++++++----- 8 files changed, 210 insertions(+), 19 deletions(-) create mode 100644 commitbot-macros/Cargo.toml create mode 100644 commitbot-macros/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 53d6d07..e0a0d47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -263,6 +263,7 @@ dependencies = [ "assert_cmd", "clap", "colored", + "commitbot_macros", "crossterm", "dirs", "env_logger", @@ -276,6 +277,15 @@ dependencies = [ "toml", ] +[[package]] +name = "commitbot_macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "console" version = "0.16.2" diff --git a/Cargo.toml b/Cargo.toml index 6f4a4f8..726b23b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ reqwest = { version = "^0.13", features = ["json", "blocking"] } serde = { version = "^1", features = ["derive"] } serde_json = "^1" toml = "^1.0" +commitbot_macros = { path = "commitbot-macros" } [dev-dependencies] assert_cmd = "^2.1.1" diff --git a/Taskfile.yaml b/Taskfile.yaml index d1b6290..d373958 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -31,7 +31,7 @@ tasks: run:simple: desc: "Run commitbot in simple mode (no model, debug) using cargo run" cmds: - - cargo run -- -vv + - cargo run -- -v run:ask: desc: "Run commitbot in interactive ask mode (no model, debug)" @@ -53,8 +53,16 @@ tasks: install: desc: "Install commitbot binary locally via cargo install --path ." cmds: + - brew uninstall mikegarde/tap/commitbot || true - cargo install --path . --force + install:brew: + desc: "Install commitbot via Homebrew (macOS)" + cmds: + - cargo uninstall commitbot || true + - brew uninstall mikegarde/tap/commitbot || true + - brew install mikegarde/tap/commitbot + build:release: desc: "Build optimized release binary for the host" silent: true diff --git a/commitbot-macros/Cargo.toml b/commitbot-macros/Cargo.toml new file mode 100644 index 0000000..fc18714 --- /dev/null +++ b/commitbot-macros/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "commitbot_macros" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full"] } + diff --git a/commitbot-macros/src/lib.rs b/commitbot-macros/src/lib.rs new file mode 100644 index 0000000..1939a61 --- /dev/null +++ b/commitbot-macros/src/lib.rs @@ -0,0 +1,46 @@ +use proc_macro::TokenStream; +use quote::quote; +use syn::{parse_macro_input, DeriveInput, Data, DataStruct, Fields}; + +#[proc_macro_derive(SensitiveFields, attributes(sensitive))] +pub fn derive_sensitive_fields(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let name = input.ident; + + let mut sensitive_fields: Vec = Vec::new(); + + if let Data::Struct(DataStruct { fields: Fields::Named(ref fields_named), .. }) = input.data { + for field in fields_named.named.iter() { + for attr in &field.attrs { + if let Some(ident) = attr.path().get_ident() { + if ident == "sensitive" { + if let Some(ident_field) = &field.ident { + sensitive_fields.push(ident_field.to_string()); + } + } + } + } + } + } else { + // Only support named-field structs + } + + // build an array of string literals + let literals: Vec = sensitive_fields + .iter() + .map(|s| { + let lit = syn::LitStr::new(s, proc_macro2::Span::call_site()); + quote! { #lit } + }) + .collect(); + + let expanded = quote! { + impl #name { + pub fn sensitive_field_names() -> &'static [&'static str] { + &[#(#literals),*] + } + } + }; + + TokenStream::from(expanded) +} diff --git a/src/config.rs b/src/config.rs index 9b642e0..9f13b98 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,11 +8,12 @@ use std::fs; use std::path::{Path, PathBuf}; /// Final resolved configuration for commitbot. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, commitbot_macros::SensitiveFields)] pub struct Config { /// LLM provider (openai, ollama) pub provider: String, /// OpenAI API key for authentication + #[sensitive] pub openai_api_key: Option, /// Base URL for the LLM provider pub base_url: Option, @@ -253,24 +254,52 @@ impl<'a> ConfigResolver<'a> { } fn log_decision(&self, key: &str, value: &T, src: ValueSource) { + // Redact sensitive keys (API keys, tokens, secrets) when printing + // so verbose/debug logs don't leak credentials. For option-like + // values we print /, otherwise we print . + let printable = if self.is_sensitive_key(key) { + // Try to detect Option formatted output ("Some(...)" / "None"). + let debug_str = format!("{:?}", value); + if debug_str == "None" { + "".to_string() + } else if debug_str.starts_with("Some(") { + "".to_string() + } else { + "".to_string() + } + } else { + format!("{:?}", value) + }; + if let Some(env_key) = self.env_key_for(key) { log::debug!( - "Config: {} = {:?} (source={}, env={})", + "Config: {} = {} (source={}, env={})", key, - value, + printable, source_label(src), env_key ); } else { log::debug!( - "Config: {} = {:?} (source={})", + "Config: {} = {} (source={})", key, - value, + printable, source_label(src) ); } } + // Treat a small set of keys as sensitive so logs redact them. + // Add other names here if you later introduce more secrets. + // Currently only the OpenAI API key is treated as sensitive. We keep the + // check centralized here so it can later be expanded. The field in the + // structs is annotated with a doc comment to indicate sensitivity. + fn is_sensitive_key(&self, key: &str) -> bool { + // Use the generated list from the Config struct (proc-macro) + // to determine which fields are sensitive. + Config::sensitive_field_names().contains(&key) + } + fn log_decision_secret_opt_string(&self, key: &str, present: bool, src: ValueSource) { let printable = if present { "" } else { "" }; if let Some(env_key) = self.env_key_for(key) { diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index d24d97a..61619a4 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -5,6 +5,7 @@ use musli::{Decode, Encode}; use reqwest::StatusCode; use reqwest::blocking::Client; use std::io::BufReader; +use std::sync::Mutex; use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; @@ -29,6 +30,13 @@ struct OllamaStreamResponse { done: Option, } +#[derive(Debug, Decode)] +struct OllamaUsage { + prompt_tokens: Option, + completion_tokens: Option, + total_tokens: Option, +} + #[derive(Debug, Decode)] struct OllamaTagModel { name: String, @@ -45,6 +53,14 @@ pub struct OllamaClient { base_url: String, model: String, stream: bool, + usage: Mutex, +} + +#[derive(Default)] +struct TokenUsage { + prompt_tokens: u64, + completion_tokens: u64, + total_tokens: u64, } impl OllamaClient { @@ -57,6 +73,7 @@ impl OllamaClient { base_url: base_url.into().trim_end_matches('/').to_string(), model: model.into(), stream, + usage: Mutex::new(TokenUsage::default()), } } @@ -119,10 +136,31 @@ impl OllamaClient { log::trace!("Ollama raw JSON response: {resp_text}"); - let parsed: OllamaChatResponse = - json::from_str(&resp_text).map_err(|e| anyhow!("Failed to decode Ollama JSON: {e}"))?; + #[derive(Debug, Decode)] + struct OllamaChatWrapper { + message: OllamaMessage, + usage: Option, + } - Ok(parsed.message.content.trim().to_string()) + // First try decoding into the wrapper. If that fails fall back to the + // older shape without usage. + match json::from_str::(&resp_text) { + Ok(parsed) => { + if let Some(usage) = parsed.usage { + let mut u = self.usage.lock().expect("usage mutex poisoned"); + u.prompt_tokens += usage.prompt_tokens.unwrap_or(0) as u64; + u.completion_tokens += usage.completion_tokens.unwrap_or(0) as u64; + u.total_tokens += usage.total_tokens.unwrap_or(0) as u64; + } + Ok(parsed.message.content.trim().to_string()) + } + Err(_) => { + // Fallback to the simple response shape. + let parsed: OllamaChatResponse = json::from_str(&resp_text) + .map_err(|e| anyhow!("Failed to decode Ollama JSON: {e}"))?; + Ok(parsed.message.content.trim().to_string()) + } + } } fn tags_url(&self) -> String { @@ -222,7 +260,9 @@ impl LlmClient for OllamaClient { ticket_summary: Option<&str>, ) -> Result { let prompts = prompt_builder::commit_message_prompt(branch, files, ticket_summary); - self.chat(prompts.system, prompts.user, self.stream) + let content = self.chat(prompts.system, prompts.user, self.stream)?; + self.log_and_reset_usage(); + Ok(content) } fn generate_pr_message( @@ -240,7 +280,24 @@ impl LlmClient for OllamaClient { items, ticket_summary, ); - self.chat(prompts.system, prompts.user, self.stream) + let content = self.chat(prompts.system, prompts.user, self.stream)?; + self.log_and_reset_usage(); + Ok(content) + } +} + +impl OllamaClient { + fn log_and_reset_usage(&self) { + let mut u = self.usage.lock().expect("usage mutex poisoned"); + if u.total_tokens > 0 { + log::warn!( + "Token usage (aggregate): prompt={}, completion={}, total={}", + u.prompt_tokens, + u.completion_tokens, + u.total_tokens + ); + *u = TokenUsage::default(); + } } } diff --git a/src/llm/openai.rs b/src/llm/openai.rs index ed55e4a..8dc7976 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -9,6 +9,7 @@ use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::time::Duration; +use std::sync::Mutex; /// Minimal request/response structs for OpenAI Chat Completions API. #[derive(Serialize)] @@ -69,6 +70,14 @@ pub struct OpenAiClient { model: String, api_base_url: String, stream: bool, + usage: Mutex, +} + +#[derive(Default)] +struct TokenUsage { + prompt_tokens: u64, + completion_tokens: u64, + total_tokens: u64, } impl OpenAiClient { @@ -84,6 +93,7 @@ impl OpenAiClient { model, api_base_url: api_base_url.trim_end_matches('/').to_string(), stream, + usage: Mutex::new(TokenUsage::default()), } } @@ -138,12 +148,10 @@ impl OpenAiClient { .ok_or_else(|| anyhow!("no choices returned from OpenAI"))?; if let Some(usage) = &chat_resp.usage { - log::warn!( - "Token usage: prompt={}, completion={}, total={}", - usage.prompt_tokens, - usage.completion_tokens, - usage.total_tokens - ); + let mut u = self.usage.lock().expect("usage mutex poisoned"); + u.prompt_tokens += usage.prompt_tokens as u64; + u.completion_tokens += usage.completion_tokens as u64; + u.total_tokens += usage.total_tokens as u64; } Ok(content) @@ -236,13 +244,13 @@ impl LlmClient for OpenAiClient { ticket_summary, ); - log::info!( + log::debug!( "Per-file summarize prompt for {} ({:?}) [truncated]:\n{}", file.path, file.category, truncate(&prompts.user, 1000) ); - log::debug!( + log::trace!( "Per-file summarize prompt for {} ({:?}) [full]:\n--- SYSTEM ---\n{}\n--- USER ---\n{}", file.path, file.category, @@ -303,6 +311,7 @@ impl LlmClient for OpenAiClient { }; let content = self.call_chat(&req)?; + self.log_and_reset_usage(); Ok(content) } @@ -348,10 +357,28 @@ impl LlmClient for OpenAiClient { }; let content = self.call_chat(&req)?; + // Final PR message generation — report aggregated usage once. + self.log_and_reset_usage(); Ok(content) } } +impl OpenAiClient { + fn log_and_reset_usage(&self) { + let mut u = self.usage.lock().expect("usage mutex poisoned"); + if u.total_tokens > 0 { + println!(); + log::warn!( + "Token usage: prompt={}, completion={}, total={}", + u.prompt_tokens, + u.completion_tokens, + u.total_tokens + ); + *u = TokenUsage::default(); + } + } +} + /// Truncate long strings for debug logging. fn truncate(s: &str, max_len: usize) -> String { if s.len() <= max_len { From 6eb4d919cd36b671e9b146557f7e640dc2a17525 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 8 Apr 2026 22:17:46 -0400 Subject: [PATCH 09/40] Update src/cli_args.rs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/cli_args.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cli_args.rs b/src/cli_args.rs index da0fda4..dd3b845 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -42,7 +42,7 @@ pub struct Cli { pub diff: Option, /// Branch name to use in the commit message context (used with --diff). - /// If not specified with --diff, defaults to the current branch. + /// If not specified when using --diff, defaults to the current branch. #[arg(long, global = true)] pub branch: Option, From bce6bfa2b476853bd545cd1c669daea371d3dc2d Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 8 Apr 2026 22:31:50 -0400 Subject: [PATCH 10/40] Update Taskfile.yaml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- Taskfile.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index d373958..6e02ae2 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -29,7 +29,7 @@ tasks: - cargo test --test prompt_live -- --ignored --nocapture run:simple: - desc: "Run commitbot in simple mode (no model, debug) using cargo run" + desc: "Run commitbot in simple mode (no model, info verbosity) using cargo run" cmds: - cargo run -- -v From f88123c6f71f836f9126008867340753c3519916 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 8 Apr 2026 22:32:38 -0400 Subject: [PATCH 11/40] Update Cargo.toml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 726b23b..418bd06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ reqwest = { version = "^0.13", features = ["json", "blocking"] } serde = { version = "^1", features = ["derive"] } serde_json = "^1" toml = "^1.0" -commitbot_macros = { path = "commitbot-macros" } +commitbot_macros = { version = "0.6.0", path = "commitbot-macros" } [dev-dependencies] assert_cmd = "^2.1.1" From c86f230affb2636e1ebd5ff2ad38327d64724ad7 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Thu, 9 Apr 2026 00:05:34 -0400 Subject: [PATCH 12/40] Unify usage reporting and resilience in logging - Align `commitbot_macros` in `Cargo.toml` to 0.1.0 to match workspace API. - Remove the no-op else branch and its limitation comment in `commitbot-macros/src/lib.rs`. - Introduce optional `LlmClient` API to report and reset aggregated token usage with a default no-op implementation in `src/llm/mod.rs`. - In `src/llm/ollama.rs`, recover from poisoned usage mutex and centralize usage reset via `take_and_reset_usage`. - In `src/llm/openai.rs`, recover from poisoned mutex, stop per-call usage logging, and implement `take_and_reset_usage` returning activity, with a warning when poisoned. - Surface warnings by default in `src/logging.rs` to boost visibility. - In `src/main.rs`, improve output formatting by avoiding extra newline after LLM messages, respect trailing newlines in streaming mode, surface token usage metrics after runs, and ensure consistent PR message output. Token usage: prompt=3199, completion=7202, total=10401 --- Cargo.toml | 2 +- commitbot-macros/src/lib.rs | 2 -- src/llm/mod.rs | 5 +++++ src/llm/ollama.rs | 28 ++++++++++++++------------- src/llm/openai.rs | 28 +++++++++++++-------------- src/logging.rs | 2 +- src/main.rs | 38 +++++++++++++++++++++++++++---------- 7 files changed, 63 insertions(+), 42 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 418bd06..76ff318 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ reqwest = { version = "^0.13", features = ["json", "blocking"] } serde = { version = "^1", features = ["derive"] } serde_json = "^1" toml = "^1.0" -commitbot_macros = { version = "0.6.0", path = "commitbot-macros" } +commitbot_macros = { version = "0.1.0", path = "commitbot-macros" } [dev-dependencies] assert_cmd = "^2.1.1" diff --git a/commitbot-macros/src/lib.rs b/commitbot-macros/src/lib.rs index 1939a61..16574da 100644 --- a/commitbot-macros/src/lib.rs +++ b/commitbot-macros/src/lib.rs @@ -21,8 +21,6 @@ pub fn derive_sensitive_fields(input: TokenStream) -> TokenStream { } } } - } else { - // Only support named-field structs } // build an array of string literals diff --git a/src/llm/mod.rs b/src/llm/mod.rs index fd3fe0d..e352a1e 100644 --- a/src/llm/mod.rs +++ b/src/llm/mod.rs @@ -40,4 +40,9 @@ pub trait LlmClient: Send + Sync { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result; + + /// Take aggregated token usage from the client, resetting counters. + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + None + } } diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 61619a4..f0b71ba 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -147,7 +147,12 @@ impl OllamaClient { match json::from_str::(&resp_text) { Ok(parsed) => { if let Some(usage) = parsed.usage { - let mut u = self.usage.lock().expect("usage mutex poisoned"); + // Recover from a poisoned mutex instead of panicking so the CLI + // can continue in the face of concurrent thread panics. + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); u.prompt_tokens += usage.prompt_tokens.unwrap_or(0) as u64; u.completion_tokens += usage.completion_tokens.unwrap_or(0) as u64; u.total_tokens += usage.total_tokens.unwrap_or(0) as u64; @@ -261,7 +266,6 @@ impl LlmClient for OllamaClient { ) -> Result { let prompts = prompt_builder::commit_message_prompt(branch, files, ticket_summary); let content = self.chat(prompts.system, prompts.user, self.stream)?; - self.log_and_reset_usage(); Ok(content) } @@ -281,22 +285,20 @@ impl LlmClient for OllamaClient { ticket_summary, ); let content = self.chat(prompts.system, prompts.user, self.stream)?; - self.log_and_reset_usage(); Ok(content) } -} + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); -impl OllamaClient { - fn log_and_reset_usage(&self) { - let mut u = self.usage.lock().expect("usage mutex poisoned"); if u.total_tokens > 0 { - log::warn!( - "Token usage (aggregate): prompt={}, completion={}, total={}", - u.prompt_tokens, - u.completion_tokens, - u.total_tokens - ); + let res = (u.prompt_tokens, u.completion_tokens, u.total_tokens); *u = TokenUsage::default(); + Some(res) + } else { + None } } } diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 8dc7976..91c383f 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -148,7 +148,9 @@ impl OpenAiClient { .ok_or_else(|| anyhow!("no choices returned from OpenAI"))?; if let Some(usage) = &chat_resp.usage { - let mut u = self.usage.lock().expect("usage mutex poisoned"); + // Recover from a poisoned mutex instead of panicking so the CLI + // can continue in the face of concurrent thread panics. + let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); u.prompt_tokens += usage.prompt_tokens as u64; u.completion_tokens += usage.completion_tokens as u64; u.total_tokens += usage.total_tokens as u64; @@ -311,7 +313,6 @@ impl LlmClient for OpenAiClient { }; let content = self.call_chat(&req)?; - self.log_and_reset_usage(); Ok(content) } @@ -357,24 +358,21 @@ impl LlmClient for OpenAiClient { }; let content = self.call_chat(&req)?; - // Final PR message generation — report aggregated usage once. - self.log_and_reset_usage(); Ok(content) } -} -impl OpenAiClient { - fn log_and_reset_usage(&self) { - let mut u = self.usage.lock().expect("usage mutex poisoned"); + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); + if u.total_tokens > 0 { - println!(); - log::warn!( - "Token usage: prompt={}, completion={}, total={}", - u.prompt_tokens, - u.completion_tokens, - u.total_tokens - ); + let res = (u.prompt_tokens, u.completion_tokens, u.total_tokens); *u = TokenUsage::default(); + Some(res) + } else { + None } } } diff --git a/src/logging.rs b/src/logging.rs index 8dc793e..8b1f6d7 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -6,7 +6,7 @@ use log::{Level, LevelFilter}; pub fn init_logger(verbosity: u8) { let level = match verbosity { - 0 => LevelFilter::Error, // default: only errors + 0 => LevelFilter::Warn, // default: warn & errors 1 => LevelFilter::Info, // -v: info and up 2 => LevelFilter::Debug, // -vv: debug and up _ => LevelFilter::Trace, // -vvv: trace and up diff --git a/src/main.rs b/src/main.rs index 6f59632..32142bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -382,12 +382,19 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if cfg.stream { - let _msg = - llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - println!(); + let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; } else { let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - println!("{msg}"); + if msg.ends_with('\n') { + print!("{msg}"); + } else { + println!("{msg}"); + } + } + + println!(); + if let Some((p, c, t)) = llm.take_and_reset_usage() { + println!("Token usage: prompt={}, completion={}, total={}", p, c, t); } Ok(()) @@ -509,12 +516,19 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if cfg.stream { - let _msg = - llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - println!(); + let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; } else { let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - println!("{msg}"); + if msg.ends_with('\n') { + print!("{msg}"); + } else { + println!("{msg}"); + } + } + + println!(); + if let Some((p, c, t)) = llm.take_and_reset_usage() { + println!("Token usage: prompt={}, completion={}, total={}", p, c, t); } Ok(()) @@ -573,12 +587,16 @@ fn run_pr( llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; println!(); msg - } else { + } else { println!(); let msg = llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; - println!("{msg}"); + if msg.ends_with('\n') { + print!("{msg}"); + } else { + println!("{msg}"); + } msg }; From c7df39f59fca26775a34b361c91f7bdde8eb2a44 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Thu, 9 Apr 2026 00:26:46 -0400 Subject: [PATCH 13/40] 0.6.1 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0a0d47..8a5731d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 76ff318..93b9711 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.6.0" +version = "0.6.1" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 0fa10a69b3bae1a28f8c2fcfde34ed95b6081b06 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Thu, 9 Apr 2026 00:35:37 -0400 Subject: [PATCH 14/40] Remove commitbot_macros crate and associated dependencies. --- Cargo.lock | 10 --------- Cargo.toml | 1 - commitbot-macros/Cargo.toml | 13 ----------- commitbot-macros/src/lib.rs | 44 ------------------------------------- src/config.rs | 11 +++++++--- 5 files changed, 8 insertions(+), 71 deletions(-) delete mode 100644 commitbot-macros/Cargo.toml delete mode 100644 commitbot-macros/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 8a5731d..572f285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -263,7 +263,6 @@ dependencies = [ "assert_cmd", "clap", "colored", - "commitbot_macros", "crossterm", "dirs", "env_logger", @@ -277,15 +276,6 @@ dependencies = [ "toml", ] -[[package]] -name = "commitbot_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "console" version = "0.16.2" diff --git a/Cargo.toml b/Cargo.toml index 93b9711..4dbb38c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,6 @@ reqwest = { version = "^0.13", features = ["json", "blocking"] } serde = { version = "^1", features = ["derive"] } serde_json = "^1" toml = "^1.0" -commitbot_macros = { version = "0.1.0", path = "commitbot-macros" } [dev-dependencies] assert_cmd = "^2.1.1" diff --git a/commitbot-macros/Cargo.toml b/commitbot-macros/Cargo.toml deleted file mode 100644 index fc18714..0000000 --- a/commitbot-macros/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "commitbot_macros" -version = "0.1.0" -edition = "2024" - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "2", features = ["full"] } - diff --git a/commitbot-macros/src/lib.rs b/commitbot-macros/src/lib.rs deleted file mode 100644 index 16574da..0000000 --- a/commitbot-macros/src/lib.rs +++ /dev/null @@ -1,44 +0,0 @@ -use proc_macro::TokenStream; -use quote::quote; -use syn::{parse_macro_input, DeriveInput, Data, DataStruct, Fields}; - -#[proc_macro_derive(SensitiveFields, attributes(sensitive))] -pub fn derive_sensitive_fields(input: TokenStream) -> TokenStream { - let input = parse_macro_input!(input as DeriveInput); - let name = input.ident; - - let mut sensitive_fields: Vec = Vec::new(); - - if let Data::Struct(DataStruct { fields: Fields::Named(ref fields_named), .. }) = input.data { - for field in fields_named.named.iter() { - for attr in &field.attrs { - if let Some(ident) = attr.path().get_ident() { - if ident == "sensitive" { - if let Some(ident_field) = &field.ident { - sensitive_fields.push(ident_field.to_string()); - } - } - } - } - } - } - - // build an array of string literals - let literals: Vec = sensitive_fields - .iter() - .map(|s| { - let lit = syn::LitStr::new(s, proc_macro2::Span::call_site()); - quote! { #lit } - }) - .collect(); - - let expanded = quote! { - impl #name { - pub fn sensitive_field_names() -> &'static [&'static str] { - &[#(#literals),*] - } - } - }; - - TokenStream::from(expanded) -} diff --git a/src/config.rs b/src/config.rs index 9f13b98..9e06104 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,12 +8,11 @@ use std::fs; use std::path::{Path, PathBuf}; /// Final resolved configuration for commitbot. -#[derive(Debug, Clone, commitbot_macros::SensitiveFields)] +#[derive(Debug, Clone)] pub struct Config { /// LLM provider (openai, ollama) pub provider: String, - /// OpenAI API key for authentication - #[sensitive] + /// OpenAI API key for authentication (sensitive – redacted in logs) pub openai_api_key: Option, /// Base URL for the LLM provider pub base_url: Option, @@ -26,6 +25,12 @@ pub struct Config { } impl Config { + /// Returns the names of fields that contain sensitive data (e.g. API keys). + /// These are redacted in debug/verbose log output. + pub fn sensitive_field_names() -> &'static [&'static str] { + &["openai_api_key"] + } + /// Build the final config from CLI flags, environment, TOML file, and defaults. /// /// Precedence (highest to lowest): From 598260dc8b28c6b5d3da1b4d48f61bd4364a2a94 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Thu, 9 Apr 2026 00:48:20 -0400 Subject: [PATCH 15/40] 0.6.2 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 572f285..df5129e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 4dbb38c..e59be51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.6.1" +version = "0.6.2" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 12f28f1fddec8c1629b56d89f4b5dd9ca5b87619 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 24 Jun 2026 00:52:00 -0400 Subject: [PATCH 16/40] Enhance software release orchestration and tooling - CI/CD Workflow Management - Overhaul `release.yml` to manage the full lifecycle, including planning validation and API interaction for draft creation. - Update asset building and publishing in `release-assets.yml` with cross-platform matrix support. - Improve primary release flow robustness using `devops/release.sh` and implement a final publishing gate via `devops/publish-if-complete.sh`. - Versioning and Planning Logic - Centralize semantic version calculation and planning validation in `devops/ga-release-plan.sh`, supporting branch conventions (feat/*, bugfix/*). - Update local tasks with `Taskfile.yaml` to clarify build targets and report debug binary sizes. - Documentation and Assets Generation - Implement automated generation of markdown release assets using `devops/render-release-notes.sh`. - Enhance `README.md` structure by removing unnecessary whitespace. --- .github/workflows/release-assets.yml | 153 ++++++++++++++ .github/workflows/release.yml | 294 +++++++++++++++++++++++++++ README.md | 1 - Taskfile.yaml | 12 +- devops/ga-release-plan.sh | 124 +++++++++++ devops/publish-if-complete.sh | 40 ++++ devops/release.sh | 162 +++++++++++---- devops/render-release-notes.sh | 32 +++ 8 files changed, 778 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/release-assets.yml create mode 100644 .github/workflows/release.yml create mode 100755 devops/ga-release-plan.sh create mode 100755 devops/publish-if-complete.sh create mode 100644 devops/render-release-notes.sh diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml new file mode 100644 index 0000000..6e8c63c --- /dev/null +++ b/.github/workflows/release-assets.yml @@ -0,0 +1,153 @@ +name: Release Assets + +run-name: Release Assets (${{ inputs.tag }}) + +on: + workflow_dispatch: + inputs: + tag: + description: "Existing release tag to build and upload assets for" + required: true + type: string + source_run_id: + description: "Optional parent release workflow run id" + required: false + type: string + source_run_url: + description: "Optional parent release workflow run URL" + required: false + type: string + +permissions: + contents: write + +env: + CARGO_TERM_COLOR: always + +jobs: + build-release-assets: + name: ${{ matrix.name }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - name: Linux arm64 + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + archive_ext: tar.gz + binary_name: commitbot + install_cmd: "" + linker: "" + - name: Linux x86_64 + runner: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + archive_ext: tar.gz + binary_name: commitbot + install_cmd: "" + linker: "" + - name: Amazon Linux / CentOS / RHEL arm64 + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-musl + archive_ext: tar.gz + binary_name: commitbot + install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools + linker: musl-gcc + - name: Amazon Linux / CentOS / RHEL x86_64 + runner: ubuntu-24.04 + target: x86_64-unknown-linux-musl + archive_ext: tar.gz + binary_name: commitbot + install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools + linker: musl-gcc + - name: Windows x86_64 + runner: ubuntu-24.04 + target: x86_64-pc-windows-gnu + archive_ext: zip + binary_name: commitbot.exe + install_cmd: sudo apt-get update && sudo apt-get install -y mingw-w64 + linker: "" + + steps: + - name: Resolve release tag + id: meta + shell: bash + run: | + set -euo pipefail + + if [ -n "${{ inputs.tag || '' }}" ]; then + echo "tag=${{ inputs.tag }}" >> "$GITHUB_OUTPUT" + else + echo "No release tag was provided." >&2 + exit 1 + fi + + - name: Check out tagged source + uses: actions/checkout@v4 + with: + ref: ${{ steps.meta.outputs.tag }} + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + + - name: Install target-specific build tooling + if: matrix.install_cmd != '' + shell: bash + run: ${{ matrix.install_cmd }} + + - name: Run tests + if: matrix.target == 'x86_64-unknown-linux-gnu' + run: cargo test --locked --all-features + + - name: Build release binary + shell: bash + env: + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: ${{ matrix.target == 'aarch64-unknown-linux-musl' && matrix.linker || '' }} + CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: ${{ matrix.target == 'x86_64-unknown-linux-musl' && matrix.linker || '' }} + run: cargo build --locked --release --target ${{ matrix.target }} + + - name: Package tar.gz archive + if: matrix.archive_ext == 'tar.gz' + shell: bash + run: | + set -euo pipefail + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.target }}.tar.gz" + tar -C "target/${{ matrix.target }}/release" -czf "$asset" "${{ matrix.binary_name }}" + echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" + + - name: Package zip archive + if: matrix.archive_ext == 'zip' + shell: bash + run: | + set -euo pipefail + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.target }}.zip" + cd "target/${{ matrix.target }}/release" + zip "../../../${asset}" "${{ matrix.binary_name }}" + cd - + echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" + + - name: Upload asset to GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "${{ steps.meta.outputs.tag }}" "$ASSET_PATH" --clobber + + - name: Publish release if all assets are present + env: + GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + shell: bash + run: bash devops/publish-if-complete.sh "${{ steps.meta.outputs.tag }}" + + - name: Add run summary + shell: bash + run: | + { + echo "## Release Assets" + echo + echo "- Tag: \`${{ steps.meta.outputs.tag }}\`" + echo "- Target: \`${{ matrix.target }}\`" + if [[ -n "${{ inputs.source_run_url }}" ]]; then + echo "- Triggered by: ${{ inputs.source_run_url }}" + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ff8d75a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,294 @@ +name: Release + +on: + workflow_dispatch: + inputs: + target_branch: + description: Release branch + required: true + type: choice + options: + - develop + - main + version: + description: Release version (X.Y.Z) + required: true + type: string + pull_request: + types: [closed] + branches: + - develop + - main + +permissions: + actions: write + contents: write + pull-requests: read + +concurrency: + group: release-${{ github.event_name == 'workflow_dispatch' && inputs.target_branch || github.event.pull_request.base.ref }} + cancel-in-progress: false + +env: + CARGO_TERM_COLOR: always + MAIN_BASE_VERSION: ${{ vars.MAIN_BASE_VERSION }} + DEVELOP_BASE_VERSION: ${{ vars.DEVELOP_BASE_VERSION }} + +jobs: + plan: + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true + runs-on: ubuntu-latest + outputs: + should_release: ${{ steps.plan.outputs.should_release }} + reason: ${{ steps.plan.outputs.reason }} + bump: ${{ steps.plan.outputs.bump }} + base_version: ${{ steps.plan.outputs.base_version }} + previous_version: ${{ steps.plan.outputs.previous_version }} + version: ${{ steps.plan.outputs.version }} + target_branch: ${{ steps.plan.outputs.target_branch }} + source_branch: ${{ steps.plan.outputs.source_branch }} + merge_sha: ${{ steps.context.outputs.merge_sha }} + steps: + - name: Checkout selected branch + if: github.event_name == 'workflow_dispatch' + uses: actions/checkout@v4 + with: + ref: ${{ inputs.target_branch }} + fetch-depth: 0 + + - name: Checkout merge commit + if: github.event_name == 'pull_request' + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.merge_commit_sha }} + fetch-depth: 0 + + - name: Fetch tags + run: git fetch --force --tags + + - name: Resolve base versions + id: bases + shell: bash + run: | + set -euo pipefail + + current_version="$( + sed -nE 's/^version = "([0-9]+\.[0-9]+\.[0-9]+)"/\1/p' Cargo.toml | head -n1 + )" + + if [[ -z "${current_version}" ]]; then + echo "Could not determine the current Cargo version." >&2 + exit 1 + fi + + echo "main_base_version=${MAIN_BASE_VERSION:-$current_version}" >> "$GITHUB_OUTPUT" + echo "develop_base_version=${DEVELOP_BASE_VERSION:-$current_version}" >> "$GITHUB_OUTPUT" + + - name: Resolve release context + id: context + shell: bash + run: | + set -euo pipefail + + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + echo "target_branch=${{ inputs.target_branch }}" >> "$GITHUB_OUTPUT" + echo "source_branch=workflow_dispatch" >> "$GITHUB_OUTPUT" + echo "release_version=${{ inputs.version }}" >> "$GITHUB_OUTPUT" + echo "merge_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + else + echo "target_branch=${{ github.event.pull_request.base.ref }}" >> "$GITHUB_OUTPUT" + echo "source_branch=${{ github.event.pull_request.head.ref }}" >> "$GITHUB_OUTPUT" + echo "release_version=" >> "$GITHUB_OUTPUT" + echo "merge_sha=${{ github.event.pull_request.merge_commit_sha }}" >> "$GITHUB_OUTPUT" + fi + + - name: Plan release + id: plan + env: + TARGET_BRANCH: ${{ steps.context.outputs.target_branch }} + SOURCE_BRANCH: ${{ steps.context.outputs.source_branch }} + RELEASE_VERSION: ${{ steps.context.outputs.release_version }} + MAIN_BASE_VERSION: ${{ steps.bases.outputs.main_base_version }} + DEVELOP_BASE_VERSION: ${{ steps.bases.outputs.develop_base_version }} + run: devops/ga-release-plan.sh + + - name: Stop on non-release branches + if: steps.plan.outputs.should_release != 'true' + shell: bash + run: | + echo "Skipping release: ${{ steps.plan.outputs.reason }}" + + prepare_release: + needs: plan + if: needs.plan.outputs.should_release == 'true' + runs-on: ubuntu-latest + outputs: + release_sha: ${{ steps.release_commit.outputs.release_sha }} + steps: + - name: Checkout target branch + uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.target_branch }} + fetch-depth: 0 + + - name: Fetch tags + run: git fetch --force --tags + + - name: Verify tag does not already exist + shell: bash + run: | + if git rev-parse "refs/tags/${{ needs.plan.outputs.version }}" >/dev/null 2>&1; then + echo "Tag ${{ needs.plan.outputs.version }} already exists." + exit 1 + fi + + - name: Ensure release commit includes merged change + if: github.event_name == 'pull_request' + shell: bash + run: | + set -euo pipefail + + if ! git merge-base --is-ancestor "${{ needs.plan.outputs.merge_sha }}" HEAD; then + echo "The target branch no longer contains merge commit ${{ needs.plan.outputs.merge_sha }}." >&2 + exit 1 + fi + + - name: Configure git author + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Create release commit + id: release_commit + shell: bash + run: | + set -euo pipefail + + version="${{ needs.plan.outputs.version }}" + + perl -pi -e 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"/version = "'"$version"'"/' Cargo.toml + perl -0pi -e 's/name = "commitbot"\nversion = "[0-9]+\.[0-9]+\.[0-9]+"/name = "commitbot"\nversion = "'"$version"'"/m' Cargo.lock + + if git diff --quiet -- Cargo.toml Cargo.lock; then + echo "Release version ${version} is already present in Cargo metadata." >&2 + exit 1 + fi + + git add Cargo.toml Cargo.lock + git commit -m "Release ${version}" + git tag "${version}" + + echo "release_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + - name: Push release commit and tag + shell: bash + run: | + set -euo pipefail + git push origin "HEAD:${{ needs.plan.outputs.target_branch }}" + git push origin "refs/tags/${{ needs.plan.outputs.version }}" + + create_release: + needs: [plan, prepare_release] + if: needs.plan.outputs.should_release == 'true' + runs-on: ubuntu-latest + steps: + - name: Check out release commit + uses: actions/checkout@v4 + with: + ref: ${{ needs.prepare_release.outputs.release_sha }} + + - name: Generate release notes + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + NOTES_ARGS=() + if [[ "${{ needs.plan.outputs.previous_version }}" != "${{ needs.plan.outputs.base_version }}" ]]; then + NOTES_ARGS+=(-f previous_tag_name="${{ needs.plan.outputs.previous_version }}") + fi + + gh api \ + -H "Accept: application/vnd.github+json" \ + "/repos/${{ github.repository }}/releases/generate-notes" \ + -f tag_name="${{ needs.plan.outputs.version }}" \ + -f target_commitish="${{ needs.prepare_release.outputs.release_sha }}" \ + "${NOTES_ARGS[@]}" \ + --jq .body > generated-release-notes.md + + bash devops/render-release-notes.sh \ + "${{ needs.plan.outputs.version }}" \ + "${{ github.repository }}" \ + generated-release-notes.md > release-notes.md + + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + gh release create "${{ needs.plan.outputs.version }}" \ + --draft \ + --verify-tag \ + --target "${{ needs.prepare_release.outputs.release_sha }}" \ + --title "${{ needs.plan.outputs.version }}" \ + --notes-file release-notes.md + + - name: Dispatch release-assets workflow + id: dispatch_assets + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + dispatch_started_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + source_run_url="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + gh workflow run release-assets.yml \ + --ref "${{ needs.plan.outputs.target_branch }}" \ + -f tag="${{ needs.plan.outputs.version }}" \ + -f source_run_id="${{ github.run_id }}" \ + -f source_run_url="${source_run_url}" + + assets_run_url="" + for _ in {1..12}; do + sleep 5 + + assets_run_url="$( + gh api "/repos/${{ github.repository }}/actions/workflows/release-assets.yml/runs?event=workflow_dispatch&branch=${{ needs.plan.outputs.target_branch }}&per_page=20" \ + --jq '.workflow_runs + | map(select(.head_sha == "${{ needs.prepare_release.outputs.release_sha }}" and .status != null)) + | sort_by(.created_at) + | reverse + | .[0].html_url // ""' + )" + + if [[ -n "${assets_run_url}" ]]; then + break + fi + done + + echo "dispatch_started_at=${dispatch_started_at}" >> "$GITHUB_OUTPUT" + echo "assets_run_url=${assets_run_url}" >> "$GITHUB_OUTPUT" + + - name: Add release summary + shell: bash + run: | + release_url="https://github.com/${{ github.repository }}/releases/tag/${{ needs.plan.outputs.version }}" + assets_url="${{ steps.dispatch_assets.outputs.assets_run_url }}" + + { + echo "## Release" + echo + echo "- Version: \`${{ needs.plan.outputs.version }}\`" + echo "- Release: [${{ needs.plan.outputs.version }}](${release_url})" + if [[ -n "${assets_url}" ]]; then + echo "- Release assets workflow: [Open run](${assets_url})" + else + echo "- Release assets workflow: dispatched, but the run URL was not discovered yet." + echo "- Release assets workflow page: [Open workflow](https://github.com/${{ github.repository }}/actions/workflows/release-assets.yml)" + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 6d8fcf1..c23f7b0 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ A Rust-powered CLI that writes meaningful, structured Git commit messages using [![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](https://github.com/MikeGarde/commitbot/blob/main/LICENSE) [![Downloads](https://img.shields.io/github/downloads/MikeGarde/commitbot/total.svg?color=blue)](https://GitHub.com/MikeGarde/commitbot/releases/) - --- **Commitbot** analyzes your staged Git changes and helps you craft clear, consistent commit messages that describe *why* changes were made — not just *what* changed. diff --git a/Taskfile.yaml b/Taskfile.yaml index 6e02ae2..4a4d4da 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -63,6 +63,13 @@ tasks: - brew uninstall mikegarde/tap/commitbot || true - brew install mikegarde/tap/commitbot + build: + desc: "Build debug binary for the host" + silent: true + cmds: + - cargo build 2>$1 + - du -h target/debug/commitbot + build:release: desc: "Build optimized release binary for the host" silent: true @@ -81,7 +88,7 @@ tasks: - | set -euo pipefail - echo "Building release binaries..." + echo "Building Mac release binaries..." cargo build --release --target aarch64-apple-darwin cargo build --release --target x86_64-apple-darwin @@ -112,9 +119,6 @@ tasks: - task: publish:dry - task: publish - task: install - - TAG=$(commitbot --version) && \ - cd ../homebrew-tap && \ - gh workflow run update-formula.yml -f formula=commitbot -f repo=mikegarde/commitbot -f tag=$TAG publish:dry: desc: "Dry-run crates.io publish to verify packaging" diff --git a/devops/ga-release-plan.sh b/devops/ga-release-plan.sh new file mode 100755 index 0000000..41e95c0 --- /dev/null +++ b/devops/ga-release-plan.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash + +set -euo pipefail + +TARGET_BRANCH="${TARGET_BRANCH:-${1:-}}" +SOURCE_BRANCH="${SOURCE_BRANCH:-${2:-}}" +MAIN_BASE_VERSION="${MAIN_BASE_VERSION:-}" +DEVELOP_BASE_VERSION="${DEVELOP_BASE_VERSION:-}" +RELEASE_VERSION="${RELEASE_VERSION:-}" + +if [[ -z "${TARGET_BRANCH}" ]]; then + echo "usage: TARGET_BRANCH= SOURCE_BRANCH= RELEASE_VERSION=X.Y.Z MAIN_BASE_VERSION=X.Y.Z DEVELOP_BASE_VERSION=X.Y.Z $0" >&2 + exit 1 +fi + +semver_pattern='^[0-9]+\.[0-9]+\.[0-9]+$' + +require_semver() { + local value="$1" + local label="$2" + + if [[ ! "${value}" =~ ${semver_pattern} ]]; then + echo "${label} must be a semantic version like 1.0.0" >&2 + exit 1 + fi +} + +require_semver "${MAIN_BASE_VERSION}" "MAIN_BASE_VERSION" +require_semver "${DEVELOP_BASE_VERSION}" "DEVELOP_BASE_VERSION" + +if [[ -n "${RELEASE_VERSION}" ]]; then + require_semver "${RELEASE_VERSION}" "RELEASE_VERSION" +fi + +case "${TARGET_BRANCH}" in + main) + BASE_VERSION="${MAIN_BASE_VERSION}" + ;; + develop) + BASE_VERSION="${DEVELOP_BASE_VERSION}" + ;; + *) + echo "Unsupported target branch: ${TARGET_BRANCH}" >&2 + exit 1 + ;; +esac + +BASE_MAJOR="${BASE_VERSION%%.*}" +TAG_PATTERN="^${BASE_MAJOR}\\.[0-9]+\\.[0-9]+$" +PREVIOUS_VERSION="$( + git tag --list \ + | grep -E "${TAG_PATTERN}" || true +)" +PREVIOUS_VERSION="$( + printf '%s\n' "${PREVIOUS_VERSION}" \ + | sort -V \ + | tail -n 1 +)" +PREVIOUS_VERSION="${PREVIOUS_VERSION:-${BASE_VERSION}}" + +CURRENT_VERSION="$( + printf '%s\n%s\n' "${BASE_VERSION}" "${PREVIOUS_VERSION}" \ + | sort -V \ + | tail -n 1 +)" + +if [[ -n "${RELEASE_VERSION}" ]]; then + SHOULD_RELEASE="true" + REASON="" + BUMP="manual" + + RELEASE_MAJOR="${RELEASE_VERSION%%.*}" + if [[ "${RELEASE_MAJOR}" != "${BASE_MAJOR}" ]]; then + echo "RELEASE_VERSION ${RELEASE_VERSION} does not match the ${TARGET_BRANCH} release line ${BASE_MAJOR}.x.x" >&2 + exit 1 + fi + + if [[ "$(printf '%s\n%s\n' "${CURRENT_VERSION}" "${RELEASE_VERSION}" | sort -V | tail -n 1)" != "${RELEASE_VERSION}" ]] || [[ "${RELEASE_VERSION}" == "${CURRENT_VERSION}" ]]; then + echo "RELEASE_VERSION ${RELEASE_VERSION} must be newer than ${CURRENT_VERSION}" >&2 + exit 1 + fi + + VERSION="${RELEASE_VERSION}" +elif [[ "${SOURCE_BRANCH}" == feat/* ]]; then + SHOULD_RELEASE="true" + REASON="" + BUMP="minor" + IFS='.' read -r MAJOR MINOR PATCH <<< "${CURRENT_VERSION}" + MINOR=$((MINOR + 1)) + PATCH=0 + VERSION="${MAJOR}.${MINOR}.${PATCH}" +elif [[ "${SOURCE_BRANCH}" == bugfix/* ]]; then + SHOULD_RELEASE="true" + REASON="" + BUMP="patch" + IFS='.' read -r MAJOR MINOR PATCH <<< "${CURRENT_VERSION}" + PATCH=$((PATCH + 1)) + VERSION="${MAJOR}.${MINOR}.${PATCH}" +else + SHOULD_RELEASE="false" + REASON="Source branch must start with feat/ or bugfix/." + BUMP="none" + VERSION="" +fi + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + { + echo "should_release=${SHOULD_RELEASE}" + echo "reason=${REASON}" + echo "bump=${BUMP}" + echo "base_version=${BASE_VERSION}" + echo "previous_version=${PREVIOUS_VERSION}" + echo "version=${VERSION}" + echo "target_branch=${TARGET_BRANCH}" + echo "source_branch=${SOURCE_BRANCH}" + } >> "${GITHUB_OUTPUT}" +fi + +echo "should_release=${SHOULD_RELEASE}" +echo "reason=${REASON}" +echo "bump=${BUMP}" +echo "base_version=${BASE_VERSION}" +echo "previous_version=${PREVIOUS_VERSION}" +echo "version=${VERSION}" diff --git a/devops/publish-if-complete.sh b/devops/publish-if-complete.sh new file mode 100755 index 0000000..3904e8a --- /dev/null +++ b/devops/publish-if-complete.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +set -euo pipefail + +TAG="${1:?usage: publish-if-complete.sh }" + +EXPECTED=( + "commitbot-${TAG}-aarch64-apple-darwin.tar.gz" + "commitbot-${TAG}-x86_64-apple-darwin.tar.gz" + "commitbot-${TAG}-aarch64-unknown-linux-gnu.tar.gz" + "commitbot-${TAG}-x86_64-unknown-linux-gnu.tar.gz" + "commitbot-${TAG}-aarch64-unknown-linux-musl.tar.gz" + "commitbot-${TAG}-x86_64-unknown-linux-musl.tar.gz" + "commitbot-${TAG}-x86_64-pc-windows-gnu.zip" +) + +ACTUAL="$(gh release view "${TAG}" --json assets --jq '[.assets[].name]')" + +for asset in "${EXPECTED[@]}"; do + if ! printf '%s' "${ACTUAL}" | jq -e --arg n "${asset}" 'any(.[]; . == $n)' > /dev/null 2>&1; then + echo "Release not yet complete (missing: ${asset}). Skipping publish." + exit 0 + fi +done + +echo "All expected assets present. Publishing release ${TAG}..." +gh release edit "${TAG}" --draft=false +echo "Published." + +echo "Triggering Homebrew tap formula update..." +if gh workflow run update-formula.yml \ + --repo MikeGarde/homebrew-tap \ + -f formula=commitbot \ + -f repo=MikeGarde/commitbot \ + -f tag="${TAG}"; then + echo "Homebrew tap update dispatched." +else + echo "Warning: could not dispatch Homebrew tap update. Trigger it manually with:" + echo " gh workflow run update-formula.yml --repo MikeGarde/homebrew-tap -f formula=commitbot -f repo=MikeGarde/commitbot -f tag=${TAG}" +fi diff --git a/devops/release.sh b/devops/release.sh index dbb0256..f1cedf5 100644 --- a/devops/release.sh +++ b/devops/release.sh @@ -1,16 +1,16 @@ #!/bin/zsh set -euo pipefail -# --------------------------------------------------------- +# # Config -# --------------------------------------------------------- +# DIST_DIR="dist" STEP=${1:?usage: release.sh [major|minor|patch|X.Y.Z]} -# --------------------------------------------------------- +# # Pre-flight checks -# --------------------------------------------------------- +# if ! command -v task >/dev/null 2>&1; then echo "Error: 'task' command not found. Install Taskfile runner first." exit 1 @@ -21,6 +21,13 @@ if ! command -v gh >/dev/null 2>&1; then exit 1 fi +if ! command -v jq >/dev/null 2>&1; then + echo "Error: 'jq' not found. Install jq first." + exit 1 +fi + +REPO_SLUG=$(gh repo view --json nameWithOwner -q .nameWithOwner) + BRANCH=$(git rev-parse --abbrev-ref HEAD) if [ "$BRANCH" != "main" ]; then echo "Error: releases may only be created from 'main' (current: $BRANCH)." @@ -33,9 +40,9 @@ if ! git diff --quiet || ! git diff --cached --quiet; then exit 1 fi -# --------------------------------------------------------- +# # Read current version from Cargo.toml -# --------------------------------------------------------- +# CURRENT_VERSION=$( grep -E '^version = "[0-9]+\.[0-9]+\.[0-9]+"' Cargo.toml \ | head -n1 \ @@ -52,9 +59,9 @@ MINOR=$(echo "$CURRENT_VERSION" | cut -d. -f2) PATCH=$(echo "$CURRENT_VERSION" | cut -d. -f3) LATEST=true -# --------------------------------------------------------- +# # Compute new version -# --------------------------------------------------------- +# case "$STEP" in major) MAJOR=$((MAJOR+1)) @@ -84,12 +91,57 @@ esac NEW_VERSION="$MAJOR.$MINOR.$PATCH" -# Check that tag does not already exist +# +# Join mode: tag already exists (e.g. GA created the release first) +# if git rev-parse -q --verify "refs/tags/$NEW_VERSION" >/dev/null 2>&1; then - echo "Error: git tag $NEW_VERSION already exists." - exit 1 + echo "Tag $NEW_VERSION already exists. Joining existing draft release to upload Mac assets..." + echo + + RELEASE_IS_DRAFT=$(gh release view "$NEW_VERSION" --json isDraft --jq .isDraft 2>/dev/null || echo "not_found") + if [ "$RELEASE_IS_DRAFT" = "false" ]; then + echo "Release $NEW_VERSION is already published. Nothing to do." + exit 0 + fi + if [ "$RELEASE_IS_DRAFT" = "not_found" ]; then + echo "Error: tag $NEW_VERSION exists in git but no GitHub release was found." + exit 1 + fi + + CARGO_VERSION=$( + grep -E '^version = "[0-9]+\.[0-9]+\.[0-9]+"' Cargo.toml \ + | head -n1 \ + | sed -E 's/version = "([^"]+)"/\1/' + ) + if [ "$CARGO_VERSION" != "$NEW_VERSION" ]; then + echo "Error: Cargo.toml version ($CARGO_VERSION) does not match release version ($NEW_VERSION)." + echo "Run 'git pull' to sync the release commit, then retry." + exit 1 + fi + + echo "Building Mac binaries for $NEW_VERSION..." + task setup + task "build:release:${NEW_VERSION}" + + MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.tar.gz) + if [ ${#MAC_ASSETS[@]} -eq 0 ]; then + echo "Error: no Mac assets found in $DIST_DIR after build." + exit 1 + fi + + echo "Uploading Mac assets to existing draft release $NEW_VERSION:" + for a in "${MAC_ASSETS[@]}"; do + echo " - $a" + done + gh release upload "$NEW_VERSION" "${MAC_ASSETS[@]}" --clobber + + bash devops/publish-if-complete.sh "$NEW_VERSION" + exit 0 fi +# +# Full release flow +# echo "Current version: $CURRENT_VERSION" echo "New version: $NEW_VERSION" echo "Branch: $BRANCH" @@ -101,9 +153,9 @@ if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then exit 1 fi -# --------------------------------------------------------- +# # Bump Cargo.toml with rollback on failure -# --------------------------------------------------------- +# CARGO_BAK="Cargo.toml.bak.$$" cp Cargo.toml "$CARGO_BAK" @@ -120,22 +172,22 @@ trap cleanup_on_error INT TERM ERR echo "Updating Cargo.toml to version $NEW_VERSION..." perl -pi -e 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"/version = "'"$NEW_VERSION"'"/' Cargo.toml -# --------------------------------------------------------- +# # Run tasks: setup, test, build -# --------------------------------------------------------- +# echo "Running task setup..." task setup -echo "Running task build:release:all..." +echo "Running task build:release:${NEW_VERSION}..." task "build:release:${NEW_VERSION}" # If we got here, tasks succeeded – stop rollback trap trap - INT TERM ERR rm -f "$CARGO_BAK" -# --------------------------------------------------------- +# # Commit, tag, push -# --------------------------------------------------------- +# if git diff --quiet -- Cargo.toml; then echo "Warning: Cargo.toml did not change; nothing to commit." else @@ -151,37 +203,77 @@ echo "Pushing main and tag..." git push origin main git push origin "refs/tags/$NEW_VERSION" -# --------------------------------------------------------- -# Create GitHub release from artifacts in DIST_DIR -# --------------------------------------------------------- +# +# Create draft GitHub release with Mac assets +# if [ ! -d "$DIST_DIR" ]; then echo "Error: build artifacts directory '$DIST_DIR' not found." echo "Check task build:release:all" exit 1 fi -ASSETS=("$DIST_DIR"/*) -if [ ${#ASSETS[@]} -eq 0 ]; then - echo "Error: no build artifacts found in '$DIST_DIR'." +MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.tar.gz) +if [ ${#MAC_ASSETS[@]} -eq 0 ]; then + echo "Error: no Mac assets found in '$DIST_DIR'." exit 1 fi -LATEST_FLAG="" -if [ "$LATEST" = true ]; then - LATEST_FLAG="--latest" -fi - -echo "Creating GitHub release $NEW_VERSION with assets:" -for a in "${ASSETS[@]}"; do +echo "Creating draft GitHub release $NEW_VERSION with Mac assets:" +for a in "${MAC_ASSETS[@]}"; do echo " - $a" done +NOTES_FILE="$(mktemp)" +COMBINED_NOTES_FILE="$(mktemp)" + +cleanup_notes() { + rm -f "$NOTES_FILE" "$COMBINED_NOTES_FILE" +} +trap cleanup_notes EXIT + +gh api \ + -H "Accept: application/vnd.github+json" \ + "/repos/$REPO_SLUG/releases/generate-notes" \ + -f tag_name="$NEW_VERSION" \ + -f target_commitish="$HASH" \ + --jq .body > "$NOTES_FILE" + +bash devops/render-release-notes.sh "$NEW_VERSION" "$REPO_SLUG" "$NOTES_FILE" > "$COMBINED_NOTES_FILE" + +LATEST_ARGS=() +if [ "$LATEST" = true ]; then + LATEST_ARGS+=(--latest) +fi + gh release create "$NEW_VERSION" \ + --draft \ --fail-on-no-commits \ - --generate-notes \ - $LATEST_FLAG \ + "${LATEST_ARGS[@]}" \ + --notes-file "$COMBINED_NOTES_FILE" \ --target "$HASH" \ - "${ASSETS[@]}" + "${MAC_ASSETS[@]}" + +# +# Dispatch release-assets workflow for Linux + Windows +# +echo +echo "Dispatching release-assets workflow for Linux and Windows builds..." + +SOURCE_RUN_URL="local:$(hostname)" + +gh workflow run release-assets.yml \ + --ref main \ + -f tag="$NEW_VERSION" \ + -f source_run_url="${SOURCE_RUN_URL}" + +echo "Dispatched. Linux and Windows assets will be uploaded by GitHub Actions." +echo "The release will be published automatically once all assets are present." +echo + +# +# Check if all assets happen to already be present (rare but possible) +# +bash devops/publish-if-complete.sh "$NEW_VERSION" -echo "Release $NEW_VERSION created successfully." +echo "Release $NEW_VERSION draft created successfully." exit 0 diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh new file mode 100644 index 0000000..07cc1d9 --- /dev/null +++ b/devops/render-release-notes.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +set -euo pipefail + +VERSION="${1:?usage: render-release-notes.sh [notes-file]}" +REPO="${2:?usage: render-release-notes.sh [notes-file]}" +NOTES_FILE="${3:-}" + +asset_url() { + local filename="$1" + printf 'https://github.com/%s/releases/download/%s/%s' "${REPO}" "${VERSION}" "${filename}" +} + +cat < Date: Wed, 24 Jun 2026 01:09:53 -0400 Subject: [PATCH 17/40] lockfile update --- Cargo.lock | 663 ++++++++++++++++++++++++++--------------------------- 1 file changed, 324 insertions(+), 339 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index df5129e..890ad46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,9 +13,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.21" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" dependencies = [ "anstyle", "anstyle-parse", @@ -28,15 +28,15 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anstyle-parse" -version = "0.2.7" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" dependencies = [ "utf8parse", ] @@ -69,9 +69,9 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "assert_cmd" -version = "2.1.2" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c5bcfa8749ac45dd12cb11055aeeb6b27a3895560d60d71e3c23bf979e60514" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" dependencies = [ "anstyle", "bstr", @@ -90,15 +90,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9a7b350e3bb1767102698302bc37256cbd48422809984b98d292c40e2579aa9" +checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" dependencies = [ "aws-lc-sys", "zeroize", @@ -106,9 +106,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.37.1" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549" +checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" dependencies = [ "cc", "cmake", @@ -124,9 +124,15 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bitflags" -version = "2.11.0" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" [[package]] name = "bstr" @@ -141,21 +147,21 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" [[package]] name = "cc" -version = "1.2.56" +version = "1.2.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" dependencies = [ "find-msvc-tools", "jobserver", @@ -163,12 +169,6 @@ dependencies = [ "shlex", ] -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" - [[package]] name = "cfg-if" version = "1.0.4" @@ -183,9 +183,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "clap" -version = "4.5.60" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" dependencies = [ "clap_builder", "clap_derive", @@ -193,9 +193,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.60" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ "anstream", "anstyle", @@ -205,9 +205,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.55" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" dependencies = [ "heck", "proc-macro2", @@ -217,24 +217,24 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "cmake" -version = "0.1.57" +version = "0.1.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" dependencies = [ "cc", ] [[package]] name = "colorchoice" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "colored" @@ -278,13 +278,12 @@ dependencies = [ [[package]] name = "console" -version = "0.16.2" +version = "0.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e45a4a8926227e4197636ba97a9fc9b00477e9f4bd711395687c5f0734bec4" +checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87" dependencies = [ "encode_unicode", "libc", - "once_cell", "unicode-width", "windows-sys 0.61.2", ] @@ -330,7 +329,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags", + "bitflags 2.13.0", "crossterm_winapi", "derive_more", "document-features", @@ -351,6 +350,38 @@ dependencies = [ "winapi", ] +[[package]] +name = "defmt" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6e524506490a1953d237cb87b1cfc1e46f88c18f10a22dfe0f507dc6bfc7f7f" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a27770e9c8f719a79d8b638281f4d828f77d8fd61e0bd94451b9b85e576a0b" +dependencies = [ + "defmt-parser", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -402,9 +433,9 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", @@ -443,9 +474,9 @@ dependencies = [ [[package]] name = "env_filter" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" dependencies = [ "log", "regex", @@ -453,9 +484,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.11.9" +version = "0.11.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" dependencies = [ "anstream", "anstyle", @@ -567,9 +598,9 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" +checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae" dependencies = [ "cc", "cfg-if", @@ -609,9 +640,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.13" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" dependencies = [ "atomic-waker", "bytes", @@ -628,9 +659,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.16.1" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "heck" @@ -640,9 +671,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "http" -version = "1.4.0" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" dependencies = [ "bytes", "itoa", @@ -679,9 +710,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" -version = "1.8.1" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" dependencies = [ "atomic-waker", "bytes", @@ -693,7 +724,6 @@ dependencies = [ "httparse", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -701,15 +731,14 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.7" +version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http", "hyper", "hyper-util", "rustls", - "rustls-pki-types", "tokio", "tokio-rustls", "tower-service", @@ -742,12 +771,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -755,9 +785,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" dependencies = [ "displaydoc", "litemap", @@ -768,9 +798,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -782,15 +812,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" [[package]] name = "icu_properties" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" dependencies = [ "icu_collections", "icu_locale_core", @@ -802,15 +832,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" dependencies = [ "displaydoc", "icu_locale_core", @@ -834,9 +864,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -844,9 +874,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown", @@ -867,19 +897,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.11.0" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" -dependencies = [ - "memchr", - "serde", -] +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" [[package]] name = "is_terminal_polyfill" @@ -889,16 +909,17 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.22" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819b44bc7c87d9117eb522f14d46e918add69ff12713c475946b0a29363ed1c2" +checksum = "34f877a98676d2fb664698d74cc6a51ce6c484ce8c770f05d0108ec9090aeb46" dependencies = [ + "defmt", "jiff-static", "log", "portable-atomic", @@ -908,9 +929,9 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.22" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "470252db18ecc35fd766c0891b1e3ec6cbbcd62507e85276c01bf75d8e94d4a1" +checksum = "0666b5ab5ecaca213fc2a85b8c0083d9004e84ee2d5f9a7e0017aaf50986f25f" dependencies = [ "proc-macro2", "quote", @@ -919,25 +940,52 @@ dependencies = [ [[package]] name = "jni" -version = "0.21.1" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" dependencies = [ - "cesu8", "cfg-if", "combine", + "jni-macros", "jni-sys", "log", - "thiserror 1.0.69", + "simd_cesu8", + "thiserror", "walkdir", - "windows-sys 0.45.0", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn", ] [[package]] name = "jni-sys" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn", +] [[package]] name = "jobserver" @@ -951,11 +999,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.91" +version = "0.3.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -967,15 +1016,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.182" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] name = "libredox" -version = "0.1.14" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a" +checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" dependencies = [ "libc", ] @@ -988,9 +1037,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "litrs" @@ -1009,9 +1058,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "loom" @@ -1043,9 +1092,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" [[package]] name = "mime" @@ -1055,9 +1104,9 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "mio" -version = "1.1.1" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", "log", @@ -1125,9 +1174,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.3" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "once_cell_polyfill" @@ -1182,12 +1231,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "portable-atomic" version = "1.13.1" @@ -1196,18 +1239,18 @@ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] name = "portable-atomic-util" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" dependencies = [ "portable-atomic", ] [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" dependencies = [ "zerovec", ] @@ -1251,6 +1294,28 @@ dependencies = [ "termtree", ] +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1262,9 +1327,9 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.9" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" dependencies = [ "bytes", "cfg_aliases", @@ -1274,7 +1339,7 @@ dependencies = [ "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror", "tokio", "tracing", "web-time", @@ -1282,9 +1347,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.13" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" dependencies = [ "aws-lc-rs", "bytes", @@ -1296,7 +1361,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror", "tinyvec", "tracing", "web-time", @@ -1318,9 +1383,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.44" +version = "1.0.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" dependencies = [ "proc-macro2", ] @@ -1333,9 +1398,9 @@ checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rand" -version = "0.9.2" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" dependencies = [ "rand_chacha", "rand_core", @@ -1366,7 +1431,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.0", ] [[package]] @@ -1377,14 +1442,14 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror", ] [[package]] name = "regex" -version = "1.12.3" +version = "1.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" dependencies = [ "aho-corasick", "memchr", @@ -1405,15 +1470,15 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "reqwest" -version = "0.13.2" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" dependencies = [ "base64", "bytes", @@ -1467,9 +1532,9 @@ dependencies = [ [[package]] name = "rustc-hash" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" [[package]] name = "rustc_version" @@ -1486,7 +1551,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags", + "bitflags 2.13.0", "errno", "libc", "linux-raw-sys", @@ -1495,9 +1560,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.37" +version = "0.23.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" +checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ "aws-lc-rs", "once_cell", @@ -1509,9 +1574,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -1521,9 +1586,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" dependencies = [ "web-time", "zeroize", @@ -1531,9 +1596,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", @@ -1558,9 +1623,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.9" +version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ "aws-lc-rs", "ring", @@ -1591,9 +1656,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.28" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ "windows-sys 0.61.2", ] @@ -1616,7 +1681,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.13.0", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -1635,9 +1700,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" @@ -1671,9 +1736,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.150" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" dependencies = [ "itoa", "memchr", @@ -1684,9 +1749,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.0.4" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" dependencies = [ "serde_core", ] @@ -1702,9 +1767,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.3.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook" @@ -1737,6 +1802,16 @@ dependencies = [ "libc", ] +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -1751,18 +1826,18 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" [[package]] name = "socket2" -version = "0.6.2" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1785,9 +1860,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.117" +version = "2.0.118" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" dependencies = [ "proc-macro2", "quote", @@ -1820,7 +1895,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags", + "bitflags 2.13.0", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -1841,33 +1916,13 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - [[package]] name = "thiserror" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "thiserror-impl 2.0.18", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn", + "thiserror-impl", ] [[package]] @@ -1892,9 +1947,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" dependencies = [ "displaydoc", "zerovec", @@ -1902,9 +1957,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" dependencies = [ "tinyvec_macros", ] @@ -1917,9 +1972,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.49.0" +version = "1.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" dependencies = [ "bytes", "libc", @@ -1954,9 +2009,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.0.3+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7614eaf19ad818347db24addfa201729cf2a9b6fdfd9eb0ab870fcacc606c0c" +checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" dependencies = [ "indexmap", "serde_core", @@ -1969,27 +2024,27 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.0.0+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" -version = "1.0.9+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.0.6+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tower" @@ -2008,20 +2063,20 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.8" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.13.0", "bytes", "futures-util", "http", "http-body", - "iri-string", "pin-project-lite", "tower", "tower-layer", "tower-service", + "url", ] [[package]] @@ -2069,9 +2124,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.22" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" dependencies = [ "matchers", "nu-ansi-term", @@ -2099,9 +2154,9 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-segmentation" -version = "1.12.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" @@ -2187,18 +2242,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.2+wasi-0.2.9" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.114" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" dependencies = [ "cfg-if", "once_cell", @@ -2209,23 +2264,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.64" +version = "0.4.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +checksum = "503b14d284f2c8dac03b819967e155ea753f573586193b2b2c95990cb5d69280" dependencies = [ - "cfg-if", - "futures-util", "js-sys", - "once_cell", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.114" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2233,9 +2284,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.114" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" dependencies = [ "bumpalo", "proc-macro2", @@ -2246,18 +2297,18 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.114" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.91" +version = "0.3.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d" dependencies = [ "js-sys", "wasm-bindgen", @@ -2275,9 +2326,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.6" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca" +checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" dependencies = [ "rustls-pki-types", ] @@ -2348,15 +2399,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -2384,21 +2426,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-targets" version = "0.52.6" @@ -2432,12 +2459,6 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -2450,12 +2471,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -2468,12 +2483,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -2498,12 +2507,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -2516,12 +2519,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -2534,12 +2531,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -2552,12 +2543,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -2572,27 +2557,27 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.7.14" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" [[package]] name = "wit-bindgen" -version = "0.51.0" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2601,9 +2586,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", @@ -2613,18 +2598,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.40" +version = "0.8.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a789c6e490b576db9f7e6b6d661bcc9799f7c0ac8352f56ea20193b2681532e5" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.40" +version = "0.8.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" dependencies = [ "proc-macro2", "quote", @@ -2633,18 +2618,18 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", @@ -2654,15 +2639,15 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" dependencies = [ "displaydoc", "yoke", @@ -2671,9 +2656,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" dependencies = [ "yoke", "zerofrom", @@ -2682,9 +2667,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", From 1cc25daa2e19a521bb0a4ff787145879f68004bc Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 24 Jun 2026 01:59:56 -0400 Subject: [PATCH 18/40] 0.6.3 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 890ad46..6c13ea2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.6.2" +version = "0.6.3" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index e59be51..c71754d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.6.2" +version = "0.6.3" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 0fe3c7e8c9e0c451c474116d41e6e0e569e65bef Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 29 Jun 2026 11:38:48 -0400 Subject: [PATCH 19/40] Release ordering for CI/CD publishing - Refactor release assets workflow: - Updated dependency versions for `actions/checkout`. - Centralized logic for publishing releases and updating Homebrew tap. - Secure publish script: - Mandated explicit use of `HOMEBREW_TAP_TOKEN` in `publish-if-complete.sh`. - Fix release notes formatting: - Adjusted markdown markers in `render-release-notes.sh` from hyphens to escaped asterisks. --- .github/workflows/release-assets.yml | 25 ++++++++++++++++++------- devops/publish-if-complete.sh | 2 +- devops/render-release-notes.sh | 6 +++--- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml index 6e8c63c..4086c65 100644 --- a/.github/workflows/release-assets.yml +++ b/.github/workflows/release-assets.yml @@ -83,7 +83,7 @@ jobs: fi - name: Check out tagged source - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: ref: ${{ steps.meta.outputs.tag }} @@ -133,12 +133,6 @@ jobs: GH_TOKEN: ${{ github.token }} run: gh release upload "${{ steps.meta.outputs.tag }}" "$ASSET_PATH" --clobber - - name: Publish release if all assets are present - env: - GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} - shell: bash - run: bash devops/publish-if-complete.sh "${{ steps.meta.outputs.tag }}" - - name: Add run summary shell: bash run: | @@ -151,3 +145,20 @@ jobs: echo "- Triggered by: ${{ inputs.source_run_url }}" fi } >> "$GITHUB_STEP_SUMMARY" + + publish-release: + name: Publish release + needs: build-release-assets + runs-on: ubuntu-24.04 + steps: + - name: Check out source + uses: actions/checkout@v7 + with: + ref: ${{ inputs.tag }} + + - name: Publish release and trigger Homebrew tap update + env: + GH_TOKEN: ${{ github.token }} + HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + shell: bash + run: bash devops/publish-if-complete.sh "${{ inputs.tag }}" diff --git a/devops/publish-if-complete.sh b/devops/publish-if-complete.sh index 3904e8a..789e9ce 100755 --- a/devops/publish-if-complete.sh +++ b/devops/publish-if-complete.sh @@ -28,7 +28,7 @@ gh release edit "${TAG}" --draft=false echo "Published." echo "Triggering Homebrew tap formula update..." -if gh workflow run update-formula.yml \ +if GH_TOKEN="${HOMEBREW_TAP_TOKEN:-}" gh workflow run update-formula.yml \ --repo MikeGarde/homebrew-tap \ -f formula=commitbot \ -f repo=MikeGarde/commitbot \ diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh index 07cc1d9..2b9a280 100644 --- a/devops/render-release-notes.sh +++ b/devops/render-release-notes.sh @@ -21,9 +21,9 @@ cat < Date: Mon, 29 Jun 2026 11:46:46 -0400 Subject: [PATCH 20/40] 0.6.4 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6c13ea2..369687a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.6.3" +version = "0.6.4" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index c71754d..2052364 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.6.3" +version = "0.6.4" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 137aed353e5480549c024c08f03401de9afd49a4 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 29 Jun 2026 12:57:02 -0400 Subject: [PATCH 21/40] Standardize release artifact naming conventions - Update CI workflows (`release-assets.yml`) to use explicit `asset_target` definitions for asset packaging. - Refactor build scripts and tasks to standardize artifact filenames, enforcing OS-before-arch order in all generated names. - Adjust validation and documentation scripts to consume the new standardized naming format. --- .github/workflows/release-assets.yml | 9 +++++++-- Taskfile.yaml | 4 ++-- devops/publish-if-complete.sh | 14 +++++++------- devops/render-release-notes.sh | 8 ++++---- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml index 4086c65..5018508 100644 --- a/.github/workflows/release-assets.yml +++ b/.github/workflows/release-assets.yml @@ -35,6 +35,7 @@ jobs: - name: Linux arm64 runner: ubuntu-24.04-arm target: aarch64-unknown-linux-gnu + asset_target: unknown-linux-gnu-aarch64 archive_ext: tar.gz binary_name: commitbot install_cmd: "" @@ -42,6 +43,7 @@ jobs: - name: Linux x86_64 runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu + asset_target: unknown-linux-gnu-x86_64 archive_ext: tar.gz binary_name: commitbot install_cmd: "" @@ -49,6 +51,7 @@ jobs: - name: Amazon Linux / CentOS / RHEL arm64 runner: ubuntu-24.04-arm target: aarch64-unknown-linux-musl + asset_target: unknown-linux-musl-aarch64 archive_ext: tar.gz binary_name: commitbot install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools @@ -56,6 +59,7 @@ jobs: - name: Amazon Linux / CentOS / RHEL x86_64 runner: ubuntu-24.04 target: x86_64-unknown-linux-musl + asset_target: unknown-linux-musl-x86_64 archive_ext: tar.gz binary_name: commitbot install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools @@ -63,6 +67,7 @@ jobs: - name: Windows x86_64 runner: ubuntu-24.04 target: x86_64-pc-windows-gnu + asset_target: pc-windows-gnu-x86_64 archive_ext: zip binary_name: commitbot.exe install_cmd: sudo apt-get update && sudo apt-get install -y mingw-w64 @@ -113,7 +118,7 @@ jobs: shell: bash run: | set -euo pipefail - asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.target }}.tar.gz" + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.tar.gz" tar -C "target/${{ matrix.target }}/release" -czf "$asset" "${{ matrix.binary_name }}" echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" @@ -122,7 +127,7 @@ jobs: shell: bash run: | set -euo pipefail - asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.target }}.zip" + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.zip" cd "target/${{ matrix.target }}/release" zip "../../../${asset}" "${{ matrix.binary_name }}" cd - diff --git a/Taskfile.yaml b/Taskfile.yaml index 4a4d4da..044f1af 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -98,11 +98,11 @@ tasks: echo "Packaging into dist with version {{.VERSION}}..." tar -C target/aarch64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-aarch64-apple-darwin.tar.gz \ + -czf dist/commitbot-{{.VERSION}}-apple-darwin-aarch64.tar.gz \ commitbot tar -C target/x86_64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-x86_64-apple-darwin.tar.gz \ + -czf dist/commitbot-{{.VERSION}}-apple-darwin-x86_64.tar.gz \ commitbot echo "Artifacts created:" diff --git a/devops/publish-if-complete.sh b/devops/publish-if-complete.sh index 789e9ce..75b5d0f 100755 --- a/devops/publish-if-complete.sh +++ b/devops/publish-if-complete.sh @@ -5,13 +5,13 @@ set -euo pipefail TAG="${1:?usage: publish-if-complete.sh }" EXPECTED=( - "commitbot-${TAG}-aarch64-apple-darwin.tar.gz" - "commitbot-${TAG}-x86_64-apple-darwin.tar.gz" - "commitbot-${TAG}-aarch64-unknown-linux-gnu.tar.gz" - "commitbot-${TAG}-x86_64-unknown-linux-gnu.tar.gz" - "commitbot-${TAG}-aarch64-unknown-linux-musl.tar.gz" - "commitbot-${TAG}-x86_64-unknown-linux-musl.tar.gz" - "commitbot-${TAG}-x86_64-pc-windows-gnu.zip" + "commitbot-${TAG}-apple-darwin-aarch64.tar.gz" + "commitbot-${TAG}-apple-darwin-x86_64.tar.gz" + "commitbot-${TAG}-unknown-linux-gnu-aarch64.tar.gz" + "commitbot-${TAG}-unknown-linux-gnu-x86_64.tar.gz" + "commitbot-${TAG}-unknown-linux-musl-aarch64.tar.gz" + "commitbot-${TAG}-unknown-linux-musl-x86_64.tar.gz" + "commitbot-${TAG}-pc-windows-gnu-x86_64.zip" ) ACTUAL="$(gh release view "${TAG}" --json assets --jq '[.assets[].name]')" diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh index 2b9a280..d2b0e8a 100644 --- a/devops/render-release-notes.sh +++ b/devops/render-release-notes.sh @@ -16,10 +16,10 @@ cat < Date: Mon, 29 Jun 2026 14:34:47 -0400 Subject: [PATCH 22/40] Simplify and stabilize release process logic - Refactor `release.yml` to use only manual workflow dispatch inputs, removing reliance on complex event triggers and simplifying context resolution. - Update `ga-release-plan.sh` by standardizing version validation to strictly enforce semantic versioning against existing tags. - Streamline the release script arguments and output reporting for clearer version calculation focus. --- .github/workflows/release.yml | 89 ++-------------------------- devops/ga-release-plan.sh | 106 ++++++++-------------------------- 2 files changed, 29 insertions(+), 166 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ff8d75a..e76d072 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,113 +14,44 @@ on: description: Release version (X.Y.Z) required: true type: string - pull_request: - types: [closed] - branches: - - develop - - main permissions: actions: write contents: write - pull-requests: read concurrency: - group: release-${{ github.event_name == 'workflow_dispatch' && inputs.target_branch || github.event.pull_request.base.ref }} + group: release-${{ inputs.target_branch }} cancel-in-progress: false env: CARGO_TERM_COLOR: always - MAIN_BASE_VERSION: ${{ vars.MAIN_BASE_VERSION }} - DEVELOP_BASE_VERSION: ${{ vars.DEVELOP_BASE_VERSION }} jobs: plan: - if: github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true runs-on: ubuntu-latest outputs: - should_release: ${{ steps.plan.outputs.should_release }} - reason: ${{ steps.plan.outputs.reason }} - bump: ${{ steps.plan.outputs.bump }} - base_version: ${{ steps.plan.outputs.base_version }} previous_version: ${{ steps.plan.outputs.previous_version }} version: ${{ steps.plan.outputs.version }} target_branch: ${{ steps.plan.outputs.target_branch }} - source_branch: ${{ steps.plan.outputs.source_branch }} - merge_sha: ${{ steps.context.outputs.merge_sha }} steps: - name: Checkout selected branch - if: github.event_name == 'workflow_dispatch' uses: actions/checkout@v4 with: ref: ${{ inputs.target_branch }} fetch-depth: 0 - - name: Checkout merge commit - if: github.event_name == 'pull_request' - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.merge_commit_sha }} - fetch-depth: 0 - - name: Fetch tags run: git fetch --force --tags - - name: Resolve base versions - id: bases - shell: bash - run: | - set -euo pipefail - - current_version="$( - sed -nE 's/^version = "([0-9]+\.[0-9]+\.[0-9]+)"/\1/p' Cargo.toml | head -n1 - )" - - if [[ -z "${current_version}" ]]; then - echo "Could not determine the current Cargo version." >&2 - exit 1 - fi - - echo "main_base_version=${MAIN_BASE_VERSION:-$current_version}" >> "$GITHUB_OUTPUT" - echo "develop_base_version=${DEVELOP_BASE_VERSION:-$current_version}" >> "$GITHUB_OUTPUT" - - - name: Resolve release context - id: context - shell: bash - run: | - set -euo pipefail - - if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then - echo "target_branch=${{ inputs.target_branch }}" >> "$GITHUB_OUTPUT" - echo "source_branch=workflow_dispatch" >> "$GITHUB_OUTPUT" - echo "release_version=${{ inputs.version }}" >> "$GITHUB_OUTPUT" - echo "merge_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - else - echo "target_branch=${{ github.event.pull_request.base.ref }}" >> "$GITHUB_OUTPUT" - echo "source_branch=${{ github.event.pull_request.head.ref }}" >> "$GITHUB_OUTPUT" - echo "release_version=" >> "$GITHUB_OUTPUT" - echo "merge_sha=${{ github.event.pull_request.merge_commit_sha }}" >> "$GITHUB_OUTPUT" - fi - - name: Plan release id: plan env: - TARGET_BRANCH: ${{ steps.context.outputs.target_branch }} - SOURCE_BRANCH: ${{ steps.context.outputs.source_branch }} - RELEASE_VERSION: ${{ steps.context.outputs.release_version }} - MAIN_BASE_VERSION: ${{ steps.bases.outputs.main_base_version }} - DEVELOP_BASE_VERSION: ${{ steps.bases.outputs.develop_base_version }} + TARGET_BRANCH: ${{ inputs.target_branch }} + RELEASE_VERSION: ${{ inputs.version }} run: devops/ga-release-plan.sh - - name: Stop on non-release branches - if: steps.plan.outputs.should_release != 'true' - shell: bash - run: | - echo "Skipping release: ${{ steps.plan.outputs.reason }}" - prepare_release: needs: plan - if: needs.plan.outputs.should_release == 'true' runs-on: ubuntu-latest outputs: release_sha: ${{ steps.release_commit.outputs.release_sha }} @@ -142,17 +73,6 @@ jobs: exit 1 fi - - name: Ensure release commit includes merged change - if: github.event_name == 'pull_request' - shell: bash - run: | - set -euo pipefail - - if ! git merge-base --is-ancestor "${{ needs.plan.outputs.merge_sha }}" HEAD; then - echo "The target branch no longer contains merge commit ${{ needs.plan.outputs.merge_sha }}." >&2 - exit 1 - fi - - name: Configure git author run: | git config user.name "github-actions[bot]" @@ -189,7 +109,6 @@ jobs: create_release: needs: [plan, prepare_release] - if: needs.plan.outputs.should_release == 'true' runs-on: ubuntu-latest steps: - name: Check out release commit @@ -205,7 +124,7 @@ jobs: set -euo pipefail NOTES_ARGS=() - if [[ "${{ needs.plan.outputs.previous_version }}" != "${{ needs.plan.outputs.base_version }}" ]]; then + if [[ -n "${{ needs.plan.outputs.previous_version }}" ]]; then NOTES_ARGS+=(-f previous_tag_name="${{ needs.plan.outputs.previous_version }}") fi diff --git a/devops/ga-release-plan.sh b/devops/ga-release-plan.sh index 41e95c0..f849235 100755 --- a/devops/ga-release-plan.sh +++ b/devops/ga-release-plan.sh @@ -3,122 +3,66 @@ set -euo pipefail TARGET_BRANCH="${TARGET_BRANCH:-${1:-}}" -SOURCE_BRANCH="${SOURCE_BRANCH:-${2:-}}" -MAIN_BASE_VERSION="${MAIN_BASE_VERSION:-}" -DEVELOP_BASE_VERSION="${DEVELOP_BASE_VERSION:-}" -RELEASE_VERSION="${RELEASE_VERSION:-}" +RELEASE_VERSION="${RELEASE_VERSION:-${2:-}}" if [[ -z "${TARGET_BRANCH}" ]]; then - echo "usage: TARGET_BRANCH= SOURCE_BRANCH= RELEASE_VERSION=X.Y.Z MAIN_BASE_VERSION=X.Y.Z DEVELOP_BASE_VERSION=X.Y.Z $0" >&2 + echo "usage: TARGET_BRANCH= RELEASE_VERSION=X.Y.Z $0" >&2 exit 1 fi -semver_pattern='^[0-9]+\.[0-9]+\.[0-9]+$' - -require_semver() { - local value="$1" - local label="$2" - - if [[ ! "${value}" =~ ${semver_pattern} ]]; then - echo "${label} must be a semantic version like 1.0.0" >&2 - exit 1 - fi -} - -require_semver "${MAIN_BASE_VERSION}" "MAIN_BASE_VERSION" -require_semver "${DEVELOP_BASE_VERSION}" "DEVELOP_BASE_VERSION" - -if [[ -n "${RELEASE_VERSION}" ]]; then - require_semver "${RELEASE_VERSION}" "RELEASE_VERSION" -fi - case "${TARGET_BRANCH}" in - main) - BASE_VERSION="${MAIN_BASE_VERSION}" - ;; - develop) - BASE_VERSION="${DEVELOP_BASE_VERSION}" - ;; + main|develop) ;; *) echo "Unsupported target branch: ${TARGET_BRANCH}" >&2 exit 1 ;; esac -BASE_MAJOR="${BASE_VERSION%%.*}" -TAG_PATTERN="^${BASE_MAJOR}\\.[0-9]+\\.[0-9]+$" +semver_pattern='^[0-9]+\.[0-9]+\.[0-9]+$' + +if [[ ! "${RELEASE_VERSION}" =~ ${semver_pattern} ]]; then + echo "RELEASE_VERSION must be a semantic version like 1.0.0" >&2 + exit 1 +fi + +# Newest released version (empty when no semver tags exist yet). PREVIOUS_VERSION="$( git tag --list \ - | grep -E "${TAG_PATTERN}" || true + | grep -E "${semver_pattern}" || true )" PREVIOUS_VERSION="$( printf '%s\n' "${PREVIOUS_VERSION}" \ | sort -V \ | tail -n 1 )" -PREVIOUS_VERSION="${PREVIOUS_VERSION:-${BASE_VERSION}}" + +# Baseline for the next version: the newest of the latest tag and the version +# currently in Cargo.toml, so the requested version can never move backwards. +CARGO_VERSION="$( + sed -nE 's/^version = "([0-9]+\.[0-9]+\.[0-9]+)"/\1/p' Cargo.toml | head -n1 +)" CURRENT_VERSION="$( - printf '%s\n%s\n' "${BASE_VERSION}" "${PREVIOUS_VERSION}" \ + printf '%s\n%s\n' "${PREVIOUS_VERSION}" "${CARGO_VERSION}" \ | sort -V \ | tail -n 1 )" -if [[ -n "${RELEASE_VERSION}" ]]; then - SHOULD_RELEASE="true" - REASON="" - BUMP="manual" - - RELEASE_MAJOR="${RELEASE_VERSION%%.*}" - if [[ "${RELEASE_MAJOR}" != "${BASE_MAJOR}" ]]; then - echo "RELEASE_VERSION ${RELEASE_VERSION} does not match the ${TARGET_BRANCH} release line ${BASE_MAJOR}.x.x" >&2 - exit 1 - fi - - if [[ "$(printf '%s\n%s\n' "${CURRENT_VERSION}" "${RELEASE_VERSION}" | sort -V | tail -n 1)" != "${RELEASE_VERSION}" ]] || [[ "${RELEASE_VERSION}" == "${CURRENT_VERSION}" ]]; then - echo "RELEASE_VERSION ${RELEASE_VERSION} must be newer than ${CURRENT_VERSION}" >&2 - exit 1 - fi - - VERSION="${RELEASE_VERSION}" -elif [[ "${SOURCE_BRANCH}" == feat/* ]]; then - SHOULD_RELEASE="true" - REASON="" - BUMP="minor" - IFS='.' read -r MAJOR MINOR PATCH <<< "${CURRENT_VERSION}" - MINOR=$((MINOR + 1)) - PATCH=0 - VERSION="${MAJOR}.${MINOR}.${PATCH}" -elif [[ "${SOURCE_BRANCH}" == bugfix/* ]]; then - SHOULD_RELEASE="true" - REASON="" - BUMP="patch" - IFS='.' read -r MAJOR MINOR PATCH <<< "${CURRENT_VERSION}" - PATCH=$((PATCH + 1)) - VERSION="${MAJOR}.${MINOR}.${PATCH}" -else - SHOULD_RELEASE="false" - REASON="Source branch must start with feat/ or bugfix/." - BUMP="none" - VERSION="" +newest="$(printf '%s\n%s\n' "${CURRENT_VERSION}" "${RELEASE_VERSION}" | sort -V | tail -n 1)" +if [[ "${newest}" != "${RELEASE_VERSION}" ]] || [[ "${RELEASE_VERSION}" == "${CURRENT_VERSION}" ]]; then + echo "RELEASE_VERSION ${RELEASE_VERSION} must be newer than ${CURRENT_VERSION}" >&2 + exit 1 fi +VERSION="${RELEASE_VERSION}" + if [[ -n "${GITHUB_OUTPUT:-}" ]]; then { - echo "should_release=${SHOULD_RELEASE}" - echo "reason=${REASON}" - echo "bump=${BUMP}" - echo "base_version=${BASE_VERSION}" echo "previous_version=${PREVIOUS_VERSION}" echo "version=${VERSION}" echo "target_branch=${TARGET_BRANCH}" - echo "source_branch=${SOURCE_BRANCH}" } >> "${GITHUB_OUTPUT}" fi -echo "should_release=${SHOULD_RELEASE}" -echo "reason=${REASON}" -echo "bump=${BUMP}" -echo "base_version=${BASE_VERSION}" echo "previous_version=${PREVIOUS_VERSION}" echo "version=${VERSION}" From 780fcdc47750d65d22495b3460ff31a9584fabda Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 24 Jul 2026 22:04:28 -0400 Subject: [PATCH 23/40] Add tempfile and improve git error handling - Add `tempfile` as a dev-dependency in `Cargo.toml` to enable temporary file handling in tests - Update `Cargo.lock` to lock `tempfile` and its transitive dependencies for reproducible CI - Improve `src/git.rs` error handling to include git's `stderr` when present, falling back to exit status if not - Make `staged_diff_for_file` robust when run from subdirectories by anchoring the pathspec to the repo root with `:/path`; document this behavior - Extend `tests/git.rs` with a focused test for `staged_diff_for_file` and `staged_files` from a subdirectory; add helper `repo_with_staged_nested_file` to create a temp repo with a nested staged change - Update imports in tests to include `staged_diff_for_file` and `staged_files` to exercise staging-related functionality --- Cargo.lock | 20 ++++++++++++++++++ Cargo.toml | 1 + src/git.rs | 22 +++++++++++++++++--- tests/git.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 98 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 369687a..d55320d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -273,6 +273,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "tempfile", "toml", ] @@ -511,6 +512,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1910,6 +1917,19 @@ dependencies = [ "libc", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "termtree" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index 2052364..fe2867b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ toml = "^1.0" [dev-dependencies] assert_cmd = "^2.1.1" predicates = "^3.1.3" +tempfile = "^3.10" [profile.release] opt-level = 3 diff --git a/src/git.rs b/src/git.rs index 20f3879..5a3dbc2 100644 --- a/src/git.rs +++ b/src/git.rs @@ -91,10 +91,20 @@ pub fn git_output(args: &[&str]) -> Result { .with_context(|| format!("failed to run git {:?}", args))?; if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stderr = stderr.trim(); + if stderr.is_empty() { + return Err(anyhow!( + "git {:?} exited with status {:?}", + args, + output.status.code() + )); + } return Err(anyhow!( - "git {:?} exited with status {:?}", + "git {:?} exited with status {:?}: {}", args, - output.status.code() + output.status.code(), + stderr )); } @@ -137,8 +147,14 @@ pub fn staged_files() -> Result> { } /// Get per-file staged diff. +/// +/// `staged_files` returns paths relative to the repo root, but a bare pathspec +/// is resolved by git relative to the current working directory. Anchor it +/// with the `:/` top-level magic pathspec so this still works when commitbot +/// is invoked from a subdirectory of the repo. pub fn staged_diff_for_file(path: &str) -> Result { - let diff = git_output(&["diff", "--cached", "--", path])?; + let pathspec = format!(":/{path}"); + let diff = git_output(&["diff", "--cached", "--", &pathspec])?; Ok(diff) } diff --git a/tests/git.rs b/tests/git.rs index 2589c68..9f41680 100644 --- a/tests/git.rs +++ b/tests/git.rs @@ -1,7 +1,41 @@ use commitbot::git::{ find_first_pr_number, format_pr_commit_appendix_with_remote, parse_remote_repo, - short_commit_hash, split_diff_by_file, PrItem, PrSummaryMode, + short_commit_hash, split_diff_by_file, staged_diff_for_file, staged_files, PrItem, + PrSummaryMode, }; +use std::process::Command; + +/// Set up a throwaway git repo with a staged change in a nested file, and +/// return its tempdir handle plus the nested directory's path. +fn repo_with_staged_nested_file() -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let root = dir.path(); + + let run = |args: &[&str]| { + let status = Command::new("git") + .args(args) + .current_dir(root) + .status() + .expect("run git"); + assert!(status.success(), "git {:?} failed", args); + }; + + run(&["init", "-q"]); + run(&["config", "user.email", "test@example.com"]); + run(&["config", "user.name", "Test"]); + + let nested_dir = root.join("app").join("Models"); + std::fs::create_dir_all(&nested_dir).expect("mkdir"); + let file = nested_dir.join("OrderItem.php"); + std::fs::write(&file, "original\n").expect("write"); + run(&["add", "."]); + run(&["commit", "-q", "-m", "initial"]); + + std::fs::write(&file, "original\nchanged\n").expect("rewrite"); + run(&["add", "."]); + + (dir, nested_dir) +} #[test] fn parses_github_ssh_remote() { @@ -136,6 +170,29 @@ fn short_commit_hash_short_input() { assert_eq!(result, "abc"); } +#[test] +fn staged_diff_for_file_works_from_subdirectory() { + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = (|| { + let files = staged_files()?; + assert_eq!(files, vec!["app/Models/OrderItem.php".to_string()]); + + let diff = staged_diff_for_file(&files[0])?; + assert!( + diff.contains("+changed"), + "expected diff to contain the staged change, got: {diff:?}" + ); + anyhow::Ok(()) + })(); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + result.expect("staged diff lookup from subdirectory"); +} + #[test] fn pr_summary_mode_as_str() { assert_eq!(PrSummaryMode::ByCommits.as_str(), "commits"); From 8d39519408f858b89084991267dfce842af224b7 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 12 Aug 2026 21:13:37 -0400 Subject: [PATCH 24/40] Add configurable HTTP timeouts and observability - devops/render-release-notes.sh: Extend release notes to cover Amazon Linux (musl) installation with a dedicated section and a one-shot install command that downloads the linux-musl tarball for the current architecture and installs to /usr/local/bin. - devops/render-release-notes.sh: Acknowledge the need for a musl-compatible build and document a curl | tar approach for easy installation on Amazon Linux. - src/config.rs: Add request_timeout_secs with default 90s across default, file, repo, and environment sources; extend Config and FileConfig to store and propagate the new timeout. - src/config.rs: Introduce u64-based resolution paths (get_u64, file_u64, env_u64) to align with existing numeric config handling. - src/config.rs: Ensure proper precedence and log the decision source (Hardcoded/FileDefault/FileRepo/Env) when resolving the timeout. - src/llm/ollama.rs: Add configurable HTTP timeout and latency timing for Ollama requests; include explicit request/response timing logs for streaming and non-streaming paths. - src/llm/ollama.rs: Skip real Ollama /api/tags validation to reduce network dependency; defer model listing to a separate command. - src/llm/ollama.rs: Update tests to reflect the new timeout parameter and adjusted tags behavior for compatibility. - src/llm/openai.rs: Add configurable HTTP timeout via timeout_secs to OpenAiClient::new, replacing the hard-coded 90s timeout. - src/llm/openai.rs: Add timing instrumentation to log non-stream OpenAI response times and total streaming response time for observability. - src/llm/openai.rs: Update tests to pass the new timeout parameter when constructing the client. - src/main.rs: Instrument performance timing around file summarization, commit message generation, and PR message generation; expose elapsed durations in user-visible output. - src/main.rs: Apply minor formatting/bracing/whitespace adjustments with no functional impact. - src/setup.rs: Wire cfg.request_timeout_secs through to OpenAiClient and OllamaClient constructors; include timeout value in debug logs for both providers. Token usage: prompt=4924, completion=5829, total=10753 --- devops/render-release-notes.sh | 6 ++++ src/config.rs | 45 ++++++++++++++++++++++++ src/llm/ollama.rs | 64 ++++++++-------------------------- src/llm/openai.rs | 13 +++++-- src/main.rs | 20 ++++++++--- src/setup.rs | 12 ++++--- 6 files changed, 99 insertions(+), 61 deletions(-) diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh index d2b0e8a..5aa0411 100644 --- a/devops/render-release-notes.sh +++ b/devops/render-release-notes.sh @@ -25,6 +25,12 @@ cat <, pub max_concurrent_requests: Option, pub stream: Option, + pub request_timeout_secs: Option, } /// Root of the TOML file: @@ -169,6 +174,7 @@ impl<'a> ConfigResolver<'a> { "base_url" => Some("COMMITBOT_BASE_URL"), "max_concurrent_requests" => Some("COMMITBOT_MAX_CONCURRENT_REQUESTS"), "stream" => Some("COMMITBOT_STREAM"), + "request_timeout_secs" => Some("COMMITBOT_REQUEST_TIMEOUT_SECS"), _ => None, } } @@ -202,6 +208,18 @@ impl<'a> ConfigResolver<'a> { } } + fn file_u64(&self, key: &str, repo: bool) -> Option { + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; + match key { + "request_timeout_secs" => cfg.request_timeout_secs, + _ => None, + } + } + fn file_bool(&self, key: &str, repo: bool) -> Option { let cfg = if repo { &self.file_repo @@ -226,6 +244,11 @@ impl<'a> ConfigResolver<'a> { env::var(env_key).ok().and_then(|s| s.parse::().ok()) } + fn env_u64(&self, key: &str) -> Option { + let env_key = self.env_key_for(key)?; + env::var(env_key).ok().and_then(|s| s.parse::().ok()) + } + fn env_bool(&self, key: &str) -> Option { let env_key = self.env_key_for(key)?; env::var(env_key).ok().and_then(|s| s.parse::().ok()) @@ -429,6 +452,28 @@ impl<'a> ConfigResolver<'a> { value } + /// Resolve a u64. + pub fn get_u64(&self, key: &str, default: u64) -> u64 { + let mut value = default; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_u64(key, false) { + value = v; + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_u64(key, true) { + value = v; + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_u64(key) { + value = v; + src = ValueSource::Env; + } + + self.log_decision(key, &value, src); + value + } + /// Resolve a bool. pub fn get_bool(&self, key: &str, default: bool) -> bool { let mut value = default; diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index f0b71ba..5c9778e 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -2,10 +2,10 @@ use anyhow::{Result, anyhow}; use log; use musli::json; use musli::{Decode, Encode}; -use reqwest::StatusCode; use reqwest::blocking::Client; use std::io::BufReader; use std::sync::Mutex; +use std::time::Instant; use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; @@ -64,8 +64,9 @@ struct TokenUsage { } impl OllamaClient { - pub fn new(base_url: impl Into, model: impl Into, stream: bool) -> Self { + pub fn new(base_url: impl Into, model: impl Into, stream: bool, timeout_secs: u64) -> Self { let http = Client::builder() + .timeout(std::time::Duration::from_secs(timeout_secs)) .build() .expect("failed to build HTTP client"); Self { @@ -115,6 +116,7 @@ impl OllamaClient { let url = format!("{}/api/chat", self.base_url); + let t0 = Instant::now(); let resp = self .http .post(&url) @@ -127,13 +129,16 @@ impl OllamaClient { if stream { let reader = BufReader::new(resp); - return read_stream_to_string(reader, parse_stream_line); + let result = read_stream_to_string(reader, parse_stream_line); + log::debug!("Ollama response time: {:.2?}", t0.elapsed()); + return result; } let resp_text = resp .text() .map_err(|e| anyhow!("Failed to read Ollama response body: {e}"))?; + log::debug!("Ollama response time: {:.2?}", t0.elapsed()); log::trace!("Ollama raw JSON response: {resp_text}"); #[derive(Debug, Decode)] @@ -194,50 +199,9 @@ fn parse_stream_line(line: &str) -> Result> { impl LlmClient for OllamaClient { fn validate_model(&self) -> Result<()> { - let url = self.tags_url(); - let resp = self - .http - .get(&url) - .send() - .map_err(|e| anyhow!("Error calling Ollama at {url}: {e}"))?; - - if resp.status() != StatusCode::OK { - let status = resp.status(); - let body = resp.text().unwrap_or_default(); - return Err(anyhow!( - "Ollama model validation failed at {url}: HTTP {} - {}", - status.as_u16(), - body - )); - } - - let body = resp - .text() - .map_err(|e| anyhow!("Failed to read Ollama tags response from {url}: {e}"))?; - let parsed: OllamaTagsResponse = json::from_str(&body) - .map_err(|e| anyhow!("Failed to decode Ollama tags response from {url}: {e}"))?; - - if parsed.models.iter().any(|model| model.name == self.model) { - return Ok(()); - } - - let available = parsed - .models - .iter() - .map(|model| model.name.as_str()) - .collect::>() - .join(", "); - - Err(anyhow!( - "Model {:?} was not found at {}. Available models: {}", - self.model, - url, - if available.is_empty() { - "" - } else { - &available - } - )) + // Skipping model validation for Ollama; use a future "list models" command + // to query /api/tags if the user requests it. + Ok(()) } fn summarize_file( @@ -309,19 +273,19 @@ mod tests { #[test] fn trims_trailing_slash_in_tags_url() { - let client = OllamaClient::new("http://localhost:11434/", "qwen3-coder:30b", false); + let client = OllamaClient::new("http://localhost:11434/", "gemma4:31b", false, 90); assert_eq!(client.tags_url(), "http://localhost:11434/api/tags"); } #[test] fn decodes_ollama_tags_payload() { - let body = r#"{"models":[{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#; + let body = r#"{"models":[{"name":"gemma4:31b"},{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#; let parsed: OllamaTagsResponse = json::from_str(body).expect("valid tags payload"); assert!(parsed .models .iter() - .any(|model| model.name == "qwen3-coder:30b")); + .any(|model| model.name == "gemma4:31b")); assert!(!parsed .models .iter() diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 91c383f..72d14d1 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -81,9 +81,9 @@ struct TokenUsage { } impl OpenAiClient { - pub fn new(api_key: String, model: String, api_base_url: String, stream: bool) -> Self { + pub fn new(api_key: String, model: String, api_base_url: String, stream: bool, timeout_secs: u64) -> Self { let client = Client::builder() - .timeout(Duration::from_secs(90)) + .timeout(Duration::from_secs(timeout_secs)) .build() .expect("failed to build HTTP client"); @@ -122,6 +122,7 @@ impl OpenAiClient { log::info!("Calling OpenAI model {:?}", &req.model); + let t0 = std::time::Instant::now(); let resp = self .client .post(url) @@ -141,6 +142,7 @@ impl OpenAiClient { } let chat_resp: ChatResponse = resp.json().context("failed to parse OpenAI response")?; + log::debug!("OpenAI response time: {:.2?}", t0.elapsed()); let content = chat_resp .choices .first() @@ -164,6 +166,7 @@ impl OpenAiClient { log::info!("Streaming OpenAI model {:?}", &req.model); + let t0 = std::time::Instant::now(); let resp = self .client .post(url) @@ -183,7 +186,9 @@ impl OpenAiClient { } let reader = BufReader::new(resp); - read_stream_to_string(reader, parse_stream_line) + let result = read_stream_to_string(reader, parse_stream_line); + log::debug!("OpenAI streaming response time: {:.2?}", t0.elapsed()); + result } } @@ -401,6 +406,7 @@ mod tests { "gpt-5-nano".into(), "https://api.openai.com".into(), false, + 90, ); assert_eq!( @@ -416,6 +422,7 @@ mod tests { "gpt-5-nano".into(), "https://api.openai.com/v1".into(), false, + 90, ); assert_eq!( diff --git a/src/main.rs b/src/main.rs index 32142bd..714085e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -188,6 +188,7 @@ fn summarize_files_concurrently( scope.spawn(move || { log::debug!("Summarizing file: {}", path); + let t0 = std::time::Instant::now(); let res = (|| -> Result { let fc = FileChange { path, @@ -205,6 +206,7 @@ fn summarize_files_concurrently( )?; Ok(summary) })(); + let elapsed = t0.elapsed(); pb.inc(1); @@ -212,10 +214,10 @@ fn summarize_files_concurrently( match &res { Ok(summary) => { let snippet = preview_snippet(summary); - line.finish_with_message(dimmed(&snippet)); + line.finish_with_message(dimmed(&format!("{snippet} ({elapsed:.2?})"))); } Err(err) => { - line.finish_with_message(dimmed(&format!("error: {err}"))); + line.finish_with_message(dimmed(&format!("error: {err} ({elapsed:.2?})"))); } } } @@ -384,12 +386,15 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { if cfg.stream { let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; } else { + let t0 = std::time::Instant::now(); let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; + let elapsed = t0.elapsed(); if msg.ends_with('\n') { print!("{msg}"); } else { println!("{msg}"); } + println!("Commit message generated in {elapsed:.2?}"); } println!(); @@ -518,12 +523,15 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { if cfg.stream { let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; } else { + let t0 = std::time::Instant::now(); let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; + let elapsed = t0.elapsed(); if msg.ends_with('\n') { print!("{msg}"); } else { println!("{msg}"); } + println!("Commit message generated in {elapsed:.2?}"); } println!(); @@ -532,8 +540,8 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { } Ok(()) -} +} fn run_pr( cli: &Cli, cfg: &Config, @@ -583,20 +591,24 @@ fn run_pr( let ticket_summary = resolved_ticket_summary(cli); let _pr_message = if cfg.stream { println!(); + let t0 = std::time::Instant::now(); let msg = llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; - println!(); + println!("\nPR message generated in {:.2?}", t0.elapsed()); msg } else { println!(); + let t0 = std::time::Instant::now(); let msg = llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; + let elapsed = t0.elapsed(); if msg.ends_with('\n') { print!("{msg}"); } else { println!("{msg}"); } + println!("PR message generated in {elapsed:.2?}"); msg }; diff --git a/src/setup.rs b/src/setup.rs index 3e2bd3b..62444e7 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -18,9 +18,10 @@ pub fn build_llm_client(cfg: &Config) -> Result> { .unwrap_or_else(|| "https://api.openai.com".to_string()); log::debug!( - "Using OpenAiClient with model: {} (stream={})", + "Using OpenAiClient with model: {} (stream={}, timeout={}s)", cfg.model, - cfg.stream + cfg.stream, + cfg.request_timeout_secs ); Ok(Box::new(OpenAiClient::new( @@ -28,6 +29,7 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.model.clone(), base_url, cfg.stream, + cfg.request_timeout_secs, ))) } "ollama" => { @@ -37,15 +39,17 @@ pub fn build_llm_client(cfg: &Config) -> Result> { .unwrap_or_else(|| "http://localhost:11434".to_string()); log::debug!( - "Using OllamaClient with model: {} (stream={})", + "Using OllamaClient with model: {} (stream={}, timeout={}s)", cfg.model, - cfg.stream + cfg.stream, + cfg.request_timeout_secs ); Ok(Box::new(OllamaClient::new( base_url, cfg.model.clone(), cfg.stream, + cfg.request_timeout_secs, ))) } other => Err(anyhow!("Unknown provider: {}", other)), From 167902d3cd002854e81a89bd7f9ff0fd0aef39b9 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 10:19:02 -0400 Subject: [PATCH 25/40] Add LM Studio support and generalize OpenAI client - Support `lmstudio` as an LLM provider in config and setup. - Generalize `src/llm/openai.rs` to support any OpenAI-compatible provider. - Allow optional API keys and configurable model validation logic. - Handle flexible base URLs and treat blank URLs as missing values. - Update documentation and configuration tests. --- README.md | 23 +++- commitbot.toml | 11 +- src/cli_args.rs | 2 +- src/config.rs | 9 +- src/llm/openai.rs | 299 ++++++++++++++++++++++++++++++++++++++-------- src/setup.rs | 31 ++++- tests/config.rs | 57 +++++++++ 7 files changed, 375 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index c23f7b0..eb499b5 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ It can summarize diffs, ask you how each file relates to the purpose of the comm - **Interactive “ask” mode** – Classify each file as main, supporting, or consequential. - **Quick mode** – Instantly summarize staged diffs into a commit message. -- **LLM-powered** – Uses OpenAI’s GPT models to generate concise and structured messages. +- **LLM-powered** – Uses OpenAI, or a local model via [Ollama](#providers) or [LM Studio](#providers). - **Configurable** – Choose models, tweak behavior, and set defaults in a config file. - **Pull request summaries** – Generate clean, readable PR descriptions from your commit history. @@ -26,7 +26,7 @@ It can summarize diffs, ask you how each file relates to the purpose of the comm ## Installation -You’ll need an OpenAI API key set as an environment variable: +To use OpenAI (the default provider) you’ll need an API key set as an environment variable: ```bash export OPENAI_API_KEY="sk-..." @@ -126,6 +126,25 @@ model = "gpt-5-nano" --- +## Providers + +Set `provider` to choose a backend. Any of them can be overridden per repository. + +| Provider | Default `url` | API key | +|------------|--------------------------|----------| +| `openai` | `https://api.openai.com` | required | +| `ollama` | `http://localhost:11434` | not used | +| `lmstudio` | `http://localhost:1234` | optional | + +```toml +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +url = "http://192.168.1.16:1234/v1" +``` + +--- + ## Roadmap - [x] Support for local/offline LLMs (Ollama, LM Studio). diff --git a/commitbot.toml b/commitbot.toml index 17c2a88..a2e3aaf 100644 --- a/commitbot.toml +++ b/commitbot.toml @@ -7,14 +7,14 @@ model = "gpt-5-nano" # Optional: OpenAI-style API key (falls back to env OPENAI_API_KEY) openai_api_key = "your api key here" -# Optional: provider base URL (e.g. http://localhost:11434 for Ollama) +# Optional: provider base URL (e.g. http://localhost:11434 for local LLM) url = "https://api.openai.com" # 1 = fully serial, >1 = parallel API calls max_concurrent_requests = 4 -["mikegarde/commitbot"] +["company/repo"] provider = "openai" stream = false model = "gpt-4o-mini" @@ -22,6 +22,13 @@ openai_api_key = "alternative for spend identification" max_concurrent_requests = 8 +["MikeGarde/commitbot"] +provider = "lmstudio" +model = "google/gemma-4-12b-qat" +url = "http://GPU.localdomain:1234/v1" +max_concurrent_requests = 2 + + ["company/enterprise"] # Enterprise / self-hosted style config base_url = "https://enterprise.api.endpoint" diff --git a/src/cli_args.rs b/src/cli_args.rs index dd3b845..7f7544f 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -28,7 +28,7 @@ pub struct Cli { #[arg(short = 'k', long, global = true)] pub api_key: Option, - /// LLM provider / API style (openai or ollama) + /// LLM provider / API style (openai, ollama, or lmstudio) #[arg(long, global = true)] pub provider: Option, diff --git a/src/config.rs b/src/config.rs index 654bce3..3440d8d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; /// Final resolved configuration for commitbot. #[derive(Debug, Clone)] pub struct Config { - /// LLM provider (openai, ollama) + /// LLM provider (openai, ollama, lmstudio) pub provider: String, /// OpenAI API key for authentication (sensitive – redacted in logs) pub openai_api_key: Option, @@ -55,13 +55,16 @@ impl Config { let max_concurrent_requests = r.get_usize("max_concurrent_requests", 4); let stream = r.get_bool("stream", true); - let request_timeout_secs = r.get_u64("request_timeout_secs", 90); + let request_timeout_secs = r.get_u64("request_timeout_secs", 300); // Cleanup: trim stray quotes if any upstream included them let provider = provider.trim_matches('"').to_string(); let model = model.trim_matches('"').to_string(); let openai_api_key = openai_api_key.map(|s| s.trim_matches('"').to_string()); - let base_url = base_url.map(|s| s.trim_matches('"').to_string()); + // A blank url is the same as no url + let base_url = base_url + .map(|s| s.trim_matches('"').trim().to_string()) + .filter(|s| !s.is_empty()); if provider == "openai" && openai_api_key.is_none() { return Err(anyhow!( diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 72d14d1..f4bc392 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -5,7 +5,7 @@ use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; use anyhow::{Context, Result, anyhow}; use reqwest::StatusCode; -use reqwest::blocking::Client; +use reqwest::blocking::{Client, RequestBuilder}; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::time::Duration; @@ -48,6 +48,16 @@ struct ChatUsage { total_tokens: u32, } +#[derive(Deserialize)] +struct ModelListResponse { + data: Vec, +} + +#[derive(Deserialize)] +struct ModelListEntry { + id: String, +} + #[derive(Deserialize)] struct StreamResponse { choices: Vec, @@ -63,13 +73,26 @@ struct StreamDelta { content: Option, } -/// OpenAI-based implementation of LlmClient. +/// How to confirm the configured model exists on the upstream server. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModelValidation { + /// `GET {base}/v1/models/{model}` — OpenAI's retrieve-model endpoint. + Retrieve, + /// `GET {base}/v1/models`, then look for the id in the listing. LM Studio + /// only implements the list endpoint, not retrieve. + List, +} + +/// Client for OpenAI and any server speaking the same chat-completions API. pub struct OpenAiClient { client: Client, - api_key: String, + api_key: Option, model: String, api_base_url: String, stream: bool, + /// Name used in logs and error messages (e.g. "OpenAI", "LM Studio"). + provider_label: String, + model_validation: ModelValidation, usage: Mutex, } @@ -82,6 +105,30 @@ struct TokenUsage { impl OpenAiClient { pub fn new(api_key: String, model: String, api_base_url: String, stream: bool, timeout_secs: u64) -> Self { + Self::openai_compatible( + Some(api_key), + model, + api_base_url, + stream, + timeout_secs, + "OpenAI", + ModelValidation::Retrieve, + ) + } + + /// Client for an OpenAI-compatible server (LM Studio, self-hosted gateways). + /// + /// `api_key` is optional: LM Studio serves unauthenticated requests by + /// default, and omitting the key sends no `Authorization` header at all. + pub fn openai_compatible( + api_key: Option, + model: String, + api_base_url: String, + stream: bool, + timeout_secs: u64, + provider_label: impl Into, + model_validation: ModelValidation, + ) -> Self { let client = Client::builder() .timeout(Duration::from_secs(timeout_secs)) .build() @@ -93,26 +140,42 @@ impl OpenAiClient { model, api_base_url: api_base_url.trim_end_matches('/').to_string(), stream, + provider_label: provider_label.into(), + model_validation, usage: Mutex::new(TokenUsage::default()), } } - fn chat_url(&self) -> String { - if self.api_base_url.ends_with("/v1") { - format!("{}/chat/completions", self.api_base_url) - } else { - format!("{}/v1/chat/completions", self.api_base_url) + /// Attach bearer auth when a key is configured, otherwise send the request + /// unauthenticated. + fn authed(&self, req: RequestBuilder) -> RequestBuilder { + match &self.api_key { + Some(key) => req.bearer_auth(key), + None => req, } } - fn model_url(&self) -> String { + /// Join `path` under `/v1`, tolerating a base URL that already ends in `/v1`. + fn v1_url(&self, path: &str) -> String { if self.api_base_url.ends_with("/v1") { - format!("{}/models/{}", self.api_base_url, self.model) + format!("{}/{}", self.api_base_url, path) } else { - format!("{}/v1/models/{}", self.api_base_url, self.model) + format!("{}/v1/{}", self.api_base_url, path) } } + fn chat_url(&self) -> String { + self.v1_url("chat/completions") + } + + fn model_url(&self) -> String { + self.v1_url(&format!("models/{}", self.model)) + } + + fn models_url(&self) -> String { + self.v1_url("models") + } + fn call_chat(&self, req: &ChatRequest) -> Result { if req.stream { return self.call_chat_streaming(req); @@ -120,34 +183,35 @@ impl OpenAiClient { let url = self.chat_url(); - log::info!("Calling OpenAI model {:?}", &req.model); + log::info!("Calling {} model {:?}", self.provider_label, req.model); let t0 = std::time::Instant::now(); let resp = self - .client - .post(url) - .bearer_auth(&self.api_key) + .authed(self.client.post(&url)) .json(req) .send() - .context("failed to send request to OpenAI")?; + .with_context(|| format!("failed to send request to {} at {}", self.provider_label, url))?; if !resp.status().is_success() { let status = resp.status(); let text = resp.text().unwrap_or_default(); return Err(anyhow!( - "OpenAI API error: HTTP {} - {}", + "{} API error: HTTP {} - {}", + self.provider_label, status.as_u16(), text )); } - let chat_resp: ChatResponse = resp.json().context("failed to parse OpenAI response")?; - log::debug!("OpenAI response time: {:.2?}", t0.elapsed()); + let chat_resp: ChatResponse = resp + .json() + .with_context(|| format!("failed to parse {} response", self.provider_label))?; + log::debug!("{} response time: {:.2?}", self.provider_label, t0.elapsed()); let content = chat_resp .choices .first() .map(|c| c.message.content.clone()) - .ok_or_else(|| anyhow!("no choices returned from OpenAI"))?; + .ok_or_else(|| anyhow!("no choices returned from {}", self.provider_label))?; if let Some(usage) = &chat_resp.usage { // Recover from a poisoned mutex instead of panicking so the CLI @@ -164,22 +228,26 @@ impl OpenAiClient { fn call_chat_streaming(&self, req: &ChatRequest) -> Result { let url = self.chat_url(); - log::info!("Streaming OpenAI model {:?}", &req.model); + log::info!("Streaming {} model {:?}", self.provider_label, req.model); let t0 = std::time::Instant::now(); let resp = self - .client - .post(url) - .bearer_auth(&self.api_key) + .authed(self.client.post(&url)) .json(req) .send() - .context("failed to send streaming request to OpenAI")?; + .with_context(|| { + format!( + "failed to send streaming request to {} at {}", + self.provider_label, url + ) + })?; if !resp.status().is_success() { let status = resp.status(); let text = resp.text().unwrap_or_default(); return Err(anyhow!( - "OpenAI API error: HTTP {} - {}", + "{} API error: HTTP {} - {}", + self.provider_label, status.as_u16(), text )); @@ -187,9 +255,96 @@ impl OpenAiClient { let reader = BufReader::new(resp); let result = read_stream_to_string(reader, parse_stream_line); - log::debug!("OpenAI streaming response time: {:.2?}", t0.elapsed()); + log::debug!( + "{} streaming response time: {:.2?}", + self.provider_label, + t0.elapsed() + ); result } + + /// `GET /v1/models/{model}` — OpenAI's retrieve-model endpoint. + fn validate_model_by_retrieve(&self) -> Result<()> { + let url = self.model_url(); + let resp = self + .authed(self.client.get(&url)) + .send() + .with_context(|| { + format!( + "failed to send model validation request to {} at {}", + self.provider_label, url + ) + })?; + + if resp.status() == StatusCode::OK { + return Ok(()); + } + + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + Err(anyhow!( + "{} model validation failed for {:?} at {}: HTTP {} - {}", + self.provider_label, + self.model, + url, + status.as_u16(), + text + )) + } + + /// `GET /v1/models` plus a membership check, for servers that list models + /// but do not implement retrieve-by-id. + fn validate_model_by_list(&self) -> Result<()> { + let url = self.models_url(); + let resp = self + .authed(self.client.get(&url)) + .send() + .with_context(|| { + format!( + "failed to reach {} at {} — is the server running and reachable?", + self.provider_label, url + ) + })?; + + if !resp.status().is_success() { + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + return Err(anyhow!( + "{} model listing failed at {}: HTTP {} - {}", + self.provider_label, + url, + status.as_u16(), + text + )); + } + + let listed: ModelListResponse = resp + .json() + .with_context(|| format!("failed to parse model list from {url}"))?; + + if listed.data.iter().any(|m| m.id == self.model) { + return Ok(()); + } + + let available = listed + .data + .iter() + .map(|m| m.id.as_str()) + .collect::>() + .join(", "); + + Err(anyhow!( + "{} at {} has no model {:?}. Available: {}", + self.provider_label, + url, + self.model, + if available.is_empty() { + "(none)" + } else { + &available + } + )) + } } fn parse_stream_line(line: &str) -> Result> { @@ -212,27 +367,10 @@ fn parse_stream_line(line: &str) -> Result> { impl LlmClient for OpenAiClient { fn validate_model(&self) -> Result<()> { - let url = self.model_url(); - let resp = self - .client - .get(&url) - .bearer_auth(&self.api_key) - .send() - .context("failed to send model validation request to OpenAI")?; - - if resp.status() == StatusCode::OK { - return Ok(()); + match self.model_validation { + ModelValidation::Retrieve => self.validate_model_by_retrieve(), + ModelValidation::List => self.validate_model_by_list(), } - - let status = resp.status(); - let text = resp.text().unwrap_or_default(); - Err(anyhow!( - "OpenAI model validation failed for {:?} at {}: HTTP {} - {}", - self.model, - url, - status.as_u16(), - text - )) } fn summarize_file( @@ -430,4 +568,71 @@ mod tests { "https://api.openai.com/v1/models/gpt-5-nano" ); } + + fn lm_studio(base_url: &str) -> OpenAiClient { + OpenAiClient::openai_compatible( + None, + "qwen/qwen3-coder-30b".into(), + base_url.into(), + false, + 90, + "LM Studio", + ModelValidation::List, + ) + } + + #[test] + fn builds_lm_studio_urls_from_v1_base() { + let client = lm_studio("http://localhost:1234/v1"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_root_base() { + // Given without the /v1 suffix, and with a trailing slash, still lands + // on the same paths. + let client = lm_studio("http://localhost:1234/"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn lm_studio_validates_against_the_model_list() { + // LM Studio implements GET /v1/models but not GET /v1/models/{id}, + // so validation has to go through the listing. + assert_eq!( + lm_studio("http://localhost:1234/v1").model_validation, + ModelValidation::List + ); + assert_eq!( + OpenAiClient::new("k".into(), "m".into(), "https://api.openai.com".into(), false, 90) + .model_validation, + ModelValidation::Retrieve + ); + } + + #[test] + fn decodes_model_list_payload() { + let body = r#"{"object":"list","data":[ + {"id":"qwen/qwen3-coder-30b","object":"model","owned_by":"organization_owner"}, + {"id":"text-embedding-nomic-embed-text-v1.5","object":"model","owned_by":"organization_owner"} + ]}"#; + + let parsed: ModelListResponse = serde_json::from_str(body).expect("valid model list"); + let ids: Vec<&str> = parsed.data.iter().map(|m| m.id.as_str()).collect(); + + assert_eq!( + ids, + ["qwen/qwen3-coder-30b", "text-embedding-nomic-embed-text-v1.5"] + ); + } } diff --git a/src/setup.rs b/src/setup.rs index 62444e7..b80965b 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -2,7 +2,7 @@ use anyhow::{anyhow, Result}; use crate::config::Config; use crate::llm::LlmClient; use crate::llm::ollama::OllamaClient; -use crate::llm::openai::OpenAiClient; +use crate::llm::openai::{ModelValidation, OpenAiClient}; /// Build the LLM client based on CLI + config. pub fn build_llm_client(cfg: &Config) -> Result> { @@ -52,6 +52,33 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.request_timeout_secs, ))) } - other => Err(anyhow!("Unknown provider: {}", other)), + "lmstudio" => { + let base_url = cfg + .base_url + .clone() + .unwrap_or_else(|| "http://localhost:1234".to_string()); + + log::debug!( + "Using LM Studio at {} with model: {} (stream={}, timeout={}s)", + base_url, + cfg.model, + cfg.stream, + cfg.request_timeout_secs + ); + + Ok(Box::new(OpenAiClient::openai_compatible( + cfg.openai_api_key.clone(), + cfg.model.clone(), + base_url, + cfg.stream, + cfg.request_timeout_secs, + "LM Studio", + ModelValidation::List, + ))) + } + other => Err(anyhow!( + "Unknown provider: {:?} (expected one of: openai, ollama, lmstudio)", + other + )), } } diff --git a/tests/config.rs b/tests/config.rs index 3a9420e..f072860 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -108,6 +108,63 @@ stream = true fs::remove_file(config_path).ok(); } +#[test] +fn lmstudio_needs_no_url_or_api_key() { + // Like ollama: the url is optional and falls back to a local default, + // and no API key is required. + let config_path = write_temp_config( + "lmstudio_defaults", + r#" +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("lmstudio config should resolve"); + assert_eq!(cfg.provider, "lmstudio"); + assert_eq!(cfg.model, "qwen/qwen3-coder-30b"); + assert_eq!(cfg.base_url, None, "the default is applied when building the client"); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn lmstudio_url_can_point_at_a_remote_host() { + let config_path = write_temp_config( + "lmstudio_remote", + r#" +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +url = "http://localhost:1234/v1" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + "--url", + "http://gpu.example.com:1234/v1", + ]); + + let cfg = Config::from_sources(&cli).expect("cli url should override file"); + assert_eq!(cfg.provider, "lmstudio"); + assert_eq!( + cfg.base_url.as_deref(), + Some("http://gpu.example.com:1234/v1") + ); + + fs::remove_file(config_path).ok(); +} + #[test] fn invalid_openai_config_returns_error() { let config_path = write_temp_config( From 4e207de4be051027062eabf10d9469fa1492eeae Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 10:35:23 -0400 Subject: [PATCH 26/40] Add Rust CI pipeline for testing - Automate linting and tests on every push and pull request. - Integrate Codecov for automated coverage reporting. --- .github/workflows/test.yml | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..434d21b --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,39 @@ +name: Test Rust + +on: + push: + branches: [ "main", "develop" ] + pull_request: + branches: [ "main", "develop" ] + +permissions: + contents: read + +jobs: + test: + name: Test and Coverage + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + + - name: Set up Rust + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - name: Lint + run: cargo clippy --all-targets --all-features -- -D warnings + + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@cargo-llvm-cov + + - name: Generate coverage + run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + files: lcov.info + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true From 94fd823c3295a4fd51bbaeacecc3365b76852403 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 10:40:13 -0400 Subject: [PATCH 27/40] Allowing dead code for now Future version will allow interactive model selection --- src/llm/ollama.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 5c9778e..e7fbece 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -37,11 +37,14 @@ struct OllamaUsage { total_tokens: Option, } +// Scaffolding for a future "list models" command; only exercised by tests today. +#[allow(dead_code)] #[derive(Debug, Decode)] struct OllamaTagModel { name: String, } +#[allow(dead_code)] #[derive(Debug, Decode)] struct OllamaTagsResponse { models: Vec, @@ -173,6 +176,8 @@ impl OllamaClient { } } + /// Scaffolding for a future "list models" command; only exercised by tests today. + #[allow(dead_code)] fn tags_url(&self) -> String { format!("{}/api/tags", self.base_url) } From abe4dd95bf715b62c27071fd01a6b71b8b05ad23 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 11:31:20 -0400 Subject: [PATCH 28/40] Exclude lock files from LLM summarization - Create a "Lock" category to track files while ignoring content. - Update `prompt_builder` to separate lock files and fix numbering. - Expose `prompt_builder` and update logs to track lock files separately. - Add tests for lock file detection and prompt generation. Token usage: prompt=5689, completion=2950, total=8639 --- src/lib.rs | 41 ++++++++++++++++++- src/llm/mod.rs | 2 +- src/llm/prompt_builder.rs | 49 +++++++++++++++++----- src/main.rs | 71 +++++++++++++++++++++++--------- tests/lib_types.rs | 26 +++++++++++- tests/prompt_builder.rs | 85 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 242 insertions(+), 32 deletions(-) create mode 100644 tests/prompt_builder.rs diff --git a/src/lib.rs b/src/lib.rs index bcbf502..a525a10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,13 +16,48 @@ pub use git::{ }; pub use llm::LlmClient; -/// How the user categorizes each file in interactive mode. +/// Lock files whose names don't end in `.lock`, so the extension check misses them. +const LOCK_FILE_NAMES: &[&str] = &[ + "package-lock.json", // npm + "npm-shrinkwrap.json", // npm + "pnpm-lock.yaml", // pnpm + "bun.lockb", // bun (pre-1.2 binary format) + "packages.lock.json", // NuGet + "gradle.lockfile", // Gradle +]; + +/// True when the path names a dependency lock file: any `*.lock` file, plus the +/// well-known lock files that use a different extension ([`LOCK_FILE_NAMES`]). +/// +/// Lock files are regenerated wholesale by a package manager, so their diffs +/// carry no intent worth asking the LLM about. We skip summarizing them and +/// only tell the final summary that they were touched. +pub fn is_lock_file(path: &str) -> bool { + let path = std::path::Path::new(path); + + if path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("lock")) + { + return true; + } + + path.file_name().is_some_and(|name| { + LOCK_FILE_NAMES + .iter() + .any(|known| name.eq_ignore_ascii_case(known)) + }) +} + +/// How each file is categorized. The first four come from the user in +/// interactive mode; `Lock` is assigned automatically by [`is_lock_file`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] pub enum FileCategory { Main, // 1 Supporting, // 2 Consequence, // 3 Ignored, // 4 + Lock, // auto-assigned to *.lock files } impl FileCategory { @@ -33,6 +68,7 @@ impl FileCategory { FileCategory::Supporting => "supporting", FileCategory::Consequence => "consequence", FileCategory::Ignored => "ignored", + FileCategory::Lock => "lock", } } } @@ -46,6 +82,7 @@ pub struct FileChange { pub category: FileCategory, /// Git diff for this file pub diff: String, - /// LLM-generated summary for this file + /// LLM-generated summary for this file. Always `None` for + /// [`FileCategory::Lock`] and [`FileCategory::Ignored`] files. pub summary: Option, } diff --git a/src/llm/mod.rs b/src/llm/mod.rs index e352a1e..68d6b2a 100644 --- a/src/llm/mod.rs +++ b/src/llm/mod.rs @@ -1,6 +1,6 @@ pub mod ollama; pub mod openai; -mod prompt_builder; +pub mod prompt_builder; mod prompts; mod stream; diff --git a/src/llm/prompt_builder.rs b/src/llm/prompt_builder.rs index e203886..dcfc57c 100644 --- a/src/llm/prompt_builder.rs +++ b/src/llm/prompt_builder.rs @@ -51,12 +51,13 @@ pub fn commit_message_prompt( } let per_file = render_per_file_summaries(files); - let file_count = files.len(); + let lock_files = render_lock_files_touched(files); let user = format!( - "Branch: {branch}\n\nFiles Changed: {file_count}\n\nPer-file summaries:\n\n{per_file}", + "Branch: {branch}\n\nFiles Changed: {file_count}\n\nPer-file summaries:\n\n{per_file}{lock_files}", branch = branch, - file_count = file_count + 1, - per_file = per_file + file_count = files.len(), + per_file = per_file, + lock_files = lock_files ); PromptPair { system, user } @@ -147,14 +148,18 @@ pub fn pr_message_prompt( PromptPair { system, user } } +/// Renders only the files we actually asked the LLM about, numbered against +/// that subset so the list has no gaps. Ignored and lock files are reported +/// elsewhere (or not at all), not counted here. fn render_per_file_summaries(files: &[FileChange]) -> String { - let total_files = files.len(); - let mut out = String::new(); - for (idx, file) in files + let summarized: Vec<&FileChange> = files .iter() - .enumerate() - .filter(|(_, f)| !matches!(f.category, FileCategory::Ignored)) - { + .filter(|f| !matches!(f.category, FileCategory::Ignored | FileCategory::Lock)) + .collect(); + + let total_files = summarized.len(); + let mut out = String::new(); + for (idx, file) in summarized.iter().enumerate() { out.push_str(&format!( "File {file_num} of {total_files}: {path}\nCategory: {category}\nSummary:\n{summary}\n\n", file_num = idx + 1, @@ -169,3 +174,27 @@ fn render_per_file_summaries(files: &[FileChange]) -> String { } out } + +/// Lock file diffs are never sent to the LLM, so the final summary is told only +/// that they were touched. +fn render_lock_files_touched(files: &[FileChange]) -> String { + let paths: Vec<&str> = files + .iter() + .filter(|f| matches!(f.category, FileCategory::Lock)) + .map(|f| f.path.as_str()) + .collect(); + + if paths.is_empty() { + return String::new(); + } + + let mut out = String::from("Lock files touched/updated (diffs not reviewed):\n"); + for path in paths { + out.push_str(&format!("- {path}\n")); + } + out.push_str( + "\nThese were regenerated by a package manager. Mention them only as a dependency \ + lock update, and do not speculate about their contents.\n", + ); + out +} diff --git a/src/main.rs b/src/main.rs index 714085e..0f2c937 100644 --- a/src/main.rs +++ b/src/main.rs @@ -306,7 +306,11 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let total_files = file_pairs.len(); for (idx, (path, diff)) in file_pairs.into_iter().enumerate() { - let category = categorize_file_interactive(idx, total_files, &path)?; + let category = if commitbot::is_lock_file(&path) { + FileCategory::Lock + } else { + categorize_file_interactive(idx, total_files, &path)? + }; file_changes.push(FileChange { path, category, @@ -329,7 +333,9 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { .expect("progress style template"), ); line.set_prefix(fc.path.clone()); - if matches!(fc.category, FileCategory::Ignored) { + if matches!(fc.category, FileCategory::Lock) { + line.finish_with_message(dimmed("lock file updated, not summarized")); + } else if matches!(fc.category, FileCategory::Ignored) { line.finish_with_message(dimmed("ignored")); } else { line.enable_steady_tick(Duration::from_millis(120)); @@ -346,20 +352,27 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let mut indices_to_summarize = Vec::new(); let mut ignored_count = 0usize; + let mut lock_count = 0usize; for (idx, fc) in file_changes.iter().enumerate() { - if matches!(fc.category, FileCategory::Ignored) { - pb.inc(1); - ignored_count += 1; - } else { - indices_to_summarize.push(idx); + match fc.category { + FileCategory::Ignored => { + pb.inc(1); + ignored_count += 1; + } + FileCategory::Lock => { + pb.inc(1); + lock_count += 1; + } + _ => indices_to_summarize.push(idx), } } log::info!( - "Summarizing {} files ({} ignored). max_concurrent_requests = {}", + "Summarizing {} files ({} ignored, {} lock). max_concurrent_requests = {}", indices_to_summarize.len(), ignored_count, + lock_count, cfg.max_concurrent_requests, ); @@ -450,11 +463,18 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let mut file_changes: Vec = file_pairs .into_iter() - .map(|(path, diff)| FileChange { - path, - category: FileCategory::Main, - diff, - summary: None, + .map(|(path, diff)| { + let category = if commitbot::is_lock_file(&path) { + FileCategory::Lock + } else { + FileCategory::Main + }; + FileChange { + path, + category, + diff, + summary: None, + } }) .collect(); @@ -481,8 +501,12 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { fc.path.clone() }; line.set_prefix(prefix); - line.enable_steady_tick(Duration::from_millis(120)); - line.set_message("waiting"); + if matches!(fc.category, FileCategory::Lock) { + line.finish_with_message(dimmed("lock file updated, not summarized")); + } else { + line.enable_steady_tick(Duration::from_millis(120)); + line.set_message("waiting"); + } file_lines.push(line); } @@ -492,11 +516,22 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { .unwrap_or_else(|_| ProgressStyle::default_bar()), ); - let indices_to_summarize: Vec = (0..total).collect(); + let mut indices_to_summarize: Vec = Vec::new(); + let mut lock_count = 0usize; + + for (idx, fc) in file_changes.iter().enumerate() { + if matches!(fc.category, FileCategory::Lock) { + pb.inc(1); + lock_count += 1; + } else { + indices_to_summarize.push(idx); + } + } log::info!( - "Auto-summarizing {} files. max_concurrent_requests = {}", - total, + "Auto-summarizing {} files ({} lock). max_concurrent_requests = {}", + indices_to_summarize.len(), + lock_count, cfg.max_concurrent_requests, ); diff --git a/tests/lib_types.rs b/tests/lib_types.rs index ec4b102..d13de98 100644 --- a/tests/lib_types.rs +++ b/tests/lib_types.rs @@ -1,6 +1,6 @@ //! Tests for core types and functionality in lib.rs -use commitbot::{FileCategory, FileChange}; +use commitbot::{is_lock_file, FileCategory, FileChange}; #[test] fn file_category_str_representation() { @@ -8,6 +8,30 @@ fn file_category_str_representation() { assert_eq!(FileCategory::Supporting.as_str(), "supporting"); assert_eq!(FileCategory::Consequence.as_str(), "consequence"); assert_eq!(FileCategory::Ignored.as_str(), "ignored"); + assert_eq!(FileCategory::Lock.as_str(), "lock"); +} + +#[test] +fn lock_files_are_detected_by_extension() { + assert!(is_lock_file("Cargo.lock")); + assert!(is_lock_file("yarn.lock")); + assert!(is_lock_file("sub/dir/Gemfile.lock")); + assert!(is_lock_file("composer.LOCK")); + + // Lock files that do not use the .lock extension. + assert!(is_lock_file("package-lock.json")); + assert!(is_lock_file("npm-shrinkwrap.json")); + assert!(is_lock_file("pnpm-lock.yaml")); + assert!(is_lock_file("bun.lockb")); + assert!(is_lock_file("packages.lock.json")); + assert!(is_lock_file("gradle.lockfile")); + assert!(is_lock_file("web/frontend/package-lock.json")); + + assert!(!is_lock_file("Cargo.toml")); + assert!(!is_lock_file("package.json")); + assert!(!is_lock_file("src/lock.rs")); + assert!(!is_lock_file("lock")); + assert!(!is_lock_file("locked.json")); } #[test] diff --git a/tests/prompt_builder.rs b/tests/prompt_builder.rs new file mode 100644 index 0000000..18eafe8 --- /dev/null +++ b/tests/prompt_builder.rs @@ -0,0 +1,85 @@ +//! Tests for the prompts we hand to the LLM. + +use commitbot::llm::prompt_builder::commit_message_prompt; +use commitbot::{FileCategory, FileChange}; + +fn file(path: &str, category: FileCategory, summary: Option<&str>) -> FileChange { + FileChange { + path: path.to_string(), + category, + diff: "diff --git a/x b/x".to_string(), + summary: summary.map(str::to_string), + } +} + +#[test] +fn lock_files_are_listed_instead_of_summarized() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("Cargo.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(prompt.user.contains("src/main.rs")); + assert!(prompt.user.contains("- Wire up X")); + assert!(prompt.user.contains("Lock files touched/updated")); + assert!(prompt.user.contains("- Cargo.lock")); + // The lock file never gets a per-file block, so it can't be reported missing. + assert!(!prompt.user.contains("Cargo.lock\nCategory:")); + assert!(!prompt.user.contains("[missing per-file summary]")); +} + +#[test] +fn no_lock_section_without_lock_files() { + let files = vec![file("src/main.rs", FileCategory::Main, Some("- Wire up X"))]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(!prompt.user.contains("Lock files touched/updated")); +} + +#[test] +fn ignored_files_stay_out_of_the_lock_section() { + let files = vec![ + file("notes.txt", FileCategory::Ignored, None), + file("yarn.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(!prompt.user.contains("notes.txt")); + assert!(prompt.user.contains("- yarn.lock")); +} + +#[test] +fn file_count_matches_the_changeset() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("src/lib.rs", FileCategory::Supporting, Some("- Export X")), + file("Cargo.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + // Every changed file is counted, including the ones we did not summarize. + assert!(prompt.user.contains("Files Changed: 3")); +} + +#[test] +fn per_file_blocks_are_numbered_without_gaps() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("Cargo.lock", FileCategory::Lock, None), + file("notes.txt", FileCategory::Ignored, None), + file("src/lib.rs", FileCategory::Supporting, Some("- Export X")), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + // Two files were summarized, so they are "1 of 2" and "2 of 2" — the + // skipped files in between must not leave a hole in the numbering. + assert!(prompt.user.contains("File 1 of 2: src/main.rs")); + assert!(prompt.user.contains("File 2 of 2: src/lib.rs")); + assert!(!prompt.user.contains("of 4")); +} From aedbfc9135dcad50105638f13508b478cbf49e99 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 11:44:04 -0400 Subject: [PATCH 29/40] 0.7.0 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d55320d..043dcd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.6.4" +version = "0.7.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index fe2867b..c06a0cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.6.4" +version = "0.7.0" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 82e604af203b0f5cbc06ef59be9e90315378b203 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 12:24:44 -0400 Subject: [PATCH 30/40] Use gzip compression for release artifacts - Replace `tar.gz` with direct `gzip` in the release workflow and `Taskfile.yaml`. - Update artifact naming and search patterns in publishing and release scripts. - Adjust release notes to reflect new binary names and installation instructions. Token usage: prompt=3369, completion=1584, total=4953 --- .github/workflows/release-assets.yml | 16 ++++++++-------- Taskfile.yaml | 12 +++++------- devops/publish-if-complete.sh | 12 ++++++------ devops/release.sh | 4 ++-- devops/render-release-notes.sh | 9 +++++---- 5 files changed, 26 insertions(+), 27 deletions(-) diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml index 5018508..c2caf0d 100644 --- a/.github/workflows/release-assets.yml +++ b/.github/workflows/release-assets.yml @@ -36,7 +36,7 @@ jobs: runner: ubuntu-24.04-arm target: aarch64-unknown-linux-gnu asset_target: unknown-linux-gnu-aarch64 - archive_ext: tar.gz + archive_ext: gz binary_name: commitbot install_cmd: "" linker: "" @@ -44,7 +44,7 @@ jobs: runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu asset_target: unknown-linux-gnu-x86_64 - archive_ext: tar.gz + archive_ext: gz binary_name: commitbot install_cmd: "" linker: "" @@ -52,7 +52,7 @@ jobs: runner: ubuntu-24.04-arm target: aarch64-unknown-linux-musl asset_target: unknown-linux-musl-aarch64 - archive_ext: tar.gz + archive_ext: gz binary_name: commitbot install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools linker: musl-gcc @@ -60,7 +60,7 @@ jobs: runner: ubuntu-24.04 target: x86_64-unknown-linux-musl asset_target: unknown-linux-musl-x86_64 - archive_ext: tar.gz + archive_ext: gz binary_name: commitbot install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools linker: musl-gcc @@ -113,13 +113,13 @@ jobs: CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: ${{ matrix.target == 'x86_64-unknown-linux-musl' && matrix.linker || '' }} run: cargo build --locked --release --target ${{ matrix.target }} - - name: Package tar.gz archive - if: matrix.archive_ext == 'tar.gz' + - name: Compress release binary + if: matrix.archive_ext == 'gz' shell: bash run: | set -euo pipefail - asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.tar.gz" - tar -C "target/${{ matrix.target }}/release" -czf "$asset" "${{ matrix.binary_name }}" + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.gz" + gzip -n -c "target/${{ matrix.target }}/release/${{ matrix.binary_name }}" > "$asset" echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" - name: Package zip archive diff --git a/Taskfile.yaml b/Taskfile.yaml index 044f1af..a859054 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -84,7 +84,7 @@ tasks: silent: true cmds: - mkdir -p dist - - rm -f dist/commitbot-*.tar.gz + - rm -f dist/commitbot-*.gz - | set -euo pipefail @@ -97,13 +97,11 @@ tasks: echo "Packaging into dist with version {{.VERSION}}..." - tar -C target/aarch64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-apple-darwin-aarch64.tar.gz \ - commitbot + gzip -n -c target/aarch64-apple-darwin/release/commitbot \ + > dist/commitbot-{{.VERSION}}-apple-darwin-aarch64.gz - tar -C target/x86_64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-apple-darwin-x86_64.tar.gz \ - commitbot + gzip -n -c target/x86_64-apple-darwin/release/commitbot \ + > dist/commitbot-{{.VERSION}}-apple-darwin-x86_64.gz echo "Artifacts created:" ls -lh dist diff --git a/devops/publish-if-complete.sh b/devops/publish-if-complete.sh index 75b5d0f..c045eb6 100755 --- a/devops/publish-if-complete.sh +++ b/devops/publish-if-complete.sh @@ -5,12 +5,12 @@ set -euo pipefail TAG="${1:?usage: publish-if-complete.sh }" EXPECTED=( - "commitbot-${TAG}-apple-darwin-aarch64.tar.gz" - "commitbot-${TAG}-apple-darwin-x86_64.tar.gz" - "commitbot-${TAG}-unknown-linux-gnu-aarch64.tar.gz" - "commitbot-${TAG}-unknown-linux-gnu-x86_64.tar.gz" - "commitbot-${TAG}-unknown-linux-musl-aarch64.tar.gz" - "commitbot-${TAG}-unknown-linux-musl-x86_64.tar.gz" + "commitbot-${TAG}-apple-darwin-aarch64.gz" + "commitbot-${TAG}-apple-darwin-x86_64.gz" + "commitbot-${TAG}-unknown-linux-gnu-aarch64.gz" + "commitbot-${TAG}-unknown-linux-gnu-x86_64.gz" + "commitbot-${TAG}-unknown-linux-musl-aarch64.gz" + "commitbot-${TAG}-unknown-linux-musl-x86_64.gz" "commitbot-${TAG}-pc-windows-gnu-x86_64.zip" ) diff --git a/devops/release.sh b/devops/release.sh index f1cedf5..aaf725f 100644 --- a/devops/release.sh +++ b/devops/release.sh @@ -123,7 +123,7 @@ if git rev-parse -q --verify "refs/tags/$NEW_VERSION" >/dev/null 2>&1; then task setup task "build:release:${NEW_VERSION}" - MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.tar.gz) + MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.gz) if [ ${#MAC_ASSETS[@]} -eq 0 ]; then echo "Error: no Mac assets found in $DIST_DIR after build." exit 1 @@ -212,7 +212,7 @@ if [ ! -d "$DIST_DIR" ]; then exit 1 fi -MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.tar.gz) +MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.gz) if [ ${#MAC_ASSETS[@]} -eq 0 ]; then echo "Error: no Mac assets found in '$DIST_DIR'." exit 1 diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh index 5aa0411..802946f 100644 --- a/devops/render-release-notes.sh +++ b/devops/render-release-notes.sh @@ -16,9 +16,9 @@ cat < /dev/null +sudo chmod +x /usr/local/bin/commitbot ~~~ EOF From ef0a3715121ac4efe4a3b5c8d08695a2a1f22623 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 12:42:22 -0400 Subject: [PATCH 31/40] Include provider and model in token usage feedback - Add provider and model details to token usage feedback. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=499, completion=283, total=782 --- src/main.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0f2c937..302efd5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -412,7 +412,9 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if let Some((p, c, t)) = llm.take_and_reset_usage() { - println!("Token usage: prompt={}, completion={}, total={}", p, c, t); + print!("\n"); + println!("Provider: {} {}", cfg.provider, cfg.model ); + println!("Tokens: prompt={}, completion={}, total={}", p, c, t); } Ok(()) @@ -571,7 +573,9 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if let Some((p, c, t)) = llm.take_and_reset_usage() { - println!("Token usage: prompt={}, completion={}, total={}", p, c, t); + print!("\n"); + println!("Provider: {} {}", cfg.provider, cfg.model ); + println!("Tokens: prompt={}, completion={}, total={}", p, c, t); } Ok(()) From 8bfba65d3abce49cb041c8abfe0a8e0c373e4ba2 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Fri, 14 Aug 2026 12:44:53 -0400 Subject: [PATCH 32/40] I'm dumb --- src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 302efd5..754c00f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -412,7 +412,7 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if let Some((p, c, t)) = llm.take_and_reset_usage() { - print!("\n"); + println!(); println!("Provider: {} {}", cfg.provider, cfg.model ); println!("Tokens: prompt={}, completion={}, total={}", p, c, t); } @@ -573,7 +573,7 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { println!(); if let Some((p, c, t)) = llm.take_and_reset_usage() { - print!("\n"); + println!(); println!("Provider: {} {}", cfg.provider, cfg.model ); println!("Tokens: prompt={}, completion={}, total={}", p, c, t); } From a5484b68ffc22cb4b87da955fdff54467c454d77 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Tue, 15 Sep 2026 21:18:26 -0400 Subject: [PATCH 33/40] nhance OpenAI compatibility and Git error reporting OpenAI Compatibility: - Support `reasoning_content` and handle null/missing content. - Normalize base URLs to strip inconsistent prefixes. - Allow OpenAI usage without API keys on custom endpoints. - Implement flexible model ID matching and dynamic validation. Git Improvements: - Capture `stderr` and provide human-readable git errors. - Add unit tests for Xcode license and standard git failures. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=7072, completion=2611, total=9683 --- commitbot.toml | 3 +- src/config.rs | 7 +- src/llm/openai.rs | 273 +++++++++++++++++++++++++++++++++++++++++++--- src/setup.rs | 17 ++- tests/config.rs | 26 +++++ tests/git.rs | 50 ++++++++- 6 files changed, 345 insertions(+), 31 deletions(-) diff --git a/commitbot.toml b/commitbot.toml index a2e3aaf..e817015 100644 --- a/commitbot.toml +++ b/commitbot.toml @@ -25,7 +25,8 @@ max_concurrent_requests = 8 ["MikeGarde/commitbot"] provider = "lmstudio" model = "google/gemma-4-12b-qat" -url = "http://GPU.localdomain:1234/v1" +url = "http://gpu.garde.one:1234/v1" +# Fallback / direct IP: url = "http://192.168.1.16:1234/v1" max_concurrent_requests = 2 diff --git a/src/config.rs b/src/config.rs index 3440d8d..2f0c1ac 100644 --- a/src/config.rs +++ b/src/config.rs @@ -66,7 +66,12 @@ impl Config { .map(|s| s.trim_matches('"').trim().to_string()) .filter(|s| !s.is_empty()); - if provider == "openai" && openai_api_key.is_none() { + let is_custom_endpoint = base_url + .as_deref() + .map(|u| !u.starts_with("https://api.openai.com")) + .unwrap_or(false); + + if provider == "openai" && openai_api_key.is_none() && !is_custom_endpoint { return Err(anyhow!( "OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai" )); diff --git a/src/llm/openai.rs b/src/llm/openai.rs index f4bc392..6007a19 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -27,6 +27,7 @@ struct ChatMessage { #[derive(Deserialize)] struct ChatResponse { + #[serde(default)] choices: Vec, usage: Option, } @@ -38,18 +39,25 @@ struct ChatChoice { #[derive(Deserialize)] struct ChatMessageResponse { - content: String, + #[serde(default)] + content: Option, + #[serde(default)] + reasoning_content: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, Default)] struct ChatUsage { + #[serde(default)] prompt_tokens: u32, + #[serde(default)] completion_tokens: u32, + #[serde(default)] total_tokens: u32, } #[derive(Deserialize)] struct ModelListResponse { + #[serde(default)] data: Vec, } @@ -60,6 +68,7 @@ struct ModelListEntry { #[derive(Deserialize)] struct StreamResponse { + #[serde(default)] choices: Vec, } @@ -70,7 +79,11 @@ struct StreamChoice { #[derive(Deserialize)] struct StreamDelta { + #[serde(default)] content: Option, + #[serde(default)] + #[allow(dead_code)] + reasoning_content: Option, } /// How to confirm the configured model exists on the upstream server. @@ -138,7 +151,7 @@ impl OpenAiClient { client, api_key, model, - api_base_url: api_base_url.trim_end_matches('/').to_string(), + api_base_url: normalize_base_url(&api_base_url), stream, provider_label: provider_label.into(), model_validation, @@ -155,13 +168,9 @@ impl OpenAiClient { } } - /// Join `path` under `/v1`, tolerating a base URL that already ends in `/v1`. + /// Join `path` under `/v1`, with base URL guaranteed normalized. fn v1_url(&self, path: &str) -> String { - if self.api_base_url.ends_with("/v1") { - format!("{}/{}", self.api_base_url, path) - } else { - format!("{}/v1/{}", self.api_base_url, path) - } + format!("{}/v1/{}", self.api_base_url, path.trim_start_matches('/')) } fn chat_url(&self) -> String { @@ -210,8 +219,19 @@ impl OpenAiClient { let content = chat_resp .choices .first() - .map(|c| c.message.content.clone()) - .ok_or_else(|| anyhow!("no choices returned from {}", self.provider_label))?; + .and_then(|c| { + c.message + .content + .clone() + .filter(|s| !s.trim().is_empty()) + .or_else(|| { + c.message + .reasoning_content + .clone() + .filter(|s| !s.trim().is_empty()) + }) + }) + .ok_or_else(|| anyhow!("no content returned from {}", self.provider_label))?; if let Some(usage) = &chat_resp.usage { // Recover from a poisoned mutex instead of panicking so the CLI @@ -318,11 +338,30 @@ impl OpenAiClient { )); } - let listed: ModelListResponse = resp - .json() - .with_context(|| format!("failed to parse model list from {url}"))?; + let listed: ModelListResponse = match resp.json() { + Ok(l) => l, + Err(e) => { + log::warn!( + "{} model listing at {} could not be parsed: {}. Proceeding anyway...", + self.provider_label, + url, + e + ); + return Ok(()); + } + }; - if listed.data.iter().any(|m| m.id == self.model) { + if listed.data.is_empty() { + log::warn!( + "{} at {} returned an empty model list; proceeding with {:?}", + self.provider_label, + url, + self.model + ); + return Ok(()); + } + + if listed.data.iter().any(|m| matches_model_id(&self.model, &m.id)) { return Ok(()); } @@ -347,6 +386,60 @@ impl OpenAiClient { } } +/// Normalizes any variation of base URL (e.g. `http://host:1234`, `http://host:1234/v1`, +/// `http://host:1234/V1/`, `http://host:1234/api/v1`, `http://host:1234/v1/chat/completions`) +/// down to the base origin so that `v1_url` can deterministically append `/v1/{path}`. +pub fn normalize_base_url(raw: &str) -> String { + let mut url = raw.trim().trim_end_matches('/').to_string(); + + if url.to_ascii_lowercase().ends_with("/chat/completions") { + url = url[..url.len() - "/chat/completions".len()] + .trim_end_matches('/') + .to_string(); + } else if url.to_ascii_lowercase().ends_with("/models") { + url = url[..url.len() - "/models".len()] + .trim_end_matches('/') + .to_string(); + } + + if url.to_ascii_lowercase().ends_with("/api/v1") { + url = url[..url.len() - "/api/v1".len()] + .trim_end_matches('/') + .to_string(); + } else if url.to_ascii_lowercase().ends_with("/v1") { + url = url[..url.len() - "/v1".len()] + .trim_end_matches('/') + .to_string(); + } + + url +} + +fn clean_model_name(s: &str) -> &str { + let without_gguf = s.strip_suffix(".gguf").unwrap_or(s); + without_gguf.split(':').next().unwrap_or(without_gguf) +} + +/// Check if a model candidate string from the server matches the configured model name. +/// Handles exact match, case-insensitivity, repo prefixes (e.g. "google/gemma-4-12b-qat" vs "gemma-4-12b-qat"), +/// and stripping file extensions like ".gguf" or tags like ":latest". +pub fn matches_model_id(configured: &str, candidate: &str) -> bool { + if configured == candidate { + return true; + } + if configured.eq_ignore_ascii_case(candidate) { + return true; + } + let conf_base = configured.rsplit('/').next().unwrap_or(configured); + let cand_base = candidate.rsplit('/').next().unwrap_or(candidate); + if conf_base.eq_ignore_ascii_case(cand_base) { + return true; + } + let conf_clean = clean_model_name(conf_base); + let cand_clean = clean_model_name(cand_base); + conf_clean.eq_ignore_ascii_case(cand_clean) +} + fn parse_stream_line(line: &str) -> Result> { let line = line.trim_start(); if !line.starts_with("data:") { @@ -368,8 +461,40 @@ fn parse_stream_line(line: &str) -> Result> { impl LlmClient for OpenAiClient { fn validate_model(&self) -> Result<()> { match self.model_validation { - ModelValidation::Retrieve => self.validate_model_by_retrieve(), - ModelValidation::List => self.validate_model_by_list(), + ModelValidation::Retrieve => match self.validate_model_by_retrieve() { + Ok(()) => Ok(()), + Err(e) => { + log::debug!( + "Retrieve model validation failed: {e}. Falling back to list validation." + ); + if let Ok(()) = self.validate_model_by_list() { + return Ok(()); + } + if self.provider_label != "OpenAI" { + log::warn!( + "Could not validate model {:?} on {}: {}. Proceeding anyway...", + self.model, + self.provider_label, + e + ); + Ok(()) + } else { + Err(e) + } + } + }, + ModelValidation::List => match self.validate_model_by_list() { + Ok(()) => Ok(()), + Err(e) => { + log::debug!( + "List model validation failed: {e}. Falling back to retrieve validation." + ); + if let Ok(()) = self.validate_model_by_retrieve() { + return Ok(()); + } + Err(e) + } + }, } } @@ -620,6 +745,120 @@ mod tests { ); } + #[test] + fn builds_lm_studio_urls_from_uppercase_v1_base() { + let client = lm_studio("http://gpu.garde.one:1234/V1/"); + + assert_eq!(client.models_url(), "http://gpu.garde.one:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://gpu.garde.one:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_api_v1_base() { + let client = lm_studio("http://localhost:1234/api/v1"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_full_endpoint() { + let client = lm_studio("http://localhost:1234/v1/chat/completions"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn matches_model_id_variations() { + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "google/gemma-4-12b-qat" + )); + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "GOOGLE/GEMMA-4-12B-QAT" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat" + )); + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "gemma-4-12b-qat" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat.gguf" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat:latest" + )); + assert!(!matches_model_id( + "gemma-4-12b-qat", + "ibm/granite-4-h-tiny" + )); + } + + #[test] + fn decodes_chat_response_with_null_content_and_reasoning() { + let body = r#"{ + "id": "chatcmpl-test", + "object": "chat.completion", + "created": 123456, + "model": "google/gemma-4-12b-qat", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": null, + "reasoning_content": "Just thinking..." + }, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 10, + "completion_tokens": 5, + "total_tokens": 15 + } + }"#; + + let parsed: ChatResponse = serde_json::from_str(body).expect("valid chat response"); + let choice = parsed.choices.first().expect("choice present"); + assert_eq!(choice.message.content, None); + assert_eq!( + choice.message.reasoning_content.as_deref(), + Some("Just thinking...") + ); + } + + #[test] + fn decodes_streaming_chunk_with_reasoning_and_no_content() { + let line = r#"data: {"id":"c","choices":[{"index":0,"delta":{"reasoning_content":"thought"}}]}"#; + let res = parse_stream_line(line).expect("valid stream line"); + assert_eq!(res, None); + + let line_content = r#"data: {"id":"c","choices":[{"index":0,"delta":{"content":"word"}}]}"#; + let res_content = parse_stream_line(line_content).expect("valid stream line"); + assert_eq!(res_content, Some("word".to_string())); + + let line_done = "data: [DONE]"; + let res_done = parse_stream_line(line_done).expect("valid stream line"); + assert_eq!(res_done, None); + } + #[test] fn decodes_model_list_payload() { let body = r#"{"object":"list","data":[ diff --git a/src/setup.rs b/src/setup.rs index b80965b..85990ab 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -8,15 +8,18 @@ use crate::llm::openai::{ModelValidation, OpenAiClient}; pub fn build_llm_client(cfg: &Config) -> Result> { match cfg.provider.as_str() { "openai" => { - let key = cfg - .openai_api_key - .clone() - .ok_or_else(|| anyhow!("OPENAI_API_KEY must be set for provider=openai"))?; let base_url = cfg .base_url .clone() .unwrap_or_else(|| "https://api.openai.com".to_string()); + let is_custom_endpoint = !base_url.starts_with("https://api.openai.com"); + let validation = if is_custom_endpoint { + ModelValidation::List + } else { + ModelValidation::Retrieve + }; + log::debug!( "Using OpenAiClient with model: {} (stream={}, timeout={}s)", cfg.model, @@ -24,12 +27,14 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.request_timeout_secs ); - Ok(Box::new(OpenAiClient::new( - key, + Ok(Box::new(OpenAiClient::openai_compatible( + cfg.openai_api_key.clone(), cfg.model.clone(), base_url, cfg.stream, cfg.request_timeout_secs, + "OpenAI", + validation, ))) } "ollama" => { diff --git a/tests/config.rs b/tests/config.rs index f072860..b6c8de5 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -190,3 +190,29 @@ model = "gpt-5-nano" fs::remove_file(config_path).ok(); } + +#[test] +fn custom_openai_endpoint_needs_no_api_key() { + let config_path = write_temp_config( + "custom_openai", + r#" +[default] +provider = "openai" +model = "local-model" +url = "http://192.168.1.16:1234/v1" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("custom openai endpoint should allow no api key"); + assert_eq!(cfg.provider, "openai"); + assert_eq!(cfg.openai_api_key, None); + assert_eq!(cfg.base_url.as_deref(), Some("http://192.168.1.16:1234/v1")); + + fs::remove_file(config_path).ok(); +} diff --git a/tests/git.rs b/tests/git.rs index 9f41680..6678ed5 100644 --- a/tests/git.rs +++ b/tests/git.rs @@ -1,7 +1,7 @@ use commitbot::git::{ - find_first_pr_number, format_pr_commit_appendix_with_remote, parse_remote_repo, - short_commit_hash, split_diff_by_file, staged_diff_for_file, staged_files, PrItem, - PrSummaryMode, + find_first_pr_number, format_git_error, format_pr_commit_appendix_with_remote, + parse_remote_repo, short_commit_hash, split_diff_by_file, staged_diff_for_file, staged_files, + PrItem, PrSummaryMode, }; use std::process::Command; @@ -12,12 +12,16 @@ fn repo_with_staged_nested_file() -> (tempfile::TempDir, std::path::PathBuf) { let root = dir.path(); let run = |args: &[&str]| { - let status = Command::new("git") + let output = Command::new("git") .args(args) .current_dir(root) - .status() + .output() .expect("run git"); - assert!(status.success(), "git {:?} failed", args); + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let err = format_git_error(args, output.status.code(), &stderr); + panic!("{err}"); + } }; run(&["init", "-q"]); @@ -198,3 +202,37 @@ fn pr_summary_mode_as_str() { assert_eq!(PrSummaryMode::ByCommits.as_str(), "commits"); assert_eq!(PrSummaryMode::ByPrs.as_str(), "prs"); } + +#[test] +fn format_git_error_detects_xcode_license_error() { + let stderr = "You have not agreed to the Xcode license agreements. Please run 'sudo xcodebuild -license' from within a Terminal window to review and agree to the Xcode and Apple SDKs license."; + let err = format_git_error(&["rev-parse", "--abbrev-ref", "HEAD"], Some(69), stderr); + let msg = err.to_string(); + assert!(msg.contains("Xcode license agreement required")); + assert!(msg.contains("sudo xcodebuild -license")); +} + +#[test] +fn format_git_error_legacy_xcode_license_error() { + let stderr = "Agreeing to the Xcode/iOS license requires admin privileges, please run 'sudo xcodebuild -license' and then retry this command."; + let err = format_git_error(&["diff", "--cached"], Some(69), stderr); + let msg = err.to_string(); + assert!(msg.contains("Xcode license agreement required")); + assert!(msg.contains("sudo xcodebuild -license")); +} + +#[test] +fn format_git_error_standard_git_error() { + let stderr = "fatal: not a git repository (or any of the parent directories): .git"; + let err = format_git_error(&["status"], Some(128), stderr); + let msg = err.to_string(); + assert!(msg.contains("git [\"status\"] exited with status Some(128)")); + assert!(msg.contains("fatal: not a git repository")); +} + +#[test] +fn format_git_error_empty_stderr() { + let err = format_git_error(&["status"], Some(1), ""); + let msg = err.to_string(); + assert_eq!(msg, "git [\"status\"] exited with status Some(1)"); +} From 803375e36da378b078059c6c07e3f06e009807d5 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 23 Sep 2026 12:03:17 -0400 Subject: [PATCH 34/40] Enhance diff handling and context limits - Refactor `--diff` to support stdin, commit hashes, and file paths. - Truncate large diffs at line boundaries to prevent LLM context overflows. - Add commit hash validation and specific Xcode license error reporting. - Synchronize CWD-modifying tests with a mutex. - Update documentation to clarify `--diff` flag usage. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=6479, completion=2986, total=9465 --- README.md | 11 +++++- src/config.rs | 9 +++++ src/git.rs | 56 ++++++++++++++++++-------- src/lib.rs | 50 +++++++++++++++++++++++ src/main.rs | 107 +++++++++++++++++++++++++++++--------------------- tests/git.rs | 62 ++++++++++++++++++++++++++++- 6 files changed, 230 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index eb499b5..874aa8a 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,19 @@ commitbot --diff my-changes.diff # With a custom branch name for context commitbot --diff my-changes.diff --branch feature/ISSUE-123-auth -# From stdin (pipe a diff) +# From stdin (pipe a diff)task : git diff HEAD~3 | commitbot --diff - + +# From a commit hash (looked up in git history automatically) +commitbot --diff aabcf3b6ce03e4f1503c7a0fdda7c120bf73c8bc ``` +When `--diff` looks like a commit hash, Commitbot first checks whether it +exists in the current repo's history and, if so, summarizes the diff +introduced by that commit. If it doesn't match a commit, Commitbot falls +back to treating the value as a file path; if neither a matching commit nor +a file is found, it reports an error instead of guessing. + --- ### Pull Request Summaries diff --git a/src/config.rs b/src/config.rs index 2f0c1ac..3fdb6dd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -24,6 +24,10 @@ pub struct Config { pub stream: bool, /// HTTP request timeout in seconds for LLM calls pub request_timeout_secs: u64, + /// Maximum size (in bytes) of a single file's diff sent to the LLM. + /// Larger diffs (e.g. notebooks with embedded base64 output, minified + /// bundles) are truncated to avoid exceeding the model's context window. + pub max_diff_bytes: usize, } impl Config { @@ -56,6 +60,7 @@ impl Config { let max_concurrent_requests = r.get_usize("max_concurrent_requests", 4); let stream = r.get_bool("stream", true); let request_timeout_secs = r.get_u64("request_timeout_secs", 300); + let max_diff_bytes = r.get_usize("max_diff_bytes", 20_000); // Cleanup: trim stray quotes if any upstream included them let provider = provider.trim_matches('"').to_string(); @@ -85,6 +90,7 @@ impl Config { max_concurrent_requests, stream, request_timeout_secs, + max_diff_bytes, }) } } @@ -99,6 +105,7 @@ struct FileConfig { pub max_concurrent_requests: Option, pub stream: Option, pub request_timeout_secs: Option, + pub max_diff_bytes: Option, } /// Root of the TOML file: @@ -183,6 +190,7 @@ impl<'a> ConfigResolver<'a> { "max_concurrent_requests" => Some("COMMITBOT_MAX_CONCURRENT_REQUESTS"), "stream" => Some("COMMITBOT_STREAM"), "request_timeout_secs" => Some("COMMITBOT_REQUEST_TIMEOUT_SECS"), + "max_diff_bytes" => Some("COMMITBOT_MAX_DIFF_BYTES"), _ => None, } } @@ -212,6 +220,7 @@ impl<'a> ConfigResolver<'a> { }; match key { "max_concurrent_requests" => cfg.max_concurrent_requests, + "max_diff_bytes" => cfg.max_diff_bytes, _ => None, } } diff --git a/src/git.rs b/src/git.rs index 5a3dbc2..079d86e 100644 --- a/src/git.rs +++ b/src/git.rs @@ -83,7 +83,25 @@ impl RemoteRepo { } } -/// Run a git command and capture stdout as String. +pub fn format_git_error(args: &[&str], code: Option, stderr: &str) -> anyhow::Error { + let stderr = stderr.trim(); + + if stderr.contains("xcodebuild -license") || stderr.contains("Xcode license") { + return anyhow!( + "Xcode license agreement required.\n\ + Apple's git cannot run until the Xcode / Command Line Tools license is accepted.\n\n\ + Please run:\n sudo xcodebuild -license\n\n\ + Once accepted, run commitbot again." + ); + } + + if stderr.is_empty() { + anyhow!("git {:?} exited with status {:?}", args, code) + } else { + anyhow!("git {:?} exited with status {:?}: {}", args, code, stderr) + } +} + pub fn git_output(args: &[&str]) -> Result { let output = GitCommand::new("git") .args(args) @@ -92,20 +110,7 @@ pub fn git_output(args: &[&str]) -> Result { if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - let stderr = stderr.trim(); - if stderr.is_empty() { - return Err(anyhow!( - "git {:?} exited with status {:?}", - args, - output.status.code() - )); - } - return Err(anyhow!( - "git {:?} exited with status {:?}: {}", - args, - output.status.code(), - stderr - )); + return Err(format_git_error(args, output.status.code(), &stderr)); } Ok(String::from_utf8_lossy(&output.stdout).to_string()) @@ -127,7 +132,6 @@ fn remote_origin_url() -> Option { .filter(|url| !url.is_empty()) } -/// Get the current branch name. pub fn current_branch() -> Result { let name = git_output(&["rev-parse", "--abbrev-ref", "HEAD"])? .trim() @@ -135,7 +139,25 @@ pub fn current_branch() -> Result { Ok(name) } -/// Get a list of staged files. +pub fn looks_like_commit_hash(s: &str) -> bool { + let len = s.len(); + (4..=40).contains(&len) && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +pub fn resolve_commit_diff(hash: &str) -> Result> { + let verified = GitCommand::new("git") + .args(["rev-parse", "--verify", "--quiet", &format!("{hash}^{{commit}}")]) + .output() + .with_context(|| format!("failed to run git rev-parse for '{hash}'"))?; + + if !verified.status.success() { + return Ok(None); + } + + let diff = git_output(&["show", "--format=", hash])?; + Ok(Some(diff)) +} + pub fn staged_files() -> Result> { let output = git_output(&["diff", "--cached", "--name-only"])?; let files = output diff --git a/src/lib.rs b/src/lib.rs index a525a10..e701e1d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,6 +73,35 @@ impl FileCategory { } } +/// Truncates an oversized diff before it's ever sent to an LLM. +/// +/// Some diffs (Jupyter notebooks with embedded base64 image outputs, minified +/// bundles, generated files) can run into the megabytes, which blows past any +/// local model's context window and can wedge the upstream server for every +/// other in-flight request. Cutting on a line boundary keeps the remaining +/// diff readable instead of ending mid-line. +pub fn truncate_diff(diff: &str, max_bytes: usize) -> String { + if diff.len() <= max_bytes { + return diff.to_string(); + } + + let mut cut = max_bytes; + while cut > 0 && !diff.is_char_boundary(cut) { + cut -= 1; + } + + let head = match diff[..cut].rfind('\n') { + Some(idx) => &diff[..idx], + None => &diff[..cut], + }; + + let omitted = diff.len() - head.len(); + format!( + "{head}\n... [diff truncated, {omitted} bytes omitted — file is unusually large, \ + likely generated or contains embedded binary/base64 content]" + ) +} + /// Represents a single staged file's change and metadata. #[derive(Debug, Clone)] pub struct FileChange { @@ -86,3 +115,24 @@ pub struct FileChange { /// [`FileCategory::Lock`] and [`FileCategory::Ignored`] files. pub summary: Option, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncate_diff_leaves_small_diffs_untouched() { + let diff = "diff --git a/f b/f\n+hello\n"; + assert_eq!(truncate_diff(diff, 1_000), diff); + } + + #[test] + fn truncate_diff_cuts_oversized_diffs_on_a_line_boundary() { + let diff = "line one\nline two\nline three\n"; + let result = truncate_diff(diff, 15); + + assert!(result.starts_with("line one\n")); + assert!(!result.contains("line three")); + assert!(result.contains("truncated")); + } +} diff --git a/src/main.rs b/src/main.rs index 754c00f..a0c013d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,8 @@ use anyhow::{anyhow, Result}; use clap::Parser; use commitbot::config::Config; use commitbot::git::{ - collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, - staged_diff_for_file, staged_files, PrSummaryMode, + collect_pr_items, current_branch, format_pr_commit_appendix, looks_like_commit_hash, + resolve_commit_diff, split_diff_by_file, staged_diff_for_file, staged_files, PrSummaryMode, }; use commitbot::llm::LlmClient; use commitbot::{Cli, Command, FileCategory, FileChange}; @@ -256,29 +256,64 @@ fn summarize_files_concurrently( Ok(()) } +/// Read the content behind `--diff `. +/// +/// `-` reads stdin. Otherwise, if the argument looks like a commit hash, we +/// first try to resolve it against git history; if that doesn't find a +/// commit, or the argument didn't look like a hash to begin with, we fall +/// back to treating it as a file path. +fn read_diff_arg(diff_arg: &str) -> Result { + if diff_arg == "-" { + let mut buf = String::new(); + io::stdin().read_to_string(&mut buf)?; + return Ok(buf); + } + + if looks_like_commit_hash(diff_arg) && let Some(diff) = resolve_commit_diff(diff_arg)? { + return Ok(diff); + } + + let path = std::path::Path::new(diff_arg); + if path.is_file() { + std::fs::read_to_string(path) + .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e)) + } else { + Err(anyhow!( + "'{}' is not a known commit hash or an existing file.", + diff_arg + )) + } +} + +/// Load per-file diffs from `--diff `, splitting a combined diff +/// into (path, diff) pairs. Returns `None` when the resolved content is +/// empty (already reported to the user). +fn load_external_diff( + cli: &Cli, + diff_arg: &str, +) -> Result)>> { + let combined = read_diff_arg(diff_arg)?; + if combined.trim().is_empty() { + println!("No diff content found."); + return Ok(None); + } + let mut per_file = split_diff_by_file(&combined); + if per_file.is_empty() { + per_file = vec![("(diff)".to_string(), combined)]; + } + let branch = cli + .branch + .clone() + .unwrap_or_else(|| current_branch().unwrap_or_else(|_| "unknown-branch".to_string())); + Ok(Some((branch, per_file))) +} + fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let (branch, file_pairs) = if let Some(ref diff_arg) = cli.diff { - let combined = if diff_arg == "-" { - let mut buf = String::new(); - io::stdin().read_to_string(&mut buf)?; - buf - } else { - std::fs::read_to_string(diff_arg) - .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e))? - }; - if combined.trim().is_empty() { - println!("No diff content found."); - return Ok(()); - } - let mut per_file = split_diff_by_file(&combined); - if per_file.is_empty() { - per_file = vec![("(diff)".to_string(), combined)]; + match load_external_diff(cli, diff_arg)? { + Some(pair) => pair, + None => return Ok(()), } - let branch = cli - .branch - .clone() - .unwrap_or_else(|| current_branch().unwrap_or_else(|_| "unknown-branch".to_string())); - (branch, per_file) } else { let branch = current_branch()?; let files = staged_files()?; @@ -314,7 +349,7 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { file_changes.push(FileChange { path, category, - diff, + diff: commitbot::truncate_diff(&diff, cfg.max_diff_bytes), summary: None, }); } @@ -424,28 +459,10 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let using_external_diff = cli.diff.is_some(); let (branch, file_pairs): (String, Vec<(String, String)>) = if let Some(ref diff_arg) = cli.diff { - let combined = if diff_arg == "-" { - let mut buf = String::new(); - io::stdin().read_to_string(&mut buf)?; - buf - } else { - std::fs::read_to_string(diff_arg) - .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e))? - }; - - if combined.trim().is_empty() { - println!("No diff content found."); - return Ok(()); - } - - let mut per_file = split_diff_by_file(&combined); - if per_file.is_empty() { - per_file = vec![("(diff)".to_string(), combined)]; + match load_external_diff(cli, diff_arg)? { + Some(pair) => pair, + None => return Ok(()), } - let branch = cli.branch.clone().unwrap_or_else(|| { - current_branch().unwrap_or_else(|_| "unknown-branch".to_string()) - }); - (branch, per_file) } else { let branch = current_branch()?; let files = staged_files()?; @@ -474,7 +491,7 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { FileChange { path, category, - diff, + diff: commitbot::truncate_diff(&diff, cfg.max_diff_bytes), summary: None, } }) diff --git a/tests/git.rs b/tests/git.rs index 6678ed5..4b2ef63 100644 --- a/tests/git.rs +++ b/tests/git.rs @@ -1,9 +1,14 @@ use commitbot::git::{ find_first_pr_number, format_git_error, format_pr_commit_appendix_with_remote, - parse_remote_repo, short_commit_hash, split_diff_by_file, staged_diff_for_file, staged_files, - PrItem, PrSummaryMode, + looks_like_commit_hash, parse_remote_repo, resolve_commit_diff, short_commit_hash, + split_diff_by_file, staged_diff_for_file, staged_files, PrItem, PrSummaryMode, }; use std::process::Command; +use std::sync::Mutex; + +/// `std::env::set_current_dir` changes process-wide state, so tests that use +/// it must not run concurrently with each other. +static CWD_LOCK: Mutex<()> = Mutex::new(()); /// Set up a throwaway git repo with a staged change in a nested file, and /// return its tempdir handle plus the nested directory's path. @@ -176,6 +181,7 @@ fn short_commit_hash_short_input() { #[test] fn staged_diff_for_file_works_from_subdirectory() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); let (_dir, nested_dir) = repo_with_staged_nested_file(); let original_cwd = std::env::current_dir().expect("current dir"); @@ -230,6 +236,58 @@ fn format_git_error_standard_git_error() { assert!(msg.contains("fatal: not a git repository")); } +#[test] +fn looks_like_commit_hash_accepts_hex_strings_in_range() { + assert!(looks_like_commit_hash("a5484b6")); + assert!(looks_like_commit_hash("a5484b6ce03e4f1503c7a0fdda7c120bf73c8bc")); + assert!(looks_like_commit_hash("dead")); +} + +#[test] +fn looks_like_commit_hash_rejects_non_hex_or_bad_length() { + assert!(!looks_like_commit_hash("abc")); // too short + assert!(!looks_like_commit_hash("my-changes.diff")); // not hex + assert!(!looks_like_commit_hash("-")); // stdin marker + assert!(!looks_like_commit_hash( + "a5484b6ce03e4f1503c7a0fdda7c120bf73c8bcaa" // too long + )); +} + +#[test] +fn resolve_commit_diff_finds_existing_commit() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = (|| { + let hash = commitbot::git::git_output(&["rev-parse", "HEAD"])? + .trim() + .to_string(); + let diff = resolve_commit_diff(&hash)?.expect("commit should resolve"); + assert!(diff.contains("OrderItem.php")); + anyhow::Ok(()) + })(); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + result.expect("resolve_commit_diff for existing commit"); +} + +#[test] +fn resolve_commit_diff_returns_none_for_unknown_hash() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = resolve_commit_diff("deadbeef"); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + assert_eq!(result.expect("should not error"), None); +} + #[test] fn format_git_error_empty_stderr() { let err = format_git_error(&["status"], Some(1), ""); From 9322e4cf39322a22ba56a51fde77c9ac6e9db3f4 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 23 Sep 2026 12:39:01 -0400 Subject: [PATCH 35/40] Introduce type alias for branch diffs - Create a named type for the branch diffs data structure to improve code readability. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=434, completion=390, total=824 --- src/main.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index a0c013d..4dffc2b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -285,13 +285,13 @@ fn read_diff_arg(diff_arg: &str) -> Result { } } +/// Branch name paired with a list of (file path, diff) pairs. +type BranchDiffs = (String, Vec<(String, String)>); + /// Load per-file diffs from `--diff `, splitting a combined diff /// into (path, diff) pairs. Returns `None` when the resolved content is /// empty (already reported to the user). -fn load_external_diff( - cli: &Cli, - diff_arg: &str, -) -> Result)>> { +fn load_external_diff(cli: &Cli, diff_arg: &str) -> Result> { let combined = read_diff_arg(diff_arg)?; if combined.trim().is_empty() { println!("No diff content found."); From da8e69c0004416a73cfbb7d1acec218e9aefe929 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Wed, 23 Sep 2026 14:17:29 -0400 Subject: [PATCH 36/40] 0.7.1 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 043dcd5..1e5dd92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.7.0" +version = "0.7.1" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index c06a0cf..7ffbbe7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.7.0" +version = "0.7.1" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." From 37dad810f22491bfe7f57a8c0800ff49f3a04b9f Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 9 Nov 2026 14:46:58 -0500 Subject: [PATCH 37/40] Enforce lockfile for reproducible builds - Update `Taskfile.yaml` to use the lockfile during local installation. - Ensure consistent dependency versions across environments. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=280, completion=292, total=572 Time: 9.09s --- Taskfile.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index a859054..120a8cc 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -54,7 +54,7 @@ tasks: desc: "Install commitbot binary locally via cargo install --path ." cmds: - brew uninstall mikegarde/tap/commitbot || true - - cargo install --path . --force + - cargo install --path . --force --locked install:brew: desc: "Install commitbot via Homebrew (macOS)" From eb03f66a4c8b69d7ce5a79ba41b6a3bd7166d768 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 9 Nov 2026 14:49:39 -0500 Subject: [PATCH 38/40] Add `--oneline` and `--oneline quiet` output modes - Introduce `--oneline` and `--oneline quiet` flags in `cli_args` and `config`. - Support "quiet" mode to suppress live printing in `ollama`, `openai`, and `stream` clients. - Centralize LLM output reporting and statistics in `src/main.rs`. - Move output formatting to CLI arguments to isolate local display from provider logic. Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=6115, completion=3009, total=9124 Time: 30.32s --- src/cli_args.rs | 15 ++++ src/config.rs | 13 ++++ src/llm/ollama.rs | 16 ++++- src/llm/openai.rs | 10 ++- src/llm/stream.rs | 12 +++- src/main.rs | 173 ++++++++++++++++++++++++++-------------------- src/setup.rs | 5 +- 7 files changed, 164 insertions(+), 80 deletions(-) diff --git a/src/cli_args.rs b/src/cli_args.rs index 7f7544f..5b0ab9f 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -50,6 +50,21 @@ pub struct Cli { #[arg(long, global = true)] pub no_stream: bool, + /// Also emit a single-line version of the generated message (with the + /// LLM stats appended), suitable for worktree/scripted commits. + /// + /// Pass with no value to keep the normal readable output and print the + /// one-line summary afterward. Pass `--oneline quiet` to suppress the + /// normal readable output entirely and print only the one-line summary. + #[arg( + long, + global = true, + value_name = "MODE", + num_args = 0..=1, + default_missing_value = "readable" + )] + pub oneline: Option, + /// Increase verbosity (-v, -vv, -vvv) #[arg(short = 'v', long = "verbose", action = ArgAction::Count)] pub verbose: u8, diff --git a/src/config.rs b/src/config.rs index 3fdb6dd..f5d2404 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,6 +28,12 @@ pub struct Config { /// Larger diffs (e.g. notebooks with embedded base64 output, minified /// bundles) are truncated to avoid exceeding the model's context window. pub max_diff_bytes: usize, + /// `--oneline` was passed (in either mode): emit a one-line summary + /// (message + LLM stats, newlines escaped as `\n`) after generation. + pub oneline: bool, + /// `--oneline quiet`: suppress the normal readable output (including + /// live streaming) and only emit the one-line summary. + pub oneline_quiet: bool, } impl Config { @@ -62,6 +68,11 @@ impl Config { let request_timeout_secs = r.get_u64("request_timeout_secs", 300); let max_diff_bytes = r.get_usize("max_diff_bytes", 20_000); + // CLI-only: not sourced from env/file, since it controls this + // process's own stdout shape rather than provider behavior. + let oneline = cli.oneline.is_some(); + let oneline_quiet = cli.oneline.as_deref() == Some("quiet"); + // Cleanup: trim stray quotes if any upstream included them let provider = provider.trim_matches('"').to_string(); let model = model.trim_matches('"').to_string(); @@ -91,6 +102,8 @@ impl Config { stream, request_timeout_secs, max_diff_bytes, + oneline, + oneline_quiet, }) } } diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index e7fbece..1722f4d 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -56,6 +56,9 @@ pub struct OllamaClient { base_url: String, model: String, stream: bool, + /// When true, suppress live-printed streaming chunks (still captured + /// into the returned string) — used for `--oneline quiet`. + quiet: bool, usage: Mutex, } @@ -68,6 +71,16 @@ struct TokenUsage { impl OllamaClient { pub fn new(base_url: impl Into, model: impl Into, stream: bool, timeout_secs: u64) -> Self { + Self::with_quiet(base_url, model, stream, false, timeout_secs) + } + + pub fn with_quiet( + base_url: impl Into, + model: impl Into, + stream: bool, + quiet: bool, + timeout_secs: u64, + ) -> Self { let http = Client::builder() .timeout(std::time::Duration::from_secs(timeout_secs)) .build() @@ -77,6 +90,7 @@ impl OllamaClient { base_url: base_url.into().trim_end_matches('/').to_string(), model: model.into(), stream, + quiet, usage: Mutex::new(TokenUsage::default()), } } @@ -132,7 +146,7 @@ impl OllamaClient { if stream { let reader = BufReader::new(resp); - let result = read_stream_to_string(reader, parse_stream_line); + let result = read_stream_to_string(reader, self.quiet, parse_stream_line); log::debug!("Ollama response time: {:.2?}", t0.elapsed()); return result; } diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 6007a19..ea07e0d 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -103,6 +103,9 @@ pub struct OpenAiClient { model: String, api_base_url: String, stream: bool, + /// When true, suppress live-printed streaming chunks (still captured + /// into the returned string) — used for `--oneline quiet`. + quiet: bool, /// Name used in logs and error messages (e.g. "OpenAI", "LM Studio"). provider_label: String, model_validation: ModelValidation, @@ -123,6 +126,7 @@ impl OpenAiClient { model, api_base_url, stream, + false, timeout_secs, "OpenAI", ModelValidation::Retrieve, @@ -133,11 +137,13 @@ impl OpenAiClient { /// /// `api_key` is optional: LM Studio serves unauthenticated requests by /// default, and omitting the key sends no `Authorization` header at all. + #[allow(clippy::too_many_arguments)] pub fn openai_compatible( api_key: Option, model: String, api_base_url: String, stream: bool, + quiet: bool, timeout_secs: u64, provider_label: impl Into, model_validation: ModelValidation, @@ -153,6 +159,7 @@ impl OpenAiClient { model, api_base_url: normalize_base_url(&api_base_url), stream, + quiet, provider_label: provider_label.into(), model_validation, usage: Mutex::new(TokenUsage::default()), @@ -274,7 +281,7 @@ impl OpenAiClient { } let reader = BufReader::new(resp); - let result = read_stream_to_string(reader, parse_stream_line); + let result = read_stream_to_string(reader, self.quiet, parse_stream_line); log::debug!( "{} streaming response time: {:.2?}", self.provider_label, @@ -700,6 +707,7 @@ mod tests { "qwen/qwen3-coder-30b".into(), base_url.into(), false, + false, 90, "LM Studio", ModelValidation::List, diff --git a/src/llm/stream.rs b/src/llm/stream.rs index ef50704..e07a3fe 100644 --- a/src/llm/stream.rs +++ b/src/llm/stream.rs @@ -2,7 +2,11 @@ use anyhow::Result; use std::io::{self, BufRead, Write}; /// Read a streaming response line-by-line, printing chunks as they arrive. -pub fn read_stream_to_string(reader: R, mut parse_line: F) -> Result +/// +/// When `quiet` is true, chunks are still captured into the returned string +/// but nothing is written to stdout — used for `--oneline quiet`, where only +/// the final one-line summary should be printed. +pub fn read_stream_to_string(reader: R, quiet: bool, mut parse_line: F) -> Result where R: BufRead, F: FnMut(&str) -> Result>, @@ -19,8 +23,10 @@ where if let Some(chunk) = parse_line(line)? { out.push_str(&chunk); - print!("{}", chunk); - stdout.flush()?; + if !quiet { + print!("{}", chunk); + stdout.flush()?; + } } } diff --git a/src/main.rs b/src/main.rs index 4dffc2b..14069c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,6 +57,89 @@ fn dimmed(text: &str) -> String { format!("\x1b[2m{text}\x1b[0m") } +/// Print `s` only when `--oneline quiet` hasn't asked for silence. +macro_rules! readable_println { + ($cfg:expr) => { + if !$cfg.oneline_quiet { + println!(); + } + }; + ($cfg:expr, $($arg:tt)*) => { + if !$cfg.oneline_quiet { + println!($($arg)*); + } + }; +} + +/// Flatten a generated message onto one line by escaping real newlines as the +/// two-character sequence `\n`, and append the LLM stats when available. +fn oneline_summary(cfg: &Config, msg: &str, usage: Option<(u64, u64, u64)>) -> String { + let mut flat = String::with_capacity(msg.len()); + for ch in msg.trim().chars() { + match ch { + '\n' => flat.push_str("\\n"), + '\r' => {} + _ => flat.push(ch), + } + } + + if let Some((p, c, t)) = usage { + flat.push_str(&format!( + " [{} {} | tokens prompt={} completion={} total={}]", + cfg.provider, cfg.model, p, c, t + )); + } + + flat +} + +/// Run `generate`, print it the normal (readable) way unless `--oneline quiet` +/// was passed, then optionally emit a trailing one-line summary when +/// `--oneline` (in either mode) was passed. +/// +/// Streaming's live chunk-printing already happens (or is suppressed) inside +/// the LLM client itself, based on the same quiet setting, so this function +/// only needs to print the message when *not* streaming. +fn generate_and_report( + cfg: &Config, + llm: &dyn LlmClient, + print_stats: bool, + generate: impl FnOnce() -> Result, +) -> Result { + readable_println!(cfg); + + let t0 = std::time::Instant::now(); + let msg = generate()?; + let elapsed = t0.elapsed(); + + let usage = llm.take_and_reset_usage(); + + if !cfg.oneline_quiet { + // Streaming already printed the message live; just make sure the + // cursor ends up on a fresh line before the footer. + if !cfg.stream { + print!("{msg}"); + } + if !msg.ends_with('\n') { + println!(); + } + + println!(); + if print_stats && let Some((p, c, t)) = usage { + println!("Provider: {} {}", cfg.provider, cfg.model); + println!("Tokens: prompt={}, completion={}, total={}", p, c, t); + } + println!("Time: {elapsed:.2?}"); + } + + if cfg.oneline { + readable_println!(cfg); + println!("{}", oneline_summary(cfg, &msg, usage)); + } + + Ok(msg) +} + fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { use FileCategory::*; @@ -354,8 +437,8 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { }); } - println!(); - println!("Asking {}...", cfg.model); + readable_println!(cfg); + readable_println!(cfg, "Asking {}...", cfg.model); let total = file_changes.len(); let mp = MultiProgress::new(); @@ -429,28 +512,9 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { pb.inc(1); pb.finish_with_message("Done"); - println!(); - - if cfg.stream { - let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - } else { - let t0 = std::time::Instant::now(); - let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - let elapsed = t0.elapsed(); - if msg.ends_with('\n') { - print!("{msg}"); - } else { - println!("{msg}"); - } - println!("Commit message generated in {elapsed:.2?}"); - } - - println!(); - if let Some((p, c, t)) = llm.take_and_reset_usage() { - println!(); - println!("Provider: {} {}", cfg.provider, cfg.model ); - println!("Tokens: prompt={}, completion={}, total={}", p, c, t); - } + generate_and_report(cfg, llm, true, || { + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) + })?; Ok(()) } @@ -497,11 +561,11 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { }) .collect(); - println!(); - println!("Asking {}...", cfg.model); + readable_println!(cfg); + readable_println!(cfg, "Asking {}...", cfg.model); if let Some(ref diff_arg) = cli.diff { let diff_source = if diff_arg == "-" { "stdin" } else { diff_arg }; - println!("Using external diff: {diff_source}"); + readable_println!(cfg, "Using external diff: {diff_source}"); } let total = file_changes.len(); @@ -572,31 +636,11 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { pb.inc(1); pb.finish_with_message("Done"); - println!(); - - if cfg.stream { - let _msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - } else { - let t0 = std::time::Instant::now(); - let msg = llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref())?; - let elapsed = t0.elapsed(); - if msg.ends_with('\n') { - print!("{msg}"); - } else { - println!("{msg}"); - } - println!("Commit message generated in {elapsed:.2?}"); - } - - println!(); - if let Some((p, c, t)) = llm.take_and_reset_usage() { - println!(); - println!("Provider: {} {}", cfg.provider, cfg.model ); - println!("Tokens: prompt={}, completion={}, total={}", p, c, t); - } + generate_and_report(cfg, llm, true, || { + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) + })?; Ok(()) - } fn run_pr( cli: &Cli, @@ -645,33 +689,14 @@ fn run_pr( log::info!("Found {} commits in range.", items.len()); let ticket_summary = resolved_ticket_summary(cli); - let _pr_message = if cfg.stream { - println!(); - let t0 = std::time::Instant::now(); - let msg = - llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; - println!("\nPR message generated in {:.2?}", t0.elapsed()); - msg - } else { - println!(); - let t0 = std::time::Instant::now(); - let msg = - llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref())?; - let elapsed = t0.elapsed(); - - if msg.ends_with('\n') { - print!("{msg}"); - } else { - println!("{msg}"); - } - println!("PR message generated in {elapsed:.2?}"); - msg - }; + generate_and_report(cfg, llm, false, || { + llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref()) + })?; let appendix = format_pr_commit_appendix(&items); if !appendix.is_empty() { - println!(); - println!("{appendix}"); + readable_println!(cfg); + readable_println!(cfg, "{appendix}"); } Ok(()) diff --git a/src/setup.rs b/src/setup.rs index 85990ab..4d2d652 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -32,6 +32,7 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.model.clone(), base_url, cfg.stream, + cfg.oneline_quiet, cfg.request_timeout_secs, "OpenAI", validation, @@ -50,10 +51,11 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.request_timeout_secs ); - Ok(Box::new(OllamaClient::new( + Ok(Box::new(OllamaClient::with_quiet( base_url, cfg.model.clone(), cfg.stream, + cfg.oneline_quiet, cfg.request_timeout_secs, ))) } @@ -76,6 +78,7 @@ pub fn build_llm_client(cfg: &Config) -> Result> { cfg.model.clone(), base_url, cfg.stream, + cfg.oneline_quiet, cfg.request_timeout_secs, "LM Studio", ModelValidation::List, From 38b8967201ff16d048e4c5048759b649fe0c4097 Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 9 Nov 2026 15:14:50 -0500 Subject: [PATCH 39/40] Implement token usage tracking and expand tests - Enable token usage tracking for Ollama and OpenAI streaming - Refactor stream reading into a generic writer for testability - Centralize report formatting and add support for optional appendices - Add E2E tests with a mock server and expand unit tests Provider: lmstudio google/gemma-4-12b-qat Tokens: prompt=11327, completion=3985, total=15312 Time: 28.18s --- src/llm/ollama.rs | 43 +++++- src/llm/openai.rs | 63 +++++++- src/llm/stream.rs | 93 +++++++++++- src/main.rs | 72 +++++++-- tests/config.rs | 42 ++++++ tests/oneline_output.rs | 326 ++++++++++++++++++++++++++++++++++++++++ tests/setup.rs | 31 ++++ 7 files changed, 643 insertions(+), 27 deletions(-) create mode 100644 tests/oneline_output.rs create mode 100644 tests/setup.rs diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 1722f4d..898d132 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -28,6 +28,11 @@ struct OllamaChatResponse { struct OllamaStreamResponse { message: Option, done: Option, + /// Token counts, reported only on the final (`done`) chunk. + #[musli(default)] + prompt_eval_count: Option, + #[musli(default)] + eval_count: Option, } #[derive(Debug, Decode)] @@ -146,7 +151,15 @@ impl OllamaClient { if stream { let reader = BufReader::new(resp); - let result = read_stream_to_string(reader, self.quiet, parse_stream_line); + let result = read_stream_to_string(reader, self.quiet, |line| { + if let Some((prompt, completion)) = parse_stream_usage(line) { + let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); + u.prompt_tokens += prompt; + u.completion_tokens += completion; + u.total_tokens += prompt + completion; + } + parse_stream_line(line) + }); log::debug!("Ollama response time: {:.2?}", t0.elapsed()); return result; } @@ -197,6 +210,17 @@ impl OllamaClient { } } +/// (prompt, completion) token counts from a final streamed chunk, if present. +fn parse_stream_usage(line: &str) -> Option<(u64, u64)> { + let parsed: OllamaStreamResponse = json::from_str(line).ok()?; + if !parsed.done.unwrap_or(false) { + return None; + } + let prompt = parsed.prompt_eval_count? as u64; + let completion = parsed.eval_count.unwrap_or(0) as u64; + Some((prompt, completion)) +} + fn parse_stream_line(line: &str) -> Result> { let parsed: OllamaStreamResponse = json::from_str(line).map_err(|e| anyhow!("Failed to decode Ollama stream JSON: {e}"))?; @@ -310,4 +334,21 @@ mod tests { .iter() .any(|model| model.name == "missing:model")); } + + #[test] + fn reads_token_counts_from_the_final_stream_chunk() { + let line = r#"{"message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":12,"eval_count":5}"#; + assert_eq!(parse_stream_usage(line), Some((12, 5))); + } + + #[test] + fn stream_usage_is_none_until_the_final_chunk() { + let mid = r#"{"message":{"role":"assistant","content":"hi"},"done":false}"#; + assert_eq!(parse_stream_usage(mid), None); + + let done_without_counts = r#"{"message":{"role":"assistant","content":""},"done":true}"#; + assert_eq!(parse_stream_usage(done_without_counts), None); + + assert_eq!(parse_stream_usage("not json"), None); + } } diff --git a/src/llm/openai.rs b/src/llm/openai.rs index ea07e0d..6104980 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -241,26 +241,36 @@ impl OpenAiClient { .ok_or_else(|| anyhow!("no content returned from {}", self.provider_label))?; if let Some(usage) = &chat_resp.usage { - // Recover from a poisoned mutex instead of panicking so the CLI - // can continue in the face of concurrent thread panics. - let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); - u.prompt_tokens += usage.prompt_tokens as u64; - u.completion_tokens += usage.completion_tokens as u64; - u.total_tokens += usage.total_tokens as u64; + self.record_usage(usage); } Ok(content) } + /// Add a response's token counts to the running totals. + fn record_usage(&self, usage: &ChatUsage) { + // Recover from a poisoned mutex instead of panicking so the CLI + // can continue in the face of concurrent thread panics. + let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); + u.prompt_tokens += usage.prompt_tokens as u64; + u.completion_tokens += usage.completion_tokens as u64; + u.total_tokens += usage.total_tokens as u64; + } + fn call_chat_streaming(&self, req: &ChatRequest) -> Result { let url = self.chat_url(); log::info!("Streaming {} model {:?}", self.provider_label, req.model); + // Streamed responses only carry token usage (in a final chunk) when + // asked to. + let mut body = serde_json::to_value(req).context("failed to encode streaming request")?; + body["stream_options"] = serde_json::json!({ "include_usage": true }); + let t0 = std::time::Instant::now(); let resp = self .authed(self.client.post(&url)) - .json(req) + .json(&body) .send() .with_context(|| { format!( @@ -281,7 +291,12 @@ impl OpenAiClient { } let reader = BufReader::new(resp); - let result = read_stream_to_string(reader, self.quiet, parse_stream_line); + let result = read_stream_to_string(reader, self.quiet, |line| { + if let Some(usage) = parse_stream_usage(line) { + self.record_usage(&usage); + } + parse_stream_line(line) + }); log::debug!( "{} streaming response time: {:.2?}", self.provider_label, @@ -447,6 +462,20 @@ pub fn matches_model_id(configured: &str, candidate: &str) -> bool { conf_clean.eq_ignore_ascii_case(cand_clean) } +#[derive(Deserialize)] +struct StreamUsageChunk { + usage: Option, +} + +/// Token usage from the final streamed chunk, when the server sends one. +fn parse_stream_usage(line: &str) -> Option { + let data = line.trim_start().strip_prefix("data:")?.trim(); + if data == "[DONE]" { + return None; + } + serde_json::from_str::(data).ok()?.usage +} + fn parse_stream_line(line: &str) -> Result> { let line = line.trim_start(); if !line.starts_with("data:") { @@ -669,6 +698,24 @@ fn truncate(s: &str, max_len: usize) -> String { mod tests { use super::*; + #[test] + fn parses_usage_from_the_final_stream_chunk() { + let usage = parse_stream_usage( + r#"data: {"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":4,"total_tokens":7}}"#, + ) + .expect("usage chunk"); + assert_eq!((usage.prompt_tokens, usage.completion_tokens, usage.total_tokens), (3, 4, 7)); + } + + #[test] + fn stream_usage_ignores_content_chunks_done_and_garbage() { + assert!(parse_stream_usage(r#"data: {"choices":[{"delta":{"content":"hi"}}]}"#).is_none()); + assert!(parse_stream_usage(r#"data: {"choices":[{"delta":{"content":"hi"}}],"usage":null}"#).is_none()); + assert!(parse_stream_usage("data: [DONE]").is_none()); + assert!(parse_stream_usage("data: not json").is_none()); + assert!(parse_stream_usage(": keep-alive").is_none()); + } + #[test] fn builds_model_url_from_root_base() { let client = OpenAiClient::new( diff --git a/src/llm/stream.rs b/src/llm/stream.rs index e07a3fe..f34f674 100644 --- a/src/llm/stream.rs +++ b/src/llm/stream.rs @@ -6,13 +6,28 @@ use std::io::{self, BufRead, Write}; /// When `quiet` is true, chunks are still captured into the returned string /// but nothing is written to stdout — used for `--oneline quiet`, where only /// the final one-line summary should be printed. -pub fn read_stream_to_string(reader: R, quiet: bool, mut parse_line: F) -> Result +pub fn read_stream_to_string(reader: R, quiet: bool, parse_line: F) -> Result where R: BufRead, F: FnMut(&str) -> Result>, { - let mut out = String::new(); - let mut stdout = io::stdout(); + read_stream_to_writer(reader, quiet, &mut io::stdout(), parse_line) +} + +/// Same as [`read_stream_to_string`], but echoes chunks to `out` instead of +/// stdout so the quiet/non-quiet behavior can be tested. +fn read_stream_to_writer( + reader: R, + quiet: bool, + out: &mut W, + mut parse_line: F, +) -> Result +where + R: BufRead, + W: Write, + F: FnMut(&str) -> Result>, +{ + let mut captured = String::new(); for line in reader.lines() { let line = line?; @@ -22,13 +37,77 @@ where } if let Some(chunk) = parse_line(line)? { - out.push_str(&chunk); + captured.push_str(&chunk); if !quiet { - print!("{}", chunk); - stdout.flush()?; + write!(out, "{}", chunk)?; + out.flush()?; } } } - Ok(out) + Ok(captured) +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::anyhow; + + /// Treat every non-empty line as a chunk, except `skip` which yields none. + fn echo_lines(line: &str) -> Result> { + Ok(if line == "skip" { None } else { Some(line.to_string()) }) + } + + #[test] + fn echoes_chunks_and_returns_them_when_not_quiet() { + let mut out = Vec::new(); + let result = + read_stream_to_writer("one\ntwo\n".as_bytes(), false, &mut out, echo_lines).unwrap(); + + assert_eq!(result, "onetwo"); + assert_eq!(String::from_utf8(out).unwrap(), "onetwo"); + } + + #[test] + fn quiet_captures_chunks_without_writing_anything() { + let mut out = Vec::new(); + let result = + read_stream_to_writer("one\ntwo\n".as_bytes(), true, &mut out, echo_lines).unwrap(); + + assert_eq!(result, "onetwo"); + assert!(out.is_empty(), "quiet mode must not write: {out:?}"); + } + + #[test] + fn skips_blank_lines_and_lines_without_a_chunk() { + let mut out = Vec::new(); + let result = read_stream_to_writer( + "\n \none\nskip\n\ntwo\n".as_bytes(), + false, + &mut out, + echo_lines, + ) + .unwrap(); + + assert_eq!(result, "onetwo"); + assert_eq!(String::from_utf8(out).unwrap(), "onetwo"); + } + + #[test] + fn propagates_parse_errors() { + let mut out = Vec::new(); + let err = read_stream_to_writer("boom\n".as_bytes(), false, &mut out, |_| { + Err(anyhow!("bad chunk")) + }) + .unwrap_err(); + + assert!(err.to_string().contains("bad chunk")); + } + + #[test] + fn public_wrapper_returns_captured_text() { + // Quiet so the test doesn't spray into the harness's stdout. + let result = read_stream_to_string("a\nb\n".as_bytes(), true, echo_lines).unwrap(); + assert_eq!(result, "ab"); + } } diff --git a/src/main.rs b/src/main.rs index 14069c6..7a4ae92 100644 --- a/src/main.rs +++ b/src/main.rs @@ -97,13 +97,16 @@ fn oneline_summary(cfg: &Config, msg: &str, usage: Option<(u64, u64, u64)>) -> S /// was passed, then optionally emit a trailing one-line summary when /// `--oneline` (in either mode) was passed. /// +/// `appendix` is extra readable text (e.g. the PR commit list) printed between +/// the message and the Provider/Tokens/Time footer, so the footer is always last. +/// /// Streaming's live chunk-printing already happens (or is suppressed) inside /// the LLM client itself, based on the same quiet setting, so this function /// only needs to print the message when *not* streaming. fn generate_and_report( cfg: &Config, llm: &dyn LlmClient, - print_stats: bool, + appendix: &str, generate: impl FnOnce() -> Result, ) -> Result { readable_println!(cfg); @@ -124,8 +127,13 @@ fn generate_and_report( println!(); } + if !appendix.is_empty() { + println!(); + println!("{appendix}"); + } + println!(); - if print_stats && let Some((p, c, t)) = usage { + if let Some((p, c, t)) = usage { println!("Provider: {} {}", cfg.provider, cfg.model); println!("Tokens: prompt={}, completion={}, total={}", p, c, t); } @@ -512,7 +520,7 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { pb.inc(1); pb.finish_with_message("Done"); - generate_and_report(cfg, llm, true, || { + generate_and_report(cfg, llm, "", || { llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) })?; @@ -636,7 +644,7 @@ fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { pb.inc(1); pb.finish_with_message("Done"); - generate_and_report(cfg, llm, true, || { + generate_and_report(cfg, llm, "", || { llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) })?; @@ -689,16 +697,11 @@ fn run_pr( log::info!("Found {} commits in range.", items.len()); let ticket_summary = resolved_ticket_summary(cli); - generate_and_report(cfg, llm, false, || { + let appendix = format_pr_commit_appendix(&items); + generate_and_report(cfg, llm, &appendix, || { llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref()) })?; - let appendix = format_pr_commit_appendix(&items); - if !appendix.is_empty() { - readable_println!(cfg); - readable_println!(cfg, "{appendix}"); - } - Ok(()) } @@ -753,3 +756,50 @@ fn main() -> Result<()> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn test_config() -> Config { + Config { + provider: "lmstudio".into(), + openai_api_key: None, + base_url: None, + model: "test-model".into(), + max_concurrent_requests: 1, + stream: false, + request_timeout_secs: 5, + max_diff_bytes: 1_000, + oneline: true, + oneline_quiet: false, + } + } + + #[test] + fn oneline_summary_escapes_newlines_and_appends_stats() { + let cfg = test_config(); + let flat = oneline_summary(&cfg, "Subject\n\n- one\n- two", Some((10, 20, 30))); + + assert_eq!( + flat, + "Subject\\n\\n- one\\n- two [lmstudio test-model | tokens prompt=10 completion=20 total=30]" + ); + assert!(!flat.contains('\n')); + } + + #[test] + fn oneline_summary_without_usage_has_no_stats_suffix() { + let cfg = test_config(); + assert_eq!(oneline_summary(&cfg, "Subject\n- body", None), "Subject\\n- body"); + } + + #[test] + fn oneline_summary_trims_and_drops_carriage_returns() { + let cfg = test_config(); + assert_eq!( + oneline_summary(&cfg, "\n Subject\r\n- body\r\n\n", None), + "Subject\\n- body" + ); + } +} diff --git a/tests/config.rs b/tests/config.rs index b6c8de5..88a3297 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -216,3 +216,45 @@ url = "http://192.168.1.16:1234/v1" fs::remove_file(config_path).ok(); } + +fn cfg_for(args: &[&str]) -> Config { + let missing = unique_config_path("oneline"); + // ollama needs no API key, so this works regardless of the environment. + let mut argv = vec![ + "commitbot", + "--config", + missing.to_str().expect("utf-8 path"), + "--provider", + "ollama", + ]; + argv.extend_from_slice(args); + Config::from_sources(&Cli::parse_from(argv)).expect("config should resolve") +} + +#[test] +fn oneline_is_off_by_default() { + let cfg = cfg_for(&[]); + assert!(!cfg.oneline); + assert!(!cfg.oneline_quiet); +} + +#[test] +fn bare_oneline_keeps_readable_output() { + let cfg = cfg_for(&["--oneline"]); + assert!(cfg.oneline); + assert!(!cfg.oneline_quiet); +} + +#[test] +fn oneline_quiet_suppresses_readable_output() { + let cfg = cfg_for(&["--oneline", "quiet"]); + assert!(cfg.oneline); + assert!(cfg.oneline_quiet); +} + +#[test] +fn oneline_with_any_other_mode_stays_readable() { + let cfg = cfg_for(&["--oneline", "readable"]); + assert!(cfg.oneline); + assert!(!cfg.oneline_quiet); +} diff --git a/tests/oneline_output.rs b/tests/oneline_output.rs new file mode 100644 index 0000000..1184a1c --- /dev/null +++ b/tests/oneline_output.rs @@ -0,0 +1,326 @@ +//! End-to-end tests for the output modes (`--oneline`, `--oneline quiet`) and +//! the trailing Provider/Tokens/Time footer. +//! +//! They run the real binary against a tiny in-process fake of an +//! OpenAI-compatible server (what LM Studio speaks), so no network or real +//! model is needed. + +use assert_cmd::cargo; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::thread; + +const MESSAGE_PARTS: [&str; 2] = ["Add widget\n\n", "- first bullet\n- second bullet"]; +const MESSAGE: &str = "Add widget\n\n- first bullet\n- second bullet"; +const ESCAPED_MESSAGE: &str = "Add widget\\n\\n- first bullet\\n- second bullet"; + +const DIFF: &str = "diff --git a/src/widget.rs b/src/widget.rs\n\ +index 111..222 100644\n\ +--- a/src/widget.rs\n\ ++++ b/src/widget.rs\n\ +@@ -1,2 +1,3 @@\n\ + fn widget() {}\n\ ++fn gadget() {}\n"; + +/// Read one HTTP request, returning (request line, body). +fn read_request(stream: &mut TcpStream) -> Option<(String, String)> { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let header_end = loop { + let n = stream.read(&mut chunk).ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break pos + 4; + } + }; + + let head = String::from_utf8_lossy(&buf[..header_end]).to_string(); + let content_length = head + .lines() + .find_map(|l| { + let (k, v) = l.split_once(':')?; + k.eq_ignore_ascii_case("content-length").then(|| v.trim().parse::().ok())? + }) + .unwrap_or(0); + + while buf.len() < header_end + content_length { + let n = stream.read(&mut chunk).ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + + let body = String::from_utf8_lossy(&buf[header_end..]).to_string(); + let request_line = head.lines().next().unwrap_or("").to_string(); + Some((request_line, body)) +} + +fn respond(stream: &mut TcpStream, content_type: &str, body: &str) { + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); +} + +fn handle(mut stream: TcpStream) { + let Some((request_line, body)) = read_request(&mut stream) else { + return; + }; + + if request_line.contains("/api/chat") { + // Ollama: NDJSON when streaming, a single JSON document otherwise. + if body.contains("\"stream\":true") { + let mut nd = String::new(); + for part in MESSAGE_PARTS { + nd.push_str(&format!( + "{}\n", + serde_json::json!({ "message": { "role": "assistant", "content": part }, "done": false }) + )); + } + nd.push_str(&format!("{}\n", serde_json::json!({ "message": { "role": "assistant", "content": "" }, "done": true, "prompt_eval_count": 11, "eval_count": 7 }))); + respond(&mut stream, "application/x-ndjson", &nd); + } else { + let body = serde_json::json!({ + "message": { "role": "assistant", "content": MESSAGE }, + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }) + .to_string(); + respond(&mut stream, "application/json", &body); + } + } else if request_line.contains("/models") { + let body = serde_json::json!({ "data": [{ "id": "test-model" }] }).to_string(); + respond(&mut stream, "application/json", &body); + } else if body.contains("\"stream\":true") { + let mut sse = String::new(); + for part in MESSAGE_PARTS { + let chunk = serde_json::json!({ "choices": [{ "delta": { "content": part } }] }); + sse.push_str(&format!("data: {chunk}\n\n")); + } + // Like a real server, report usage in a trailing chunk, but only when + // the client asked for it. + if body.contains("include_usage") { + let usage = serde_json::json!({ + "choices": [], + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }); + sse.push_str(&format!("data: {usage}\n\n")); + } + sse.push_str("data: [DONE]\n\n"); + respond(&mut stream, "text/event-stream", &sse); + } else { + let body = serde_json::json!({ + "choices": [{ "message": { "content": MESSAGE } }], + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }) + .to_string(); + respond(&mut stream, "application/json", &body); + } +} + +/// Start the fake server on a free port; it lives until the test process exits. +fn spawn_fake_server() -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fake server"); + let url = format!("http://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + thread::spawn(move || handle(stream)); + } + }); + url +} + +struct Run { + stdout: String, + stderr: String, +} + +fn run_commitbot(extra_args: &[&str]) -> Run { + run_commitbot_with("lmstudio", extra_args) +} + +fn run_commitbot_with(provider: &str, extra_args: &[&str]) -> Run { + let url = spawn_fake_server(); + let dir = tempfile::tempdir().expect("tempdir"); + let diff_path: PathBuf = dir.path().join("change.diff"); + std::fs::write(&diff_path, DIFF).unwrap(); + + let output = cargo::cargo_bin_cmd!() + .current_dir(dir.path()) + // Never pick up the developer's real config or credentials. + .env("HOME", dir.path()) + .env_remove("OPENAI_API_KEY") + .args(["--config", dir.path().join("none.toml").to_str().unwrap()]) + .args(["--provider", provider, "--model", "test-model", "--url", &url]) + .args(["--branch", "main", "--diff", diff_path.to_str().unwrap()]) + .args(extra_args) + .output() + .expect("run commitbot"); + + let run = Run { + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + }; + assert!(output.status.success(), "commitbot failed: {}", run.stderr); + run +} + +fn assert_footer_order(stdout: &str) { + let provider = stdout.find("Provider: ").expect("Provider line"); + let tokens = stdout.find("Tokens:").expect("Tokens line"); + let time = stdout.find("Time:").expect("Time line"); + assert!(provider < tokens && tokens < time, "footer order wrong:\n{stdout}"); + assert!(!stdout.contains("generated in"), "old timing line is back:\n{stdout}"); +} + +#[test] +fn default_output_streams_message_then_footer() { + let run = run_commitbot(&[]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); + // The streamed message has no trailing newline; the footer must not be + // glued onto its last line. + assert!( + run.stdout.contains("- second bullet\n"), + "footer ran into message:\n{}", + run.stdout + ); + assert!(!run.stdout.contains(ESCAPED_MESSAGE)); +} + +#[test] +fn no_stream_output_prints_message_then_footer() { + let run = run_commitbot(&["--no-stream"]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); +} + +#[test] +fn oneline_adds_a_summary_after_the_readable_output() { + for extra in [&["--oneline"][..], &["--oneline", "--no-stream"][..]] { + let run = run_commitbot(extra); + + assert!(run.stdout.contains("Asking test-model"), "readable output missing"); + assert_footer_order(&run.stdout); + + let last = run.stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap(); + assert!(last.starts_with(ESCAPED_MESSAGE), "one-liner wrong: {last}"); + assert!(last.contains("[lmstudio test-model | tokens prompt="), "stats missing: {last}"); + } +} + +#[test] +fn oneline_quiet_prints_only_the_summary_line() { + for extra in [&["--oneline", "quiet"][..], &["--oneline=quiet", "--no-stream"][..]] { + let run = run_commitbot(extra); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); + assert!(lines[0].contains("[lmstudio test-model | tokens prompt=")); + + for noise in ["Asking", "Provider:", "Tokens:", "Time:", "Using external diff"] { + assert!(!run.stdout.contains(noise), "{noise:?} leaked:\n{}", run.stdout); + } + } +} + +#[test] +fn ollama_quiet_streaming_prints_only_the_summary_line() { + for extra in [&["--oneline", "quiet"][..], &["--oneline", "quiet", "--no-stream"][..]] { + let run = run_commitbot_with("ollama", extra); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); + assert!(lines[0].contains("[ollama test-model | tokens prompt="), "stats: {}", lines[0]); + } +} + +#[test] +fn ollama_default_output_streams_message_then_footer() { + let run = run_commitbot_with("ollama", &[]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); +} + +fn git(dir: &std::path::Path, args: &[&str]) { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(["-c", "user.name=Test", "-c", "user.email=test@example.com"]) + .args(["-c", "commit.gpgsign=false", "-c", "init.defaultBranch=main"]) + .args(args) + .output() + .expect("run git"); + assert!(out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// Run `commitbot pr main feature` in a throwaway repo with one commit ahead. +fn run_pr(extra_args: &[&str]) -> Run { + let url = spawn_fake_server(); + let dir = tempfile::tempdir().expect("tempdir"); + let repo = dir.path(); + + git(repo, &["init", "-q"]); + std::fs::write(repo.join("a.txt"), "one\n").unwrap(); + git(repo, &["add", "."]); + git(repo, &["commit", "-q", "-m", "Initial commit"]); + git(repo, &["checkout", "-q", "-b", "feature"]); + std::fs::write(repo.join("a.txt"), "two\n").unwrap(); + git(repo, &["commit", "-q", "-am", "Add the second line"]); + + let output = cargo::cargo_bin_cmd!() + .current_dir(repo) + .env("HOME", repo) + .env_remove("OPENAI_API_KEY") + .args(["--config", repo.join("none.toml").to_str().unwrap()]) + .args(["--provider", "lmstudio", "--model", "test-model", "--url", &url]) + .args(extra_args) + .args(["pr", "main", "feature"]) + .output() + .expect("run commitbot pr"); + + let run = Run { + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + }; + assert!(output.status.success(), "commitbot pr failed: {}", run.stderr); + run +} + +#[test] +fn pr_output_puts_the_footer_below_the_commit_appendix() { + for extra in [&["--no-stream"][..], &[][..]] { + let run = run_pr(extra); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); + assert!( + run.stdout.contains("Tokens: prompt=11, completion=7, total=18"), + "token counts missing:\n{}", + run.stdout + ); + + let commits = run.stdout.find("Add the second line").expect("commit appendix missing"); + let provider = run.stdout.find("Provider: ").unwrap(); + assert!(commits < provider, "footer must come after the commit list:\n{}", run.stdout); + assert!(run.stdout.trim_end().lines().last().unwrap().starts_with("Time:")); + } +} + +#[test] +fn pr_oneline_quiet_prints_only_the_summary_line() { + let run = run_pr(&["--oneline", "quiet", "--no-stream"]); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); +} diff --git a/tests/setup.rs b/tests/setup.rs new file mode 100644 index 0000000..17401de --- /dev/null +++ b/tests/setup.rs @@ -0,0 +1,31 @@ +use clap::Parser; +use commitbot::config::Config; +use commitbot::setup::build_llm_client; +use commitbot::Cli; + +fn build(args: &[&str]) -> anyhow::Result<()> { + let missing = std::env::temp_dir().join("commitbot_setup_test_missing.toml"); + let mut argv = vec!["commitbot", "--config", missing.to_str().unwrap()]; + argv.extend_from_slice(args); + let cfg = Config::from_sources(&Cli::parse_from(argv))?; + build_llm_client(&cfg).map(|_| ()) +} + +#[test] +fn builds_every_provider_with_and_without_quiet_oneline() { + for quiet in [&[][..], &["--oneline", "quiet"][..]] { + for provider_args in [ + &["--provider", "openai", "--api-key", "test-key", "--model", "m"][..], + &["--provider", "ollama", "--url", "http://localhost:11434", "--model", "m"][..], + &["--provider", "lmstudio", "--url", "http://localhost:1234", "--model", "m"][..], + ] { + let args: Vec<&str> = provider_args.iter().chain(quiet).copied().collect(); + build(&args).unwrap_or_else(|e| panic!("{args:?} failed: {e}")); + } + } +} + +#[test] +fn rejects_unknown_provider() { + assert!(build(&["--provider", "nope", "--model", "m"]).is_err()); +} From 1232a7aae0eebe1c8e74d65bd0b6f0c96db5851a Mon Sep 17 00:00:00 2001 From: Mike Garde Date: Mon, 9 Nov 2026 15:26:01 -0500 Subject: [PATCH 40/40] 0.8.0 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1e5dd92..1c2eb2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -257,7 +257,7 @@ dependencies = [ [[package]] name = "commitbot" -version = "0.7.1" +version = "0.8.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 7ffbbe7..84b777d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.7.1" +version = "0.8.0" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs."