返回 CodeWhale
git.rs
1 //! Workspace git surface for native clients (APPS-106).
2 //!
3 //! One authority: these routes run `git` against the server's configured
4 //! workspace through the same hardened primitives the agent tools use —
5 //! diffs and token reads go through [`Git::review_command`] (filters,
6 //! fsmonitor, hooks, lazy fetches and replace-objects neutralized), writes run through
7 //! [`Git::tokio_command`] with interactive prompts disabled so a credential
8 //! or host-key prompt can never hang an HTTP request. There is no second
9 //! index, cache, or diff store here; every response is computed live from
10 //! the repository. Status uses normal Git filters and untracked settings,
11 //! matching the workspace counts and operator writes.
12 //!
13 //! Routes (workspace-scoped, matching the client contract):
14 //! GET /v1/git — branch/head/ahead-behind, per-file porcelain
15 //! entries, local branches and remotes
16 //! GET /v1/changes — the file-change inventory only (status rows)
17 //! GET /v1/diff?path= — unified diff for one workspace-relative file
18 //! GET /v1/workspace/diff — bounded whole-tree diff + per-file numstat
19 //! GET /v1/git/graph — recent commit graph rows (bounded)
20 //! POST /v1/git/stage — `{ "paths": [...] }` or `{ "all": true }`
21 //! POST /v1/git/unstage — `{ "paths": [...] }` or `{ "all": true }`
22 //! POST /v1/git/discard — `{ "paths": [...] }` (tracked only; no `all`)
23 //! POST /v1/git/commit — `{ "message": "…", "all": false }`
24 //! POST /v1/git/push — `{ "branch"?, "expect"?: { "head" }, "remote"?,
25 //! "set_upstream"?: bool }`
26 //! POST /v1/git/branch — `{ "name": "…", "create"?: bool }`
27 //! GET /v1/worktrees — the repository's worktrees
28 //! POST /v1/worktrees — `{ "branch", "base"? }` new branch + worktree
29 //! under `<repo>/.codewhale/worktrees/`
30 //! POST /v1/worktrees/remove — `{ "path" }` archive a clean managed one
31 //!
32 //! Every route takes `?thread_id=` and then acts on that thread's workspace.
33 //!
34 //! Mutations answer with the command output tail plus a refreshed workspace
35 //! status and the full `current` detail so the client re-renders in one
36 //! round trip. The caller holds the operator token; the repository's own
37 //! hooks run for `commit` exactly as they would for the user's terminal.
38 //!
39 //! Preconditions (#6647): the detail read carries `head_oid`, `index_token`,
40 //! a whole-tree `revision` and a per-row `files[].rev`. Stage, unstage,
41 //! discard and commit accept an optional `expect` built from those values;
42 //! when the repository no longer matches, the route answers 409
43 //! `git_state_changed` with the current detail and writes nothing. Every
44 //! path in this module — request paths, `files[].path`, `expect.files`
45 //! keys — is workspace-relative; the one translation from git's
46 //! repository-root frame is [`workspace_frame_path`]. Status is best-effort:
47 //! unreadable rows have no token, and incomplete reads have no whole-tree
48 //! revision. These guards do not authorize content the read could not hash.
49
50 use std::collections::{BTreeMap, BTreeSet};
51 use std::path::{Path as FsPath, PathBuf};
52 use std::time::Duration;
53
54 use axum::Json;
55 use axum::extract::{Query, State};
56 use axum::http::StatusCode;
57 use axum::response::{IntoResponse, Response};
58 use serde::{Deserialize, Deserializer, Serialize};
59 use serde_json::{Value, json};
60 use sha2::{Digest, Sha256};
61
62 use codewhale_dependencies::{ExternalTool as _, Git};
63
64 use super::workspace::{
65 FILE_SERVE_MAX_BYTES, ThreadScopeQuery, canonical_workspace, collect_workspace_status,
66 content_revision, relative_request_path, scoped_workspace,
67 };
68 use super::{ApiError, RuntimeApiState};
69
70 /// Generous bound for local git work on very large repositories.
71 const GIT_READ_TIMEOUT: Duration = Duration::from_secs(30);
72 /// Pushes cross the network; still bounded so a dead remote cannot pin a
73 /// handler forever.
74 const GIT_WRITE_TIMEOUT: Duration = Duration::from_secs(120);
75 /// Output tail carried back to the client for mutations.
76 const MAX_OUTPUT_TAIL: usize = 8 * 1024;
77 /// Commit-graph row bounds.
78 const GRAPH_LIMIT_DEFAULT: usize = 100;
79 const GRAPH_LIMIT_MAX: usize = 500;
80 /// Unified-diff response caps: a single file gets a generous window; the
81 /// whole-tree surface defaults smaller and always reports `truncated`.
82 const FILE_DIFF_MAX_BYTES: usize = 512 * 1024;
83 const WORKSPACE_DIFF_DEFAULT_BYTES: usize = 256 * 1024;
84 const WORKSPACE_DIFF_MAX_BYTES: usize = 4 * 1024 * 1024;
85 /// The empty tree — diff base for repositories whose HEAD is unborn.
86 const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
87 /// Branch/commit message caps — generous for real messages, hostile to
88 /// accidental binary paste.
89 const MAX_COMMIT_MESSAGE_BYTES: usize = 64 * 1024;
90 const MAX_BRANCH_NAME_BYTES: usize = 256;
91 const MAX_PATH_ARGS: usize = 512;
92 const MAX_PATCH_BYTES: usize = 1024 * 1024;
93 /// Per-read bound on working-tree bytes hashed for `files[].rev`. Rows past
94 /// the budget get a stat fingerprint (`s-` token) instead of a content digest
95 /// (`c-` token), so a large untracked tree cannot turn a status poll into
96 /// gigabytes of reads. Stat tokens are display-only: guarded writes refuse
97 /// them, and a tree containing one has no whole-tree revision.
98 const REV_CONTENT_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
99 const REV_CONTENT_BUDGET_FILES: usize = 4_096;
100
101 // ---------------------------------------------------------------------------
102 // git invocation
103 // ---------------------------------------------------------------------------
104
105 struct GitRun {
106 status_success: bool,
107 exit_code: Option<i32>,
108 stdout: String,
109 stderr: String,
110 }
111
112 /// Hardened read path: the same primitive review/tooling uses, so fsmonitor,
113 /// content filters, hooks, lazy fetches and replace-objects cannot run inside
114 /// an HTTP read either.
115 async fn git_read(workspace: &FsPath, args: &[&str]) -> Result<GitRun, ApiError> {
116 run_prepared_read(Git::review_command, workspace, args).await
117 }
118
119 async fn git_status_read(workspace: &FsPath, args: &[&str]) -> Result<GitRun, ApiError> {
120 run_prepared_read(Git::status_command, workspace, args).await
121 }
122
123 async fn git_status_read_ok(workspace: &FsPath, args: &[&str]) -> Result<String, ApiError> {
124 let run = git_status_read(workspace, args).await?;
125 if !run.status_success {
126 return Err(ApiError::internal(format!(
127 "git status failed: {}",
128 run.stderr.trim()
129 )));
130 }
131 Ok(run.stdout)
132 }
133
134 async fn run_prepared_read(
135 prepare: fn(&FsPath) -> anyhow::Result<std::process::Command>,
136 workspace: &FsPath,
137 args: &[&str],
138 ) -> Result<GitRun, ApiError> {
139 let workspace = workspace.to_path_buf();
140 let command = tokio::task::spawn_blocking(move || prepare(&workspace))
141 .await
142 .map_err(|_| ApiError::internal("git read setup failed"))?
143 .map_err(|error| ApiError::internal(format!("git is unavailable: {error}")))?;
144 let mut command = tokio::process::Command::from(command);
145 command.args(args);
146 finish_git(
147 codewhale_runtime::process_tree::contained_output(&mut command),
148 GIT_READ_TIMEOUT,
149 )
150 .await
151 }
152
153 /// Write path for operator-driven mutations. Non-interactive by contract:
154 /// [`Git::tokio_command`] carries the shared no-prompt environment
155 /// ([`codewhale_dependencies::apply_git_noninteractive_env`]) so a credential or
156 /// key prompt can never hang the request. Hooks and filters run exactly as they do for the user's own
157 /// `git` — a Review-sheet commit is the user's commit.
158 async fn git_write(workspace: &FsPath, args: Vec<String>) -> Result<GitRun, ApiError> {
159 let mut command = Git::tokio_command()
160 .ok_or_else(|| ApiError::internal("git is not installed or not in PATH"))?;
161 command.args(&args).current_dir(workspace);
162 // Contained: hooks and filters run here, and a timeout or a dropped
163 // request must end them too, not only the `git` process itself.
164 finish_git(
165 codewhale_runtime::process_tree::contained_output(&mut command),
166 GIT_WRITE_TIMEOUT,
167 )
168 .await
169 }
170
171 async fn finish_git(
172 output: impl std::future::Future<Output = std::io::Result<std::process::Output>>,
173 timeout: Duration,
174 ) -> Result<GitRun, ApiError> {
175 let output = tokio::time::timeout(timeout, output)
176 .await
177 .map_err(|_| ApiError::internal("git operation timed out"))?
178 .map_err(|error| ApiError::internal(format!("failed to run git: {error}")))?;
179 Ok(GitRun {
180 status_success: output.status.success(),
181 exit_code: output.status.code(),
182 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
183 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
184 })
185 }
186
187 fn output_tail(run: &GitRun) -> String {
188 let mut text = String::new();
189 for part in [run.stdout.trim(), run.stderr.trim()] {
190 if !part.is_empty() {
191 if !text.is_empty() {
192 text.push('\n');
193 }
194 text.push_str(part);
195 }
196 }
197 if text.len() > MAX_OUTPUT_TAIL {
198 let mut boundary = text.len() - MAX_OUTPUT_TAIL;
199 while !text.is_char_boundary(boundary) {
200 boundary -= 1;
201 }
202 text = text[boundary..].to_string();
203 }
204 text
205 }
206
207 async fn resolve_workspace(workspace: &FsPath, check_repo: bool) -> Result<PathBuf, ApiError> {
208 let workspace = workspace.to_path_buf();
209 tokio::task::spawn_blocking(move || {
210 let workspace = canonical_workspace(&workspace)?;
211 if check_repo {
212 require_repo(&workspace)?;
213 }
214 Ok(workspace)
215 })
216 .await
217 .map_err(|_| ApiError::internal("workspace resolution failed"))?
218 }
219
220 /// A non-repo workspace is a 404, not a 500: `rev-parse --is-inside-work-tree`
221 /// exits 128 there, so probe directly rather than through the erroring helper.
222 fn require_repo(workspace: &FsPath) -> Result<(), ApiError> {
223 match Git::output(&["rev-parse", "--is-inside-work-tree"], workspace) {
224 Ok(output)
225 if output.status.success()
226 && String::from_utf8_lossy(&output.stdout).trim() == "true" =>
227 {
228 Ok(())
229 }
230 Ok(_) => Err(ApiError::not_found("workspace is not a git repository")),
231 Err(error) => Err(ApiError::internal(format!("failed to run git: {error}"))),
232 }
233 }
234
235 /// Normal Git reads for repository chrome and filter-aware status, matching
236 /// the workspace counts and operator writes.
237 fn run_git_sync(workspace: &FsPath, args: &[&str]) -> Result<String, ApiError> {
238 let output = Git::output(args, workspace)
239 .map_err(|error| ApiError::internal(format!("failed to run git: {error}")))?;
240 if !output.status.success() {
241 return Err(ApiError::internal(format!(
242 "git {} failed: {}",
243 args.first().copied().unwrap_or(""),
244 String::from_utf8_lossy(&output.stderr).trim()
245 )));
246 }
247 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
248 }
249
250 fn status_sync(workspace: &FsPath, args: &[&str]) -> Result<String, ApiError> {
251 let output = Git::status_command(workspace)
252 .map_err(|error| ApiError::internal(format!("git is unavailable: {error}")))?
253 .args(args)
254 .output()
255 .map_err(|error| ApiError::internal(format!("failed to run git: {error}")))?;
256 if !output.status.success() {
257 return Err(ApiError::internal(format!(
258 "git status failed: {}",
259 String::from_utf8_lossy(&output.stderr).trim()
260 )));
261 }
262 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
263 }
264
265 // ---------------------------------------------------------------------------
266 // GET /v1/git — status detail
267 // ---------------------------------------------------------------------------
268
269 #[derive(Clone, Debug, Serialize)]
270 struct GitFileEntry {
271 /// Workspace-relative, like every other path on this surface.
272 path: String,
273 /// Raw porcelain v1 index (X) and worktree (Y) columns.
274 index: String,
275 worktree: String,
276 /// True when the index column records a change.
277 staged: bool,
278 /// Leading human state: modified / added / deleted / renamed /
279 /// typechange / untracked / conflicted / ignored / unknown.
280 status: &'static str,
281 /// Rename/copy source, when it lies inside the workspace.
282 #[serde(skip_serializing_if = "Option::is_none")]
283 old_path: Option<String>,
284 /// Opaque per-row precondition token: this row's index entries plus the
285 /// working-tree state of every file it covers (a rename's source and
286 /// every file under a collapsed untracked directory included).
287 rev: Option<String>,
288 }
289
290 #[derive(Debug, Serialize)]
291 pub(super) struct GitStatusDetailResponse {
292 git_repo: bool,
293 workspace: PathBuf,
294 branch: Option<String>,
295 detached: bool,
296 /// Abbreviated HEAD for display. Preconditions use `head_oid`.
297 head: Option<String>,
298 /// Full HEAD commit id; null on an unborn branch.
299 head_oid: Option<String>,
300 /// True when `git status` could not be read: the counts are unknown.
301 status_unavailable: bool,
302 /// Opaque token for the whole index (every stage entry, repository-wide).
303 index_token: Option<String>,
304 /// Opaque token for the whole tree: HEAD, the index and every row.
305 revision: Option<String>,
306 ahead: Option<u32>,
307 behind: Option<u32>,
308 staged: usize,
309 unstaged: usize,
310 untracked: usize,
311 files: Vec<GitFileEntry>,
312 branches: Vec<String>,
313 remotes: Vec<String>,
314 remote_repositories: Vec<Value>,
315 branch_preconditions: bool,
316 diff_options: bool,
317 named_push: bool,
318 }
319
320 pub(super) async fn git_status_detail(
321 State(state): State<RuntimeApiState>,
322 Query(scope): Query<ThreadScopeQuery>,
323 ) -> Result<Json<GitStatusDetailResponse>, ApiError> {
324 let workspace = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
325 tokio::task::spawn_blocking(move || collect_git_status_detail(&workspace))
326 .await
327 .map_err(|_| ApiError::internal("git status failed"))?
328 .map(Json)
329 }
330
331 fn collect_git_status_detail(workspace: &FsPath) -> Result<GitStatusDetailResponse, ApiError> {
332 let status = collect_workspace_status(workspace);
333 let mut detail = GitStatusDetailResponse {
334 git_repo: status.git_repo,
335 workspace: workspace.to_path_buf(),
336 branch: status.branch.clone(),
337 detached: false,
338 head: status.head,
339 head_oid: None,
340 status_unavailable: status.status_unavailable,
341 index_token: None,
342 revision: None,
343 ahead: status.ahead,
344 behind: status.behind,
345 staged: status.staged,
346 unstaged: status.unstaged,
347 untracked: status.untracked,
348 files: Vec::new(),
349 branches: Vec::new(),
350 remotes: Vec::new(),
351 remote_repositories: Vec::new(),
352 branch_preconditions: true,
353 diff_options: true,
354 named_push: true,
355 };
356 if !status.git_repo {
357 return Ok(detail);
358 }
359 detail.detached = status.branch.is_none()
360 || status
361 .branch
362 .as_deref()
363 .is_some_and(|branch| branch.starts_with("detached@"));
364
365 if let Ok(branches) = run_git_sync(workspace, &["branch", "--format=%(refname:short)"]) {
366 detail.branches = branches
367 .lines()
368 .map(str::trim)
369 .filter(|line| !line.is_empty())
370 .map(str::to_string)
371 .collect();
372 }
373 if let Ok(remotes) = run_git_sync(workspace, &["remote"]) {
374 detail.remotes = remotes
375 .lines()
376 .map(str::trim)
377 .filter(|line| !line.is_empty())
378 .map(str::to_string)
379 .collect();
380 }
381 detail.head_oid = head_oid(workspace).ok().flatten();
382 for name in &detail.remotes {
383 if let Ok(remote) = run_git_sync(workspace, &["remote", "get-url", "--", name]) {
384 let remote = remote.trim();
385 let path = remote
386 .strip_prefix("git@github.com:")
387 .map(str::to_string)
388 .or_else(|| {
389 url::Url::parse(remote)
390 .ok()
391 .filter(|url| {
392 matches!(url.scheme(), "https" | "ssh")
393 && url.host_str() == Some("github.com")
394 && url.query().is_none()
395 && url.fragment().is_none()
396 })
397 .map(|url| url.path().trim_start_matches('/').to_string())
398 });
399 if let Some(path) = path {
400 let repo = path.trim_end_matches('/').trim_end_matches(".git");
401 let parts: Vec<_> = repo.split('/').collect();
402 if parts.len() == 2
403 && parts.iter().all(|part| {
404 !part.is_empty()
405 && part.len() <= 100
406 && *part != "."
407 && *part != ".."
408 && part
409 .bytes()
410 .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
411 })
412 {
413 detail
414 .remote_repositories
415 .push(json!({"name": name, "provider": "github", "repo": repo}));
416 }
417 }
418 }
419 }
420 if let Ok(frame) = RepoFrame::read(workspace)
421 && let Ok((rows, complete)) = status_rows(workspace, &frame)
422 {
423 let (inside, outside) = split_by_workspace(rows, &frame.prefix);
424 detail.files = inside;
425 if let Ok(tokens) = compute_tokens(workspace, &frame, &mut detail.files, &outside) {
426 detail.head_oid = tokens.head_oid;
427 detail.index_token = Some(tokens.index_token);
428 detail.revision = tokens.revision.filter(|_| complete);
429 }
430 }
431 Ok(detail)
432 }
433
434 /// Preserve the user's own filters and untracked mode; submodules compare by
435 /// commit. Only a collapsed row naming the workspace itself needs expansion
436 /// to give clients addressable paths.
437 fn status_rows(
438 workspace: &FsPath,
439 frame: &RepoFrame,
440 ) -> Result<(Vec<GitFileEntry>, bool), ApiError> {
441 let mut complete = true;
442 let mut rows = parse_porcelain(&status_sync(workspace, &["--porcelain=v1", "-z"])?);
443 for (path, records) in IndexSnapshot::read(frame)?.by_path {
444 if !records
445 .split(|byte| *byte == 0)
446 .any(|record| record.starts_with(b"160000 "))
447 {
448 continue;
449 }
450 if rows
451 .iter()
452 .any(|row| normalized_row_path(&row.path) == path)
453 {
454 continue;
455 }
456 let sub = frame.toplevel.join(&path);
457 let git_entry = sub.join(".git");
458 let unreadable = !has_linked_ancestor(&frame.toplevel, &path)
459 && std::fs::symlink_metadata(&sub).is_ok_and(|metadata| metadata.is_dir())
460 && if git_entry.exists() {
461 submodule_head_oid(&sub).is_err()
462 } else {
463 std::fs::symlink_metadata(&git_entry).is_ok()
464 };
465 if unreadable {
466 complete = false;
467 rows.push(GitFileEntry {
468 path,
469 index: " ".to_string(),
470 worktree: "?".to_string(),
471 staged: false,
472 status: "unknown",
473 old_path: None,
474 rev: None,
475 });
476 }
477 }
478 if let Some(position) = rows
479 .iter()
480 .position(|row| row.status == "untracked" && row.path == frame.prefix)
481 {
482 match untracked_paths(&frame.toplevel, &[frame.prefix.as_str()]) {
483 Ok(paths) => {
484 rows.remove(position);
485 for path in paths {
486 rows.extend(parse_porcelain(&format!("?? {path}\0")));
487 }
488 }
489 Err(_) => complete = false,
490 }
491 }
492 Ok((rows, complete))
493 }
494
495 fn untracked_paths(workspace: &FsPath, members: &[&str]) -> Result<BTreeSet<String>, ApiError> {
496 if members.is_empty() {
497 return Ok(BTreeSet::new());
498 }
499 let mut args = vec![
500 "--literal-pathspecs",
501 "ls-files",
502 "-z",
503 "--others",
504 "--exclude-standard",
505 "--",
506 ];
507 args.extend_from_slice(members);
508 let others = review_sync_ok(workspace, &args)?;
509 Ok(others
510 .split(|byte| *byte == 0)
511 .filter(|path| !path.is_empty())
512 .map(|path| String::from_utf8_lossy(path).into_owned())
513 .collect())
514 }
515
516 /// Porcelain rows in git's frame: paths are relative to the repository root.
517 fn parse_porcelain(porcelain: &str) -> Vec<GitFileEntry> {
518 let mut entries = Vec::new();
519 let mut records = porcelain.split('\0').peekable();
520 while let Some(record) = records.next() {
521 if record.is_empty() || record.starts_with("## ") {
522 continue;
523 }
524 if record.len() < 4 {
525 continue;
526 }
527 let index = record.as_bytes()[0] as char;
528 let worktree = record.as_bytes()[1] as char;
529 let Some(path) = record.get(3..).map(str::to_string) else {
530 continue;
531 };
532 let mut old_path = None;
533 if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
534 old_path = records.next().map(str::to_string);
535 }
536 entries.push(GitFileEntry {
537 path,
538 index: index.to_string(),
539 worktree: worktree.to_string(),
540 staged: !matches!(index, ' ' | '?' | '!'),
541 status: porcelain_status(index, worktree),
542 old_path,
543 rev: None,
544 });
545 }
546 entries
547 }
548
549 /// Move repository-root rows into the workspace frame. Omitted paths still
550 /// feed the whole-tree revision because stage-all and commit reach them.
551 /// A rename leaving the workspace is shown as its source deletion.
552 fn split_by_workspace(
553 rows: Vec<GitFileEntry>,
554 prefix: &str,
555 ) -> (Vec<GitFileEntry>, Vec<GitFileEntry>) {
556 let mut inside = Vec::new();
557 let mut outside = Vec::new();
558 for mut row in rows {
559 let old_path = row
560 .old_path
561 .as_deref()
562 .and_then(|old| workspace_frame_path(prefix, old));
563 match workspace_frame_path(prefix, &row.path) {
564 Some(path) => {
565 if row.old_path.is_some() && old_path.is_none() {
566 outside.push(row.clone());
567 }
568 row.path = path;
569 row.old_path = old_path;
570 inside.push(row);
571 }
572 None => {
573 let renamed = row.index == "R" || row.worktree == "R";
574 if renamed && let Some(path) = old_path {
575 let worktree_side = row.worktree == "R";
576 inside.push(GitFileEntry {
577 path,
578 index: if worktree_side {
579 " ".to_string()
580 } else {
581 "D".to_string()
582 },
583 worktree: if worktree_side {
584 "D".to_string()
585 } else {
586 " ".to_string()
587 },
588 staged: !worktree_side,
589 status: "deleted",
590 old_path: None,
591 rev: None,
592 });
593 }
594 outside.push(row);
595 }
596 }
597 }
598 (inside, outside)
599 }
600
601 /// The one translation from git's repository-root frame to the workspace
602 /// frame. `None` means the path lies outside the workspace.
603 fn workspace_frame_path(prefix: &str, root_path: &str) -> Option<String> {
604 let path = root_path.strip_prefix(prefix)?;
605 (!path.is_empty()).then(|| path.to_string())
606 }
607
608 /// A row path as a precondition key: git's collapsed-directory `dir/` and a
609 /// request's `dir` name the same thing.
610 fn normalized_row_path(path: &str) -> &str {
611 path.trim_end_matches('/')
612 }
613
614 // ---------------------------------------------------------------------------
615 // Precondition tokens (#6647)
616 // ---------------------------------------------------------------------------
617
618 /// Hardened one-shot read for token material: the review command, so
619 /// fsmonitor, filters, hooks and replace-objects cannot run (or alter what
620 /// the token sees) during a precondition read.
621 fn review_sync(cwd: &FsPath, args: &[&str]) -> Result<std::process::Output, ApiError> {
622 #[cfg(test)]
623 tests::GIT_READS.with(|count| count.set(count.get() + 1));
624 let mut command = Git::review_command(cwd)
625 .map_err(|error| ApiError::internal(format!("git is unavailable: {error}")))?;
626 command
627 .args(args)
628 .output()
629 .map_err(|error| ApiError::internal(format!("failed to run git: {error}")))
630 }
631
632 fn review_sync_ok(cwd: &FsPath, args: &[&str]) -> Result<Vec<u8>, ApiError> {
633 let output = review_sync(cwd, args)?;
634 if !output.status.success() {
635 return Err(ApiError::internal(format!(
636 "git {} failed: {}",
637 args.iter()
638 .find(|arg| !arg.starts_with("--"))
639 .copied()
640 .unwrap_or(""),
641 String::from_utf8_lossy(&output.stderr).trim()
642 )));
643 }
644 Ok(output.stdout)
645 }
646
647 /// Where the workspace sits inside its repository.
648 struct RepoFrame {
649 toplevel: PathBuf,
650 /// `sub/dir/` for a subdirectory workspace, empty at the root.
651 prefix: String,
652 }
653
654 impl RepoFrame {
655 fn read(workspace: &FsPath) -> Result<Self, ApiError> {
656 let output = review_sync_ok(
657 workspace,
658 &["rev-parse", "--show-toplevel", "--show-prefix"],
659 )?;
660 let text = String::from_utf8_lossy(&output);
661 let mut lines = text.lines();
662 let toplevel = lines
663 .next()
664 .map(str::trim)
665 .filter(|line| !line.is_empty())
666 .ok_or_else(|| ApiError::internal("git rev-parse returned no toplevel"))?;
667 Ok(Self {
668 toplevel: PathBuf::from(toplevel),
669 prefix: lines
670 .next()
671 .unwrap_or("")
672 .trim_end_matches('\n')
673 .to_string(),
674 })
675 }
676 }
677
678 /// Resolve HEAD inside `sub` only after verifying `sub/.git` itself resolves
679 /// without walking up to a parent repository.
680 fn submodule_head_oid(sub: &FsPath) -> Result<Option<String>, ApiError> {
681 review_sync_ok(sub, &["rev-parse", "--resolve-git-dir", ".git"])?;
682 head_oid(sub)
683 }
684
685 /// Full HEAD commit id, `None` on an unborn branch.
686 fn head_oid(workspace: &FsPath) -> Result<Option<String>, ApiError> {
687 let output = review_sync(workspace, &["rev-parse", "--verify", "-q", "HEAD^{commit}"])?;
688 if output.status.success() {
689 let oid = String::from_utf8_lossy(&output.stdout).trim().to_string();
690 if !oid.is_empty() {
691 return Ok(Some(oid));
692 }
693 } else {
694 let symbolic = review_sync(workspace, &["symbolic-ref", "-q", "HEAD"])?;
695 if symbolic.status.success() {
696 let reference = String::from_utf8_lossy(&symbolic.stdout);
697 let reference = reference.trim();
698 if reference.starts_with("refs/heads/") {
699 // for-each-ref warns when it ignores a broken ref. Only a
700 // clean, empty enumeration establishes an unborn branch.
701 let refs = review_sync(
702 workspace,
703 &["for-each-ref", "--format=%(refname)", reference],
704 )?;
705 if refs.status.success() && refs.stdout.is_empty() && refs.stderr.is_empty() {
706 return Ok(None);
707 }
708 }
709 }
710 }
711 Err(ApiError::internal(
712 "git HEAD does not resolve to a commit or an unborn branch",
713 ))
714 }
715
716 /// The semantic index (mode, blob, stage, path — never the stat cache that
717 /// `git status` rewrites), read once from the repository root with no
718 /// pathspec so it covers every entry, including unmerged stages and entries
719 /// outside a subdirectory workspace.
720 struct IndexSnapshot {
721 token: String,
722 /// Repository-root path → that path's raw `ls-files --stage` records.
723 by_path: BTreeMap<String, Vec<u8>>,
724 /// One scoped inventory, loaded only for directory members. None means
725 /// enumeration failed or was not requested; directory tokens fail closed.
726 untracked: Option<BTreeSet<String>>,
727 }
728
729 impl IndexSnapshot {
730 fn read(frame: &RepoFrame) -> Result<Self, ApiError> {
731 let raw = review_sync_ok(&frame.toplevel, &["ls-files", "--stage", "-z"])?;
732 let mut by_path: BTreeMap<String, Vec<u8>> = BTreeMap::new();
733 for record in raw.split(|byte| *byte == 0).filter(|r| !r.is_empty()) {
734 let Some(tab) = record.iter().position(|byte| *byte == b'\t') else {
735 continue;
736 };
737 let root_path = String::from_utf8_lossy(&record[tab + 1..]);
738 let slot = by_path.entry(root_path.into_owned()).or_default();
739 slot.extend_from_slice(record);
740 slot.push(0);
741 }
742 Ok(Self {
743 token: content_revision(&raw),
744 by_path,
745 untracked: None,
746 })
747 }
748
749 fn load_untracked(&mut self, workspace: &FsPath, members: &[String]) {
750 let directories: Vec<&str> = members
751 .iter()
752 .filter(|member| {
753 !has_linked_ancestor(workspace, member)
754 && std::fs::symlink_metadata(workspace.join(member))
755 .is_ok_and(|metadata| metadata.is_dir())
756 && !workspace.join(member).join(".git").exists()
757 })
758 .map(String::as_str)
759 .collect();
760 self.untracked = untracked_paths(workspace, &directories).ok();
761 }
762
763 /// Records at `member` or anywhere below it, in path order.
764 fn records_under<'a>(&'a self, member: &'a str) -> impl Iterator<Item = (&'a str, &'a [u8])> {
765 self.by_path
766 .range::<str, _>((
767 std::ops::Bound::Included(member),
768 std::ops::Bound::Unbounded,
769 ))
770 .take_while(move |(path, _)| path.starts_with(member))
771 .filter(move |(path, _)| is_at_or_under(path, member))
772 .map(|(path, records)| (path.as_str(), records.as_slice()))
773 }
774 }
775
776 fn is_at_or_under(path: &str, member: &str) -> bool {
777 path == member
778 || path
779 .strip_prefix(member)
780 .is_some_and(|rest| rest.starts_with('/'))
781 }
782
783 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
784 enum RevMode {
785 /// Working-tree files are identified by a sha256 of their bytes (the
786 /// Files routes' content revision).
787 Content,
788 /// Display-only size + mtime (oversized files or past the read budget).
789 Stat,
790 }
791
792 impl RevMode {
793 fn tag(self) -> &'static str {
794 match self {
795 Self::Content => "c-",
796 Self::Stat => "s-",
797 }
798 }
799 }
800
801 /// One member path of a row (the row itself, or a rename's source) with
802 /// everything its token covers.
803 struct MemberListing {
804 member: String,
805 index_records: Vec<u8>,
806 /// Repository-root files whose working-tree state is part of the token.
807 files: BTreeSet<String>,
808 }
809
810 fn list_member(
811 workspace: &FsPath,
812 index: &IndexSnapshot,
813 member: &str,
814 ) -> Result<MemberListing, ApiError> {
815 let mut listing = MemberListing {
816 member: member.to_string(),
817 index_records: Vec::new(),
818 files: BTreeSet::new(),
819 };
820 for (path, records) in index.records_under(member) {
821 listing.index_records.extend_from_slice(records);
822 listing.files.insert(path.to_string());
823 }
824 // A path beyond a symlinked directory is not part of this repository's
825 // worktree; never read through the link.
826 if has_linked_ancestor(workspace, member) {
827 return Err(ApiError::internal(
828 "cannot fingerprint through a symlinked directory",
829 ));
830 }
831 match std::fs::symlink_metadata(workspace.join(member)) {
832 Ok(metadata) if metadata.is_dir() && workspace.join(member).join(".git").exists() => {
833 listing.files.insert(member.to_string());
834 }
835 Ok(metadata) if metadata.is_dir() => {
836 // Untracked files below a directory (a collapsed `dir/` row, or a
837 // directory named in a request): exactly what `git add dir`
838 // would pick up, with the same ignore rules.
839 let untracked = index
840 .untracked
841 .as_ref()
842 .ok_or_else(|| ApiError::internal("cannot enumerate untracked directory"))?;
843 for path in untracked.range(member.to_string()..) {
844 if !path.starts_with(member) {
845 break;
846 }
847 if is_at_or_under(path, member) {
848 listing.files.insert(normalized_row_path(path).to_string());
849 }
850 }
851 }
852 Ok(_) => {
853 listing.files.insert(member.to_string());
854 }
855 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
856 Err(error) => {
857 return Err(ApiError::internal(format!(
858 "cannot inspect {member}: {error}"
859 )));
860 }
861 }
862 Ok(listing)
863 }
864
865 fn has_linked_ancestor(workspace: &FsPath, member: &str) -> bool {
866 let mut current = workspace.to_path_buf();
867 let mut parts = member.split('/').peekable();
868 while let Some(part) = parts.next() {
869 if parts.peek().is_none() {
870 break;
871 }
872 current.push(part);
873 match std::fs::symlink_metadata(&current) {
874 Ok(metadata) if metadata.file_type().is_symlink() => return true,
875 Ok(_) => {}
876 Err(_) => return false,
877 }
878 }
879 false
880 }
881
882 fn stat_fingerprint(metadata: &std::fs::Metadata) -> String {
883 let mtime_ns = metadata
884 .modified()
885 .ok()
886 .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
887 .map_or(0, |duration| duration.as_nanos());
888 format!("stat:{}:{mtime_ns}", metadata.len())
889 }
890
891 /// A file's working-tree identity. Links are never followed.
892 fn worktree_fingerprint(workspace: &FsPath, path: &str, mode: RevMode) -> Result<String, ApiError> {
893 if has_linked_ancestor(workspace, path) {
894 return Err(ApiError::internal(
895 "cannot fingerprint through a symlinked directory",
896 ));
897 }
898 let full = workspace.join(path);
899 let unreadable = |error| ApiError::internal(format!("cannot fingerprint {path}: {error}"));
900 let metadata = match std::fs::symlink_metadata(&full) {
901 Ok(metadata) => metadata,
902 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok("absent".into()),
903 Err(error) => return Err(unreadable(error)),
904 };
905 let file_type = metadata.file_type();
906 if file_type.is_symlink() {
907 return std::fs::read_link(&full)
908 .map(|target| format!("link:{}", target.to_string_lossy()))
909 .map_err(unreadable);
910 }
911 if file_type.is_dir() {
912 // Gitlinks (including newly added nested repositories) record HEAD.
913 // Dirty submodule contents are summarized by status, not recursively
914 // hashed: ordinary add/checkout do not write those contents.
915 if full.join(".git").exists() {
916 let head = submodule_head_oid(&full)?;
917 let status = status_sync(&full, &["--porcelain=v1", "-z"])?;
918 return Ok(format!(
919 "gitlink:{}:{}",
920 head.as_deref().unwrap_or("unborn"),
921 content_revision(status.as_bytes())
922 ));
923 }
924 return Ok("dir".into());
925 }
926 if !file_type.is_file() {
927 return Err(ApiError::internal(format!(
928 "cannot fingerprint special file {path}"
929 )));
930 }
931 #[cfg(unix)]
932 let executable = {
933 use std::os::unix::fs::PermissionsExt;
934 metadata.permissions().mode() & 0o100 != 0
935 };
936 #[cfg(not(unix))]
937 let executable = false;
938 let fingerprint = if mode == RevMode::Stat || metadata.len() > FILE_SERVE_MAX_BYTES {
939 stat_fingerprint(&metadata)
940 } else {
941 use std::io::Read as _;
942 let mut bytes = Vec::new();
943 std::fs::File::open(&full)
944 .and_then(|file| file.take(FILE_SERVE_MAX_BYTES + 1).read_to_end(&mut bytes))
945 .map_err(unreadable)?;
946 if bytes.len() as u64 > FILE_SERVE_MAX_BYTES {
947 stat_fingerprint(&metadata)
948 } else {
949 content_revision(&bytes)
950 }
951 };
952 Ok(format!("{fingerprint}:exec:{executable}"))
953 }
954
955 fn members_of(path: &str, old_path: Option<&str>) -> Vec<String> {
956 let mut members = BTreeSet::new();
957 members.insert(normalized_row_path(path).to_string());
958 if let Some(old) = old_path {
959 members.insert(normalized_row_path(old).to_string());
960 }
961 members.into_iter().collect()
962 }
963
964 fn row_rev(
965 workspace: &FsPath,
966 listings: &[MemberListing],
967 mode: RevMode,
968 ) -> Result<String, ApiError> {
969 let mut effective_mode = mode;
970 let mut hasher = Sha256::new();
971 hasher.update(b"cw-git-rev-1\0");
972 for listing in listings {
973 hasher.update(b"member\0");
974 hasher.update(listing.member.as_bytes());
975 hasher.update(b"\0index\0");
976 hasher.update(&listing.index_records);
977 hasher.update(b"\0worktree\0");
978 for file in &listing.files {
979 hasher.update(file.as_bytes());
980 hasher.update(b"\0");
981 let fingerprint = worktree_fingerprint(workspace, file, mode)?;
982 if fingerprint.starts_with("stat:") {
983 effective_mode = RevMode::Stat;
984 }
985 hasher.update(fingerprint.as_bytes());
986 hasher.update(b"\0");
987 }
988 }
989 Ok(format!(
990 "{}{}",
991 effective_mode.tag(),
992 hex(&hasher.finalize())
993 ))
994 }
995
996 fn hex(bytes: &[u8]) -> String {
997 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
998 }
999
1000 /// Running content-hash budget for one read.
1001 #[derive(Default)]
1002 struct RevBudget {
1003 bytes: u64,
1004 files: usize,
1005 }
1006
1007 impl RevBudget {
1008 /// Content mode while the whole row still fits; otherwise stat mode for
1009 /// the whole row (a token has exactly one mode).
1010 fn choose(&mut self, workspace: &FsPath, listings: &[MemberListing]) -> RevMode {
1011 let mut bytes = 0u64;
1012 let mut files = 0usize;
1013 for file in listings.iter().flat_map(|listing| listing.files.iter()) {
1014 if !has_linked_ancestor(workspace, file)
1015 && let Ok(metadata) = std::fs::symlink_metadata(workspace.join(file))
1016 && metadata.is_file()
1017 {
1018 if metadata.len() > FILE_SERVE_MAX_BYTES {
1019 return RevMode::Stat;
1020 }
1021 bytes += metadata.len();
1022 files += 1;
1023 }
1024 }
1025 if self.bytes + bytes <= REV_CONTENT_BUDGET_BYTES
1026 && self.files + files <= REV_CONTENT_BUDGET_FILES
1027 {
1028 self.bytes += bytes;
1029 self.files += files;
1030 RevMode::Content
1031 } else {
1032 RevMode::Stat
1033 }
1034 }
1035 }
1036
1037 struct GitTokens {
1038 head_oid: Option<String>,
1039 index_token: String,
1040 revision: Option<String>,
1041 }
1042
1043 fn compute_tokens(
1044 workspace: &FsPath,
1045 frame: &RepoFrame,
1046 files: &mut [GitFileEntry],
1047 outside: &[GitFileEntry],
1048 ) -> Result<GitTokens, ApiError> {
1049 let head = head_oid(workspace);
1050 let mut index = IndexSnapshot::read(frame)?;
1051 let members: Vec<String> = files
1052 .iter()
1053 .flat_map(|entry| {
1054 members_of(&entry.path, entry.old_path.as_deref())
1055 .into_iter()
1056 .map(|member| format!("{}{member}", frame.prefix))
1057 })
1058 .chain(
1059 outside
1060 .iter()
1061 .flat_map(|entry| members_of(&entry.path, entry.old_path.as_deref())),
1062 )
1063 .collect();
1064 index.load_untracked(&frame.toplevel, &members);
1065 let mut budget = RevBudget::default();
1066 // Hidden untracked paths are deliberately not enumerated, so the read
1067 // cannot authorize a repository-wide add that would include them.
1068 let mut content_safe = head.is_ok()
1069 && review_sync_ok(
1070 workspace,
1071 &[
1072 "config",
1073 "--default",
1074 "normal",
1075 "--get",
1076 "status.showUntrackedFiles",
1077 ],
1078 )
1079 .is_ok_and(|mode| String::from_utf8_lossy(&mode).trim() != "no");
1080 let head_oid = head.ok().flatten();
1081 let mut row_token = |entry: &GitFileEntry, prefix: &str| -> Option<String> {
1082 let result = (|| {
1083 if entry.status == "unknown" {
1084 return Err(ApiError::internal("submodule status is unavailable"));
1085 }
1086 let listings = members_of(&entry.path, entry.old_path.as_deref())
1087 .iter()
1088 .map(|member| list_member(&frame.toplevel, &index, &format!("{prefix}{member}")))
1089 .collect::<Result<Vec<_>, _>>()?;
1090 let mode = budget.choose(&frame.toplevel, &listings);
1091 row_rev(&frame.toplevel, &listings, mode)
1092 })();
1093 let rev = result.ok();
1094 content_safe &= rev.as_deref().is_some_and(|rev| rev.starts_with("c-"));
1095 rev
1096 };
1097 for entry in files.iter_mut() {
1098 entry.rev = row_token(entry, &frame.prefix);
1099 }
1100 let mut hasher = Sha256::new();
1101 hasher.update(b"cw-git-revision-1\0");
1102 hasher.update(head_oid.as_deref().unwrap_or("unborn").as_bytes());
1103 hasher.update(b"\0");
1104 hasher.update(index.token.as_bytes());
1105 hasher.update(b"\0");
1106 let mut rows: Vec<&GitFileEntry> = files.iter().collect();
1107 rows.sort_by(|a, b| a.path.cmp(&b.path));
1108 for row in rows {
1109 hasher.update(row.path.as_bytes());
1110 hasher.update(b"\0");
1111 hasher.update(row.rev.as_deref().unwrap_or("").as_bytes());
1112 hasher.update(b"\0");
1113 }
1114 let mut outside: Vec<&GitFileEntry> = outside.iter().collect();
1115 outside.sort_by(|a, b| a.path.cmp(&b.path));
1116 for row in outside {
1117 hasher.update(b"outside\0");
1118 hasher.update(row.path.as_bytes());
1119 hasher.update(b"\0");
1120 hasher.update(row_token(row, "").as_deref().unwrap_or("").as_bytes());
1121 hasher.update(b"\0");
1122 }
1123 Ok(GitTokens {
1124 head_oid,
1125 index_token: index.token,
1126 revision: content_safe.then(|| hex(&hasher.finalize())),
1127 })
1128 }
1129
1130 fn porcelain_status(index: char, worktree: char) -> &'static str {
1131 match (index, worktree) {
1132 ('?', '?') => "untracked",
1133 ('!', '!') => "ignored",
1134 ('U', _) | (_, 'U') | ('D', 'D') | ('A', 'A') => "conflicted",
1135 ('R', _) | (_, 'R') => "renamed",
1136 ('C', _) | (_, 'C') => "copied",
1137 ('A', _) | (_, 'A') => "added",
1138 ('D', _) | (_, 'D') => "deleted",
1139 ('T', _) | (_, 'T') => "typechange",
1140 ('M', _) | (_, 'M') => "modified",
1141 _ => "unchanged",
1142 }
1143 }
1144
1145 // ---------------------------------------------------------------------------
1146 // GET /v1/changes — the file-change inventory only
1147 // ---------------------------------------------------------------------------
1148
1149 /// The Review sheet's change list: the same porcelain projection as
1150 /// `GET /v1/git` minus repo chrome (branches/remotes). One authority — a
1151 /// client that loaded both cannot see them disagree.
1152 pub(super) async fn git_changes(
1153 State(state): State<RuntimeApiState>,
1154 Query(scope): Query<ThreadScopeQuery>,
1155 ) -> Result<Json<Value>, ApiError> {
1156 let workspace = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
1157 let detail = tokio::task::spawn_blocking(move || collect_git_status_detail(&workspace))
1158 .await
1159 .map_err(|_| ApiError::internal("git status failed"))??;
1160 Ok(Json(json!({
1161 "git_repo": detail.git_repo,
1162 "branch": detail.branch,
1163 "staged": detail.staged,
1164 "unstaged": detail.unstaged,
1165 "untracked": detail.untracked,
1166 "head_oid": detail.head_oid,
1167 "index_token": detail.index_token,
1168 "revision": detail.revision,
1169 "files": detail.files,
1170 })))
1171 }
1172
1173 // ---------------------------------------------------------------------------
1174 // GET /v1/diff + /v1/workspace/diff — unified diffs against HEAD
1175 // ---------------------------------------------------------------------------
1176
1177 /// `git diff <base>` compares the worktree to <base>, covering staged and
1178 /// unstaged changes in one output. On an unborn branch the base is the
1179 /// empty tree, which reads every staged/tracked file as new — the honest
1180 /// "everything changed" picture for a repo with no commits.
1181 async fn diff_base(workspace: &FsPath) -> Result<String, ApiError> {
1182 let head = git_read(workspace, &["rev-parse", "--verify", "HEAD"]).await?;
1183 Ok(if head.status_success {
1184 "HEAD".to_string()
1185 } else {
1186 EMPTY_TREE.to_string()
1187 })
1188 }
1189
1190 async fn selected_diff_base(
1191 workspace: &FsPath,
1192 selected: Option<&str>,
1193 ) -> Result<String, ApiError> {
1194 let Some(selected) = selected.filter(|value| !value.is_empty()) else {
1195 return diff_base(workspace).await;
1196 };
1197 if selected.len() > 256 || selected.starts_with('-') || selected.chars().any(char::is_control) {
1198 return Err(ApiError::bad_request(
1199 "Choose a valid base branch or commit",
1200 ));
1201 }
1202 let reference = format!("{selected}^{{commit}}");
1203 let found = git_read(
1204 workspace,
1205 &["rev-parse", "--verify", "--end-of-options", &reference],
1206 )
1207 .await?;
1208 if !found.status_success
1209 || !matches!(found.stdout.trim().len(), 40 | 64)
1210 || !found
1211 .stdout
1212 .trim()
1213 .bytes()
1214 .all(|byte| byte.is_ascii_hexdigit())
1215 {
1216 return Err(ApiError::bad_request(
1217 "The base branch or commit is unavailable in this workspace",
1218 ));
1219 }
1220 Ok(found.stdout.trim().to_string())
1221 }
1222
1223 fn diff_context(value: Option<usize>) -> Result<String, ApiError> {
1224 let value = value.unwrap_or(3);
1225 if value > 10_000 {
1226 return Err(ApiError::bad_request(
1227 "Diff context must be at most 10000 lines",
1228 ));
1229 }
1230 Ok(format!("--unified={value}"))
1231 }
1232
1233 /// Byte-bounded cut at a char boundary; reports whether bytes were dropped.
1234 fn bounded_patch(text: &str, limit: usize) -> (String, bool) {
1235 if text.len() <= limit {
1236 return (text.to_string(), false);
1237 }
1238 let mut end = limit;
1239 while !text.is_char_boundary(end) {
1240 end -= 1;
1241 }
1242 (text[..end].to_string(), true)
1243 }
1244
1245 #[derive(Deserialize)]
1246 #[serde(deny_unknown_fields)]
1247 pub(super) struct GitDiffQuery {
1248 /// Workspace-relative file; may name a deleted file (the diff survives).
1249 path: String,
1250 base: Option<String>,
1251 context: Option<usize>,
1252 ignore_whitespace: Option<bool>,
1253 thread_id: Option<String>,
1254 }
1255
1256 /// `GET /v1/diff?path=` — one file's unified diff against HEAD (or the empty
1257 /// tree on an unborn branch). An untracked file has no diff by definition:
1258 /// the response says `untracked: true` with an empty `diff` so the client
1259 /// reads the file itself instead of mistaking it for unchanged.
1260 pub(super) async fn git_diff(
1261 State(state): State<RuntimeApiState>,
1262 Query(query): Query<GitDiffQuery>,
1263 ) -> Result<Json<Value>, ApiError> {
1264 let path = relative_request_path(&query.path, false)?;
1265 let scoped = scoped_workspace(&state, query.thread_id.as_deref()).await?;
1266 let workspace = resolve_workspace(&scoped, true).await?;
1267 let base = selected_diff_base(&workspace, query.base.as_deref()).await?;
1268 let context = diff_context(query.context)?;
1269 let path_arg = path.to_string_lossy().into_owned();
1270 let mut args = file_diff_args(&base, &path_arg);
1271 args.insert(3, &context);
1272 if query.ignore_whitespace == Some(true) {
1273 args.insert(3, "--ignore-all-space");
1274 }
1275 let run = git_read(&workspace, &args).await?;
1276 if !run.status_success {
1277 return Err(ApiError::internal(format!(
1278 "git diff failed: {}",
1279 run.stderr.trim()
1280 )));
1281 }
1282 let (diff, truncated) = bounded_patch(&run.stdout, FILE_DIFF_MAX_BYTES);
1283 let untracked = if diff.is_empty() {
1284 let status = git_read(
1285 &workspace,
1286 &[
1287 "--literal-pathspecs",
1288 "status",
1289 "--porcelain=v1",
1290 "-z",
1291 "--ignore-submodules=dirty",
1292 "--",
1293 &path_arg,
1294 ],
1295 )
1296 .await?;
1297 status
1298 .stdout
1299 .split('\0')
1300 .any(|record| record.starts_with("??"))
1301 } else {
1302 false
1303 };
1304 Ok(Json(json!({
1305 "ok": true,
1306 "path": path_arg,
1307 "base": base,
1308 "untracked": untracked,
1309 "diff": diff,
1310 "truncated": truncated,
1311 })))
1312 }
1313
1314 /// One file's diff against `base`. The path is literal, never pathspec magic
1315 /// or a glob, so `:/…`/`:(top)…` cannot reach outside a workspace that is a
1316 /// subdirectory of its repository.
1317 fn file_diff_args<'a>(base: &'a str, path: &'a str) -> Vec<&'a str> {
1318 let mut args = vec!["--literal-pathspecs", "diff", "--no-color"];
1319 args.extend(Git::REVIEW_DIFF_ARGS);
1320 args.extend([base, "--", path]);
1321 args
1322 }
1323
1324 #[derive(Deserialize)]
1325 #[serde(deny_unknown_fields)]
1326 pub(super) struct WorkspaceDiffQuery {
1327 /// Byte cap on the returned patch (default 256 KiB, max 4 MiB).
1328 limit: Option<usize>,
1329 base: Option<String>,
1330 context: Option<usize>,
1331 ignore_whitespace: Option<bool>,
1332 thread_id: Option<String>,
1333 }
1334
1335 /// `GET /v1/workspace/diff?limit=` — the whole tree's diff against HEAD plus
1336 /// a complete `--numstat` inventory, so a client renders every changed file
1337 /// row even when the patch body is truncated.
1338 pub(super) async fn workspace_diff(
1339 State(state): State<RuntimeApiState>,
1340 Query(query): Query<WorkspaceDiffQuery>,
1341 ) -> Result<Json<Value>, ApiError> {
1342 let limit = query.limit.unwrap_or(WORKSPACE_DIFF_DEFAULT_BYTES);
1343 if !(1024..=WORKSPACE_DIFF_MAX_BYTES).contains(&limit) {
1344 return Err(ApiError::bad_request(format!(
1345 "limit must be between 1024 and {WORKSPACE_DIFF_MAX_BYTES} bytes"
1346 )));
1347 }
1348 let scoped = scoped_workspace(&state, query.thread_id.as_deref()).await?;
1349 let workspace = resolve_workspace(&scoped, true).await?;
1350 let base = selected_diff_base(&workspace, query.base.as_deref()).await?;
1351 let context = diff_context(query.context)?;
1352
1353 let mut numstat_args = vec!["diff", "--numstat"];
1354 numstat_args.extend(Git::REVIEW_DIFF_ARGS);
1355 if query.ignore_whitespace == Some(true) {
1356 numstat_args.push("--ignore-all-space");
1357 }
1358 numstat_args.push(&base);
1359 let numstat = git_read(&workspace, &numstat_args).await?;
1360 if !numstat.status_success {
1361 return Err(ApiError::internal(format!(
1362 "git diff --numstat failed: {}",
1363 numstat.stderr.trim()
1364 )));
1365 }
1366 let files: Vec<Value> = numstat
1367 .stdout
1368 .lines()
1369 .filter_map(|line| {
1370 let mut fields = line.splitn(3, '\t');
1371 let added = fields.next()?;
1372 let deleted = fields.next()?;
1373 let path = fields.next()?;
1374 Some(json!({
1375 "path": path,
1376 // Binary files report "-" rather than a count.
1377 "added": added.parse::<u64>().ok(),
1378 "deleted": deleted.parse::<u64>().ok(),
1379 }))
1380 })
1381 .collect();
1382
1383 let mut diff_args = vec!["diff", "--no-color"];
1384 diff_args.extend(Git::REVIEW_DIFF_ARGS);
1385 diff_args.push(&context);
1386 if query.ignore_whitespace == Some(true) {
1387 diff_args.push("--ignore-all-space");
1388 }
1389 diff_args.push(&base);
1390 let run = git_read(&workspace, &diff_args).await?;
1391 if !run.status_success {
1392 return Err(ApiError::internal(format!(
1393 "git diff failed: {}",
1394 run.stderr.trim()
1395 )));
1396 }
1397 let (diff, truncated) = bounded_patch(&run.stdout, limit);
1398 Ok(Json(json!({
1399 "ok": true,
1400 "git_repo": true,
1401 "base": base,
1402 "files": files,
1403 "diff": diff,
1404 "truncated": truncated,
1405 })))
1406 }
1407
1408 // ---------------------------------------------------------------------------
1409 // GET /v1/git/graph — bounded commit graph rows
1410 // ---------------------------------------------------------------------------
1411
1412 #[derive(Deserialize)]
1413 #[serde(deny_unknown_fields)]
1414 pub(super) struct GitGraphQuery {
1415 limit: Option<usize>,
1416 thread_id: Option<String>,
1417 }
1418
1419 const GRAPH_FIELD: char = '\u{1f}';
1420 const GRAPH_RECORD: char = '\u{1e}';
1421
1422 pub(super) async fn git_graph(
1423 State(state): State<RuntimeApiState>,
1424 Query(query): Query<GitGraphQuery>,
1425 ) -> Result<Json<Value>, ApiError> {
1426 let limit = query.limit.unwrap_or(GRAPH_LIMIT_DEFAULT);
1427 if !(1..=GRAPH_LIMIT_MAX).contains(&limit) {
1428 return Err(ApiError::bad_request(format!(
1429 "limit must be between 1 and {GRAPH_LIMIT_MAX}"
1430 )));
1431 }
1432 let scoped = scoped_workspace(&state, query.thread_id.as_deref()).await?;
1433 let workspace = resolve_workspace(&scoped, true).await?;
1434 let limit_arg = format!("-n{limit}");
1435 let format = format!(
1436 "%H{GRAPH_FIELD}%h{GRAPH_FIELD}%P{GRAPH_FIELD}%an{GRAPH_FIELD}%ae{GRAPH_FIELD}%aI{GRAPH_FIELD}%D{GRAPH_FIELD}%s{GRAPH_RECORD}"
1437 );
1438 let format_arg = format!("--format={format}");
1439 let run = git_read(&workspace, &["log", &limit_arg, &format_arg]).await?;
1440 if !run.status_success {
1441 // `git log` exits non-zero on an unborn branch; that is a valid empty
1442 // graph, not a failure. Distinguish with a HEAD probe instead of
1443 // trusting stderr text.
1444 let head = git_read(&workspace, &["rev-parse", "--verify", "HEAD"]).await?;
1445 if head.status_success {
1446 return Err(ApiError::internal(format!(
1447 "git log failed: {}",
1448 run.stderr.trim()
1449 )));
1450 }
1451 return Ok(Json(json!({ "commits": [], "truncated": false })));
1452 }
1453 let mut commits = Vec::new();
1454 for record in run.stdout.split(GRAPH_RECORD) {
1455 let record = record.trim_matches('\n');
1456 if record.is_empty() {
1457 continue;
1458 }
1459 let mut fields = record.split(GRAPH_FIELD);
1460 let (
1461 Some(id),
1462 Some(short),
1463 Some(parents),
1464 Some(name),
1465 Some(email),
1466 Some(timestamp),
1467 Some(refs),
1468 Some(subject),
1469 ) = (
1470 fields.next(),
1471 fields.next(),
1472 fields.next(),
1473 fields.next(),
1474 fields.next(),
1475 fields.next(),
1476 fields.next(),
1477 fields.next(),
1478 )
1479 else {
1480 continue;
1481 };
1482 commits.push(json!({
1483 "id": id,
1484 "short": short,
1485 "parents": parents.split_whitespace().collect::<Vec<_>>(),
1486 "author": { "name": name, "email": email },
1487 "timestamp": timestamp,
1488 "refs": refs
1489 .split(", ")
1490 .map(str::trim)
1491 .filter(|name| !name.is_empty())
1492 .collect::<Vec<_>>(),
1493 "subject": subject,
1494 }));
1495 }
1496 let truncated = commits.len() >= limit;
1497 Ok(Json(json!({ "commits": commits, "truncated": truncated })))
1498 }
1499
1500 // ---------------------------------------------------------------------------
1501 // Mutations
1502 // ---------------------------------------------------------------------------
1503
1504 #[derive(Deserialize)]
1505 #[serde(deny_unknown_fields)]
1506 pub(super) struct GitPushRequest {
1507 remote: Option<String>,
1508 #[serde(default)]
1509 set_upstream: bool,
1510 #[serde(default)]
1511 branch: Option<String>,
1512 #[serde(default)]
1513 expect: Option<GitExpect>,
1514 }
1515
1516 #[derive(Deserialize)]
1517 #[serde(deny_unknown_fields)]
1518 pub(super) struct GitBranchRequest {
1519 name: String,
1520 /// Create and switch (`git switch -c`); default is switch to existing.
1521 #[serde(default)]
1522 create: bool,
1523 #[serde(default)]
1524 expect: Option<GitExpect>,
1525 }
1526
1527 #[derive(Deserialize)]
1528 #[serde(deny_unknown_fields)]
1529 pub(super) struct GitPathsRequest {
1530 #[serde(default)]
1531 paths: Vec<String>,
1532 /// Stage/unstage may take the whole tree; discard cannot.
1533 #[serde(default)]
1534 all: bool,
1535 /// Optional preconditions (#6647); absent keeps the unchecked behaviour.
1536 #[serde(default)]
1537 expect: Option<GitExpect>,
1538 #[serde(default)]
1539 patch: Option<String>,
1540 }
1541
1542 #[derive(Deserialize)]
1543 #[serde(deny_unknown_fields)]
1544 pub(super) struct GitCommitRequest {
1545 message: String,
1546 /// Also stage tracked modifications (`git commit -a`).
1547 #[serde(default)]
1548 all: bool,
1549 #[serde(default)]
1550 expect: Option<GitExpect>,
1551 }
1552
1553 /// What the client last read. Each present field is checked; an absent
1554 /// field is not. `head: null` means "HEAD must be unborn".
1555 #[derive(Deserialize, Default)]
1556 #[serde(deny_unknown_fields)]
1557 pub(super) struct GitExpect {
1558 #[serde(default, deserialize_with = "present")]
1559 head: Option<Option<String>>,
1560 #[serde(default)]
1561 index: Option<String>,
1562 #[serde(default, deserialize_with = "present")]
1563 revision: Option<Option<String>>,
1564 #[serde(default)]
1565 files: Option<BTreeMap<String, String>>,
1566 }
1567
1568 /// Distinguishes an explicit `null` (`Some(None)`) from an absent field.
1569 fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Option<String>>, D::Error> {
1570 Option::<String>::deserialize(deserializer).map(Some)
1571 }
1572
1573 /// A validated precondition, normalized (trimmed, lowercase hex, workspace-
1574 /// relative file keys).
1575 #[derive(Debug, Default)]
1576 struct Preconditions {
1577 head: Option<Option<String>>,
1578 index: Option<String>,
1579 revision: Option<String>,
1580 files: Option<BTreeMap<String, String>>,
1581 }
1582
1583 impl Preconditions {
1584 fn is_empty(&self) -> bool {
1585 self.head.is_none()
1586 && self.index.is_none()
1587 && self.revision.is_none()
1588 && self.files.is_none()
1589 }
1590 }
1591
1592 fn normalized_hex(raw: &str, lengths: &[usize], field: &str) -> Result<String, ApiError> {
1593 let value = raw.trim().to_ascii_lowercase();
1594 if lengths.contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1595 Ok(value)
1596 } else {
1597 Err(ApiError::bad_request(format!(
1598 "expect.{field} must be a token read from GET /v1/git"
1599 )))
1600 }
1601 }
1602
1603 /// Where the preconditions are being applied, for the rules that differ.
1604 enum ExpectTarget<'a> {
1605 /// Stage/unstage/discard with explicit, validated paths.
1606 Paths(&'a [String]),
1607 /// Stage/unstage of the whole tree.
1608 AllPaths,
1609 Commit,
1610 }
1611
1612 /// Validate `expect` before any lock or git call; every failure is a 400 and
1613 /// nothing is written.
1614 fn validate_expect(
1615 expect: Option<GitExpect>,
1616 target: ExpectTarget<'_>,
1617 ) -> Result<Preconditions, ApiError> {
1618 let Some(expect) = expect else {
1619 return Ok(Preconditions::default());
1620 };
1621 let head = match expect.head {
1622 None => None,
1623 Some(None) => Some(None),
1624 Some(Some(raw)) => Some(Some(normalized_hex(&raw, &[40, 64], "head")?)),
1625 };
1626 let index = expect
1627 .index
1628 .map(|raw| normalized_hex(&raw, &[64], "index"))
1629 .transpose()?;
1630 let revision = expect
1631 .revision
1632 .map(|raw| {
1633 let raw = raw.ok_or_else(|| ApiError::bad_request(
1634 "expect.revision cannot be null; a content-safe whole-tree revision is required",
1635 ))?;
1636 normalized_hex(&raw, &[64], "revision")
1637 })
1638 .transpose()?;
1639 let files = match (expect.files, target) {
1640 (None, _) => None,
1641 (Some(_), ExpectTarget::Commit) => {
1642 return Err(ApiError::bad_request(
1643 "expect.files applies to path operations; use expect.index or expect.revision for commit",
1644 ));
1645 }
1646 (Some(_), ExpectTarget::AllPaths) => {
1647 return Err(ApiError::bad_request(
1648 "use expect.revision for whole-tree operations",
1649 ));
1650 }
1651 (Some(raw), ExpectTarget::Paths(paths)) => {
1652 let mut files = BTreeMap::new();
1653 for (key, token) in raw {
1654 let path = relative_request_path(&key, false)?
1655 .to_string_lossy()
1656 .into_owned();
1657 let token = token.trim().to_ascii_lowercase();
1658 let valid = token.len() == 66
1659 && token.starts_with("c-")
1660 && token[2..].bytes().all(|byte| byte.is_ascii_hexdigit());
1661 if !valid {
1662 return Err(ApiError::bad_request(format!(
1663 "expect.files[{path}] must be a content-safe c- rev read from GET /v1/git; stat-only revisions cannot guard writes"
1664 )));
1665 }
1666 if files.insert(path.clone(), token).is_some() {
1667 return Err(ApiError::bad_request(format!(
1668 "expect.files names {path} twice"
1669 )));
1670 }
1671 }
1672 let requested: BTreeSet<&str> = paths.iter().map(String::as_str).collect();
1673 let guarded: BTreeSet<&str> = files.keys().map(String::as_str).collect();
1674 if requested != guarded {
1675 let missing: Vec<&str> = requested.difference(&guarded).copied().collect();
1676 let extra: Vec<&str> = guarded.difference(&requested).copied().collect();
1677 return Err(ApiError::bad_request(format!(
1678 "expect.files must name exactly the requested paths (missing: [{}]; extra: [{}])",
1679 missing.join(", "),
1680 extra.join(", ")
1681 )));
1682 }
1683 Some(files)
1684 }
1685 };
1686 Ok(Preconditions {
1687 head,
1688 index,
1689 revision,
1690 files,
1691 })
1692 }
1693
1694 /// A git-route failure. Ordinary failures keep the shared [`ApiError`]
1695 /// envelope; the precondition and busy answers add a machine `code` and
1696 /// fields a client acts on.
1697 pub(super) enum GitWriteError {
1698 Api(ApiError),
1699 Coded {
1700 status: StatusCode,
1701 code: &'static str,
1702 message: String,
1703 extra: serde_json::Map<String, Value>,
1704 },
1705 }
1706
1707 impl From<ApiError> for GitWriteError {
1708 fn from(error: ApiError) -> Self {
1709 Self::Api(error)
1710 }
1711 }
1712
1713 impl IntoResponse for GitWriteError {
1714 fn into_response(self) -> Response {
1715 match self {
1716 Self::Api(error) => error.into_response(),
1717 Self::Coded {
1718 status,
1719 code,
1720 message,
1721 mut extra,
1722 } => {
1723 extra.insert(
1724 "error".to_string(),
1725 json!({ "message": message, "status": status.as_u16(), "code": code }),
1726 );
1727 (status, Json(Value::Object(extra))).into_response()
1728 }
1729 }
1730 }
1731 }
1732
1733 fn busy_error() -> GitWriteError {
1734 GitWriteError::Coded {
1735 status: StatusCode::CONFLICT,
1736 code: "git_busy",
1737 message:
1738 "Another Git write from this runtime is still running. Try again when it finishes."
1739 .to_string(),
1740 extra: serde_json::Map::new(),
1741 }
1742 }
1743
1744 /// Compare the preconditions with the repository as it is now. Runs on a
1745 /// blocking thread under the write lock.
1746 fn check_preconditions(
1747 workspace: &FsPath,
1748 expect: &Preconditions,
1749 ) -> Result<Result<(), GitWriteError>, ApiError> {
1750 let mut stale: Vec<&'static str> = Vec::new();
1751 let mut parts: Vec<String> = Vec::new();
1752 let mut stale_paths: Vec<String> = Vec::new();
1753 let frame = RepoFrame::read(workspace)?;
1754
1755 if let Some(expected) = &expect.head {
1756 let current = head_oid(workspace)?;
1757 if &current != expected {
1758 stale.push("head");
1759 parts.push(match (expected, &current) {
1760 (None, Some(_)) => "HEAD is no longer unborn".to_string(),
1761 (Some(_), None) => "HEAD is now unborn".to_string(),
1762 _ => "HEAD moved".to_string(),
1763 });
1764 }
1765 }
1766 let index = if expect.index.is_some() || expect.files.is_some() {
1767 Some(IndexSnapshot::read(&frame)?)
1768 } else {
1769 None
1770 };
1771 if let (Some(expected), Some(index)) = (&expect.index, &index)
1772 && &index.token != expected
1773 {
1774 stale.push("index");
1775 parts.push("the index changed".to_string());
1776 }
1777 if let (Some(files), Some(mut index)) = (&expect.files, index) {
1778 // A rename row's token also covers its source path; recover that
1779 // pairing from the current status, as the read did.
1780 let (rows, _) = status_rows(workspace, &frame)?;
1781 let (rows, _) = split_by_workspace(rows, &frame.prefix);
1782 let sources: BTreeMap<String, String> = rows
1783 .iter()
1784 .filter_map(|row| {
1785 row.old_path
1786 .as_deref()
1787 .map(|old| (normalized_row_path(&row.path).to_string(), old.to_string()))
1788 })
1789 .collect();
1790 let members: Vec<String> = files
1791 .keys()
1792 .flat_map(|path| members_of(path, sources.get(path).map(String::as_str)))
1793 .map(|member| format!("{}{member}", frame.prefix))
1794 .collect();
1795 index.load_untracked(&frame.toplevel, &members);
1796 for (path, expected) in files {
1797 let current = members_of(path, sources.get(path).map(String::as_str))
1798 .iter()
1799 .map(|member| {
1800 list_member(
1801 &frame.toplevel,
1802 &index,
1803 &format!("{}{member}", frame.prefix),
1804 )
1805 })
1806 .collect::<Result<Vec<_>, _>>()
1807 .and_then(|listings| row_rev(&frame.toplevel, &listings, RevMode::Content));
1808 if current.as_ref().ok() != Some(expected)
1809 || rows
1810 .iter()
1811 .any(|row| row.status == "unknown" && is_at_or_under(&row.path, path))
1812 {
1813 stale_paths.push(path.clone());
1814 }
1815 }
1816 if !stale_paths.is_empty() {
1817 stale.push("files");
1818 parts.push(match stale_paths.as_slice() {
1819 [one] => format!("{one} changed"),
1820 many => {
1821 let shown: Vec<&str> = many.iter().take(3).map(String::as_str).collect();
1822 let more = many.len().saturating_sub(shown.len());
1823 if more == 0 {
1824 format!("{} files changed: {}", many.len(), shown.join(", "))
1825 } else {
1826 format!(
1827 "{} files changed: {} and {more} more",
1828 many.len(),
1829 shown.join(", ")
1830 )
1831 }
1832 }
1833 });
1834 }
1835 }
1836 let mut current = None;
1837 if let Some(expected) = &expect.revision {
1838 let detail = collect_git_status_detail(workspace)?;
1839 if detail.revision.as_deref() != Some(expected.as_str()) {
1840 stale.push("revision");
1841 parts.push("the working tree or index changed".to_string());
1842 }
1843 current = Some(detail);
1844 }
1845 if stale.is_empty() {
1846 return Ok(Ok(()));
1847 }
1848 let current = match current {
1849 Some(detail) => detail,
1850 None => collect_git_status_detail(workspace)?,
1851 };
1852 let mut extra = serde_json::Map::new();
1853 extra.insert("stale".to_string(), json!(stale));
1854 extra.insert("stale_paths".to_string(), json!(stale_paths));
1855 extra.insert(
1856 "current".to_string(),
1857 serde_json::to_value(current)
1858 .map_err(|_| ApiError::internal("git status serialization failed"))?,
1859 );
1860 Ok(Err(GitWriteError::Coded {
1861 status: StatusCode::CONFLICT,
1862 code: "git_state_changed",
1863 message: format!(
1864 "The repository changed since it was read ({}). Nothing was written; refresh and review again.",
1865 parts.join("; ")
1866 ),
1867 extra,
1868 }))
1869 }
1870
1871 async fn mutation_response(workspace: &FsPath, run: GitRun) -> Result<Json<Value>, ApiError> {
1872 if !run.status_success {
1873 let tail = output_tail(&run);
1874 return Err(ApiError::bad_request(if tail.is_empty() {
1875 format!("git exited {}", run.exit_code.unwrap_or(-1))
1876 } else {
1877 tail
1878 }));
1879 }
1880 let output = output_tail(&run);
1881 let workspace = workspace.to_path_buf();
1882 let (status, current) = tokio::task::spawn_blocking(move || {
1883 (
1884 collect_workspace_status(&workspace),
1885 collect_git_status_detail(&workspace),
1886 )
1887 })
1888 .await
1889 .map_err(|_| ApiError::internal("git status failed"))?;
1890 Ok(Json(json!({
1891 "ok": true,
1892 "output": output,
1893 "status": status,
1894 "current": current?,
1895 })))
1896 }
1897
1898 /// The shared check-then-write path. The per-runtime lock makes the check
1899 /// and the write atomic with respect to this server's other git writes (two
1900 /// app windows on one runtime); a second writer gets `git_busy` instead of
1901 /// waiting behind a long hook. External processes are outside the lock —
1902 /// see docs/RUNTIME_API.md for that window.
1903 async fn guarded_write(
1904 state: &RuntimeApiState,
1905 root: &FsPath,
1906 expect: Preconditions,
1907 args: Vec<String>,
1908 ) -> Result<Json<Value>, GitWriteError> {
1909 let _guard = state.git_writes.try_lock().map_err(|_| busy_error())?;
1910 let workspace = resolve_workspace(root, true).await?;
1911 if !expect.is_empty() {
1912 let root = workspace.clone();
1913 tokio::task::spawn_blocking(move || check_preconditions(&root, &expect))
1914 .await
1915 .map_err(|_| ApiError::internal("git precondition check failed"))???;
1916 }
1917 Ok(mutation_response(&workspace, git_write(&workspace, args).await?).await?)
1918 }
1919
1920 /// Validate and collect pathspecs. Every path is workspace-relative with no
1921 /// `.`/`..`/`.git` components and is passed after `--` with
1922 /// `--literal-pathspecs`, so it can never be read as an option or a glob.
1923 fn validated_paths(request: &GitPathsRequest, allow_all: bool) -> Result<Vec<String>, ApiError> {
1924 if request.all && !allow_all {
1925 return Err(ApiError::bad_request(
1926 "discard requires explicit paths; refusing to discard the whole tree",
1927 ));
1928 }
1929 if request.all && !request.paths.is_empty() {
1930 return Err(ApiError::bad_request(
1931 "all and paths are mutually exclusive",
1932 ));
1933 }
1934 if !request.all && request.paths.is_empty() {
1935 return Err(ApiError::bad_request("paths is required (or all: true)"));
1936 }
1937 if request.paths.len() > MAX_PATH_ARGS {
1938 return Err(ApiError::bad_request(format!(
1939 "at most {MAX_PATH_ARGS} paths per request"
1940 )));
1941 }
1942 request
1943 .paths
1944 .iter()
1945 .map(|raw| {
1946 relative_request_path(raw, false).map(|path| path.to_string_lossy().into_owned())
1947 })
1948 .collect()
1949 }
1950
1951 /// Validated paths plus their preconditions.
1952 fn paths_and_expect(
1953 request: GitPathsRequest,
1954 allow_all: bool,
1955 ) -> Result<(bool, Vec<String>, Preconditions), ApiError> {
1956 let paths = validated_paths(&request, allow_all)?;
1957 let target = if request.all {
1958 ExpectTarget::AllPaths
1959 } else {
1960 ExpectTarget::Paths(&paths)
1961 };
1962 let expect = validate_expect(request.expect, target)?;
1963 Ok((request.all, paths, expect))
1964 }
1965
1966 /// `git --literal-pathspecs <subcommand…> -- <paths>`.
1967 fn literal_path_args(subcommand: &[&str], paths: Vec<String>) -> Vec<String> {
1968 let mut args = vec!["--literal-pathspecs".to_string()];
1969 args.extend(subcommand.iter().map(|arg| arg.to_string()));
1970 args.push("--".to_string());
1971 args.extend(paths);
1972 args
1973 }
1974
1975 fn validated_patch(patch: &str, path: &str) -> Result<(), ApiError> {
1976 let refuse = |why: &str| Err(ApiError::bad_request(format!("patch {why}")));
1977 if patch.len() > MAX_PATCH_BYTES {
1978 return refuse(&format!("must be at most {MAX_PATCH_BYTES} bytes"));
1979 }
1980 let header = format!("diff --git a/{path} b/{path}");
1981 let old = format!("--- a/{path}");
1982 let new = format!("+++ b/{path}");
1983 let (mut seen_old, mut seen_new, mut hunks) = (false, false, 0usize);
1984 let (mut old_left, mut new_left) = (0usize, 0usize);
1985 for line in patch.lines() {
1986 if old_left > 0 || new_left > 0 {
1987 match line.as_bytes().first() {
1988 Some(b' ') | None => {
1989 old_left = old_left.saturating_sub(1);
1990 new_left = new_left.saturating_sub(1);
1991 }
1992 Some(b'-') => old_left = old_left.saturating_sub(1),
1993 Some(b'+') => new_left = new_left.saturating_sub(1),
1994 Some(b'\\') => {}
1995 _ => return refuse("has a hunk shorter than its header"),
1996 }
1997 continue;
1998 }
1999 if line.starts_with('\\') {
2000 continue;
2001 }
2002 if let Some(range) = line.strip_prefix("@@ ") {
2003 if !(seen_old && seen_new) {
2004 return refuse(&format!("must start with --- a/{path} and +++ b/{path}"));
2005 }
2006 let mut counts = range
2007 .split_whitespace()
2008 .zip(['-', '+'])
2009 .map(|(side, sign)| {
2010 let side = side.strip_prefix(sign)?;
2011 match side.split_once(',') {
2012 Some((_, count)) => count.parse::<usize>().ok(),
2013 None => side.parse::<usize>().ok().map(|_| 1),
2014 }
2015 });
2016 let (Some(Some(a)), Some(Some(b))) = (counts.next(), counts.next()) else {
2017 return refuse("has a malformed @@ line");
2018 };
2019 (old_left, new_left) = (a, b);
2020 hunks += 1;
2021 } else if line.starts_with("diff --git ") {
2022 if line != header {
2023 return refuse(&format!("may change only {path}"));
2024 }
2025 (seen_old, seen_new) = (false, false);
2026 } else if line.starts_with("--- ") {
2027 if line != old {
2028 return refuse(&format!("may change only {path}, and not create it"));
2029 }
2030 seen_old = true;
2031 } else if line.starts_with("+++ ") {
2032 if line != new {
2033 return refuse(&format!("may change only {path}, and not delete it"));
2034 }
2035 seen_new = true;
2036 } else if !line.starts_with("index ") {
2037 return refuse("may only change lines (no rename, copy, mode or binary changes)");
2038 }
2039 }
2040 if hunks == 0 || old_left > 0 || new_left > 0 {
2041 return refuse("needs at least one complete hunk");
2042 }
2043 Ok(())
2044 }
2045
2046 async fn patch_write(
2047 state: &RuntimeApiState,
2048 root: &FsPath,
2049 request: GitPathsRequest,
2050 apply: &[&str],
2051 ) -> Result<Json<Value>, GitWriteError> {
2052 let patch = request.patch.clone().unwrap_or_default();
2053 if request.all || request.paths.len() != 1 {
2054 return Err(ApiError::bad_request("patch needs exactly one path").into());
2055 }
2056 let (_, paths, expect) = paths_and_expect(request, false)?;
2057 validated_patch(&patch, &paths[0])?;
2058 let file = tokio::task::spawn_blocking(move || {
2059 use std::io::Write;
2060 let mut file = tempfile::NamedTempFile::new()?;
2061 file.write_all(patch.as_bytes())?;
2062 file.flush()?;
2063 Ok::<_, std::io::Error>(file)
2064 })
2065 .await
2066 .map_err(|_| ApiError::internal("patch staging failed"))?
2067 .map_err(|error| ApiError::internal(format!("patch staging failed: {error}")))?;
2068 let workspace = resolve_workspace(root, false).await?;
2069 let place = git_read_ok(&workspace, &["rev-parse", "--show-cdup", "--show-prefix"]).await?;
2070 let mut place = place.lines();
2071 let (cdup, prefix) = (
2072 place.next().unwrap_or_default().to_string(),
2073 place.next().unwrap_or_default().to_string(),
2074 );
2075 let mut args = Vec::new();
2076 if !cdup.is_empty() {
2077 args.extend(["-C".to_string(), cdup]);
2078 }
2079 args.extend(apply.iter().map(|arg| arg.to_string()));
2080 if !prefix.is_empty() {
2081 args.push(format!("--directory={prefix}"));
2082 }
2083 args.push("--".to_string());
2084 args.push(file.path().to_string_lossy().into_owned());
2085 let result = guarded_write(state, root, expect, args).await;
2086 drop(file);
2087 result
2088 }
2089
2090 pub(super) async fn git_stage(
2091 State(state): State<RuntimeApiState>,
2092 Query(scope): Query<ThreadScopeQuery>,
2093 Json(request): Json<GitPathsRequest>,
2094 ) -> Result<Json<Value>, GitWriteError> {
2095 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2096 if request.patch.is_some() {
2097 return patch_write(&state, &root, request, &["apply", "--cached"]).await;
2098 }
2099 let (all, paths, expect) = paths_and_expect(request, true)?;
2100 let args = if all {
2101 vec!["add".to_string(), "--all".to_string()]
2102 } else {
2103 literal_path_args(&["add"], paths)
2104 };
2105 guarded_write(&state, &root, expect, args).await
2106 }
2107
2108 pub(super) async fn git_unstage(
2109 State(state): State<RuntimeApiState>,
2110 Query(scope): Query<ThreadScopeQuery>,
2111 Json(request): Json<GitPathsRequest>,
2112 ) -> Result<Json<Value>, GitWriteError> {
2113 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2114 if request.patch.is_some() {
2115 return patch_write(&state, &root, request, &["apply", "--cached", "--reverse"]).await;
2116 }
2117 let (all, paths, expect) = paths_and_expect(request, true)?;
2118 let args = if all {
2119 // `:/` is pathspec magic for the repository root, so this one form
2120 // cannot run under --literal-pathspecs.
2121 vec![
2122 "restore".to_string(),
2123 "--staged".to_string(),
2124 ":/".to_string(),
2125 ]
2126 } else {
2127 literal_path_args(&["restore", "--staged"], paths)
2128 };
2129 guarded_write(&state, &root, expect, args).await
2130 }
2131
2132 pub(super) async fn git_discard(
2133 State(state): State<RuntimeApiState>,
2134 Query(scope): Query<ThreadScopeQuery>,
2135 Json(request): Json<GitPathsRequest>,
2136 ) -> Result<Json<Value>, GitWriteError> {
2137 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2138 if request.patch.is_some() {
2139 return patch_write(&state, &root, request, &["apply", "--reverse"]).await;
2140 }
2141 let (_, paths, expect) = paths_and_expect(request, false)?;
2142 guarded_write(
2143 &state,
2144 &root,
2145 expect,
2146 literal_path_args(&["checkout"], paths),
2147 )
2148 .await
2149 }
2150
2151 pub(super) async fn git_commit(
2152 State(state): State<RuntimeApiState>,
2153 Query(scope): Query<ThreadScopeQuery>,
2154 Json(request): Json<GitCommitRequest>,
2155 ) -> Result<Json<Value>, GitWriteError> {
2156 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2157 let message = request.message.trim();
2158 if message.is_empty() {
2159 return Err(ApiError::bad_request("message is required").into());
2160 }
2161 if message.len() > MAX_COMMIT_MESSAGE_BYTES {
2162 return Err(ApiError::bad_request(format!(
2163 "message must be at most {MAX_COMMIT_MESSAGE_BYTES} bytes"
2164 ))
2165 .into());
2166 }
2167 let expect = validate_expect(request.expect, ExpectTarget::Commit)?;
2168 let mut args = vec!["commit".to_string()];
2169 if request.all {
2170 args.push("--all".to_string());
2171 }
2172 args.push("--message".to_string());
2173 args.push(message.to_string());
2174 guarded_write(&state, &root, expect, args).await
2175 }
2176
2177 /// A push target must be one of the repository's configured remotes: never an
2178 /// option lookalike (`--force`, `--mirror`) and never a path or URL.
2179 fn validate_push_remote(remote: &str, configured: &str) -> Result<(), ApiError> {
2180 let shaped = !remote.starts_with('-')
2181 && remote
2182 .bytes()
2183 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'/'));
2184 if !shaped {
2185 return Err(ApiError::bad_request("remote must be a remote name"));
2186 }
2187 if !configured.lines().any(|name| name.trim() == remote) {
2188 return Err(ApiError::bad_request(format!(
2189 "remote {remote} is not configured in this repository"
2190 )));
2191 }
2192 Ok(())
2193 }
2194
2195 /// A bounded async read that must succeed; its stdout. Discovery for request
2196 /// validation goes through [`git_read`] so it never blocks a runtime worker.
2197 async fn git_read_ok(workspace: &FsPath, args: &[&str]) -> Result<String, ApiError> {
2198 let run = git_read(workspace, args).await?;
2199 if !run.status_success {
2200 return Err(ApiError::internal(format!(
2201 "git {} failed: {}",
2202 args.first().copied().unwrap_or(""),
2203 run.stderr.trim()
2204 )));
2205 }
2206 Ok(run.stdout)
2207 }
2208
2209 #[derive(Debug, PartialEq, Eq)]
2210 struct NamedPush {
2211 branch: String,
2212 head: String,
2213 }
2214
2215 fn named_push(
2216 branch: Option<&str>,
2217 expect: Option<GitExpect>,
2218 ) -> Result<Option<NamedPush>, ApiError> {
2219 let branch = branch.map(str::trim);
2220 let (branch, expect) = match (branch, expect) {
2221 (None, None) => return Ok(None),
2222 (None, Some(_)) => {
2223 return Err(ApiError::bad_request(
2224 "expect on push requires the branch it was read for",
2225 ));
2226 }
2227 (Some(_), None) => {
2228 return Err(ApiError::bad_request(
2229 "branch requires expect.head read from GET /v1/git",
2230 ));
2231 }
2232 (Some(branch), Some(expect)) => (branch, expect),
2233 };
2234 let shaped = !branch.is_empty()
2235 && branch.len() <= MAX_BRANCH_NAME_BYTES
2236 && !branch.starts_with('-')
2237 && branch
2238 .bytes()
2239 .all(|byte| byte > b' ' && byte != 0x7f && byte != b':');
2240 if !shaped {
2241 return Err(ApiError::bad_request("branch must be a local branch name"));
2242 }
2243 if expect.index.is_some() || expect.revision.is_some() || expect.files.is_some() {
2244 return Err(ApiError::bad_request("push takes only expect.head"));
2245 }
2246 let head = match expect.head {
2247 Some(Some(raw)) => normalized_hex(&raw, &[40, 64], "head")?,
2248 Some(None) => {
2249 return Err(ApiError::bad_request(
2250 "an unborn branch has no commit to push",
2251 ));
2252 }
2253 None => {
2254 return Err(ApiError::bad_request(
2255 "branch requires expect.head read from GET /v1/git",
2256 ));
2257 }
2258 };
2259 Ok(Some(NamedPush {
2260 branch: branch.to_string(),
2261 head,
2262 }))
2263 }
2264
2265 async fn git_config_value(workspace: &FsPath, key: &str) -> Result<Option<String>, ApiError> {
2266 let run = git_read(workspace, &["config", "--get", key]).await?;
2267 let value = run.stdout.trim();
2268 Ok((run.status_success && !value.is_empty()).then(|| value.to_string()))
2269 }
2270
2271 #[derive(Debug)]
2272 struct PushPlan {
2273 args: Vec<String>,
2274 upstream: Option<(String, String)>,
2275 }
2276
2277 async fn push_plan(
2278 workspace: &FsPath,
2279 remote: Option<&str>,
2280 set_upstream: bool,
2281 named: Option<NamedPush>,
2282 ) -> Result<Result<PushPlan, GitWriteError>, ApiError> {
2283 let symbolic = git_read(workspace, &["symbolic-ref", "-q", "HEAD"]).await?;
2284 let checked_out = symbolic
2285 .status_success
2286 .then(|| symbolic.stdout.trim().strip_prefix("refs/heads/"))
2287 .flatten()
2288 .map(str::to_string);
2289 let tip = |branch: &str| {
2290 let reference = format!("refs/heads/{branch}^{{commit}}");
2291 async move {
2292 let run = git_read(workspace, &["rev-parse", "--verify", "-q", &reference]).await?;
2293 let oid = run.stdout.trim().to_ascii_lowercase();
2294 Ok::<_, ApiError>((run.status_success && !oid.is_empty()).then_some(oid))
2295 }
2296 };
2297 let (branch, head) = match named {
2298 Some(NamedPush { branch, head }) => {
2299 let mut stale = Vec::new();
2300 let mut parts = Vec::new();
2301 if checked_out.as_deref() != Some(branch.as_str()) {
2302 stale.push("branch");
2303 parts.push(match &checked_out {
2304 Some(current) => format!("{current} is checked out, not {branch}"),
2305 None => "HEAD is detached".to_string(),
2306 });
2307 }
2308 if tip(&branch).await?.as_deref() != Some(head.as_str()) {
2309 stale.push("head");
2310 parts.push(format!("{branch} moved"));
2311 }
2312 if !stale.is_empty() {
2313 let root = workspace.to_path_buf();
2314 let current = tokio::task::spawn_blocking(move || collect_git_status_detail(&root))
2315 .await
2316 .map_err(|_| ApiError::internal("git status failed"))??;
2317 let mut extra = serde_json::Map::new();
2318 extra.insert("stale".to_string(), json!(stale));
2319 extra.insert("stale_paths".to_string(), json!([]));
2320 extra.insert(
2321 "current".to_string(),
2322 serde_json::to_value(current)
2323 .map_err(|_| ApiError::internal("git status serialization failed"))?,
2324 );
2325 return Ok(Err(GitWriteError::Coded {
2326 status: StatusCode::CONFLICT,
2327 code: "git_state_changed",
2328 message: format!(
2329 "The repository changed since it was read ({}). Nothing was pushed; refresh and review again.",
2330 parts.join("; ")
2331 ),
2332 extra,
2333 }));
2334 }
2335 (branch, head)
2336 }
2337 None => {
2338 let Some(branch) = checked_out else {
2339 return Err(ApiError::bad_request(
2340 "cannot push from a detached HEAD; check out a branch",
2341 ));
2342 };
2343 let Some(head) = tip(&branch).await? else {
2344 return Err(ApiError::bad_request(format!(
2345 "{branch} has no commits to push"
2346 )));
2347 };
2348 (branch, head)
2349 }
2350 };
2351 let tracking = git_config_value(workspace, &format!("branch.{branch}.remote")).await?;
2352 let remote = match remote.map(str::trim).filter(|remote| !remote.is_empty()) {
2353 Some(remote) => remote.to_string(),
2354 None => {
2355 let mut chosen =
2356 git_config_value(workspace, &format!("branch.{branch}.pushRemote")).await?;
2357 if chosen.is_none() {
2358 chosen = git_config_value(workspace, "remote.pushDefault").await?;
2359 }
2360 chosen
2361 .or_else(|| tracking.clone())
2362 .unwrap_or_else(|| "origin".to_string())
2363 }
2364 };
2365 validate_push_remote(&remote, &git_read_ok(workspace, &["remote"]).await?)?;
2366 let destination = format!("refs/heads/{branch}");
2367 if tracking.as_deref() == Some(remote.as_str())
2368 && let Some(merge) = git_config_value(workspace, &format!("branch.{branch}.merge")).await?
2369 && merge != destination
2370 {
2371 return Err(ApiError::bad_request(format!(
2372 "{branch} tracks {merge} on {remote}; only a push to the same-named branch is supported"
2373 )));
2374 }
2375 let args = vec![
2376 "push".to_string(),
2377 "--no-follow-tags".to_string(),
2378 "--no-recurse-submodules".to_string(),
2379 "--".to_string(),
2380 remote.clone(),
2381 format!("{head}:{destination}"),
2382 ];
2383 Ok(Ok(PushPlan {
2384 args,
2385 upstream: set_upstream.then_some((branch, remote)),
2386 }))
2387 }
2388
2389 async fn push(workspace: &FsPath, request: GitPushRequest) -> Result<Json<Value>, GitWriteError> {
2390 let named = named_push(request.branch.as_deref(), request.expect)?;
2391 let plan = push_plan(
2392 workspace,
2393 request.remote.as_deref(),
2394 request.set_upstream,
2395 named,
2396 )
2397 .await??;
2398 let run = git_write(workspace, plan.args).await?;
2399 if run.status_success
2400 && let Some((branch, remote)) = plan.upstream
2401 {
2402 for (key, value) in [
2403 (format!("branch.{branch}.remote"), remote),
2404 (
2405 format!("branch.{branch}.merge"),
2406 format!("refs/heads/{branch}"),
2407 ),
2408 ] {
2409 let config = git_write(workspace, vec!["config".to_string(), key, value]).await?;
2410 if !config.status_success {
2411 return Err(ApiError::bad_request(format!(
2412 "The push succeeded but its upstream was not recorded: {}",
2413 output_tail(&config)
2414 ))
2415 .into());
2416 }
2417 }
2418 }
2419 Ok(mutation_response(workspace, run).await?)
2420 }
2421
2422 pub(super) async fn git_push(
2423 State(state): State<RuntimeApiState>,
2424 Query(scope): Query<ThreadScopeQuery>,
2425 Json(request): Json<GitPushRequest>,
2426 ) -> Result<Json<Value>, GitWriteError> {
2427 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2428 let workspace = resolve_workspace(&root, true).await?;
2429 // Push stays outside the write lock: it crosses the network under a
2430 // 120 s bound and only moves a remote ref, never the index or worktree.
2431 push(&workspace, request).await
2432 }
2433
2434 pub(super) async fn git_branch(
2435 State(state): State<RuntimeApiState>,
2436 Query(scope): Query<ThreadScopeQuery>,
2437 Json(request): Json<GitBranchRequest>,
2438 ) -> Result<Json<Value>, GitWriteError> {
2439 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2440 let name = request.name.trim();
2441 if name.is_empty() || name.len() > MAX_BRANCH_NAME_BYTES {
2442 return Err(ApiError::bad_request("name is required").into());
2443 }
2444 let expect = validate_expect(request.expect, ExpectTarget::Commit)?;
2445 let _admission = state.runtime_threads.session_checkpoint_guard().await;
2446 // Switching rewrites the worktree and index, so it shares the lock with
2447 // stage/discard/commit.
2448 let _guard = state.git_writes.try_lock().map_err(|_| busy_error())?;
2449 let workspace = resolve_workspace(&root, true).await?;
2450 state
2451 .runtime_threads
2452 .reject_active_turns_in_workspace(&workspace)
2453 .await
2454 .map_err(|error| ApiError::conflict(error.to_string()))?;
2455 if !expect.is_empty() {
2456 let root = workspace.clone();
2457 tokio::task::spawn_blocking(move || check_preconditions(&root, &expect))
2458 .await
2459 .map_err(|_| ApiError::internal("git precondition check failed"))???;
2460 }
2461 // `check-ref-format --branch` is the ref authority — it rejects option
2462 // lookalikes, `..`, `@{`, control bytes, and every other unsafe name.
2463 let check = git_write(
2464 &workspace,
2465 vec![
2466 "check-ref-format".to_string(),
2467 "--branch".to_string(),
2468 name.to_string(),
2469 ],
2470 )
2471 .await?;
2472 if !check.status_success {
2473 return Err(ApiError::bad_request("name is not a valid branch").into());
2474 }
2475 let mut args = vec!["switch".to_string()];
2476 if request.create {
2477 args.push("--create".to_string());
2478 }
2479 args.push(name.to_string());
2480 Ok(mutation_response(&workspace, git_write(&workspace, args).await?).await?)
2481 }
2482
2483 // ---------------------------------------------------------------------------
2484 // Worktrees
2485 // ---------------------------------------------------------------------------
2486
2487 const WORKTREES_DIR: &str = ".codewhale/worktrees";
2488
2489 #[derive(Debug, Serialize)]
2490 pub(super) struct WorktreeRow {
2491 path: String,
2492 branch: Option<String>,
2493 head: Option<String>,
2494 main: bool,
2495 managed: bool,
2496 locked: bool,
2497 prunable: bool,
2498 }
2499
2500 fn parse_worktrees(porcelain: &str, managed_root: Option<&FsPath>) -> Vec<WorktreeRow> {
2501 let mut rows = Vec::new();
2502 for block in porcelain.split("\n\n") {
2503 let mut path = None;
2504 let mut branch = None;
2505 let mut head = None;
2506 let (mut locked, mut prunable, mut bare) = (false, false, false);
2507 for line in block.lines() {
2508 if let Some(value) = line.strip_prefix("worktree ") {
2509 path = Some(value.to_string());
2510 } else if let Some(value) = line.strip_prefix("HEAD ") {
2511 head = Some(value.to_string());
2512 } else if let Some(value) = line.strip_prefix("branch ") {
2513 branch = Some(
2514 value
2515 .strip_prefix("refs/heads/")
2516 .unwrap_or(value)
2517 .to_string(),
2518 );
2519 } else if line == "bare" {
2520 bare = true;
2521 } else if line == "locked" || line.starts_with("locked ") {
2522 locked = true;
2523 } else if line == "prunable" || line.starts_with("prunable ") {
2524 prunable = true;
2525 }
2526 }
2527 let Some(path) = path else { continue };
2528 if bare {
2529 continue;
2530 }
2531 let main = rows.is_empty();
2532 let managed =
2533 !main && managed_root.is_some_and(|root| FsPath::new(&path).parent() == Some(root));
2534 rows.push(WorktreeRow {
2535 path,
2536 branch,
2537 head,
2538 main,
2539 managed,
2540 locked,
2541 prunable,
2542 });
2543 }
2544 rows
2545 }
2546
2547 async fn repository_worktrees(root: &FsPath) -> Result<(PathBuf, Vec<WorktreeRow>), ApiError> {
2548 let workspace = resolve_workspace(root, true).await?;
2549 let first = git_read_ok(&workspace, &["worktree", "list", "--porcelain"]).await?;
2550 let main = parse_worktrees(&first, None)
2551 .into_iter()
2552 .next()
2553 .map(|row| PathBuf::from(row.path))
2554 .ok_or_else(|| ApiError::not_found("workspace has no main worktree"))?;
2555 let main = resolve_workspace(&main, true).await?;
2556 let managed = main.join(WORKTREES_DIR);
2557 Ok((main, parse_worktrees(&first, Some(&managed))))
2558 }
2559
2560 pub(super) async fn worktrees_list(
2561 State(state): State<RuntimeApiState>,
2562 Query(scope): Query<ThreadScopeQuery>,
2563 ) -> Result<Json<Value>, ApiError> {
2564 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2565 let (main, rows) = repository_worktrees(&root).await?;
2566 Ok(Json(json!({
2567 "repository": main.to_string_lossy(),
2568 "worktrees": rows,
2569 })))
2570 }
2571
2572 #[derive(Deserialize)]
2573 #[serde(deny_unknown_fields)]
2574 pub(super) struct WorktreeCreateRequest {
2575 branch: String,
2576 #[serde(default)]
2577 base: Option<String>,
2578 }
2579
2580 fn worktree_slug(branch: &str) -> String {
2581 let slug: String = branch
2582 .chars()
2583 .map(|c| {
2584 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
2585 c
2586 } else {
2587 '-'
2588 }
2589 })
2590 .collect();
2591 slug.trim_matches(|c| c == '-' || c == '.').to_string()
2592 }
2593
2594 fn coded(status: StatusCode, code: &'static str, message: impl Into<String>) -> GitWriteError {
2595 GitWriteError::Coded {
2596 status,
2597 code,
2598 message: message.into(),
2599 extra: serde_json::Map::new(),
2600 }
2601 }
2602
2603 pub(super) async fn worktree_create(
2604 State(state): State<RuntimeApiState>,
2605 Query(scope): Query<ThreadScopeQuery>,
2606 Json(request): Json<WorktreeCreateRequest>,
2607 ) -> Result<(StatusCode, Json<Value>), GitWriteError> {
2608 let branch = request.branch.trim().to_string();
2609 if branch.is_empty() || branch.len() > MAX_BRANCH_NAME_BYTES {
2610 return Err(ApiError::bad_request("branch is required").into());
2611 }
2612 let base = request
2613 .base
2614 .as_deref()
2615 .map(str::trim)
2616 .filter(|base| !base.is_empty())
2617 .unwrap_or("HEAD")
2618 .to_string();
2619 if base.starts_with('-') || base.len() > MAX_BRANCH_NAME_BYTES {
2620 return Err(ApiError::bad_request("base must be a ref").into());
2621 }
2622 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2623 let _guard = state.git_writes.try_lock().map_err(|_| busy_error())?;
2624 let (main, rows) = repository_worktrees(&root).await?;
2625 let check = git_write(
2626 &main,
2627 vec![
2628 "check-ref-format".to_string(),
2629 "--branch".to_string(),
2630 branch.clone(),
2631 ],
2632 )
2633 .await?;
2634 if !check.status_success {
2635 return Err(ApiError::bad_request("branch is not a valid branch name").into());
2636 }
2637 if rows
2638 .iter()
2639 .any(|row| row.branch.as_deref() == Some(branch.as_str()))
2640 {
2641 return Err(coded(
2642 StatusCode::CONFLICT,
2643 "branch_checked_out",
2644 format!("{branch} is already checked out in another worktree"),
2645 ));
2646 }
2647 let base_check = git_read(
2648 &main,
2649 &[
2650 "rev-parse",
2651 "--verify",
2652 "--quiet",
2653 &format!("{base}^{{commit}}"),
2654 ],
2655 )
2656 .await?;
2657 if !base_check.status_success {
2658 return Err(ApiError::bad_request(format!("base {base} is not a commit")).into());
2659 }
2660 let slug = worktree_slug(&branch);
2661 if slug.is_empty() {
2662 return Err(ApiError::bad_request("branch does not name a folder").into());
2663 }
2664 let common = git_read_ok(
2665 &main,
2666 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2667 )
2668 .await?;
2669 let exclude = PathBuf::from(common.trim()).join("info").join("exclude");
2670 let path = main.join(WORKTREES_DIR).join(&slug);
2671 let spec = codewhale_lane::WorktreeProvision {
2672 repo_root: main.clone(),
2673 branch: branch.clone(),
2674 path: path.clone(),
2675 base_ref: Some(base.clone()),
2676 };
2677 tokio::task::spawn_blocking(move || -> Result<(), GitWriteError> {
2678 if std::fs::symlink_metadata(&spec.path).is_ok() {
2679 return Err(coded(
2680 StatusCode::CONFLICT,
2681 "worktree_exists",
2682 format!("{} already exists", spec.path.display()),
2683 ));
2684 }
2685 let line = format!("/{WORKTREES_DIR}/");
2686 let current = std::fs::read_to_string(&exclude).unwrap_or_default();
2687 if !current.lines().any(|existing| existing.trim() == line) {
2688 if let Some(dir) = exclude.parent() {
2689 std::fs::create_dir_all(dir)
2690 .map_err(|error| ApiError::internal(format!("update info/exclude: {error}")))?;
2691 }
2692 let separator = if current.is_empty() || current.ends_with('\n') {
2693 ""
2694 } else {
2695 "\n"
2696 };
2697 std::fs::write(&exclude, format!("{current}{separator}{line}\n"))
2698 .map_err(|error| ApiError::internal(format!("update info/exclude: {error}")))?;
2699 }
2700 codewhale_lane::set_git_command(Git::workspace_command);
2701 codewhale_lane::provision_worktree(&spec)
2702 .map_err(|error| ApiError::bad_request(format!("{error:#}")))?;
2703 Ok(())
2704 })
2705 .await
2706 .map_err(|_| ApiError::internal("worktree creation failed"))??;
2707 let head = git_read_ok(&path, &["rev-parse", "HEAD"]).await?;
2708 Ok((
2709 StatusCode::CREATED,
2710 Json(json!({
2711 "path": path.to_string_lossy(),
2712 "branch": branch,
2713 "base": base,
2714 "head": head.trim(),
2715 "repository": main.to_string_lossy(),
2716 })),
2717 ))
2718 }
2719
2720 #[derive(Deserialize)]
2721 #[serde(deny_unknown_fields)]
2722 pub(super) struct WorktreeRemoveRequest {
2723 path: String,
2724 }
2725
2726 pub(super) async fn worktree_remove(
2727 State(state): State<RuntimeApiState>,
2728 Query(scope): Query<ThreadScopeQuery>,
2729 Json(request): Json<WorktreeRemoveRequest>,
2730 ) -> Result<Json<Value>, GitWriteError> {
2731 let admission = state.runtime_threads.session_checkpoint_guard().await;
2732 let root = scoped_workspace(&state, scope.thread_id.as_deref()).await?;
2733 let guard = state
2734 .git_writes
2735 .clone()
2736 .try_lock_owned()
2737 .map_err(|_| busy_error())?;
2738 let (main, rows) = repository_worktrees(&root).await?;
2739 let wanted = FsPath::new(request.path.trim());
2740 let Some(row) = rows.iter().find(|row| FsPath::new(&row.path) == wanted) else {
2741 return Err(ApiError::not_found("no worktree of this repository at that path").into());
2742 };
2743 if !row.managed {
2744 return Err(ApiError::forbidden(
2745 "only worktrees Codewhale created under .codewhale/worktrees can be archived here",
2746 )
2747 .into());
2748 }
2749 if row.locked {
2750 return Err(coded(
2751 StatusCode::CONFLICT,
2752 "worktree_locked",
2753 "the worktree is locked",
2754 ));
2755 }
2756 let path = PathBuf::from(&row.path);
2757 state
2758 .runtime_threads
2759 .reject_active_turns_in_workspace(&path)
2760 .await
2761 .map_err(|error| coded(StatusCode::CONFLICT, "worktree_busy", error.to_string()))?;
2762 let managers = state.runtime_threads.shell_managers_snapshot().await;
2763 let job_workspace = path.clone();
2764 let busy = tokio::task::spawn_blocking(move || -> Result<bool, ApiError> {
2765 let worktree = job_workspace.canonicalize().ok();
2766 for (_, manager) in managers {
2767 let mut manager = manager
2768 .lock()
2769 .map_err(|_| ApiError::internal("job listing failed"))?;
2770 for job in manager.list_jobs() {
2771 if job.stale || job.status != codewhale_engine::tools::shell::ShellStatus::Running {
2772 continue;
2773 }
2774 let cwd = job.cwd.canonicalize().ok();
2775 if match (&worktree, cwd) {
2776 (Some(worktree), Some(cwd)) => {
2777 cwd.starts_with(worktree) || worktree.starts_with(&cwd)
2778 }
2779 _ => true,
2780 } {
2781 return Ok(true);
2782 }
2783 }
2784 }
2785 Ok(false)
2786 })
2787 .await
2788 .map_err(|_| ApiError::internal("job listing failed"))??;
2789 if busy {
2790 return Err(coded(
2791 StatusCode::CONFLICT,
2792 "worktree_busy",
2793 "A shell job is still running in or around this worktree. Stop it before archiving.",
2794 ));
2795 }
2796 if !row.prunable {
2797 let status =
2798 git_status_read_ok(&path, &["--porcelain", "--untracked-files=normal"]).await?;
2799 if !status.trim().is_empty() {
2800 let mut extra = serde_json::Map::new();
2801 extra.insert(
2802 "files".to_string(),
2803 json!(
2804 status
2805 .lines()
2806 .take(50)
2807 .map(|line| line.get(3..).unwrap_or(line))
2808 .collect::<Vec<_>>()
2809 ),
2810 );
2811 return Err(GitWriteError::Coded {
2812 status: StatusCode::CONFLICT,
2813 code: "worktree_dirty",
2814 message:
2815 "The worktree has uncommitted changes. Commit or discard them before archiving."
2816 .to_string(),
2817 extra,
2818 });
2819 }
2820 }
2821 let mut args = vec!["worktree".to_string(), "remove".to_string()];
2822 if row.prunable {
2823 args.push("--force".to_string());
2824 }
2825 args.push("--".to_string());
2826 args.push(row.path.clone());
2827 let managers = state.runtime_threads.shell_managers_snapshot().await;
2828 let generation = state
2829 .runtime_threads
2830 .job_operation_generation()
2831 .map_err(super::jobs::operation_error)?;
2832 let runtime_owner = state.runtime_threads.clone();
2833 let store = state.runtime_threads.job_operation_store();
2834 let runtime = tokio::runtime::Handle::current();
2835 let fence_path = path.clone();
2836 let run = tokio::task::spawn_blocking(move || {
2837 let _admission = admission;
2838 let _guard = guard;
2839 store.with_job_operations(|transaction| {
2840 Ok((|| -> Result<GitRun, ApiError> {
2841 let worktree = fence_path.canonicalize().unwrap_or(fence_path);
2842 let worktree = if cfg!(windows) {
2843 let raw = worktree
2844 .to_str()
2845 .ok_or_else(|| ApiError::internal("worktree path unavailable"))?;
2846 PathBuf::from(super::jobs::plain_windows_path(raw))
2847 } else {
2848 worktree
2849 };
2850 for mut record in transaction.list().map_err(super::jobs::operation_error)? {
2851 let (operation, _) = super::jobs::project_operation(
2852 transaction,
2853 &mut record,
2854 &managers,
2855 &generation,
2856 )?;
2857 if !matches!(operation.status.as_str(), "completed" | "rejected")
2858 && (super::jobs::overlaps(&worktree, &operation.workspace)
2859 || super::jobs::overlaps(&worktree, &operation.cwd))
2860 {
2861 return Err(ApiError::conflict(
2862 "a workspace job is running or unconfirmed",
2863 )
2864 .with_code("worktree_busy"));
2865 }
2866 }
2867 for (_, manager) in &managers {
2868 let mut manager = manager
2869 .lock()
2870 .map_err(|_| ApiError::internal("job listing failed"))?;
2871 for job in manager.list_jobs() {
2872 if !job.stale
2873 && job.status == codewhale_engine::tools::shell::ShellStatus::Running
2874 {
2875 let cwd = job.cwd.canonicalize().ok().and_then(|cwd| {
2876 if cfg!(windows) {
2877 cwd.to_str().map(|raw| {
2878 PathBuf::from(super::jobs::plain_windows_path(raw))
2879 })
2880 } else {
2881 Some(cwd)
2882 }
2883 });
2884 if cwd.is_none_or(|cwd| super::jobs::overlaps(&worktree, &cwd)) {
2885 return Err(ApiError::conflict("a workspace job is still running")
2886 .with_code("worktree_busy"));
2887 }
2888 }
2889 }
2890 }
2891 if runtime_owner.job_operation_generation().ok().as_deref()
2892 != Some(generation.as_str())
2893 {
2894 return Err(ApiError::internal("job operation owner changed"));
2895 }
2896 runtime.block_on(git_write(&main, args))
2897 })())
2898 })
2899 })
2900 .await
2901 .map_err(|_| ApiError::internal("worktree removal failed"))?
2902 .map_err(super::jobs::operation_error)??;
2903 if !run.status_success {
2904 return Err(ApiError::bad_request(output_tail(&run)).into());
2905 }
2906 Ok(Json(
2907 json!({ "ok": true, "path": row.path, "branch": row.branch, "head": row.head }),
2908 ))
2909 }
2910
2911 #[cfg(test)]
2912 #[path = "tests/git_push.rs"]
2913 mod git_push_tests;
2914
2915 #[cfg(test)]
2916 mod tests {
2917 use super::*;
2918 #[cfg(unix)]
2919 use codewhale_engine::test_support::{EnvVarGuard, lock_test_env};
2920 use std::fs;
2921
2922 thread_local! {
2923 pub(super) static GIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2924 }
2925
2926 pub(super) fn git(dir: &FsPath, args: &[&str]) {
2927 let output = Git::output(args, dir).expect("spawn git");
2928 assert!(
2929 output.status.success(),
2930 "git {args:?} failed: {}",
2931 String::from_utf8_lossy(&output.stderr)
2932 );
2933 }
2934
2935 #[test]
2936 fn worktree_rename_consumes_its_original_path_record() {
2937 let rows = parse_porcelain(" R new.md\0ab说明.md\0 M a.txt\0");
2938 let rows: Vec<_> = rows
2939 .iter()
2940 .map(|row| (row.path.as_str(), row.status, row.old_path.as_deref()))
2941 .collect();
2942 assert_eq!(
2943 rows,
2944 [
2945 ("new.md", "renamed", Some("ab说明.md")),
2946 ("a.txt", "modified", None),
2947 ]
2948 );
2949 }
2950
2951 pub(super) fn repo() -> tempfile::TempDir {
2952 let tmp = tempfile::tempdir().expect("tempdir");
2953 let dir = tmp.path();
2954 git(dir, &["init", "-q", "-b", "main"]);
2955 git(dir, &["config", "user.email", "git-rev@example.test"]);
2956 git(dir, &["config", "user.name", "Git Rev Test"]);
2957 git(dir, &["config", "core.autocrlf", "false"]);
2958 fs::write(dir.join("a.txt"), "one\n").unwrap();
2959 git(dir, &["add", "a.txt"]);
2960 git(dir, &["commit", "-q", "-m", "initial"]);
2961 tmp
2962 }
2963
2964 fn rev(workspace: &FsPath, path: &str) -> String {
2965 let frame = RepoFrame::read(workspace).unwrap();
2966 let mut index = IndexSnapshot::read(&frame).unwrap();
2967 index.load_untracked(
2968 &frame.toplevel,
2969 &[format!("{}{}", frame.prefix, normalized_row_path(path))],
2970 );
2971 let listings: Vec<_> = members_of(path, None)
2972 .iter()
2973 .map(|member| {
2974 list_member(
2975 &frame.toplevel,
2976 &index,
2977 &format!("{}{member}", frame.prefix),
2978 )
2979 .unwrap()
2980 })
2981 .collect();
2982 row_rev(&frame.toplevel, &listings, RevMode::Content).unwrap()
2983 }
2984
2985 fn index_token(workspace: &FsPath) -> String {
2986 IndexSnapshot::read(&RepoFrame::read(workspace).unwrap())
2987 .unwrap()
2988 .token
2989 }
2990
2991 #[test]
2992 fn row_rev_tracks_content_index_and_deletion_but_not_touch() {
2993 let tmp = repo();
2994 let ws = tmp.path();
2995 fs::write(ws.join("a.txt"), "two\n").unwrap();
2996 let modified = rev(ws, "a.txt");
2997 assert!(
2998 modified.starts_with("c-") && modified.len() == 66,
2999 "{modified}"
3000 );
3001 assert_eq!(rev(ws, "a.txt"), modified, "deterministic");
3002
3003 // Touching without changing bytes keeps the content token.
3004 let file = fs::File::options()
3005 .write(true)
3006 .open(ws.join("a.txt"))
3007 .unwrap();
3008 file.set_modified(std::time::SystemTime::now() + Duration::from_secs(90))
3009 .unwrap();
3010 drop(file);
3011 assert_eq!(rev(ws, "a.txt"), modified, "touch is not a change");
3012
3013 fs::write(ws.join("a.txt"), "three\n").unwrap();
3014 let rewritten = rev(ws, "a.txt");
3015 assert_ne!(rewritten, modified, "content change");
3016
3017 git(ws, &["add", "a.txt"]);
3018 let staged = rev(ws, "a.txt");
3019 assert_ne!(staged, rewritten, "staging changes the index part");
3020
3021 fs::remove_file(ws.join("a.txt")).unwrap();
3022 assert_ne!(rev(ws, "a.txt"), staged, "deletion reads as absent");
3023 }
3024
3025 #[test]
3026 fn directory_rev_covers_untracked_files_inside() {
3027 let tmp = repo();
3028 let ws = tmp.path();
3029 fs::create_dir_all(ws.join("dir/deep")).unwrap();
3030 fs::write(ws.join("dir/deep/x.rs"), "x\n").unwrap();
3031 let before = rev(ws, "dir/");
3032 assert_eq!(rev(ws, "dir"), before, "dir and dir/ are one key");
3033 fs::write(ws.join("dir/deep/x.rs"), "y\n").unwrap();
3034 assert_ne!(rev(ws, "dir"), before);
3035 fs::write(ws.join("dir/deep/x.rs"), "x\n").unwrap();
3036 fs::write(ws.join("dir/new.rs"), "n\n").unwrap();
3037 assert_ne!(rev(ws, "dir"), before, "a new file under the row");
3038 }
3039
3040 #[test]
3041 fn index_token_ignores_stat_refresh_and_tracks_real_changes() {
3042 let tmp = repo();
3043 let ws = tmp.path();
3044 let before = index_token(ws);
3045 let file = fs::File::options()
3046 .write(true)
3047 .open(ws.join("a.txt"))
3048 .unwrap();
3049 file.set_modified(std::time::SystemTime::now() + Duration::from_secs(90))
3050 .unwrap();
3051 drop(file);
3052 git(ws, &["status", "--porcelain"]);
3053 git(ws, &["update-index", "--refresh"]);
3054 assert_eq!(index_token(ws), before, "stat refresh is not a change");
3055 fs::write(ws.join("b.txt"), "b\n").unwrap();
3056 git(ws, &["add", "b.txt"]);
3057 assert_ne!(index_token(ws), before);
3058 }
3059
3060 #[test]
3061 fn rename_row_rev_covers_the_source_path() {
3062 let tmp = repo();
3063 let ws = tmp.path();
3064 git(ws, &["mv", "a.txt", "b.txt"]);
3065 let detail = collect_git_status_detail(ws).unwrap();
3066 let row = detail.files.iter().find(|row| row.path == "b.txt").unwrap();
3067 assert_eq!(row.old_path.as_deref(), Some("a.txt"));
3068 let before = row.rev.clone().unwrap();
3069 // Recreating the source in the worktree changes what a stage of the
3070 // rename would record.
3071 fs::write(ws.join("a.txt"), "resurrected\n").unwrap();
3072 let detail = collect_git_status_detail(ws).unwrap();
3073 let after = detail
3074 .files
3075 .iter()
3076 .find(|row| row.path == "b.txt")
3077 .and_then(|row| row.rev.clone())
3078 .unwrap();
3079 assert_ne!(after, before);
3080 }
3081
3082 #[test]
3083 fn subdirectory_workspace_reports_workspace_relative_rows() {
3084 let tmp = repo();
3085 let root = tmp.path();
3086 fs::create_dir_all(root.join("sub")).unwrap();
3087 fs::write(root.join("sub/in.txt"), "in\n").unwrap();
3088 git(root, &["add", "sub/in.txt"]);
3089 git(root, &["commit", "-q", "-m", "sub"]);
3090 fs::write(root.join("sub/in.txt"), "changed\n").unwrap();
3091 fs::write(root.join("a.txt"), "outside change\n").unwrap();
3092 let ws = root.join("sub").canonicalize().unwrap();
3093 let detail = collect_git_status_detail(&ws).unwrap();
3094 let paths: Vec<&str> = detail.files.iter().map(|row| row.path.as_str()).collect();
3095 assert_eq!(
3096 paths,
3097 vec!["in.txt"],
3098 "workspace frame, outside rows dropped"
3099 );
3100 assert_eq!(
3101 detail.files[0].rev.as_deref(),
3102 Some(rev(&ws, "in.txt").as_str())
3103 );
3104 // The whole-tree revision still sees the change outside the
3105 // workspace, because stage-all and commit reach it.
3106 let before = detail.revision.clone().unwrap();
3107 fs::write(root.join("a.txt"), "outside change again\n").unwrap();
3108 git(root, &["add", "a.txt"]);
3109 let after = collect_git_status_detail(&ws).unwrap().revision.unwrap();
3110 assert_ne!(before, after);
3111 }
3112
3113 fn expect_file(path: &str, token: String) -> Preconditions {
3114 validate_expect(
3115 Some(GitExpect {
3116 files: Some(BTreeMap::from([(path.to_string(), token)])),
3117 ..Default::default()
3118 }),
3119 ExpectTarget::Paths(&[path.to_string()]),
3120 )
3121 .unwrap()
3122 }
3123
3124 fn assert_conflict(workspace: &FsPath, expect: &Preconditions) {
3125 assert!(matches!(
3126 check_preconditions(workspace, expect).unwrap(),
3127 Err(GitWriteError::Coded {
3128 status: StatusCode::CONFLICT,
3129 code: "git_state_changed",
3130 ..
3131 })
3132 ));
3133 }
3134
3135 #[cfg(unix)]
3136 #[test]
3137 fn review_executable_mode_invalidates_row_guard() {
3138 use std::os::unix::fs::PermissionsExt;
3139 let tmp = repo();
3140 let ws = tmp.path();
3141 git(ws, &["config", "core.filemode", "true"]);
3142 fs::write(ws.join("a.txt"), "modified\n").unwrap();
3143 fs::set_permissions(ws.join("a.txt"), fs::Permissions::from_mode(0o644)).unwrap();
3144 let detail = collect_git_status_detail(ws).unwrap();
3145 let expect = expect_file("a.txt", detail.files[0].rev.clone().unwrap());
3146 assert!(check_preconditions(ws, &expect).unwrap().is_ok());
3147 fs::set_permissions(ws.join("a.txt"), fs::Permissions::from_mode(0o755)).unwrap();
3148 assert_conflict(ws, &expect);
3149 assert_ne!(
3150 collect_git_status_detail(ws).unwrap().revision,
3151 detail.revision
3152 );
3153 }
3154
3155 #[test]
3156 fn review_outside_content_invalidates_whole_tree_guard() {
3157 let tmp = repo();
3158 let root = tmp.path();
3159 fs::create_dir(root.join("sub")).unwrap();
3160 let ws = root.join("sub");
3161 fs::write(root.join("a.txt"), "outside one\n").unwrap();
3162 let detail = collect_git_status_detail(&ws).unwrap();
3163 assert!(detail.files.is_empty());
3164 let expect = Preconditions {
3165 head: Some(detail.head_oid),
3166 revision: Some(detail.revision.unwrap()),
3167 ..Default::default()
3168 };
3169 assert!(check_preconditions(&ws, &expect).unwrap().is_ok());
3170 // Keep the porcelain XY and index unchanged.
3171 fs::write(root.join("a.txt"), "outside two\n").unwrap();
3172 assert_conflict(&ws, &expect);
3173 }
3174
3175 #[test]
3176 fn review_submodule_head_invalidates_row_guard() {
3177 let tmp = repo();
3178 let ws = tmp.path();
3179 let sub = ws.join("vendor");
3180 fs::create_dir(&sub).unwrap();
3181 git(&sub, &["init", "-q", "-b", "main"]);
3182 git(&sub, &["config", "user.email", "git-rev@example.test"]);
3183 git(&sub, &["config", "user.name", "Git Rev Test"]);
3184 fs::write(sub.join("lib.txt"), "one\n").unwrap();
3185 git(&sub, &["add", "lib.txt"]);
3186 git(&sub, &["commit", "-q", "-m", "one"]);
3187 git(ws, &["add", "vendor"]);
3188 git(ws, &["commit", "-q", "-m", "gitlink"]);
3189 for contents in ["two\n", "three\n"] {
3190 fs::write(sub.join("lib.txt"), contents).unwrap();
3191 git(&sub, &["commit", "-q", "-am", contents]);
3192 }
3193 git(&sub, &["checkout", "-q", "HEAD~1"]);
3194 let detail = collect_git_status_detail(ws).unwrap();
3195 let row = detail
3196 .files
3197 .iter()
3198 .find(|row| row.path == "vendor")
3199 .unwrap();
3200 let expect = expect_file("vendor", row.rev.clone().unwrap());
3201 assert!(check_preconditions(ws, &expect).unwrap().is_ok());
3202 git(&sub, &["checkout", "-q", "main"]);
3203 assert_conflict(ws, &expect);
3204 }
3205
3206 #[test]
3207 fn review_untracked_workspace_prefix_exposes_children() {
3208 let tmp = repo();
3209 let root = tmp.path();
3210 fs::create_dir_all(root.join("sub/deep")).unwrap();
3211 fs::write(root.join("sub/new.txt"), "new\n").unwrap();
3212 fs::write(root.join("sub/deep/child.txt"), "child\n").unwrap();
3213 let ws = root.join("sub");
3214 let detail = collect_git_status_detail(&ws).unwrap();
3215 assert_eq!(
3216 detail
3217 .files
3218 .iter()
3219 .map(|row| row.path.as_str())
3220 .collect::<Vec<_>>(),
3221 ["deep/child.txt", "new.txt"]
3222 );
3223 for row in detail.files {
3224 assert_eq!(row.status, "untracked");
3225 let expect = expect_file(&row.path, row.rev.unwrap());
3226 assert!(check_preconditions(&ws, &expect).unwrap().is_ok());
3227 git(&ws, &["add", "--", &row.path]);
3228 }
3229 assert_eq!(collect_git_status_detail(&ws).unwrap().staged, 2);
3230 }
3231
3232 #[test]
3233 fn review_outgoing_rename_exposes_source_deletion() {
3234 let tmp = repo();
3235 let root = tmp.path();
3236 fs::create_dir(root.join("sub")).unwrap();
3237 git(root, &["mv", "a.txt", "sub/a.txt"]);
3238 git(root, &["commit", "-q", "-m", "inside"]);
3239 git(root, &["mv", "sub/a.txt", "outside.txt"]);
3240 let ws = root.join("sub");
3241 let detail = collect_git_status_detail(&ws).unwrap();
3242 assert_eq!(detail.files.len(), 1);
3243 let row = &detail.files[0];
3244 assert_eq!(row.path, "a.txt");
3245 assert_eq!(row.index, "D");
3246 assert_eq!(row.status, "deleted");
3247 assert!(row.staged);
3248 assert!(row.old_path.is_none());
3249 let expect = expect_file("a.txt", row.rev.clone().unwrap());
3250 assert!(check_preconditions(&ws, &expect).unwrap().is_ok());
3251 // The projected row can unstage the in-workspace deletion.
3252 git(&ws, &["restore", "--staged", "--", "a.txt"]);
3253 assert_ne!(index_token(&ws), detail.index_token.unwrap());
3254 }
3255
3256 #[test]
3257 fn review_outgoing_worktree_rename_exposes_source_deletion() {
3258 let tmp = repo();
3259 let root = tmp.path();
3260 fs::create_dir(root.join("sub")).unwrap();
3261 git(root, &["mv", "a.txt", "sub/a.txt"]);
3262 git(root, &["commit", "-q", "-m", "inside"]);
3263 git(root, &["mv", "sub/a.txt", "outside.txt"]);
3264 git(root, &["reset"]);
3265 git(root, &["add", "-N", "outside.txt"]);
3266 let ws = root.join("sub");
3267 let detail = collect_git_status_detail(&ws).unwrap();
3268 assert_eq!(detail.files.len(), 1);
3269 let row = &detail.files[0];
3270 assert_eq!(row.path, "a.txt");
3271 assert_eq!(row.index, " ");
3272 assert_eq!(row.worktree, "D");
3273 assert_eq!(row.status, "deleted");
3274 assert!(!row.staged);
3275 assert!(row.old_path.is_none());
3276 let expect = expect_file("a.txt", row.rev.clone().unwrap());
3277 assert!(check_preconditions(&ws, &expect).unwrap().is_ok());
3278 }
3279
3280 #[test]
3281 fn outgoing_copy_keeps_its_source_inside_the_workspace() {
3282 let row = GitFileEntry {
3283 path: "outside.txt".to_string(),
3284 index: "C".to_string(),
3285 worktree: " ".to_string(),
3286 staged: true,
3287 status: "copied",
3288 old_path: Some("sub/a.txt".to_string()),
3289 rev: None,
3290 };
3291 let (inside, outside) = split_by_workspace(vec![row], "sub/");
3292 assert!(
3293 inside.is_empty(),
3294 "a copy leaves its source in place, so it must not read as a deletion: {:?}",
3295 inside.iter().map(|row| &row.path).collect::<Vec<_>>()
3296 );
3297 assert_eq!(outside.len(), 1);
3298 }
3299
3300 #[test]
3301 fn review_untracked_inventory_has_constant_git_reads() {
3302 let tmp = repo();
3303 let ws = tmp.path();
3304 fs::write(ws.join(".gitignore"), "*.ignored\n").unwrap();
3305 let mut read_counts = Vec::new();
3306 for count in [1, 32] {
3307 for n in 0..count {
3308 let dir = ws.join(format!("dir{n}"));
3309 fs::create_dir_all(&dir).unwrap();
3310 fs::write(dir.join("file.txt"), "file\n").unwrap();
3311 fs::write(dir.join("skip.ignored"), "ignored\n").unwrap();
3312 }
3313 GIT_READS.with(|reads| reads.set(0));
3314 let detail = collect_git_status_detail(ws).unwrap();
3315 read_counts.push(GIT_READS.with(|reads| reads.get()));
3316 assert!(detail.files.iter().all(|row| row.rev.is_some()));
3317 assert!(
3318 !detail
3319 .files
3320 .iter()
3321 .any(|row| row.path.ends_with(".ignored"))
3322 );
3323 }
3324 assert_eq!(
3325 read_counts[0], read_counts[1],
3326 "Git reads must not grow per directory"
3327 );
3328 }
3329
3330 #[test]
3331 fn review_broken_head_is_not_unborn() {
3332 let tmp = tempfile::tempdir().unwrap();
3333 let ws = tmp.path();
3334 git(ws, &["init", "-q", "-b", "main"]);
3335 assert_eq!(head_oid(ws).unwrap(), None);
3336 assert!(collect_git_status_detail(ws).unwrap().index_token.is_some());
3337 let expect = Preconditions {
3338 head: Some(None),
3339 ..Default::default()
3340 };
3341 assert!(check_preconditions(ws, &expect).unwrap().is_ok());
3342 // An existing branch pointing at a missing object is broken, not unborn.
3343 fs::write(
3344 ws.join(".git/refs/heads/main"),
3345 format!("{}\n", "1".repeat(40)),
3346 )
3347 .unwrap();
3348 assert!(head_oid(ws).is_err());
3349 assert!(collect_git_status_detail(ws).unwrap().revision.is_none());
3350 assert!(check_preconditions(ws, &expect).is_err());
3351 fs::write(ws.join(".git/refs/heads/main"), "broken\n").unwrap();
3352 assert!(
3353 head_oid(ws).is_err(),
3354 "a malformed ref is not an absent ref"
3355 );
3356 assert!(collect_git_status_detail(ws).unwrap().revision.is_none());
3357 // The same failure in detached HEAD must also propagate.
3358 fs::write(ws.join(".git/HEAD"), format!("{}\n", "1".repeat(40))).unwrap();
3359 assert!(head_oid(ws).is_err());
3360 }
3361
3362 #[test]
3363 fn review_stat_only_revisions_cannot_guard_writes() {
3364 use std::io::{Seek as _, Write as _};
3365 let tmp = repo();
3366 let ws = tmp.path();
3367 let path = ws.join("a.txt");
3368 let file = fs::File::options().write(true).open(&path).unwrap();
3369 file.set_len(FILE_SERVE_MAX_BYTES + 1).unwrap();
3370 drop(file);
3371 let detail = collect_git_status_detail(ws).unwrap();
3372 let token = detail.files[0].rev.clone().unwrap();
3373 assert!(
3374 token.starts_with("s-"),
3375 "oversized row must not claim content safety"
3376 );
3377 assert!(
3378 detail.revision.is_none(),
3379 "whole-tree token cannot hide stat-only rows"
3380 );
3381 // Same size and mtime, different bytes: the display token can match.
3382 let modified = fs::metadata(&path).unwrap().modified().unwrap();
3383 let mut file = fs::File::options().write(true).open(&path).unwrap();
3384 file.seek(std::io::SeekFrom::Start(0)).unwrap();
3385 file.write_all(b"two\n").unwrap();
3386 file.set_modified(modified).unwrap();
3387 drop(file);
3388 let after = collect_git_status_detail(ws).unwrap();
3389 assert_eq!(after.files[0].rev.as_ref(), Some(&token));
3390 assert!(
3391 validate_expect(
3392 Some(GitExpect {
3393 files: Some(BTreeMap::from([("a.txt".to_string(), token)])),
3394 ..Default::default()
3395 }),
3396 ExpectTarget::Paths(&["a.txt".to_string()]),
3397 )
3398 .is_err()
3399 );
3400 // An old c- token cannot pass after a file grows beyond the bound.
3401 fs::write(&path, "small\n").unwrap();
3402 let expect = expect_file("a.txt", rev(ws, "a.txt"));
3403 fs::File::options()
3404 .write(true)
3405 .open(&path)
3406 .unwrap()
3407 .set_len(FILE_SERVE_MAX_BYTES + 1)
3408 .unwrap();
3409 assert_conflict(ws, &expect);
3410 }
3411
3412 #[test]
3413 fn review_hash_budget_withholds_whole_tree_revision() {
3414 let tmp = repo();
3415 let ws = tmp.path();
3416 for n in 0..=REV_CONTENT_BUDGET_FILES {
3417 fs::write(ws.join(format!("file{n:05}")), "x").unwrap();
3418 }
3419 let detail = collect_git_status_detail(ws).unwrap();
3420 assert!(detail.revision.is_none());
3421 assert!(detail.index_token.is_some());
3422 assert_eq!(
3423 detail
3424 .files
3425 .iter()
3426 .filter(|row| row.rev.as_deref().unwrap().starts_with("c-"))
3427 .count(),
3428 REV_CONTENT_BUDGET_FILES
3429 );
3430 let row = detail.files.last().unwrap();
3431 assert!(row.rev.as_deref().unwrap().starts_with("s-"));
3432 assert!(
3433 validate_expect(
3434 Some(GitExpect {
3435 files: Some(BTreeMap::from([(
3436 row.path.clone(),
3437 row.rev.clone().unwrap()
3438 )])),
3439 ..Default::default()
3440 }),
3441 ExpectTarget::Paths(std::slice::from_ref(&row.path)),
3442 )
3443 .is_err()
3444 );
3445 }
3446
3447 fn assert_unguardable_row(workspace: &FsPath, bad_path: &str) {
3448 let detail = collect_git_status_detail(workspace).unwrap();
3449 assert_eq!(detail.branch.as_deref(), Some("main"));
3450 assert!(detail.head_oid.is_some());
3451 assert!(detail.index_token.is_some());
3452 assert!(detail.revision.is_none());
3453 let bad = detail
3454 .files
3455 .iter()
3456 .find(|row| normalized_row_path(&row.path) == bad_path)
3457 .unwrap();
3458 assert!(bad.rev.is_none());
3459 assert_eq!(
3460 serde_json::to_value(bad).unwrap().get("rev"),
3461 Some(&Value::Null)
3462 );
3463 let healthy = detail
3464 .files
3465 .iter()
3466 .find(|row| row.path == "healthy.txt")
3467 .unwrap();
3468 let expect = expect_file("healthy.txt", healthy.rev.clone().unwrap());
3469 assert!(check_preconditions(workspace, &expect).unwrap().is_ok());
3470 }
3471
3472 #[cfg(unix)]
3473 #[test]
3474 fn symlinked_ancestor_only_withholds_affected_row() {
3475 let tmp = repo();
3476 let ws = tmp.path();
3477 fs::create_dir(ws.join("vendor")).unwrap();
3478 fs::write(ws.join("vendor/a.txt"), "tracked\n").unwrap();
3479 git(ws, &["add", "vendor"]);
3480 git(ws, &["commit", "-q", "-m", "vendor"]);
3481 let expect = expect_file("vendor/a.txt", rev(ws, "vendor/a.txt"));
3482 fs::remove_dir_all(ws.join("vendor")).unwrap();
3483 let shared = tempfile::tempdir().unwrap();
3484 fs::write(shared.path().join("a.txt"), "outside\n").unwrap();
3485 std::os::unix::fs::symlink(shared.path(), ws.join("vendor")).unwrap();
3486 fs::write(ws.join("healthy.txt"), "healthy\n").unwrap();
3487 assert_unguardable_row(ws, "vendor/a.txt");
3488 assert_conflict(ws, &expect);
3489 assert_eq!(
3490 fs::read_to_string(shared.path().join("a.txt")).unwrap(),
3491 "outside\n"
3492 );
3493 }
3494
3495 #[cfg(unix)]
3496 #[test]
3497 fn unreadable_file_only_withholds_affected_row() {
3498 use std::os::unix::fs::PermissionsExt;
3499 let tmp = repo();
3500 let ws = tmp.path();
3501 fs::write(ws.join("private.txt"), "private\n").unwrap();
3502 fs::write(ws.join("healthy.txt"), "healthy\n").unwrap();
3503 let expect = expect_file("private.txt", rev(ws, "private.txt"));
3504 fs::set_permissions(ws.join("private.txt"), fs::Permissions::from_mode(0o000)).unwrap();
3505 assert!(
3506 fs::File::open(ws.join("private.txt")).is_err(),
3507 "fixture must be unreadable"
3508 );
3509 assert_unguardable_row(ws, "private.txt");
3510 assert_conflict(ws, &expect);
3511 }
3512
3513 #[cfg(unix)]
3514 #[test]
3515 fn special_file_only_withholds_affected_row() {
3516 let tmp = repo();
3517 let ws = tmp.path();
3518 let expect = expect_file("a.txt", rev(ws, "a.txt"));
3519 fs::remove_file(ws.join("a.txt")).unwrap();
3520 assert!(
3521 std::process::Command::new("mkfifo")
3522 .arg(ws.join("a.txt"))
3523 .status()
3524 .unwrap()
3525 .success()
3526 );
3527 fs::write(ws.join("healthy.txt"), "healthy\n").unwrap();
3528 assert_unguardable_row(ws, "a.txt");
3529 assert_conflict(ws, &expect);
3530 }
3531
3532 #[test]
3533 fn unreadable_submodule_is_reported() {
3534 for breakage in ["nohead", "garbage", "badgitdir"] {
3535 let tmp = repo();
3536 let ws = tmp.path();
3537 let nested = ws.join("vendor");
3538 fs::create_dir(&nested).unwrap();
3539 git(&nested, &["init", "-q", "-b", "main"]);
3540 git(&nested, &["config", "user.email", "git-rev@example.test"]);
3541 git(&nested, &["config", "user.name", "Git Rev Test"]);
3542 fs::write(nested.join("lib.txt"), "library\n").unwrap();
3543 git(&nested, &["add", "lib.txt"]);
3544 git(&nested, &["commit", "-q", "-m", "nested"]);
3545 git(ws, &["add", "vendor"]);
3546 git(ws, &["commit", "-q", "-m", "gitlink"]);
3547 if breakage == "nohead" {
3548 fs::remove_file(nested.join(".git/HEAD")).unwrap();
3549 } else {
3550 fs::remove_dir_all(nested.join(".git")).unwrap();
3551 let content = if breakage == "badgitdir" {
3552 "gitdir: /nonexistent\n"
3553 } else {
3554 "garbage\n"
3555 };
3556 fs::write(nested.join(".git"), content).unwrap();
3557 }
3558 let detail = collect_git_status_detail(ws).unwrap();
3559 assert!(
3560 detail.revision.is_none(),
3561 "{breakage}: whole-tree revision offered with an unreadable submodule"
3562 );
3563 assert!(
3564 detail
3565 .files
3566 .iter()
3567 .any(|row| normalized_row_path(&row.path) == "vendor"),
3568 "{breakage}: unreadable submodule has no row"
3569 );
3570 }
3571 }
3572
3573 #[test]
3574 fn broken_nested_repo_only_withholds_affected_row() {
3575 for tracked in [false, true] {
3576 let tmp = repo();
3577 let ws = tmp.path();
3578 let nested = ws.join("vendor");
3579 fs::create_dir(&nested).unwrap();
3580 git(&nested, &["init", "-q", "-b", "main"]);
3581 git(&nested, &["config", "user.email", "git-rev@example.test"]);
3582 git(&nested, &["config", "user.name", "Git Rev Test"]);
3583 fs::write(nested.join("lib.txt"), "library\n").unwrap();
3584 git(&nested, &["add", "lib.txt"]);
3585 git(&nested, &["commit", "-q", "-m", "nested"]);
3586 if tracked {
3587 git(ws, &["add", "vendor"]);
3588 git(ws, &["commit", "-q", "-m", "gitlink"]);
3589 }
3590 fs::write(
3591 nested.join(".git/refs/heads/main"),
3592 format!("{}\n", "1".repeat(40)),
3593 )
3594 .unwrap();
3595 fs::write(ws.join("healthy.txt"), "healthy\n").unwrap();
3596 assert_unguardable_row(ws, "vendor");
3597 }
3598 }
3599
3600 #[cfg(unix)]
3601 #[test]
3602 fn status_and_guards_respect_clean_filters() {
3603 let _env_lock = lock_test_env();
3604 let tmp = repo();
3605 let ws = tmp.path();
3606 let global = tempfile::tempdir().unwrap();
3607 let global_config = global.path().join("gitconfig");
3608 git(
3609 ws,
3610 &[
3611 "config",
3612 "--file",
3613 global_config.to_str().unwrap(),
3614 "filter.up.clean",
3615 "tr a-z A-Z",
3616 ],
3617 );
3618 let _global = EnvVarGuard::set("GIT_CONFIG_GLOBAL", &global_config);
3619 fs::write(ws.join(".gitattributes"), "*.txt filter=up\n").unwrap();
3620 git(ws, &["add", ".gitattributes"]);
3621 // The tracked file is unchanged since the initial commit. Apply the
3622 // new attributes explicitly instead of depending on Git's cached
3623 // stat entry deciding to run the newly configured clean filter.
3624 git(ws, &["add", "--renormalize", "a.txt"]);
3625 assert_eq!(run_git_sync(ws, &["show", ":a.txt"]).unwrap(), "ONE\n");
3626 git(ws, &["commit", "-q", "-m", "filtered"]);
3627 fs::File::options()
3628 .write(true)
3629 .open(ws.join("a.txt"))
3630 .unwrap()
3631 .set_modified(std::time::SystemTime::now() + Duration::from_secs(90))
3632 .unwrap();
3633 let detail = collect_git_status_detail(ws).unwrap();
3634 assert_eq!(detail.unstaged, 0);
3635 assert!(
3636 detail.files.is_empty(),
3637 "clean filtered files must not appear modified"
3638 );
3639 fs::write(ws.join("a.txt"), "two\n").unwrap();
3640 let detail = collect_git_status_detail(ws).unwrap();
3641 let expect = expect_file("a.txt", detail.files[0].rev.clone().unwrap());
3642 assert!(check_preconditions(ws, &expect).unwrap().is_ok());
3643 git(ws, &["add", "a.txt"]);
3644 assert_eq!(run_git_sync(ws, &["show", ":a.txt"]).unwrap(), "TWO\n");
3645 assert_conflict(ws, &expect);
3646 }
3647
3648 #[cfg(unix)]
3649 #[test]
3650 fn status_runs_no_nested_repository_filter() {
3651 use std::os::unix::fs::PermissionsExt;
3652 let tmp = repo();
3653 let ws = tmp.path();
3654 let outside = tempfile::tempdir().unwrap();
3655 let marker = outside.path().join("marker");
3656 let clean = outside.path().join("clean.sh");
3657 fs::write(
3658 &clean,
3659 format!("#!/bin/sh\necho ran >> '{}'\ncat\n", marker.display()),
3660 )
3661 .unwrap();
3662 fs::set_permissions(&clean, fs::Permissions::from_mode(0o755)).unwrap();
3663 let sub = ws.join("vendor");
3664 fs::create_dir(&sub).unwrap();
3665 git(&sub, &["init", "-q", "-b", "main"]);
3666 git(&sub, &["config", "user.email", "git-rev@example.test"]);
3667 git(&sub, &["config", "user.name", "Git Rev Test"]);
3668 fs::write(sub.join(".gitattributes"), "* filter=evil\n").unwrap();
3669 fs::write(sub.join("lib.txt"), "library\n").unwrap();
3670 git(&sub, &["add", "."]);
3671 git(&sub, &["commit", "-q", "-m", "nested"]);
3672 git(ws, &["add", "vendor"]);
3673 git(ws, &["commit", "-q", "-m", "gitlink"]);
3674 git(
3675 &sub,
3676 &["config", "filter.evil.clean", clean.to_str().unwrap()],
3677 );
3678 git(ws, &["config", "submodule.vendor.ignore", "none"]);
3679 fs::File::options()
3680 .write(true)
3681 .open(sub.join("lib.txt"))
3682 .unwrap()
3683 .set_modified(std::time::UNIX_EPOCH)
3684 .unwrap();
3685
3686 let control = Git::output(&["status", "--porcelain"], ws).unwrap();
3687 assert!(control.status.success());
3688 assert!(marker.exists(), "positive control: nested filter");
3689 fs::remove_file(&marker).unwrap();
3690
3691 let detail = collect_git_status_detail(ws).unwrap();
3692 assert!(detail.files.is_empty(), "{:?}", detail.files);
3693 assert!(
3694 !marker.exists(),
3695 "status ran a nested repository filter: {}",
3696 fs::read_to_string(&marker).unwrap_or_default()
3697 );
3698 let counts = collect_workspace_status(ws);
3699 assert!(!counts.status_unavailable);
3700 assert!(
3701 !marker.exists(),
3702 "workspace status ran a nested repository filter"
3703 );
3704 }
3705
3706 #[test]
3707 fn status_respects_collapsed_and_hidden_untracked_modes() {
3708 let tmp = repo();
3709 let ws = tmp.path();
3710 fs::create_dir_all(ws.join("build/deep")).unwrap();
3711 fs::write(ws.join("build/one.txt"), "one\n").unwrap();
3712 fs::write(ws.join("build/deep/two.txt"), "two\n").unwrap();
3713 let detail = collect_git_status_detail(ws).unwrap();
3714 assert_eq!(detail.files.len(), 1);
3715 assert_eq!(detail.files[0].path, "build/");
3716 let expect = expect_file("build", detail.files[0].rev.clone().unwrap());
3717 assert!(check_preconditions(ws, &expect).unwrap().is_ok());
3718 fs::write(ws.join("build/deep/two.txt"), "changed\n").unwrap();
3719 assert_conflict(ws, &expect);
3720 git(ws, &["config", "status.showUntrackedFiles", "no"]);
3721 let detail = collect_git_status_detail(ws).unwrap();
3722 assert!(detail.files.is_empty());
3723 assert_eq!(detail.untracked, 0);
3724 assert!(
3725 detail.revision.is_none(),
3726 "hidden untracked content cannot guard add --all"
3727 );
3728 assert!(
3729 collect_git_status_detail(&ws.join("build"))
3730 .unwrap()
3731 .files
3732 .is_empty()
3733 );
3734 }
3735
3736 #[test]
3737 fn index_token_does_not_enumerate_untracked_tree() {
3738 let tmp = repo();
3739 GIT_READS.with(|reads| reads.set(0));
3740 index_token(tmp.path());
3741 // One rev-parse for the frame and one ls-files --stage for the index.
3742 assert_eq!(GIT_READS.with(|reads| reads.get()), 2);
3743 }
3744
3745 #[test]
3746 fn expect_validation_rules() {
3747 let parse = |value: Value| serde_json::from_value::<GitExpect>(value);
3748 let paths = vec!["a.txt".to_string()];
3749 let rev = format!("c-{}", "a".repeat(64));
3750
3751 // Absent head is unchecked; explicit null means unborn.
3752 let unchecked =
3753 validate_expect(Some(parse(json!({})).unwrap()), ExpectTarget::Commit).unwrap();
3754 assert!(unchecked.is_empty());
3755 let unborn = validate_expect(
3756 Some(parse(json!({ "head": null })).unwrap()),
3757 ExpectTarget::Commit,
3758 )
3759 .unwrap();
3760 assert_eq!(unborn.head, Some(None));
3761 let upper = validate_expect(
3762 Some(parse(json!({ "head": "A".repeat(40) })).unwrap()),
3763 ExpectTarget::Commit,
3764 )
3765 .unwrap();
3766 assert_eq!(upper.head, Some(Some("a".repeat(40))));
3767
3768 for bad in [
3769 json!({ "head": "abc" }),
3770 json!({ "head": "g".repeat(40) }),
3771 json!({ "index": "a".repeat(40) }),
3772 json!({ "revision": "zz" }),
3773 json!({ "revision": null }),
3774 ] {
3775 assert!(
3776 validate_expect(Some(parse(bad.clone()).unwrap()), ExpectTarget::Commit).is_err(),
3777 "{bad}"
3778 );
3779 }
3780 assert!(parse(json!({ "heads": null })).is_err(), "unknown key");
3781
3782 let files = |map: Value| parse(json!({ "files": map })).unwrap();
3783 assert!(
3784 validate_expect(Some(files(json!({ "a.txt": rev }))), ExpectTarget::Commit).is_err()
3785 );
3786 assert!(
3787 validate_expect(Some(files(json!({ "a.txt": rev }))), ExpectTarget::AllPaths).is_err()
3788 );
3789 assert!(
3790 validate_expect(Some(files(json!({}))), ExpectTarget::Paths(&paths)).is_err(),
3791 "missing a requested path"
3792 );
3793 assert!(
3794 validate_expect(
3795 Some(files(json!({ "a.txt": rev, "b.txt": rev }))),
3796 ExpectTarget::Paths(&paths)
3797 )
3798 .is_err(),
3799 "extra path"
3800 );
3801 assert!(
3802 validate_expect(
3803 Some(files(json!({ "a.txt": "a".repeat(64) }))),
3804 ExpectTarget::Paths(&paths)
3805 )
3806 .is_err(),
3807 "rev without a mode"
3808 );
3809 let ok = validate_expect(
3810 Some(files(json!({ "./a.txt/": rev }))),
3811 ExpectTarget::Paths(&paths),
3812 );
3813 // `./` is refused by the shared path confinement, like request paths.
3814 assert!(ok.is_err());
3815 let ok = validate_expect(
3816 Some(files(json!({ "a.txt/": rev }))),
3817 ExpectTarget::Paths(&paths),
3818 )
3819 .unwrap();
3820 assert_eq!(ok.files.unwrap().keys().collect::<Vec<_>>(), vec!["a.txt"]);
3821 }
3822
3823 /// A dropped (or timed-out) write takes down what git started — a hook, a
3824 /// filter, an alias — not just the `git` process.
3825 #[cfg(unix)]
3826 #[tokio::test]
3827 async fn dropped_git_write_kills_what_git_started() {
3828 let tmp = repo();
3829 let pid_file = tmp.path().join("hang.pid");
3830 let args = vec![
3831 "-c".to_string(),
3832 "alias.hang=!sleep 300 & echo $! > hang.pid; wait".to_string(),
3833 "hang".to_string(),
3834 ];
3835 let grandchild = codewhale_runtime::process_tree::drop_once_pid_written(
3836 git_write(tmp.path(), args),
3837 &pid_file,
3838 )
3839 .await;
3840 assert!(
3841 codewhale_runtime::process_tree::wait_for_pid_exit(grandchild, Duration::from_secs(5)),
3842 "a process git started outlived the dropped request"
3843 );
3844 }
3845
3846 #[test]
3847 fn file_diff_reads_the_path_literally_inside_a_subdirectory_workspace() {
3848 let tmp = repo();
3849 let root = tmp.path();
3850 fs::create_dir_all(root.join("apps/web")).unwrap();
3851 fs::create_dir_all(root.join("apps/other")).unwrap();
3852 fs::write(root.join("apps/web/w.txt"), "w\n").unwrap();
3853 fs::write(root.join("apps/other/secret.txt"), "old\n").unwrap();
3854 git(root, &["add", "apps"]);
3855 git(root, &["commit", "-q", "-m", "apps"]);
3856 fs::write(root.join("apps/web/w.txt"), "w2\n").unwrap();
3857 fs::write(root.join("apps/other/secret.txt"), "new\n").unwrap();
3858 let workspace = root.join("apps/web");
3859 let diff = |path: &str| {
3860 let output = Git::review_command(&workspace)
3861 .unwrap()
3862 .args(file_diff_args("HEAD", path))
3863 .output()
3864 .unwrap();
3865 assert!(output.status.success(), "{output:?}");
3866 String::from_utf8_lossy(&output.stdout).into_owned()
3867 };
3868 assert!(diff("w.txt").contains("+w2"), "in-workspace diff works");
3869 for path in [
3870 ":/apps/other/secret.txt",
3871 ":(top)apps/other/secret.txt",
3872 "*",
3873 ] {
3874 let body = diff(path);
3875 assert!(!body.contains("secret"), "{path} escaped: {body}");
3876 }
3877 }
3878
3879 #[test]
3880 fn push_remote_must_be_a_configured_remote_name() {
3881 let configured = "origin\nupstream\n";
3882 assert!(validate_push_remote("origin", configured).is_ok());
3883 assert!(validate_push_remote("upstream", configured).is_ok());
3884 for remote in [
3885 "--force",
3886 "--mirror",
3887 "-f",
3888 "--delete",
3889 "../other-repo",
3890 "fork",
3891 ] {
3892 let error = validate_push_remote(remote, configured).expect_err(remote);
3893 assert_eq!(error.status, StatusCode::BAD_REQUEST, "{remote}");
3894 }
3895 }
3896 }
3897
3897 lines RUST