| 1 | //! Git history tools: `git_log`, `git_show`, and `git_blame`. |
| 2 | //! |
| 3 | //! These tools provide read-only access to commit history and attribution |
| 4 | //! without exposing arbitrary shell execution. |
| 5 | |
| 6 | use std::fs; |
| 7 | use std::path::{Path, PathBuf}; |
| 8 | use std::process::Output; |
| 9 | |
| 10 | use async_trait::async_trait; |
| 11 | use serde_json::{Value, json}; |
| 12 | |
| 13 | use super::git::run_git_command_async; |
| 14 | use super::spec::{ |
| 15 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 16 | optional_bool, optional_str, optional_u64, required_str, |
| 17 | }; |
| 18 | use codewhale_dependencies::ExternalTool; |
| 19 | |
| 20 | const DEFAULT_LOG_MAX_COUNT: u64 = 20; |
| 21 | const MAX_LOG_MAX_COUNT: u64 = 200; |
| 22 | const DEFAULT_UNIFIED: u64 = 3; |
| 23 | const MAX_UNIFIED: u64 = 50; |
| 24 | const DEFAULT_BLAME_START_LINE: u64 = 1; |
| 25 | const DEFAULT_BLAME_MAX_LINES: u64 = 200; |
| 26 | const MAX_BLAME_MAX_LINES: u64 = 2_000; |
| 27 | |
| 28 | /// Tool for reading recent commit history. |
| 29 | pub struct GitLogTool; |
| 30 | |
| 31 | #[async_trait] |
| 32 | impl ToolSpec for GitLogTool { |
| 33 | fn name(&self) -> &'static str { |
| 34 | "git_log" |
| 35 | } |
| 36 | |
| 37 | fn model_visible(&self) -> bool { |
| 38 | false |
| 39 | } |
| 40 | |
| 41 | fn description(&self) -> &'static str { |
| 42 | "Run `git log` in the workspace with optional path and author/date filters." |
| 43 | } |
| 44 | |
| 45 | fn input_schema(&self) -> Value { |
| 46 | json!({ |
| 47 | "type": "object", |
| 48 | "properties": { |
| 49 | "path": { |
| 50 | "type": "string", |
| 51 | "description": "Optional subdirectory or file path to scope history to." |
| 52 | }, |
| 53 | "max_count": { |
| 54 | "type": "integer", |
| 55 | "minimum": 1, |
| 56 | "maximum": MAX_LOG_MAX_COUNT, |
| 57 | "default": DEFAULT_LOG_MAX_COUNT, |
| 58 | "description": "Maximum number of commits to return." |
| 59 | }, |
| 60 | "author": { |
| 61 | "type": "string", |
| 62 | "description": "Optional git author filter (same semantics as `git log --author`)." |
| 63 | }, |
| 64 | "since": { |
| 65 | "type": "string", |
| 66 | "description": "Optional lower date bound, e.g. '2 weeks ago' or ISO date." |
| 67 | }, |
| 68 | "until": { |
| 69 | "type": "string", |
| 70 | "description": "Optional upper date bound, e.g. 'yesterday' or ISO date." |
| 71 | } |
| 72 | }, |
| 73 | "additionalProperties": false |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 78 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 79 | } |
| 80 | |
| 81 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 82 | ApprovalRequirement::Auto |
| 83 | } |
| 84 | |
| 85 | fn supports_parallel(&self) -> bool { |
| 86 | true |
| 87 | } |
| 88 | |
| 89 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 90 | let git_ctx = resolve_git_context(context, optional_str(&input, "path")?)?; |
| 91 | let max_count = |
| 92 | optional_u64(&input, "max_count", DEFAULT_LOG_MAX_COUNT)?.clamp(1, MAX_LOG_MAX_COUNT); |
| 93 | let author = optional_str(&input, "author")?.map(ToOwned::to_owned); |
| 94 | let since = optional_str(&input, "since")?.map(ToOwned::to_owned); |
| 95 | let until = optional_str(&input, "until")?.map(ToOwned::to_owned); |
| 96 | |
| 97 | let mut args = vec![ |
| 98 | "log".to_string(), |
| 99 | "--no-color".to_string(), |
| 100 | format!("--max-count={max_count}"), |
| 101 | "--date=iso-strict".to_string(), |
| 102 | "--pretty=format:%H%nAuthor: %an <%ae>%nDate: %ad%nSubject: %s%n".to_string(), |
| 103 | ]; |
| 104 | if let Some(author) = &author { |
| 105 | args.push(format!("--author={author}")); |
| 106 | } |
| 107 | if let Some(since) = &since { |
| 108 | args.push(format!("--since={since}")); |
| 109 | } |
| 110 | if let Some(until) = &until { |
| 111 | args.push(format!("--until={until}")); |
| 112 | } |
| 113 | if let Some(pathspec) = &git_ctx.pathspec { |
| 114 | args.push("--".to_string()); |
| 115 | args.push(pathspec.display().to_string()); |
| 116 | } |
| 117 | |
| 118 | let command_str = format_command(&git_ctx.working_dir, &args); |
| 119 | let output = run_git_command_async(git_ctx.working_dir.clone(), args).await?; |
| 120 | if !output.status.success() { |
| 121 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 122 | return Ok( |
| 123 | ToolResult::error(format!("git log failed: {}", stderr.trim())).with_metadata( |
| 124 | json!({ |
| 125 | "command": command_str, |
| 126 | "exit_code": output.status.code(), |
| 127 | "stderr": stderr.trim(), |
| 128 | }), |
| 129 | ), |
| 130 | ); |
| 131 | } |
| 132 | |
| 133 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 134 | let content = stdout.into_owned(); |
| 135 | Ok(ToolResult::success(content).with_metadata(json!({ |
| 136 | "command": command_str, |
| 137 | "working_dir": git_ctx.working_dir, |
| 138 | "pathspec": git_ctx.pathspec, |
| 139 | "max_count": max_count, |
| 140 | "author": author, |
| 141 | "since": since, |
| 142 | "until": until, |
| 143 | }))) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// Tool for showing a specific commit with optional patch/stat output. |
| 148 | pub struct GitShowTool; |
| 149 | |
| 150 | #[async_trait] |
| 151 | impl ToolSpec for GitShowTool { |
| 152 | fn name(&self) -> &'static str { |
| 153 | "git_show" |
| 154 | } |
| 155 | |
| 156 | fn model_visible(&self) -> bool { |
| 157 | false |
| 158 | } |
| 159 | |
| 160 | fn description(&self) -> &'static str { |
| 161 | "Run `git show` for a specific revision with optional patch and stats." |
| 162 | } |
| 163 | |
| 164 | fn input_schema(&self) -> Value { |
| 165 | json!({ |
| 166 | "type": "object", |
| 167 | "properties": { |
| 168 | "rev": { |
| 169 | "type": "string", |
| 170 | "description": "Revision to show (commit SHA, tag, branch, or ref expression)." |
| 171 | }, |
| 172 | "path": { |
| 173 | "type": "string", |
| 174 | "description": "Optional subdirectory or file path to scope output." |
| 175 | }, |
| 176 | "patch": { |
| 177 | "type": "boolean", |
| 178 | "default": true, |
| 179 | "description": "Include patch hunks (default true)." |
| 180 | }, |
| 181 | "stat": { |
| 182 | "type": "boolean", |
| 183 | "default": true, |
| 184 | "description": "Include --stat summary (default true)." |
| 185 | }, |
| 186 | "unified": { |
| 187 | "type": "integer", |
| 188 | "minimum": 0, |
| 189 | "maximum": MAX_UNIFIED, |
| 190 | "default": DEFAULT_UNIFIED, |
| 191 | "description": "Context lines for patch output when patch=true." |
| 192 | } |
| 193 | }, |
| 194 | "required": ["rev"], |
| 195 | "additionalProperties": false |
| 196 | }) |
| 197 | } |
| 198 | |
| 199 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 200 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 201 | } |
| 202 | |
| 203 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 204 | ApprovalRequirement::Auto |
| 205 | } |
| 206 | |
| 207 | fn supports_parallel(&self) -> bool { |
| 208 | true |
| 209 | } |
| 210 | |
| 211 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 212 | let rev = required_str(&input, "rev")?; |
| 213 | validate_git_rev(rev)?; |
| 214 | let git_ctx = resolve_git_context(context, optional_str(&input, "path")?)?; |
| 215 | let patch = optional_bool(&input, "patch", true)?; |
| 216 | let stat = optional_bool(&input, "stat", true)?; |
| 217 | let unified = optional_u64(&input, "unified", DEFAULT_UNIFIED)?.min(MAX_UNIFIED); |
| 218 | |
| 219 | let mut args = vec!["show".to_string(), "--no-color".to_string()]; |
| 220 | args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from)); |
| 221 | if patch { |
| 222 | args.push(format!("--unified={unified}")); |
| 223 | } else { |
| 224 | args.push("--no-patch".to_string()); |
| 225 | } |
| 226 | if stat { |
| 227 | args.push("--stat".to_string()); |
| 228 | } |
| 229 | args.push(rev.to_string()); |
| 230 | if let Some(pathspec) = &git_ctx.pathspec { |
| 231 | args.push("--".to_string()); |
| 232 | args.push(pathspec.display().to_string()); |
| 233 | } |
| 234 | |
| 235 | let command_str = format_command(&git_ctx.working_dir, &args); |
| 236 | let output = run_git_command_async(git_ctx.working_dir.clone(), args).await?; |
| 237 | if !output.status.success() { |
| 238 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 239 | return Ok(ToolResult::error(format!( |
| 240 | "git show failed for '{rev}': {}", |
| 241 | stderr.trim() |
| 242 | )) |
| 243 | .with_metadata(json!({ |
| 244 | "command": command_str, |
| 245 | "exit_code": output.status.code(), |
| 246 | "stderr": stderr.trim(), |
| 247 | }))); |
| 248 | } |
| 249 | |
| 250 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 251 | let content = stdout.into_owned(); |
| 252 | Ok(ToolResult::success(content).with_metadata(json!({ |
| 253 | "command": command_str, |
| 254 | "working_dir": git_ctx.working_dir, |
| 255 | "pathspec": git_ctx.pathspec, |
| 256 | "rev": rev, |
| 257 | "patch": patch, |
| 258 | "stat": stat, |
| 259 | "unified": if patch { Some(unified) } else { None }, |
| 260 | }))) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Tool for attributing lines in a file to commits and authors. |
| 265 | pub struct GitBlameTool; |
| 266 | |
| 267 | #[async_trait] |
| 268 | impl ToolSpec for GitBlameTool { |
| 269 | fn name(&self) -> &'static str { |
| 270 | "git_blame" |
| 271 | } |
| 272 | |
| 273 | fn model_visible(&self) -> bool { |
| 274 | false |
| 275 | } |
| 276 | |
| 277 | fn description(&self) -> &'static str { |
| 278 | "Run `git blame` on a file with optional revision and line-range controls." |
| 279 | } |
| 280 | |
| 281 | fn input_schema(&self) -> Value { |
| 282 | json!({ |
| 283 | "type": "object", |
| 284 | "properties": { |
| 285 | "path": { |
| 286 | "type": "string", |
| 287 | "description": "Path to a tracked file within the workspace." |
| 288 | }, |
| 289 | "rev": { |
| 290 | "type": "string", |
| 291 | "description": "Optional revision to blame against (default: HEAD)." |
| 292 | }, |
| 293 | "start_line": { |
| 294 | "type": "integer", |
| 295 | "minimum": 1, |
| 296 | "default": DEFAULT_BLAME_START_LINE, |
| 297 | "description": "First line to include in blame output." |
| 298 | }, |
| 299 | "max_lines": { |
| 300 | "type": "integer", |
| 301 | "minimum": 1, |
| 302 | "maximum": MAX_BLAME_MAX_LINES, |
| 303 | "default": DEFAULT_BLAME_MAX_LINES, |
| 304 | "description": "Maximum number of lines to include." |
| 305 | }, |
| 306 | "porcelain": { |
| 307 | "type": "boolean", |
| 308 | "default": false, |
| 309 | "description": "When true, emit `--line-porcelain` output." |
| 310 | } |
| 311 | }, |
| 312 | "required": ["path"], |
| 313 | "additionalProperties": false |
| 314 | }) |
| 315 | } |
| 316 | |
| 317 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 318 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 319 | } |
| 320 | |
| 321 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 322 | ApprovalRequirement::Auto |
| 323 | } |
| 324 | |
| 325 | fn supports_parallel(&self) -> bool { |
| 326 | true |
| 327 | } |
| 328 | |
| 329 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 330 | let path_str = required_str(&input, "path")?; |
| 331 | let resolved_path = context.resolve_path(path_str)?; |
| 332 | let metadata = tokio::fs::metadata(&resolved_path).await.map_err(|e| { |
| 333 | ToolError::invalid_input(format!( |
| 334 | "Path does not exist or is not accessible: {path_str} ({e})" |
| 335 | )) |
| 336 | })?; |
| 337 | if !metadata.is_file() { |
| 338 | return Err(ToolError::invalid_input(format!( |
| 339 | "Path must point to a file: {path_str}" |
| 340 | ))); |
| 341 | } |
| 342 | |
| 343 | let working_dir = resolved_path.parent().ok_or_else(|| { |
| 344 | ToolError::invalid_input(format!("Path has no parent directory: {path_str}")) |
| 345 | })?; |
| 346 | let pathspec = pathspec_from(working_dir, &resolved_path); |
| 347 | let rev = optional_str(&input, "rev")?.unwrap_or("HEAD"); |
| 348 | validate_git_rev(rev)?; |
| 349 | let start_line = optional_u64(&input, "start_line", DEFAULT_BLAME_START_LINE)?.max(1); |
| 350 | let max_lines = optional_u64(&input, "max_lines", DEFAULT_BLAME_MAX_LINES)? |
| 351 | .clamp(1, MAX_BLAME_MAX_LINES); |
| 352 | let end_line = start_line.saturating_add(max_lines.saturating_sub(1)); |
| 353 | let porcelain = optional_bool(&input, "porcelain", false)?; |
| 354 | |
| 355 | // Blame reads the working-tree file, so it runs under the review |
| 356 | // command (no clean filters) and skips textconv drivers. |
| 357 | let mut args = vec![ |
| 358 | "blame".to_string(), |
| 359 | "--no-textconv".to_string(), |
| 360 | "--date=iso".to_string(), |
| 361 | format!("-L{start_line},{end_line}"), |
| 362 | ]; |
| 363 | if porcelain { |
| 364 | args.push("--line-porcelain".to_string()); |
| 365 | } |
| 366 | args.push(rev.to_string()); |
| 367 | args.push("--".to_string()); |
| 368 | args.push(pathspec.display().to_string()); |
| 369 | |
| 370 | let command_str = format_command(working_dir, &args); |
| 371 | let output = run_git_command_async(working_dir.to_path_buf(), args).await?; |
| 372 | if !output.status.success() { |
| 373 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 374 | return Ok(ToolResult::error(format!( |
| 375 | "git blame failed for '{path_str}' at '{rev}': {}", |
| 376 | stderr.trim() |
| 377 | )) |
| 378 | .with_metadata(json!({ |
| 379 | "command": command_str, |
| 380 | "exit_code": output.status.code(), |
| 381 | "stderr": stderr.trim(), |
| 382 | }))); |
| 383 | } |
| 384 | |
| 385 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 386 | let content = stdout.into_owned(); |
| 387 | Ok(ToolResult::success(content).with_metadata(json!({ |
| 388 | "command": command_str, |
| 389 | "working_dir": working_dir, |
| 390 | "pathspec": pathspec, |
| 391 | "rev": rev, |
| 392 | "start_line": start_line, |
| 393 | "max_lines": max_lines, |
| 394 | "porcelain": porcelain, |
| 395 | }))) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | /// Tool for fetching remote refs: `git fetch <remote> [<refspec>...]`. |
| 400 | /// |
| 401 | /// The bounded verify-mode git surface (#6298): a verifier child cannot reach |
| 402 | /// raw shell, so `git fetch` arrives as a structured call instead of a shell |
| 403 | /// command. The bound is structural — fixed argv, argv-direct spawning (no |
| 404 | /// shell), a remote that must be a *configured* remote name (never a URL, so |
| 405 | /// an operator-supplied address cannot exfiltrate or redirect), and refspecs |
| 406 | /// that pass the option/whitespace/control gates. Only remote-tracking refs |
| 407 | /// (plus `FETCH_HEAD` and the fetched objects) move: never a checkout, merge, |
| 408 | /// or push. The execution envelope classes this as bounded fetch — shell plus |
| 409 | /// network authority, not write authority. |
| 410 | /// |
| 411 | /// Never interactive and always bounded: the spawn carries the shared no-prompt |
| 412 | /// environment (`GIT_TERMINAL_PROMPT=0`, BatchMode ssh), so a remote that wants |
| 413 | /// credentials, a passphrase or a host-key confirmation fails fast instead of |
| 414 | /// prompting on `/dev/tty` inside the raw-mode TUI; and the child runs under |
| 415 | /// [`GIT_FETCH_TIMEOUT`] with `kill_on_drop`, so a remote that never answers |
| 416 | /// ends the call with a clear error instead of freezing the turn. |
| 417 | pub struct GitFetchTool; |
| 418 | |
| 419 | /// Upper bound on one `git_fetch`. Generous enough for a first fetch of a |
| 420 | /// large repository; short enough that a silent remote cannot pass for a hang. |
| 421 | const GIT_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300); |
| 422 | |
| 423 | #[async_trait] |
| 424 | impl ToolSpec for GitFetchTool { |
| 425 | fn name(&self) -> &'static str { |
| 426 | "git_fetch" |
| 427 | } |
| 428 | |
| 429 | fn model_visible(&self) -> bool { |
| 430 | false |
| 431 | } |
| 432 | |
| 433 | fn description(&self) -> &'static str { |
| 434 | "Run `git fetch` against a configured remote. Updates remote-tracking refs only; never checks out, merges, or pushes." |
| 435 | } |
| 436 | |
| 437 | fn input_schema(&self) -> Value { |
| 438 | json!({ |
| 439 | "type": "object", |
| 440 | "properties": { |
| 441 | "remote": { |
| 442 | "type": "string", |
| 443 | "default": "origin", |
| 444 | "description": "Configured remote name to fetch from (default origin). Must be a name from `git remote`, never a URL." |
| 445 | }, |
| 446 | "refspecs": { |
| 447 | "type": "array", |
| 448 | "items": { "type": "string" }, |
| 449 | "description": "Optional refspecs to fetch (e.g. pull/123/head); a `src:dst` destination must be under refs/remotes/. Empty fetches the remote's defaults." |
| 450 | }, |
| 451 | "path": { |
| 452 | "type": "string", |
| 453 | "description": "Optional subdirectory to run from." |
| 454 | } |
| 455 | }, |
| 456 | "additionalProperties": false |
| 457 | }) |
| 458 | } |
| 459 | |
| 460 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 461 | vec![ToolCapability::Network, ToolCapability::Sandboxable] |
| 462 | } |
| 463 | |
| 464 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 465 | ApprovalRequirement::Required |
| 466 | } |
| 467 | |
| 468 | fn supports_parallel(&self) -> bool { |
| 469 | false |
| 470 | } |
| 471 | |
| 472 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 473 | let remote = optional_str(&input, "remote")?.unwrap_or("origin"); |
| 474 | validate_git_remote_name(remote)?; |
| 475 | let refspecs = parse_git_refspecs(&input)?; |
| 476 | let git_ctx = resolve_git_context(context, optional_str(&input, "path")?)?; |
| 477 | require_configured_remote(&git_ctx.working_dir, remote).await?; |
| 478 | |
| 479 | // Remote-tracking refs only (#6561 D03-01): a default fetch |
| 480 | // auto-follows tags into refs/tags/, and `tagOpt`/`pruneTags` |
| 481 | // config can add or delete local tags. The flags override both. |
| 482 | let mut args = vec![ |
| 483 | "fetch".to_string(), |
| 484 | "--no-tags".to_string(), |
| 485 | "--no-prune-tags".to_string(), |
| 486 | remote.to_string(), |
| 487 | ]; |
| 488 | args.extend(refspecs.clone()); |
| 489 | |
| 490 | let command_str = format_command(&git_ctx.working_dir, &args); |
| 491 | let Some(output) = |
| 492 | run_git_command_bounded(&git_ctx.working_dir, &args, GIT_FETCH_TIMEOUT).await? |
| 493 | else { |
| 494 | let seconds = GIT_FETCH_TIMEOUT.as_secs(); |
| 495 | return Ok(ToolResult::error(format!( |
| 496 | "git fetch from remote '{remote}' timed out after {seconds}s and was stopped; \ |
| 497 | the remote did not finish answering. No refs were changed by this call." |
| 498 | )) |
| 499 | .with_metadata(json!({ |
| 500 | "command": command_str, |
| 501 | "timed_out": true, |
| 502 | "timeout_secs": seconds, |
| 503 | }))); |
| 504 | }; |
| 505 | if !output.status.success() { |
| 506 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 507 | return Ok(ToolResult::error(format!( |
| 508 | "git fetch failed for remote '{remote}': {}", |
| 509 | stderr.trim() |
| 510 | )) |
| 511 | .with_metadata(json!({ |
| 512 | "command": command_str, |
| 513 | "exit_code": output.status.code(), |
| 514 | "stderr": stderr.trim(), |
| 515 | }))); |
| 516 | } |
| 517 | |
| 518 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 519 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 520 | let combined = if stderr.trim().is_empty() { |
| 521 | stdout.to_string() |
| 522 | } else { |
| 523 | format!("{stdout}\n{stderr}") |
| 524 | }; |
| 525 | let content = combined; |
| 526 | Ok(ToolResult::success(content).with_metadata(json!({ |
| 527 | "command": command_str, |
| 528 | "working_dir": git_ctx.working_dir, |
| 529 | "remote": remote, |
| 530 | "refspecs": refspecs, |
| 531 | }))) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// Tool for computing a merge result without touching the working tree. |
| 536 | /// |
| 537 | /// `git merge-tree` is a pure read: it performs the merge in memory and |
| 538 | /// prints the resulting tree plus conflicted-file info, writing nothing, so |
| 539 | /// the envelope classes it Bounded like the other inspection actions. Uses |
| 540 | /// the modern two-revision form (git 2.38+, 2022); an explicit base arrives |
| 541 | /// via `--merge-base`, and otherwise git finds the bases itself — including |
| 542 | /// the multi-base virtual-base case a hand-rolled `merge-base` call cannot |
| 543 | /// express. Older gits fail with their own usage error, surfaced below. |
| 544 | pub struct GitMergeTreeTool; |
| 545 | |
| 546 | #[async_trait] |
| 547 | impl ToolSpec for GitMergeTreeTool { |
| 548 | fn name(&self) -> &'static str { |
| 549 | "git_merge_tree" |
| 550 | } |
| 551 | |
| 552 | fn model_visible(&self) -> bool { |
| 553 | false |
| 554 | } |
| 555 | |
| 556 | fn description(&self) -> &'static str { |
| 557 | "Compute the merge result of two revisions without touching the working tree (`git merge-tree`). Pure read." |
| 558 | } |
| 559 | |
| 560 | fn input_schema(&self) -> Value { |
| 561 | json!({ |
| 562 | "type": "object", |
| 563 | "properties": { |
| 564 | "ours": { |
| 565 | "type": "string", |
| 566 | "description": "First revision (e.g. main)." |
| 567 | }, |
| 568 | "theirs": { |
| 569 | "type": "string", |
| 570 | "description": "Second revision (e.g. the PR head)." |
| 571 | }, |
| 572 | "base": { |
| 573 | "type": "string", |
| 574 | "description": "Optional merge base (--merge-base). Omit it and git finds the bases itself." |
| 575 | }, |
| 576 | "path": { |
| 577 | "type": "string", |
| 578 | "description": "Optional subdirectory to run from." |
| 579 | } |
| 580 | }, |
| 581 | "required": ["ours", "theirs"], |
| 582 | "additionalProperties": false |
| 583 | }) |
| 584 | } |
| 585 | |
| 586 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 587 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 588 | } |
| 589 | |
| 590 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 591 | ApprovalRequirement::Auto |
| 592 | } |
| 593 | |
| 594 | fn supports_parallel(&self) -> bool { |
| 595 | true |
| 596 | } |
| 597 | |
| 598 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 599 | let ours = required_str(&input, "ours")?; |
| 600 | let theirs = required_str(&input, "theirs")?; |
| 601 | validate_git_rev(ours)?; |
| 602 | validate_git_rev(theirs)?; |
| 603 | let git_ctx = resolve_git_context(context, optional_str(&input, "path")?)?; |
| 604 | |
| 605 | let mut args = vec!["merge-tree".to_string()]; |
| 606 | let base = match optional_str(&input, "base")? { |
| 607 | Some(base) => { |
| 608 | validate_git_rev(base)?; |
| 609 | // `--opt=value` form: a validated rev can never split into a |
| 610 | // second argv element, so no option injection through `base`. |
| 611 | args.push(format!("--merge-base={base}")); |
| 612 | Some(base.to_string()) |
| 613 | } |
| 614 | None => None, |
| 615 | }; |
| 616 | args.push(ours.to_string()); |
| 617 | args.push(theirs.to_string()); |
| 618 | let command_str = format_command(&git_ctx.working_dir, &args); |
| 619 | let output = run_git_command_async(git_ctx.working_dir.clone(), args).await?; |
| 620 | // merge-tree exits 1 both for conflicts (a successful report on |
| 621 | // stdout) and for real failures (empty stdout, reason on stderr). |
| 622 | // The report is the answer; only the empty case is an error. |
| 623 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 624 | if !output.status.success() && stdout.trim().is_empty() { |
| 625 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 626 | return Ok(ToolResult::error(format!( |
| 627 | "git merge-tree failed for '{ours}' + '{theirs}': {}", |
| 628 | stderr.trim() |
| 629 | )) |
| 630 | .with_metadata(json!({ |
| 631 | "command": command_str, |
| 632 | "exit_code": output.status.code(), |
| 633 | "stderr": stderr.trim(), |
| 634 | }))); |
| 635 | } |
| 636 | |
| 637 | let conflicts = !output.status.success(); |
| 638 | let content = stdout.into_owned(); |
| 639 | Ok(ToolResult::success(content).with_metadata(json!({ |
| 640 | "command": command_str, |
| 641 | "working_dir": git_ctx.working_dir, |
| 642 | "ours": ours, |
| 643 | "theirs": theirs, |
| 644 | "base": base, |
| 645 | "conflicts": conflicts, |
| 646 | }))) |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | struct GitContext { |
| 651 | working_dir: PathBuf, |
| 652 | pathspec: Option<PathBuf>, |
| 653 | } |
| 654 | |
| 655 | fn resolve_git_context(context: &ToolContext, path: Option<&str>) -> Result<GitContext, ToolError> { |
| 656 | let workspace = canonical_or_workspace(&context.workspace); |
| 657 | let mut working_dir = workspace.clone(); |
| 658 | let mut pathspec = None; |
| 659 | |
| 660 | if let Some(raw) = path { |
| 661 | let resolved = context.resolve_path(raw)?; |
| 662 | let metadata = fs::metadata(&resolved).map_err(|e| { |
| 663 | ToolError::invalid_input(format!( |
| 664 | "Path does not exist or is not accessible: {raw} ({e})" |
| 665 | )) |
| 666 | })?; |
| 667 | |
| 668 | if metadata.is_dir() { |
| 669 | working_dir = resolved; |
| 670 | pathspec = Some(PathBuf::from(".")); |
| 671 | } else { |
| 672 | let parent = resolved.parent().ok_or_else(|| { |
| 673 | ToolError::invalid_input(format!("Path has no parent directory: {raw}")) |
| 674 | })?; |
| 675 | working_dir = parent.to_path_buf(); |
| 676 | pathspec = Some(pathspec_from(&working_dir, &resolved)); |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | if !working_dir.exists() { |
| 681 | return Err(ToolError::invalid_input(format!( |
| 682 | "Working directory does not exist: {}", |
| 683 | working_dir.display() |
| 684 | ))); |
| 685 | } |
| 686 | |
| 687 | Ok(GitContext { |
| 688 | working_dir, |
| 689 | pathspec, |
| 690 | }) |
| 691 | } |
| 692 | |
| 693 | fn validate_git_rev(rev: &str) -> Result<(), ToolError> { |
| 694 | let trimmed = rev.trim(); |
| 695 | if trimmed.is_empty() { |
| 696 | return Err(ToolError::invalid_input( |
| 697 | "git revision must not be empty".to_string(), |
| 698 | )); |
| 699 | } |
| 700 | if trimmed.starts_with('-') { |
| 701 | return Err(ToolError::invalid_input( |
| 702 | "git revision must not start with '-'".to_string(), |
| 703 | )); |
| 704 | } |
| 705 | if trimmed.chars().any(char::is_whitespace) { |
| 706 | return Err(ToolError::invalid_input( |
| 707 | "git revision must not contain whitespace".to_string(), |
| 708 | )); |
| 709 | } |
| 710 | if trimmed |
| 711 | .chars() |
| 712 | .any(|ch| ch == '\0' || ch.is_ascii_control()) |
| 713 | { |
| 714 | return Err(ToolError::invalid_input( |
| 715 | "git revision must not contain control characters".to_string(), |
| 716 | )); |
| 717 | } |
| 718 | Ok(()) |
| 719 | } |
| 720 | |
| 721 | /// A fetch remote is a configured remote *name*, never a URL: URLs and paths |
| 722 | /// fail the membership check below, but rejecting their shapes here keeps the |
| 723 | /// refusal precise (`:` kills `https://`, `user@host:path`, and `file://`; |
| 724 | /// `/` kills paths) instead of "unknown remote". |
| 725 | fn validate_git_remote_name(remote: &str) -> Result<(), ToolError> { |
| 726 | let trimmed = remote.trim(); |
| 727 | if trimmed.is_empty() { |
| 728 | return Err(ToolError::invalid_input( |
| 729 | "git remote must not be empty".to_string(), |
| 730 | )); |
| 731 | } |
| 732 | if trimmed.starts_with('-') { |
| 733 | return Err(ToolError::invalid_input( |
| 734 | "git remote must not start with '-'".to_string(), |
| 735 | )); |
| 736 | } |
| 737 | if trimmed.chars().any(char::is_whitespace) { |
| 738 | return Err(ToolError::invalid_input( |
| 739 | "git remote must not contain whitespace".to_string(), |
| 740 | )); |
| 741 | } |
| 742 | if trimmed |
| 743 | .chars() |
| 744 | .any(|ch| ch == '\0' || ch.is_ascii_control() || ch == ':' || ch == '/') |
| 745 | { |
| 746 | return Err(ToolError::invalid_input( |
| 747 | "git remote must be a configured remote name (from `git remote`), never a URL or path" |
| 748 | .to_string(), |
| 749 | )); |
| 750 | } |
| 751 | Ok(()) |
| 752 | } |
| 753 | |
| 754 | /// Parse the optional `refspecs` array: `[+]<src>[:<dst>]`, each side passing |
| 755 | /// the revision gates. A wrong type is an error, never a silent default. |
| 756 | fn parse_git_refspecs(input: &Value) -> Result<Vec<String>, ToolError> { |
| 757 | let items = match input.get("refspecs") { |
| 758 | None | Some(Value::Null) => return Ok(Vec::new()), |
| 759 | Some(Value::Array(items)) => items, |
| 760 | Some(other) => { |
| 761 | return Err(super::spec::type_mismatch( |
| 762 | "refspecs", |
| 763 | other, |
| 764 | "an array of strings", |
| 765 | )); |
| 766 | } |
| 767 | }; |
| 768 | let mut refspecs = Vec::with_capacity(items.len()); |
| 769 | for (index, item) in items.iter().enumerate() { |
| 770 | let Some(refspec) = item.as_str() else { |
| 771 | return Err(super::spec::type_mismatch( |
| 772 | &format!("refspecs[{index}]"), |
| 773 | item, |
| 774 | "a string", |
| 775 | )); |
| 776 | }; |
| 777 | validate_git_refspec(refspec)?; |
| 778 | refspecs.push(refspec.to_string()); |
| 779 | } |
| 780 | Ok(refspecs) |
| 781 | } |
| 782 | |
| 783 | fn validate_git_refspec(refspec: &str) -> Result<(), ToolError> { |
| 784 | let body = refspec.strip_prefix('+').unwrap_or(refspec); |
| 785 | let parts: Vec<&str> = body.split(':').collect(); |
| 786 | if parts.len() > 2 { |
| 787 | return Err(ToolError::invalid_input(format!( |
| 788 | "git refspec '{refspec}' must have at most one ':'" |
| 789 | ))); |
| 790 | } |
| 791 | for side in &parts { |
| 792 | validate_git_refspec_side(refspec, side)?; |
| 793 | } |
| 794 | // `git fetch <remote> tag <name>` is shorthand for |
| 795 | // `refs/tags/<name>:refs/tags/<name>`, a local tag write. |
| 796 | if refspec == "tag" { |
| 797 | return Err(ToolError::invalid_input( |
| 798 | "git refspec 'tag' is not accepted: the `tag <name>` form writes a local tag; \ |
| 799 | fetch refs/tags/<name> into FETCH_HEAD or under refs/remotes/ instead", |
| 800 | )); |
| 801 | } |
| 802 | // The tool updates remote-tracking refs only: a destination under |
| 803 | // `refs/heads/` or `refs/tags/` (or a bare name git would resolve there) |
| 804 | // could rewrite local branches and tags. |
| 805 | if let Some(dst) = parts.get(1) |
| 806 | && (!dst.starts_with("refs/remotes/") || dst.split('/').any(|part| part == "..")) |
| 807 | { |
| 808 | return Err(ToolError::invalid_input(format!( |
| 809 | "git refspec '{refspec}' must write under refs/remotes/; omit the destination to fetch into FETCH_HEAD" |
| 810 | ))); |
| 811 | } |
| 812 | Ok(()) |
| 813 | } |
| 814 | |
| 815 | fn validate_git_refspec_side(refspec: &str, side: &str) -> Result<(), ToolError> { |
| 816 | if side.is_empty() { |
| 817 | return Err(ToolError::invalid_input(format!( |
| 818 | "git refspec '{refspec}' has an empty side" |
| 819 | ))); |
| 820 | } |
| 821 | validate_git_rev(side).map_err(|_| { |
| 822 | ToolError::invalid_input(format!( |
| 823 | "git refspec '{refspec}' is not a plain refspec (no options, whitespace, or control characters)" |
| 824 | )) |
| 825 | }) |
| 826 | } |
| 827 | |
| 828 | /// The remote must already be configured on this repository. A name git never |
| 829 | /// heard of fails here — before any network — so a typo cannot become a fetch |
| 830 | /// from somewhere else. |
| 831 | async fn require_configured_remote(working_dir: &Path, remote: &str) -> Result<(), ToolError> { |
| 832 | let output = |
| 833 | run_git_command_async(working_dir.to_path_buf(), vec!["remote".to_string()]).await?; |
| 834 | if !output.status.success() { |
| 835 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 836 | return Err(ToolError::execution_failed(format!( |
| 837 | "git remote failed: {}", |
| 838 | stderr.trim() |
| 839 | ))); |
| 840 | } |
| 841 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 842 | let configured: Vec<&str> = stdout |
| 843 | .lines() |
| 844 | .map(str::trim) |
| 845 | .filter(|line| !line.is_empty()) |
| 846 | .collect(); |
| 847 | if configured.contains(&remote) { |
| 848 | Ok(()) |
| 849 | } else { |
| 850 | Err(ToolError::invalid_input(format!( |
| 851 | "unknown git remote '{remote}'; configured remotes: {}", |
| 852 | if configured.is_empty() { |
| 853 | "(none)".to_string() |
| 854 | } else { |
| 855 | configured.join(", ") |
| 856 | } |
| 857 | ))) |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | fn canonical_or_workspace(workspace: &Path) -> PathBuf { |
| 862 | workspace |
| 863 | .canonicalize() |
| 864 | .unwrap_or_else(|_| workspace.to_path_buf()) |
| 865 | } |
| 866 | |
| 867 | fn pathspec_from(working_dir: &Path, resolved: &Path) -> PathBuf { |
| 868 | match resolved.strip_prefix(working_dir) { |
| 869 | Ok(rel) if rel.as_os_str().is_empty() => PathBuf::from("."), |
| 870 | Ok(rel) => rel.to_path_buf(), |
| 871 | Err(_) => PathBuf::from("."), |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | /// Run git under a hard deadline. `Ok(None)` means the deadline passed and the |
| 876 | /// child was killed, so a timed-out fetch never lingers. |
| 877 | /// |
| 878 | /// git runs contained ([`codewhale_runtime::process_tree::contained_output`]) and the whole |
| 879 | /// tree is killed at the deadline or when the call is cancelled: git hands the |
| 880 | /// network to a transport child (`git-remote-http`, `ssh`) that survives a |
| 881 | /// SIGKILL to git alone and would otherwise keep the stalled connection open |
| 882 | /// indefinitely. |
| 883 | async fn run_git_command_bounded( |
| 884 | working_dir: &Path, |
| 885 | args: &[String], |
| 886 | timeout: std::time::Duration, |
| 887 | ) -> Result<Option<Output>, ToolError> { |
| 888 | let Some(mut cmd) = codewhale_dependencies::Git::tokio_command() else { |
| 889 | return Err(ToolError::not_available( |
| 890 | "git is not installed or not in PATH", |
| 891 | )); |
| 892 | }; |
| 893 | cmd.args(args).current_dir(working_dir); |
| 894 | match tokio::time::timeout( |
| 895 | timeout, |
| 896 | codewhale_runtime::process_tree::contained_output(&mut cmd), |
| 897 | ) |
| 898 | .await |
| 899 | { |
| 900 | Ok(Ok(output)) => Ok(Some(output)), |
| 901 | Ok(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => Err(ToolError::not_available( |
| 902 | "git is not installed or not in PATH", |
| 903 | )), |
| 904 | Ok(Err(e)) => Err(ToolError::execution_failed(format!( |
| 905 | "Failed to run git: {e}" |
| 906 | ))), |
| 907 | // The elapsed deadline dropped the contained run, which killed git's |
| 908 | // whole tree. |
| 909 | Err(_) => Ok(None), |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | fn format_command(working_dir: &Path, args: &[String]) -> String { |
| 914 | format!( |
| 915 | "git -C {} {}", |
| 916 | working_dir.display(), |
| 917 | args.iter() |
| 918 | .map(String::as_str) |
| 919 | .collect::<Vec<_>>() |
| 920 | .join(" ") |
| 921 | ) |
| 922 | } |
| 923 | |
| 924 | #[cfg(test)] |
| 925 | mod tests { |
| 926 | use super::*; |
| 927 | use std::fs; |
| 928 | use std::path::Path; |
| 929 | use tempfile::tempdir; |
| 930 | |
| 931 | fn git_available() -> bool { |
| 932 | codewhale_dependencies::Git::available() |
| 933 | } |
| 934 | |
| 935 | fn run_git(root: &Path, args: &[&str]) { |
| 936 | let status = codewhale_dependencies::Git::status(args, root).expect("git should spawn"); |
| 937 | assert!(status.success(), "git {args:?} failed"); |
| 938 | } |
| 939 | |
| 940 | fn init_git_repo(root: &Path) { |
| 941 | run_git(root, &["init", "-q"]); |
| 942 | run_git(root, &["config", "core.autocrlf", "false"]); |
| 943 | run_git(root, &["config", "user.email", "test@example.com"]); |
| 944 | run_git(root, &["config", "user.name", "Test User"]); |
| 945 | } |
| 946 | |
| 947 | fn commit_all(root: &Path, message: &str) { |
| 948 | run_git(root, &["add", "."]); |
| 949 | run_git(root, &["commit", "-q", "-m", message]); |
| 950 | } |
| 951 | |
| 952 | #[tokio::test] |
| 953 | async fn git_log_lists_recent_commits() { |
| 954 | if !git_available() { |
| 955 | return; |
| 956 | } |
| 957 | |
| 958 | let tmp = tempdir().expect("tempdir"); |
| 959 | init_git_repo(tmp.path()); |
| 960 | fs::write(tmp.path().join("file.txt"), "one\n").expect("write"); |
| 961 | commit_all(tmp.path(), "first"); |
| 962 | fs::write(tmp.path().join("file.txt"), "two\n").expect("write"); |
| 963 | commit_all(tmp.path(), "second"); |
| 964 | |
| 965 | let ctx = ToolContext::new(tmp.path()); |
| 966 | let result = GitLogTool |
| 967 | .execute(json!({ "max_count": 1 }), &ctx) |
| 968 | .await |
| 969 | .expect("execute"); |
| 970 | assert!(result.success); |
| 971 | assert!(result.content.contains("Subject: second")); |
| 972 | } |
| 973 | |
| 974 | #[tokio::test] |
| 975 | async fn git_show_returns_patch_for_revision() { |
| 976 | if !git_available() { |
| 977 | return; |
| 978 | } |
| 979 | |
| 980 | let tmp = tempdir().expect("tempdir"); |
| 981 | init_git_repo(tmp.path()); |
| 982 | fs::write(tmp.path().join("file.txt"), "one\n").expect("write"); |
| 983 | commit_all(tmp.path(), "first"); |
| 984 | fs::write(tmp.path().join("file.txt"), "one\ntwo\n").expect("write"); |
| 985 | commit_all(tmp.path(), "second"); |
| 986 | |
| 987 | let ctx = ToolContext::new(tmp.path()); |
| 988 | let result = GitShowTool |
| 989 | .execute(json!({ "rev": "HEAD", "stat": false }), &ctx) |
| 990 | .await |
| 991 | .expect("execute"); |
| 992 | assert!(result.success); |
| 993 | assert!(result.content.contains("diff --git")); |
| 994 | assert!(result.content.contains("+two")); |
| 995 | } |
| 996 | |
| 997 | #[tokio::test] |
| 998 | async fn git_show_returns_a_large_patch_whole() { |
| 999 | // #6508: no 40,000-character per-tool cut; the end of the patch |
| 1000 | // reaches the caller. |
| 1001 | if !git_available() { |
| 1002 | return; |
| 1003 | } |
| 1004 | let tmp = tempdir().expect("tempdir"); |
| 1005 | init_git_repo(tmp.path()); |
| 1006 | fs::write(tmp.path().join("file.txt"), "one\n").expect("write"); |
| 1007 | commit_all(tmp.path(), "first"); |
| 1008 | fs::write( |
| 1009 | tmp.path().join("file.txt"), |
| 1010 | format!("{}FINAL LINE\n", "line of patch\n".repeat(4_000)), |
| 1011 | ) |
| 1012 | .expect("write"); |
| 1013 | commit_all(tmp.path(), "second"); |
| 1014 | |
| 1015 | let result = GitShowTool |
| 1016 | .execute( |
| 1017 | json!({ "rev": "HEAD", "stat": false }), |
| 1018 | &ToolContext::new(tmp.path()), |
| 1019 | ) |
| 1020 | .await |
| 1021 | .expect("execute"); |
| 1022 | assert!(result.success); |
| 1023 | assert!(result.content.chars().count() > 40_000); |
| 1024 | assert!(result.content.contains("+FINAL LINE")); |
| 1025 | assert!(!result.content.contains("output truncated")); |
| 1026 | } |
| 1027 | |
| 1028 | #[tokio::test] |
| 1029 | async fn git_show_rejects_option_like_revision() { |
| 1030 | let tmp = tempdir().expect("tempdir"); |
| 1031 | let ctx = ToolContext::new(tmp.path()); |
| 1032 | let err = GitShowTool |
| 1033 | .execute(json!({ "rev": "--stat" }), &ctx) |
| 1034 | .await |
| 1035 | .expect_err("option-shaped rev should fail before git runs"); |
| 1036 | assert!(matches!(err, ToolError::InvalidInput { .. })); |
| 1037 | assert!(err.to_string().contains("must not start with '-'")); |
| 1038 | } |
| 1039 | |
| 1040 | #[tokio::test] |
| 1041 | async fn git_show_rejects_whitespace_revision_payload() { |
| 1042 | let tmp = tempdir().expect("tempdir"); |
| 1043 | let ctx = ToolContext::new(tmp.path()); |
| 1044 | let err = GitShowTool |
| 1045 | .execute( |
| 1046 | json!({ "rev": "HEAD --output=/tmp/codewhale-git-show" }), |
| 1047 | &ctx, |
| 1048 | ) |
| 1049 | .await |
| 1050 | .expect_err("whitespace rev payload should fail before git runs"); |
| 1051 | assert!(matches!(err, ToolError::InvalidInput { .. })); |
| 1052 | assert!(err.to_string().contains("must not contain whitespace")); |
| 1053 | } |
| 1054 | |
| 1055 | #[tokio::test] |
| 1056 | async fn git_blame_reports_author_for_range() { |
| 1057 | if !git_available() { |
| 1058 | return; |
| 1059 | } |
| 1060 | |
| 1061 | let tmp = tempdir().expect("tempdir"); |
| 1062 | init_git_repo(tmp.path()); |
| 1063 | let src = tmp.path().join("src"); |
| 1064 | fs::create_dir_all(&src).expect("mkdir"); |
| 1065 | let file = src.join("lib.rs"); |
| 1066 | fs::write(&file, "pub fn one() -> i32 { 1 }\n").expect("write"); |
| 1067 | commit_all(tmp.path(), "first"); |
| 1068 | fs::write(&file, "pub fn one() -> i32 { 2 }\n").expect("write"); |
| 1069 | commit_all(tmp.path(), "second"); |
| 1070 | |
| 1071 | let ctx = ToolContext::new(tmp.path()); |
| 1072 | let result = GitBlameTool |
| 1073 | .execute( |
| 1074 | json!({ |
| 1075 | "path": "src/lib.rs", |
| 1076 | "start_line": 1, |
| 1077 | "max_lines": 1 |
| 1078 | }), |
| 1079 | &ctx, |
| 1080 | ) |
| 1081 | .await |
| 1082 | .expect("execute"); |
| 1083 | assert!(result.success); |
| 1084 | assert!(result.content.contains("Test User")); |
| 1085 | } |
| 1086 | |
| 1087 | #[tokio::test] |
| 1088 | async fn git_blame_rejects_option_like_revision() { |
| 1089 | let tmp = tempdir().expect("tempdir"); |
| 1090 | let file = tmp.path().join("file.txt"); |
| 1091 | fs::write(&file, "one\n").expect("write"); |
| 1092 | let ctx = ToolContext::new(tmp.path()); |
| 1093 | let err = GitBlameTool |
| 1094 | .execute( |
| 1095 | json!({ "path": "file.txt", "rev": "--contents=/tmp/x" }), |
| 1096 | &ctx, |
| 1097 | ) |
| 1098 | .await |
| 1099 | .expect_err("option-shaped rev should fail before git runs"); |
| 1100 | assert!(matches!(err, ToolError::InvalidInput { .. })); |
| 1101 | assert!(err.to_string().contains("must not start with '-'")); |
| 1102 | } |
| 1103 | |
| 1104 | #[tokio::test] |
| 1105 | async fn git_blame_rejects_whitespace_revision_payload() { |
| 1106 | let tmp = tempdir().expect("tempdir"); |
| 1107 | let file = tmp.path().join("file.txt"); |
| 1108 | fs::write(&file, "one\n").expect("write"); |
| 1109 | let ctx = ToolContext::new(tmp.path()); |
| 1110 | let err = GitBlameTool |
| 1111 | .execute( |
| 1112 | json!({ "path": "file.txt", "rev": "HEAD --contents=/tmp/codewhale-git-blame" }), |
| 1113 | &ctx, |
| 1114 | ) |
| 1115 | .await |
| 1116 | .expect_err("whitespace rev payload should fail before git runs"); |
| 1117 | assert!(matches!(err, ToolError::InvalidInput { .. })); |
| 1118 | assert!(err.to_string().contains("must not contain whitespace")); |
| 1119 | } |
| 1120 | |
| 1121 | #[tokio::test] |
| 1122 | async fn git_blame_errors_for_non_file_path() { |
| 1123 | if !git_available() { |
| 1124 | return; |
| 1125 | } |
| 1126 | |
| 1127 | let tmp = tempdir().expect("tempdir"); |
| 1128 | init_git_repo(tmp.path()); |
| 1129 | |
| 1130 | let ctx = ToolContext::new(tmp.path()); |
| 1131 | let result = GitBlameTool |
| 1132 | .execute(json!({ "path": "." }), &ctx) |
| 1133 | .await |
| 1134 | .expect_err("directory path should fail"); |
| 1135 | assert!(matches!(result, ToolError::InvalidInput { .. })); |
| 1136 | } |
| 1137 | |
| 1138 | #[tokio::test] |
| 1139 | async fn git_fetch_rejects_url_and_option_shaped_remotes() { |
| 1140 | let tmp = tempdir().expect("tempdir"); |
| 1141 | let ctx = ToolContext::new(tmp.path()); |
| 1142 | for remote in [ |
| 1143 | "https://example.com/repo.git", |
| 1144 | "git@example.com:org/repo.git", |
| 1145 | "/tmp/other-checkout", |
| 1146 | "--upload-pack=evil", |
| 1147 | "origin --prune", |
| 1148 | ] { |
| 1149 | let err = GitFetchTool |
| 1150 | .execute(json!({ "remote": remote }), &ctx) |
| 1151 | .await |
| 1152 | .expect_err("non-name remote should fail before git runs"); |
| 1153 | assert!( |
| 1154 | matches!(err, ToolError::InvalidInput { .. }), |
| 1155 | "{remote}: {err}" |
| 1156 | ); |
| 1157 | } |
| 1158 | } |
| 1159 | |
| 1160 | #[tokio::test] |
| 1161 | async fn git_fetch_rejects_unknown_remote_before_network() { |
| 1162 | if !git_available() { |
| 1163 | return; |
| 1164 | } |
| 1165 | |
| 1166 | let tmp = tempdir().expect("tempdir"); |
| 1167 | init_git_repo(tmp.path()); |
| 1168 | let ctx = ToolContext::new(tmp.path()); |
| 1169 | let err = GitFetchTool |
| 1170 | .execute(json!({ "remote": "origin" }), &ctx) |
| 1171 | .await |
| 1172 | .expect_err("unconfigured remote must be refused"); |
| 1173 | let message = err.to_string(); |
| 1174 | assert!(message.contains("unknown git remote 'origin'"), "{message}"); |
| 1175 | assert!(message.contains("(none)"), "{message}"); |
| 1176 | } |
| 1177 | |
| 1178 | #[tokio::test] |
| 1179 | async fn git_fetch_rejects_malformed_refspecs() { |
| 1180 | if !git_available() { |
| 1181 | return; |
| 1182 | } |
| 1183 | |
| 1184 | let tmp = tempdir().expect("tempdir"); |
| 1185 | init_git_repo(tmp.path()); |
| 1186 | let ctx = ToolContext::new(tmp.path()); |
| 1187 | for refspec in ["a:b:c", "src:", ":dst", "--prune", "a b"] { |
| 1188 | let err = GitFetchTool |
| 1189 | .execute(json!({ "refspecs": [refspec] }), &ctx) |
| 1190 | .await |
| 1191 | .expect_err("malformed refspec should fail before git runs"); |
| 1192 | assert!( |
| 1193 | matches!(err, ToolError::InvalidInput { .. }), |
| 1194 | "{refspec}: {err}" |
| 1195 | ); |
| 1196 | } |
| 1197 | for refspec in [ |
| 1198 | "+main:refs/heads/main", |
| 1199 | "v1:refs/tags/v1", |
| 1200 | "main:other", |
| 1201 | "main:refs/remotes/../heads/main", |
| 1202 | ] { |
| 1203 | let err = validate_git_refspec(refspec) |
| 1204 | .expect_err("a destination outside refs/remotes/ must be refused"); |
| 1205 | assert!( |
| 1206 | err.to_string().contains("refs/remotes/"), |
| 1207 | "{refspec}: {err}" |
| 1208 | ); |
| 1209 | } |
| 1210 | // `tag <name>` arrives as two array elements, each a plain rev. |
| 1211 | let err = GitFetchTool |
| 1212 | .execute(json!({ "refspecs": ["tag", "v1"] }), &ctx) |
| 1213 | .await |
| 1214 | .expect_err("the tag shorthand writes a local tag"); |
| 1215 | assert!( |
| 1216 | matches!(err, ToolError::InvalidInput { .. }) && err.to_string().contains("tag"), |
| 1217 | "{err}" |
| 1218 | ); |
| 1219 | for refspec in [ |
| 1220 | "pull/123/head", |
| 1221 | "refs/tags/v1", |
| 1222 | "refs/heads/x:refs/remotes/origin/x", |
| 1223 | "+refs/heads/*:refs/remotes/origin/*", |
| 1224 | ] { |
| 1225 | validate_git_refspec(refspec).expect(refspec); |
| 1226 | } |
| 1227 | let err = GitFetchTool |
| 1228 | .execute(json!({ "refspecs": "pull/1/head" }), &ctx) |
| 1229 | .await |
| 1230 | .expect_err("wrongly typed refspecs should fail"); |
| 1231 | assert!(err.to_string().contains("an array of strings"), "{err}"); |
| 1232 | } |
| 1233 | |
| 1234 | #[tokio::test] |
| 1235 | async fn git_fetch_brings_remote_refs_without_checkout() { |
| 1236 | if !git_available() { |
| 1237 | return; |
| 1238 | } |
| 1239 | |
| 1240 | let origin = tempdir().expect("tempdir"); |
| 1241 | init_git_repo(origin.path()); |
| 1242 | fs::write(origin.path().join("file.txt"), "one\n").expect("write"); |
| 1243 | commit_all(origin.path(), "first"); |
| 1244 | // An annotated tag on fetched history: a default `git fetch` |
| 1245 | // auto-follows it into the local refs/tags/ namespace. |
| 1246 | run_git(origin.path(), &["tag", "-a", "v1", "-m", "v1"]); |
| 1247 | |
| 1248 | let work = tempdir().expect("tempdir"); |
| 1249 | init_git_repo(work.path()); |
| 1250 | run_git( |
| 1251 | work.path(), |
| 1252 | &[ |
| 1253 | "remote", |
| 1254 | "add", |
| 1255 | "origin", |
| 1256 | &origin.path().display().to_string(), |
| 1257 | ], |
| 1258 | ); |
| 1259 | |
| 1260 | let ctx = ToolContext::new(work.path()); |
| 1261 | let result = GitFetchTool |
| 1262 | .execute(json!({ "remote": "origin" }), &ctx) |
| 1263 | .await |
| 1264 | .expect("execute"); |
| 1265 | assert!(result.success, "{}", result.content); |
| 1266 | |
| 1267 | // #6561 D03-01: remote-tracking refs only, so no local tag appeared. |
| 1268 | let tags = codewhale_dependencies::Git::output(&["tag", "--list"], work.path()) |
| 1269 | .expect("git should spawn"); |
| 1270 | assert!(tags.status.success()); |
| 1271 | assert_eq!(String::from_utf8_lossy(&tags.stdout).trim(), ""); |
| 1272 | |
| 1273 | // The refs arrived, but nothing was checked out: the work tree has no |
| 1274 | // file.txt and no local branch moved. |
| 1275 | let refs = codewhale_dependencies::Git::output(&["branch", "-r"], work.path()) |
| 1276 | .expect("git should spawn"); |
| 1277 | assert!(refs.status.success()); |
| 1278 | let refs = String::from_utf8_lossy(&refs.stdout); |
| 1279 | assert!(refs.contains("origin/"), "{refs}"); |
| 1280 | assert!(!work.path().join("file.txt").exists()); |
| 1281 | } |
| 1282 | |
| 1283 | /// A loopback HTTP "remote" that answers every request with `response`. |
| 1284 | /// Returns its URL. |
| 1285 | fn spawn_fake_http_remote(response: &'static str) -> String { |
| 1286 | use std::io::{Read, Write}; |
| 1287 | let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 1288 | let addr = listener.local_addr().expect("addr"); |
| 1289 | std::thread::spawn(move || { |
| 1290 | for stream in listener.incoming().take(16) { |
| 1291 | let Ok(mut stream) = stream else { continue }; |
| 1292 | let mut buf = [0u8; 4096]; |
| 1293 | let _ = stream.read(&mut buf); |
| 1294 | let _ = stream.write_all(response.as_bytes()); |
| 1295 | } |
| 1296 | }); |
| 1297 | format!("http://{addr}/repo.git") |
| 1298 | } |
| 1299 | |
| 1300 | fn init_repo_with_remote(root: &Path, url: &str) { |
| 1301 | init_git_repo(root); |
| 1302 | run_git(root, &["remote", "add", "origin", url]); |
| 1303 | // Isolate from the developer's credential helpers and askpass so the |
| 1304 | // only thing standing between git and a prompt is our environment. |
| 1305 | run_git(root, &["config", "credential.helper", ""]); |
| 1306 | run_git(root, &["config", "core.askPass", ""]); |
| 1307 | } |
| 1308 | |
| 1309 | #[tokio::test] |
| 1310 | async fn git_fetch_fails_fast_when_remote_requires_credentials() { |
| 1311 | if !git_available() { |
| 1312 | return; |
| 1313 | } |
| 1314 | let url = spawn_fake_http_remote( |
| 1315 | "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"codewhale\"\r\n\ |
| 1316 | Content-Length: 0\r\nConnection: close\r\n\r\n", |
| 1317 | ); |
| 1318 | let work = tempdir().expect("tempdir"); |
| 1319 | init_repo_with_remote(work.path(), &url); |
| 1320 | |
| 1321 | let ctx = ToolContext::new(work.path()); |
| 1322 | let started = std::time::Instant::now(); |
| 1323 | let result = tokio::time::timeout( |
| 1324 | std::time::Duration::from_secs(60), |
| 1325 | GitFetchTool.execute(json!({ "remote": "origin" }), &ctx), |
| 1326 | ) |
| 1327 | .await |
| 1328 | .expect("git_fetch must not wait on a credential prompt") |
| 1329 | .expect("execute"); |
| 1330 | assert!(!result.success, "{}", result.content); |
| 1331 | assert!( |
| 1332 | result |
| 1333 | .content |
| 1334 | .contains("git fetch failed for remote 'origin'"), |
| 1335 | "{}", |
| 1336 | result.content |
| 1337 | ); |
| 1338 | // Git names the refusal to prompt rather than blocking on /dev/tty. |
| 1339 | let lower = result.content.to_lowercase(); |
| 1340 | assert!( |
| 1341 | lower.contains("terminal prompts disabled") || lower.contains("authentication"), |
| 1342 | "{}", |
| 1343 | result.content |
| 1344 | ); |
| 1345 | assert!(started.elapsed() < std::time::Duration::from_secs(30)); |
| 1346 | } |
| 1347 | |
| 1348 | #[tokio::test] |
| 1349 | async fn git_fetch_runner_kills_a_remote_that_never_answers() { |
| 1350 | if !git_available() { |
| 1351 | return; |
| 1352 | } |
| 1353 | // Accept one connection and hand it back, never answering. |
| 1354 | let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 1355 | let url = format!("http://{}/repo.git", listener.local_addr().expect("addr")); |
| 1356 | let (accepted_tx, accepted_rx) = std::sync::mpsc::channel(); |
| 1357 | std::thread::spawn(move || { |
| 1358 | if let Ok((stream, _)) = listener.accept() { |
| 1359 | let _ = accepted_tx.send(stream); |
| 1360 | } |
| 1361 | }); |
| 1362 | let work = tempdir().expect("tempdir"); |
| 1363 | init_repo_with_remote(work.path(), &url); |
| 1364 | |
| 1365 | let started = std::time::Instant::now(); |
| 1366 | let outcome = run_git_command_bounded( |
| 1367 | work.path(), |
| 1368 | &["fetch".to_string(), "origin".to_string()], |
| 1369 | std::time::Duration::from_secs(2), |
| 1370 | ) |
| 1371 | .await |
| 1372 | .expect("git spawns"); |
| 1373 | assert!(outcome.is_none(), "a silent remote must hit the deadline"); |
| 1374 | assert!(started.elapsed() < std::time::Duration::from_secs(15)); |
| 1375 | |
| 1376 | // The connection belongs to git's transport child, not git itself. |
| 1377 | // It must close too: a lingering helper would hold the stall open. |
| 1378 | #[cfg(unix)] |
| 1379 | { |
| 1380 | use std::io::Read; |
| 1381 | let mut stream = accepted_rx |
| 1382 | .recv_timeout(std::time::Duration::from_secs(5)) |
| 1383 | .expect("git connected to the fake remote"); |
| 1384 | stream |
| 1385 | .set_read_timeout(Some(std::time::Duration::from_secs(5))) |
| 1386 | .expect("read timeout"); |
| 1387 | let mut buf = [0u8; 4096]; |
| 1388 | loop { |
| 1389 | match stream.read(&mut buf) { |
| 1390 | Ok(0) => break, |
| 1391 | Ok(_) => continue, // the request itself |
| 1392 | Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => break, |
| 1393 | Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, |
| 1394 | Err(e) => panic!("transport child outlived the deadline: {e}"), |
| 1395 | } |
| 1396 | } |
| 1397 | } |
| 1398 | #[cfg(not(unix))] |
| 1399 | drop(accepted_rx); |
| 1400 | } |
| 1401 | |
| 1402 | #[tokio::test] |
| 1403 | async fn git_merge_tree_reports_conflicts_without_touching_tree() { |
| 1404 | if !git_available() { |
| 1405 | return; |
| 1406 | } |
| 1407 | |
| 1408 | let tmp = tempdir().expect("tempdir"); |
| 1409 | init_git_repo(tmp.path()); |
| 1410 | fs::write(tmp.path().join("file.txt"), "base\n").expect("write"); |
| 1411 | commit_all(tmp.path(), "base"); |
| 1412 | let main = current_branch(tmp.path()); |
| 1413 | run_git(tmp.path(), &["checkout", "-qb", "side"]); |
| 1414 | fs::write(tmp.path().join("file.txt"), "side\n").expect("write"); |
| 1415 | commit_all(tmp.path(), "side"); |
| 1416 | run_git(tmp.path(), &["checkout", "-q", main.as_str()]); |
| 1417 | fs::write(tmp.path().join("file.txt"), "base\nmain\n").expect("write"); |
| 1418 | commit_all(tmp.path(), "main"); |
| 1419 | |
| 1420 | let ctx = ToolContext::new(tmp.path()); |
| 1421 | let before = fs::read(tmp.path().join("file.txt")).expect("read"); |
| 1422 | let result = GitMergeTreeTool |
| 1423 | .execute(json!({ "ours": main, "theirs": "side" }), &ctx) |
| 1424 | .await |
| 1425 | .expect("execute"); |
| 1426 | assert!(result.success, "{}", result.content); |
| 1427 | // Modern merge-tree shape: result tree plus the conflicted path in |
| 1428 | // the stage table and the CONFLICT notice. |
| 1429 | assert!(result.content.contains("file.txt"), "{}", result.content); |
| 1430 | assert!(result.content.contains("CONFLICT"), "{}", result.content); |
| 1431 | assert_eq!( |
| 1432 | fs::read(tmp.path().join("file.txt")).expect("read"), |
| 1433 | before, |
| 1434 | "merge-tree must not touch the working tree" |
| 1435 | ); |
| 1436 | } |
| 1437 | |
| 1438 | #[tokio::test] |
| 1439 | async fn git_merge_tree_rejects_option_shaped_revisions() { |
| 1440 | let tmp = tempdir().expect("tempdir"); |
| 1441 | let ctx = ToolContext::new(tmp.path()); |
| 1442 | let err = GitMergeTreeTool |
| 1443 | .execute(json!({ "ours": "--merge-base=x", "theirs": "HEAD" }), &ctx) |
| 1444 | .await |
| 1445 | .expect_err("option-shaped rev should fail before git runs"); |
| 1446 | assert!(matches!(err, ToolError::InvalidInput { .. })); |
| 1447 | assert!(err.to_string().contains("must not start with '-'")); |
| 1448 | } |
| 1449 | |
| 1450 | fn current_branch(root: &Path) -> String { |
| 1451 | let output = codewhale_dependencies::Git::output(&["branch", "--show-current"], root) |
| 1452 | .expect("git should spawn"); |
| 1453 | assert!(output.status.success()); |
| 1454 | String::from_utf8_lossy(&output.stdout).trim().to_string() |
| 1455 | } |
| 1456 | |
| 1457 | /// A cancelled call kills git's whole tree, not only at the deadline. |
| 1458 | #[cfg(unix)] |
| 1459 | #[tokio::test] |
| 1460 | async fn cancelled_bounded_git_run_kills_what_git_started() { |
| 1461 | if !git_available() { |
| 1462 | return; |
| 1463 | } |
| 1464 | let tmp = tempdir().expect("tempdir"); |
| 1465 | init_git_repo(tmp.path()); |
| 1466 | let pid_file = tmp.path().join("hang.pid"); |
| 1467 | let args = [ |
| 1468 | "-c".to_string(), |
| 1469 | "alias.hang=!sleep 300 & echo $! > hang.pid; wait".to_string(), |
| 1470 | "hang".to_string(), |
| 1471 | ]; |
| 1472 | let run = run_git_command_bounded(tmp.path(), &args, std::time::Duration::from_secs(600)); |
| 1473 | let grandchild = |
| 1474 | codewhale_runtime::process_tree::drop_once_pid_written(run, &pid_file).await; |
| 1475 | assert!( |
| 1476 | codewhale_runtime::process_tree::wait_for_pid_exit( |
| 1477 | grandchild, |
| 1478 | std::time::Duration::from_secs(5) |
| 1479 | ), |
| 1480 | "a process git started outlived the cancelled call" |
| 1481 | ); |
| 1482 | } |
| 1483 | } |
| 1484 |