1use serde::{Deserialize, Serialize};
4use std::fmt;
5use std::io::Read;
6use std::path::{Path, PathBuf};
7use std::process::{Command, ExitStatus, Stdio};
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11const MAX_GIT_OUTPUT_BYTES: usize = 4 * 1024 * 1024;
12const DEFAULT_GIT_TIMEOUT: Duration = Duration::from_secs(30);
13
14pub type GitResult<T> = Result<T, GitError>;
15
16#[derive(Debug)]
17pub enum GitError {
18 Io(std::io::Error),
19 InvalidInput(String),
20 NotRepository(PathBuf),
21 Timeout(String),
22 Command { operation: String, detail: String },
23 OutputLimit(String),
24}
25
26impl fmt::Display for GitError {
27 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
28 match self {
29 Self::Io(error) => write!(formatter, "Git I/O error: {error}"),
30 Self::InvalidInput(message) => write!(formatter, "invalid Git input: {message}"),
31 Self::NotRepository(path) => {
32 write!(formatter, "not a Git repository: {}", path.display())
33 }
34 Self::Timeout(operation) => write!(formatter, "Git operation timed out: {operation}"),
35 Self::Command { operation, detail } => {
36 write!(formatter, "Git operation {operation} failed: {detail}")
37 }
38 Self::OutputLimit(operation) => {
39 write!(
40 formatter,
41 "Git operation {operation} exceeded the output limit"
42 )
43 }
44 }
45 }
46}
47
48impl std::error::Error for GitError {}
49
50impl From<std::io::Error> for GitError {
51 fn from(error: std::io::Error) -> Self {
52 Self::Io(error)
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
57#[serde(rename_all = "camelCase")]
58pub struct GitStatus {
59 pub branch: Option<String>,
60 pub upstream: Option<String>,
61 pub ahead: u64,
62 pub behind: u64,
63 pub entries: Vec<GitStatusEntry>,
64 pub conflicts: Vec<String>,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68#[serde(rename_all = "camelCase")]
69pub struct GitStatusEntry {
70 pub path: String,
71 pub original_path: Option<String>,
72 pub index_status: char,
73 pub worktree_status: char,
74 pub untracked: bool,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
78#[serde(rename_all = "camelCase")]
79pub struct GitBranch {
80 pub name: String,
81 pub current: bool,
82 pub upstream: Option<String>,
83 pub commit: String,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
87#[serde(rename_all = "camelCase")]
88pub struct GitCommit {
89 pub id: String,
90 pub author: String,
91 pub timestamp: i64,
92 pub subject: String,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
96#[serde(rename_all = "camelCase")]
97pub struct GitWorktree {
98 pub path: PathBuf,
99 pub head: Option<String>,
100 pub branch: Option<String>,
101 pub bare: bool,
102 pub detached: bool,
103 pub locked: bool,
104 pub prunable: bool,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
108#[serde(rename_all = "camelCase")]
109pub struct GitCommandResult {
110 pub stdout: String,
111 pub stderr: String,
112}
113
114pub struct GitService {
115 root: PathBuf,
116 timeout: Duration,
117}
118
119impl GitService {
120 pub fn open(path: impl AsRef<Path>) -> GitResult<Self> {
121 let path = path.as_ref().canonicalize()?;
122 let probe = run_git_at(
123 &path,
124 &["rev-parse", "--show-toplevel"],
125 DEFAULT_GIT_TIMEOUT,
126 "discover repository",
127 )?;
128 let root = PathBuf::from(probe.stdout.trim()).canonicalize()?;
129 Ok(Self {
130 root,
131 timeout: DEFAULT_GIT_TIMEOUT,
132 })
133 }
134
135 pub fn root(&self) -> &Path {
136 &self.root
137 }
138
139 pub fn set_timeout(&mut self, timeout: Duration) -> GitResult<()> {
140 if timeout.is_zero() || timeout > Duration::from_secs(600) {
141 return Err(GitError::InvalidInput(
142 "Git timeout must be between 1 ms and 600 seconds".into(),
143 ));
144 }
145 self.timeout = timeout;
146 Ok(())
147 }
148
149 pub fn status(&self) -> GitResult<GitStatus> {
150 let result = self.run(&["status", "--porcelain=v2", "--branch", "-z"], "status")?;
151 parse_status(&result.stdout)
152 }
153
154 pub fn diff(&self, staged: bool, path: Option<&str>) -> GitResult<String> {
155 let mut arguments = vec!["diff", "--no-ext-diff", "--binary"];
156 if staged {
157 arguments.push("--cached");
158 }
159 let validated;
160 if let Some(path) = path {
161 validated = validate_relative_path(path)?;
162 arguments.extend(["--", validated.as_str()]);
163 }
164 Ok(self.run(&arguments, "diff")?.stdout)
165 }
166
167 pub fn stage(&self, paths: &[String]) -> GitResult<()> {
168 let paths = validate_paths(paths)?;
169 let mut arguments = vec!["add", "--"];
170 arguments.extend(paths.iter().map(String::as_str));
171 self.run(&arguments, "stage")?;
172 Ok(())
173 }
174
175 pub fn unstage(&self, paths: &[String]) -> GitResult<()> {
176 let paths = validate_paths(paths)?;
177 let mut arguments = vec!["restore", "--staged", "--"];
178 arguments.extend(paths.iter().map(String::as_str));
179 self.run(&arguments, "unstage")?;
180 Ok(())
181 }
182
183 pub fn branches(&self) -> GitResult<Vec<GitBranch>> {
184 let format = "%(HEAD)%00%(refname:short)%00%(upstream:short)%00%(objectname)%00";
185 let format_argument = format!("--format={format}");
186 let output = self
187 .run(
188 &["for-each-ref", &format_argument, "refs/heads"],
189 "list branches",
190 )?
191 .stdout;
192 let fields = output.split('\0').collect::<Vec<_>>();
193 let mut branches = Vec::new();
194 for row in fields.chunks(4) {
195 if row.len() < 4 || row[1].is_empty() {
196 continue;
197 }
198 branches.push(GitBranch {
199 current: row[0].trim() == "*",
200 name: row[1].to_string(),
201 upstream: (!row[2].is_empty()).then(|| row[2].to_string()),
202 commit: row[3].trim().to_string(),
203 });
204 }
205 Ok(branches)
206 }
207
208 pub fn create_branch(&self, name: &str, start_point: Option<&str>) -> GitResult<()> {
209 validate_ref(name)?;
210 let mut arguments = vec!["branch", name];
211 if let Some(start_point) = start_point {
212 validate_ref(start_point)?;
213 arguments.push(start_point);
214 }
215 self.run(&arguments, "create branch")?;
216 Ok(())
217 }
218
219 pub fn switch_branch(&self, name: &str, create: bool) -> GitResult<()> {
220 validate_ref(name)?;
221 let mut arguments = vec!["switch"];
222 if create {
223 arguments.push("-c");
224 }
225 arguments.push(name);
226 self.run(&arguments, "switch branch")?;
227 Ok(())
228 }
229
230 pub fn commit(&self, message: &str) -> GitResult<GitCommit> {
231 if message.trim().is_empty() || message.len() > 16 * 1024 {
232 return Err(GitError::InvalidInput(
233 "commit message must contain 1..=16384 bytes".into(),
234 ));
235 }
236 self.run(&["commit", "-m", message], "commit")?;
237 self.commit_info("HEAD")
238 }
239
240 pub fn commit_info(&self, revision: &str) -> GitResult<GitCommit> {
241 validate_ref(revision)?;
242 let format = "%H%x00%an <%ae>%x00%ct%x00%s";
243 let format_argument = format!("--format={format}");
244 let output = self
245 .run(
246 &["show", "-s", &format_argument, revision],
247 "inspect commit",
248 )?
249 .stdout;
250 let fields = output.trim_end().splitn(4, '\0').collect::<Vec<_>>();
251 if fields.len() != 4 {
252 return Err(GitError::Command {
253 operation: "inspect commit".into(),
254 detail: "Git returned an invalid commit record".into(),
255 });
256 }
257 Ok(GitCommit {
258 id: fields[0].to_string(),
259 author: fields[1].to_string(),
260 timestamp: fields[2].parse().map_err(|_| GitError::Command {
261 operation: "inspect commit".into(),
262 detail: "Git returned an invalid commit timestamp".into(),
263 })?,
264 subject: fields[3].to_string(),
265 })
266 }
267
268 pub fn blame(&self, path: &str, start_line: u64, end_line: u64) -> GitResult<String> {
269 let path = validate_relative_path(path)?;
270 if start_line == 0 || end_line < start_line || end_line - start_line > 10_000 {
271 return Err(GitError::InvalidInput(
272 "blame lines must be positive, ordered, and span at most 10001 lines".into(),
273 ));
274 }
275 let range = format!("{start_line},{end_line}");
276 Ok(self
277 .run(
278 &["blame", "--line-porcelain", "-L", &range, "--", &path],
279 "blame",
280 )?
281 .stdout)
282 }
283
284 pub fn conflicts(&self) -> GitResult<Vec<String>> {
285 Ok(self
286 .run(
287 &["diff", "--name-only", "--diff-filter=U", "-z"],
288 "list conflicts",
289 )?
290 .stdout
291 .split('\0')
292 .filter(|path| !path.is_empty())
293 .map(str::to_string)
294 .collect())
295 }
296
297 pub fn stash_push(&self, message: &str, include_untracked: bool) -> GitResult<()> {
298 if message.len() > 1024 {
299 return Err(GitError::InvalidInput(
300 "stash message exceeds 1024 bytes".into(),
301 ));
302 }
303 let mut arguments = vec!["stash", "push"];
304 if include_untracked {
305 arguments.push("--include-untracked");
306 }
307 if !message.is_empty() {
308 arguments.extend(["-m", message]);
309 }
310 self.run(&arguments, "stash changes")?;
311 Ok(())
312 }
313
314 pub fn stash_list(&self) -> GitResult<Vec<String>> {
315 Ok(self
316 .run(&["stash", "list", "--format=%gd%x00%s"], "list stashes")?
317 .stdout
318 .lines()
319 .map(str::to_string)
320 .collect())
321 }
322
323 pub fn stash_pop(&self, reference: &str) -> GitResult<()> {
324 validate_ref(reference)?;
325 self.run(&["stash", "pop", reference], "pop stash")?;
326 Ok(())
327 }
328
329 pub fn worktrees(&self) -> GitResult<Vec<GitWorktree>> {
330 let output = self
331 .run(&["worktree", "list", "--porcelain", "-z"], "list worktrees")?
332 .stdout;
333 parse_worktrees(&output)
334 }
335
336 pub fn create_worktree(&self, path: &Path, branch: &str, create_branch: bool) -> GitResult<()> {
337 validate_ref(branch)?;
338 let path = absolute_worktree_path(path)?;
339 let encoded = path
340 .to_str()
341 .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
342 let mut arguments = vec!["worktree", "add"];
343 if create_branch {
344 arguments.extend(["-b", branch]);
345 arguments.push(encoded);
346 } else {
347 arguments.extend([encoded, branch]);
348 }
349 self.run(&arguments, "create worktree")?;
350 Ok(())
351 }
352
353 pub fn remove_worktree(&self, path: &Path, force: bool) -> GitResult<()> {
354 let path = absolute_worktree_path(path)?;
355 let path = path.canonicalize()?;
356 if path == self.root {
357 return Err(GitError::InvalidInput(
358 "cannot remove the primary repository worktree".into(),
359 ));
360 }
361 let known = self.worktrees()?.into_iter().any(|item| {
362 item.path
363 .canonicalize()
364 .is_ok_and(|known_path| known_path == path)
365 });
366 if !known {
367 return Err(GitError::InvalidInput(format!(
368 "path is not an owned repository worktree: {}",
369 path.display()
370 )));
371 }
372 let encoded = path
373 .to_str()
374 .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
375 let mut arguments = vec!["worktree", "remove"];
376 if force {
377 arguments.push("--force");
378 }
379 arguments.push(encoded);
380 self.run(&arguments, "remove worktree")?;
381 Ok(())
382 }
383
384 fn run(&self, arguments: &[&str], operation: &str) -> GitResult<GitCommandResult> {
385 run_git_at(&self.root, arguments, self.timeout, operation)
386 }
387}
388
389fn run_git_at(
390 root: &Path,
391 arguments: &[&str],
392 timeout: Duration,
393 operation: &str,
394) -> GitResult<GitCommandResult> {
395 let mut child = Command::new("git")
396 .args(arguments)
397 .current_dir(root)
398 .env("GIT_TERMINAL_PROMPT", "0")
399 .env("GIT_PAGER", "cat")
400 .stdin(Stdio::null())
401 .stdout(Stdio::piped())
402 .stderr(Stdio::piped())
403 .spawn()?;
404 let stdout = child.stdout.take().ok_or_else(|| GitError::Command {
405 operation: operation.into(),
406 detail: "Git stdout was unavailable".into(),
407 })?;
408 let stderr = child.stderr.take().ok_or_else(|| GitError::Command {
409 operation: operation.into(),
410 detail: "Git stderr was unavailable".into(),
411 })?;
412 let stdout_reader = read_output(stdout);
413 let stderr_reader = read_output(stderr);
414 let deadline = Instant::now() + timeout;
415 let status = loop {
416 if let Some(status) = child.try_wait()? {
417 break status;
418 }
419 if Instant::now() >= deadline {
420 let _ = child.kill();
421 let _ = child.wait();
422 join_output(stdout_reader)?;
423 join_output(stderr_reader)?;
424 return Err(GitError::Timeout(operation.into()));
425 }
426 std::thread::sleep(Duration::from_millis(10));
427 };
428 let stdout = join_output(stdout_reader)?;
429 let stderr = join_output(stderr_reader)?;
430 command_result(status, stdout, stderr, operation)
431}
432
433type OutputReader = JoinHandle<std::io::Result<(Vec<u8>, bool)>>;
434
435fn read_output(mut stream: impl Read + Send + 'static) -> OutputReader {
436 std::thread::spawn(move || {
437 let mut retained = Vec::new();
438 let mut truncated = false;
439 let mut chunk = [0_u8; 8192];
440 loop {
441 let read = stream.read(&mut chunk)?;
442 if read == 0 {
443 break;
444 }
445 let remaining = MAX_GIT_OUTPUT_BYTES.saturating_sub(retained.len());
446 retained.extend_from_slice(&chunk[..read.min(remaining)]);
447 truncated |= read > remaining;
448 }
449 Ok((retained, truncated))
450 })
451}
452
453fn join_output(reader: OutputReader) -> GitResult<(Vec<u8>, bool)> {
454 let output = reader.join().map_err(|_| GitError::Command {
455 operation: "read output".into(),
456 detail: "Git output reader panicked".into(),
457 })??;
458 Ok(output)
459}
460
461fn command_result(
462 status: ExitStatus,
463 stdout: (Vec<u8>, bool),
464 stderr: (Vec<u8>, bool),
465 operation: &str,
466) -> GitResult<GitCommandResult> {
467 if stdout.1 || stderr.1 {
468 return Err(GitError::OutputLimit(operation.into()));
469 }
470 let stdout = String::from_utf8_lossy(&stdout.0).into_owned();
471 let stderr = String::from_utf8_lossy(&stderr.0).into_owned();
472 if !status.success() {
473 return Err(GitError::Command {
474 operation: operation.into(),
475 detail: stderr.trim().to_string(),
476 });
477 }
478 Ok(GitCommandResult { stdout, stderr })
479}
480
481fn parse_status(output: &str) -> GitResult<GitStatus> {
482 let mut status = GitStatus {
483 branch: None,
484 upstream: None,
485 ahead: 0,
486 behind: 0,
487 entries: Vec::new(),
488 conflicts: Vec::new(),
489 };
490 let records = output.split('\0').collect::<Vec<_>>();
491 let mut index = 0;
492 while index < records.len() {
493 let record = records[index];
494 index += 1;
495 if let Some(branch) = record.strip_prefix("# branch.head ") {
496 status.branch = (branch != "(detached)").then(|| branch.to_string());
497 } else if let Some(upstream) = record.strip_prefix("# branch.upstream ") {
498 status.upstream = Some(upstream.to_string());
499 } else if let Some(ab) = record.strip_prefix("# branch.ab ") {
500 for value in ab.split_whitespace() {
501 if let Some(value) = value.strip_prefix('+') {
502 status.ahead = value.parse().unwrap_or(0);
503 } else if let Some(value) = value.strip_prefix('-') {
504 status.behind = value.parse().unwrap_or(0);
505 }
506 }
507 } else if let Some(path) = record.strip_prefix("? ") {
508 status.entries.push(GitStatusEntry {
509 path: path.to_string(),
510 original_path: None,
511 index_status: '?',
512 worktree_status: '?',
513 untracked: true,
514 });
515 } else if record.starts_with("1 ") || record.starts_with("u ") {
516 let fields = record.splitn(9, ' ').collect::<Vec<_>>();
517 if fields.len() < 9 {
518 return Err(GitError::Command {
519 operation: "parse status".into(),
520 detail: "Git returned a malformed status record".into(),
521 });
522 }
523 let xy = fields[1].as_bytes();
524 let entry = GitStatusEntry {
525 path: fields[8].to_string(),
526 original_path: None,
527 index_status: xy.first().copied().unwrap_or(b'.') as char,
528 worktree_status: xy.get(1).copied().unwrap_or(b'.') as char,
529 untracked: false,
530 };
531 if record.starts_with("u ") {
532 status.conflicts.push(entry.path.clone());
533 }
534 status.entries.push(entry);
535 } else if record.starts_with("2 ") {
536 let fields = record.splitn(10, ' ').collect::<Vec<_>>();
537 if fields.len() < 10 || index >= records.len() {
538 return Err(GitError::Command {
539 operation: "parse status".into(),
540 detail: "Git returned a malformed rename record".into(),
541 });
542 }
543 let xy = fields[1].as_bytes();
544 let original_path = records[index].to_string();
545 index += 1;
546 status.entries.push(GitStatusEntry {
547 path: fields[9].to_string(),
548 original_path: Some(original_path),
549 index_status: xy.first().copied().unwrap_or(b'.') as char,
550 worktree_status: xy.get(1).copied().unwrap_or(b'.') as char,
551 untracked: false,
552 });
553 }
554 }
555 Ok(status)
556}
557
558fn parse_worktrees(output: &str) -> GitResult<Vec<GitWorktree>> {
559 let mut worktrees = Vec::new();
560 let mut current: Option<GitWorktree> = None;
561 for field in output.split('\0') {
562 if field.is_empty() {
563 if let Some(item) = current.take() {
564 worktrees.push(item);
565 }
566 } else if let Some(path) = field.strip_prefix("worktree ") {
567 if let Some(item) = current.take() {
568 worktrees.push(item);
569 }
570 current = Some(GitWorktree {
571 path: PathBuf::from(path),
572 head: None,
573 branch: None,
574 bare: false,
575 detached: false,
576 locked: false,
577 prunable: false,
578 });
579 } else if let Some(item) = current.as_mut() {
580 if let Some(head) = field.strip_prefix("HEAD ") {
581 item.head = Some(head.to_string());
582 } else if let Some(branch) = field.strip_prefix("branch ") {
583 item.branch = Some(branch.trim_start_matches("refs/heads/").to_string());
584 } else {
585 match field.split_whitespace().next().unwrap_or_default() {
586 "bare" => item.bare = true,
587 "detached" => item.detached = true,
588 "locked" => item.locked = true,
589 "prunable" => item.prunable = true,
590 _ => {}
591 }
592 }
593 }
594 }
595 if let Some(item) = current {
596 worktrees.push(item);
597 }
598 if worktrees
599 .iter()
600 .any(|item| item.path.as_os_str().is_empty())
601 {
602 return Err(GitError::Command {
603 operation: "parse worktrees".into(),
604 detail: "Git returned an empty worktree path".into(),
605 });
606 }
607 Ok(worktrees)
608}
609
610fn validate_paths(paths: &[String]) -> GitResult<Vec<String>> {
611 if paths.is_empty() || paths.len() > 1024 {
612 return Err(GitError::InvalidInput(
613 "Git path operations require 1..=1024 paths".into(),
614 ));
615 }
616 paths
617 .iter()
618 .map(|path| validate_relative_path(path))
619 .collect()
620}
621
622fn validate_relative_path(path: &str) -> GitResult<String> {
623 let candidate = Path::new(path);
624 let rooted = candidate.components().any(|part| {
625 matches!(
626 part,
627 std::path::Component::Prefix(_) | std::path::Component::RootDir
628 )
629 });
630 if path.is_empty()
631 || path.len() > 4096
632 || rooted
633 || candidate
634 .components()
635 .any(|part| matches!(part, std::path::Component::ParentDir))
636 {
637 return Err(GitError::InvalidInput(format!(
638 "Git path must be relative and remain in the repository: {path}"
639 )));
640 }
641 Ok(path.to_string())
642}
643
644fn validate_ref(reference: &str) -> GitResult<()> {
645 if reference.is_empty()
646 || reference.len() > 1024
647 || reference.starts_with('-')
648 || reference.chars().any(char::is_whitespace)
649 {
650 return Err(GitError::InvalidInput(
651 "Git reference must be non-empty, bounded, contain no whitespace, and not start with '-'"
652 .into(),
653 ));
654 }
655 Ok(())
656}
657
658fn absolute_worktree_path(path: &Path) -> GitResult<PathBuf> {
659 if !path.is_absolute() || path == Path::new("/") {
660 return Err(GitError::InvalidInput(
661 "worktree path must be an explicit absolute path".into(),
662 ));
663 }
664 Ok(path.to_path_buf())
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670 use std::sync::atomic::{AtomicU64, Ordering};
671
672 static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
673
674 fn repository() -> PathBuf {
675 let sequence = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
676 let root = std::env::temp_dir().join(format!(
677 "glass-git-service-{}-{sequence}",
678 std::process::id()
679 ));
680 std::fs::create_dir_all(&root).unwrap();
681 for arguments in [
682 vec!["init", "-q"],
683 vec!["config", "user.name", "Glass Test"],
684 vec!["config", "user.email", "glass@example.invalid"],
685 ] {
686 assert!(
687 Command::new("git")
688 .args(arguments)
689 .current_dir(&root)
690 .status()
691 .unwrap()
692 .success()
693 );
694 }
695 root
696 }
697
698 #[test]
699 fn git_service_tracks_stage_commit_diff_branch_and_blame() {
700 let root = repository();
701 std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
702 let service = GitService::open(&root).unwrap();
703 let status = service.status().unwrap();
704 assert!(status.entries.iter().any(|entry| entry.path == "main.rs"));
705
706 service.stage(&["main.rs".into()]).unwrap();
707 let commit = service.commit("test: initialize fixture").unwrap();
708 assert_eq!(commit.subject, "test: initialize fixture");
709 assert!(
710 service
711 .blame("main.rs", 1, 1)
712 .unwrap()
713 .contains("Glass Test")
714 );
715
716 std::fs::write(root.join("main.rs"), "fn main() { println!(\"ok\"); }\n").unwrap();
717 assert!(
718 service
719 .diff(false, Some("main.rs"))
720 .unwrap()
721 .contains("println")
722 );
723 service.create_branch("fixture-branch", None).unwrap();
724 assert!(
725 service
726 .branches()
727 .unwrap()
728 .iter()
729 .any(|branch| branch.name == "fixture-branch")
730 );
731 assert!(service.conflicts().unwrap().is_empty());
732 assert_eq!(service.worktrees().unwrap().len(), 1);
733
734 std::fs::remove_dir_all(root).unwrap();
735 }
736
737 #[test]
738 fn git_paths_and_references_fail_closed() {
739 assert!(validate_relative_path("src/main.rs").is_ok());
740 assert!(validate_relative_path("../escape").is_err());
741 assert!(validate_relative_path("/absolute").is_err());
742 assert!(validate_ref("--upload-pack=bad").is_err());
743 assert!(absolute_worktree_path(Path::new("relative")).is_err());
744 }
745
746 #[cfg(unix)]
747 #[test]
748 fn worktree_removal_accepts_a_canonical_path_alias() {
749 use std::os::unix::fs::symlink;
750
751 let root = repository();
752 std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
753 let service = GitService::open(&root).unwrap();
754 service.stage(&["main.rs".into()]).unwrap();
755 service.commit("test: initialize fixture").unwrap();
756
757 let worktree = root.with_extension("worktree");
758 let alias = root.with_extension("worktree-alias");
759 service
760 .create_worktree(&worktree, "canonical-alias", true)
761 .unwrap();
762 symlink(&worktree, &alias).unwrap();
763
764 service.remove_worktree(&alias, true).unwrap();
765 assert!(!worktree.exists());
766
767 std::fs::remove_file(alias).unwrap();
768 std::fs::remove_dir_all(root).unwrap();
769 }
770
771 #[test]
772 fn status_parser_handles_branch_untracked_and_rename_records() {
773 let parsed = parse_status(concat!(
774 "# branch.head main\0",
775 "# branch.upstream origin/main\0",
776 "# branch.ab +2 -1\0",
777 "? new.txt\0",
778 "2 R. N... 100644 100644 100644 a b R100 renamed.txt\0old.txt\0",
779 ))
780 .unwrap();
781 assert_eq!(parsed.branch.as_deref(), Some("main"));
782 assert_eq!(parsed.upstream.as_deref(), Some("origin/main"));
783 assert_eq!((parsed.ahead, parsed.behind), (2, 1));
784 assert_eq!(parsed.entries.len(), 2);
785 assert_eq!(parsed.entries[1].original_path.as_deref(), Some("old.txt"));
786 }
787}