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 discard(&self, paths: &[String]) -> GitResult<()> {
184 let paths = validate_paths(paths)?;
185 let mut arguments = vec!["restore", "--"];
186 arguments.extend(paths.iter().map(String::as_str));
187 self.run(&arguments, "discard working-tree changes")?;
188 Ok(())
189 }
190
191 pub fn push(&self, remote: Option<&str>, branch: Option<&str>) -> GitResult<()> {
192 let mut arguments = vec!["push"];
193 if let Some(remote) = remote {
194 validate_ref(remote)?;
195 arguments.push(remote);
196 }
197 if let Some(branch) = branch {
198 validate_ref(branch)?;
199 arguments.push(branch);
200 }
201 self.run(&arguments, "push")?;
202 Ok(())
203 }
204
205 pub fn branches(&self) -> GitResult<Vec<GitBranch>> {
206 let format = "%(HEAD)%00%(refname:short)%00%(upstream:short)%00%(objectname)%00";
207 let format_argument = format!("--format={format}");
208 let output = self
209 .run(
210 &["for-each-ref", &format_argument, "refs/heads"],
211 "list branches",
212 )?
213 .stdout;
214 let fields = output.split('\0').collect::<Vec<_>>();
215 let mut branches = Vec::new();
216 for row in fields.chunks(4) {
217 if row.len() < 4 || row[1].is_empty() {
218 continue;
219 }
220 branches.push(GitBranch {
221 current: row[0].trim() == "*",
222 name: row[1].to_string(),
223 upstream: (!row[2].is_empty()).then(|| row[2].to_string()),
224 commit: row[3].trim().to_string(),
225 });
226 }
227 Ok(branches)
228 }
229
230 pub fn create_branch(&self, name: &str, start_point: Option<&str>) -> GitResult<()> {
231 validate_ref(name)?;
232 let mut arguments = vec!["branch", name];
233 if let Some(start_point) = start_point {
234 validate_ref(start_point)?;
235 arguments.push(start_point);
236 }
237 self.run(&arguments, "create branch")?;
238 Ok(())
239 }
240
241 pub fn switch_branch(&self, name: &str, create: bool) -> GitResult<()> {
242 validate_ref(name)?;
243 let mut arguments = vec!["switch"];
244 if create {
245 arguments.push("-c");
246 }
247 arguments.push(name);
248 self.run(&arguments, "switch branch")?;
249 Ok(())
250 }
251
252 pub fn commit(&self, message: &str) -> GitResult<GitCommit> {
253 if message.trim().is_empty() || message.len() > 16 * 1024 {
254 return Err(GitError::InvalidInput(
255 "commit message must contain 1..=16384 bytes".into(),
256 ));
257 }
258 self.run(&["commit", "-m", message], "commit")?;
259 self.commit_info("HEAD")
260 }
261
262 pub fn commit_info(&self, revision: &str) -> GitResult<GitCommit> {
263 validate_ref(revision)?;
264 let format = "%H%x00%an <%ae>%x00%ct%x00%s";
265 let format_argument = format!("--format={format}");
266 let output = self
267 .run(
268 &["show", "-s", &format_argument, revision],
269 "inspect commit",
270 )?
271 .stdout;
272 let fields = output.trim_end().splitn(4, '\0').collect::<Vec<_>>();
273 if fields.len() != 4 {
274 return Err(GitError::Command {
275 operation: "inspect commit".into(),
276 detail: "Git returned an invalid commit record".into(),
277 });
278 }
279 Ok(GitCommit {
280 id: fields[0].to_string(),
281 author: fields[1].to_string(),
282 timestamp: fields[2].parse().map_err(|_| GitError::Command {
283 operation: "inspect commit".into(),
284 detail: "Git returned an invalid commit timestamp".into(),
285 })?,
286 subject: fields[3].to_string(),
287 })
288 }
289
290 pub fn blame(&self, path: &str, start_line: u64, end_line: u64) -> GitResult<String> {
291 let path = validate_relative_path(path)?;
292 if start_line == 0 || end_line < start_line || end_line - start_line > 10_000 {
293 return Err(GitError::InvalidInput(
294 "blame lines must be positive, ordered, and span at most 10001 lines".into(),
295 ));
296 }
297 let range = format!("{start_line},{end_line}");
298 Ok(self
299 .run(
300 &["blame", "--line-porcelain", "-L", &range, "--", &path],
301 "blame",
302 )?
303 .stdout)
304 }
305
306 pub fn conflicts(&self) -> GitResult<Vec<String>> {
307 Ok(self
308 .run(
309 &["diff", "--name-only", "--diff-filter=U", "-z"],
310 "list conflicts",
311 )?
312 .stdout
313 .split('\0')
314 .filter(|path| !path.is_empty())
315 .map(str::to_string)
316 .collect())
317 }
318
319 pub fn stash_push(&self, message: &str, include_untracked: bool) -> GitResult<()> {
320 if message.len() > 1024 {
321 return Err(GitError::InvalidInput(
322 "stash message exceeds 1024 bytes".into(),
323 ));
324 }
325 let mut arguments = vec!["stash", "push"];
326 if include_untracked {
327 arguments.push("--include-untracked");
328 }
329 if !message.is_empty() {
330 arguments.extend(["-m", message]);
331 }
332 self.run(&arguments, "stash changes")?;
333 Ok(())
334 }
335
336 pub fn stash_list(&self) -> GitResult<Vec<String>> {
337 Ok(self
338 .run(&["stash", "list", "--format=%gd%x00%s"], "list stashes")?
339 .stdout
340 .lines()
341 .map(str::to_string)
342 .collect())
343 }
344
345 pub fn stash_pop(&self, reference: &str) -> GitResult<()> {
346 validate_ref(reference)?;
347 self.run(&["stash", "pop", reference], "pop stash")?;
348 Ok(())
349 }
350
351 pub fn worktrees(&self) -> GitResult<Vec<GitWorktree>> {
352 let output = self
353 .run(&["worktree", "list", "--porcelain", "-z"], "list worktrees")?
354 .stdout;
355 parse_worktrees(&output)
356 }
357
358 pub fn create_worktree(&self, path: &Path, branch: &str, create_branch: bool) -> GitResult<()> {
359 validate_ref(branch)?;
360 let path = absolute_worktree_path(path)?;
361 let encoded = path
362 .to_str()
363 .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
364 let mut arguments = vec!["worktree", "add"];
365 if create_branch {
366 arguments.extend(["-b", branch]);
367 arguments.push(encoded);
368 } else {
369 arguments.extend([encoded, branch]);
370 }
371 self.run(&arguments, "create worktree")?;
372 Ok(())
373 }
374
375 pub fn remove_worktree(&self, path: &Path, force: bool) -> GitResult<()> {
376 let path = absolute_worktree_path(path)?;
377 let path = path.canonicalize()?;
378 if path == self.root {
379 return Err(GitError::InvalidInput(
380 "cannot remove the primary repository worktree".into(),
381 ));
382 }
383 let known = self.worktrees()?.into_iter().any(|item| {
384 item.path
385 .canonicalize()
386 .is_ok_and(|known_path| known_path == path)
387 });
388 if !known {
389 return Err(GitError::InvalidInput(format!(
390 "path is not an owned repository worktree: {}",
391 path.display()
392 )));
393 }
394 let encoded = path
395 .to_str()
396 .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
397 let mut arguments = vec!["worktree", "remove"];
398 if force {
399 arguments.push("--force");
400 }
401 arguments.push(encoded);
402 self.run(&arguments, "remove worktree")?;
403 Ok(())
404 }
405
406 fn run(&self, arguments: &[&str], operation: &str) -> GitResult<GitCommandResult> {
407 run_git_at(&self.root, arguments, self.timeout, operation)
408 }
409}
410
411fn run_git_at(
412 root: &Path,
413 arguments: &[&str],
414 timeout: Duration,
415 operation: &str,
416) -> GitResult<GitCommandResult> {
417 let mut child = Command::new("git")
418 .args(arguments)
419 .current_dir(root)
420 .env("GIT_TERMINAL_PROMPT", "0")
421 .env("GIT_PAGER", "cat")
422 .stdin(Stdio::null())
423 .stdout(Stdio::piped())
424 .stderr(Stdio::piped())
425 .spawn()?;
426 let stdout = child.stdout.take().ok_or_else(|| GitError::Command {
427 operation: operation.into(),
428 detail: "Git stdout was unavailable".into(),
429 })?;
430 let stderr = child.stderr.take().ok_or_else(|| GitError::Command {
431 operation: operation.into(),
432 detail: "Git stderr was unavailable".into(),
433 })?;
434 let stdout_reader = read_output(stdout);
435 let stderr_reader = read_output(stderr);
436 let deadline = Instant::now() + timeout;
437 let status = loop {
438 if let Some(status) = child.try_wait()? {
439 break status;
440 }
441 if Instant::now() >= deadline {
442 let _ = child.kill();
443 let _ = child.wait();
444 join_output(stdout_reader)?;
445 join_output(stderr_reader)?;
446 return Err(GitError::Timeout(operation.into()));
447 }
448 std::thread::sleep(Duration::from_millis(10));
449 };
450 let stdout = join_output(stdout_reader)?;
451 let stderr = join_output(stderr_reader)?;
452 command_result(status, stdout, stderr, operation)
453}
454
455type OutputReader = JoinHandle<std::io::Result<(Vec<u8>, bool)>>;
456
457fn read_output(mut stream: impl Read + Send + 'static) -> OutputReader {
458 std::thread::spawn(move || {
459 let mut retained = Vec::new();
460 let mut truncated = false;
461 let mut chunk = [0_u8; 8192];
462 loop {
463 let read = stream.read(&mut chunk)?;
464 if read == 0 {
465 break;
466 }
467 let remaining = MAX_GIT_OUTPUT_BYTES.saturating_sub(retained.len());
468 retained.extend_from_slice(&chunk[..read.min(remaining)]);
469 truncated |= read > remaining;
470 }
471 Ok((retained, truncated))
472 })
473}
474
475fn join_output(reader: OutputReader) -> GitResult<(Vec<u8>, bool)> {
476 let output = reader.join().map_err(|_| GitError::Command {
477 operation: "read output".into(),
478 detail: "Git output reader panicked".into(),
479 })??;
480 Ok(output)
481}
482
483fn command_result(
484 status: ExitStatus,
485 stdout: (Vec<u8>, bool),
486 stderr: (Vec<u8>, bool),
487 operation: &str,
488) -> GitResult<GitCommandResult> {
489 if stdout.1 || stderr.1 {
490 return Err(GitError::OutputLimit(operation.into()));
491 }
492 let stdout = String::from_utf8_lossy(&stdout.0).into_owned();
493 let stderr = String::from_utf8_lossy(&stderr.0).into_owned();
494 if !status.success() {
495 return Err(GitError::Command {
496 operation: operation.into(),
497 detail: stderr.trim().to_string(),
498 });
499 }
500 Ok(GitCommandResult { stdout, stderr })
501}
502
503fn parse_status(output: &str) -> GitResult<GitStatus> {
504 let mut status = GitStatus {
505 branch: None,
506 upstream: None,
507 ahead: 0,
508 behind: 0,
509 entries: Vec::new(),
510 conflicts: Vec::new(),
511 };
512 let records = output.split('\0').collect::<Vec<_>>();
513 let mut index = 0;
514 while index < records.len() {
515 let record = records[index];
516 index += 1;
517 if let Some(branch) = record.strip_prefix("# branch.head ") {
518 status.branch = (branch != "(detached)").then(|| branch.to_string());
519 } else if let Some(upstream) = record.strip_prefix("# branch.upstream ") {
520 status.upstream = Some(upstream.to_string());
521 } else if let Some(ab) = record.strip_prefix("# branch.ab ") {
522 for value in ab.split_whitespace() {
523 if let Some(value) = value.strip_prefix('+') {
524 status.ahead = value.parse().unwrap_or(0);
525 } else if let Some(value) = value.strip_prefix('-') {
526 status.behind = value.parse().unwrap_or(0);
527 }
528 }
529 } else if let Some(path) = record.strip_prefix("? ") {
530 status.entries.push(GitStatusEntry {
531 path: path.to_string(),
532 original_path: None,
533 index_status: '?',
534 worktree_status: '?',
535 untracked: true,
536 });
537 } else if record.starts_with("1 ") || record.starts_with("u ") {
538 let fields = record.splitn(9, ' ').collect::<Vec<_>>();
539 if fields.len() < 9 {
540 return Err(GitError::Command {
541 operation: "parse status".into(),
542 detail: "Git returned a malformed status record".into(),
543 });
544 }
545 let xy = fields[1].as_bytes();
546 let entry = GitStatusEntry {
547 path: fields[8].to_string(),
548 original_path: None,
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 if record.starts_with("u ") {
554 status.conflicts.push(entry.path.clone());
555 }
556 status.entries.push(entry);
557 } else if record.starts_with("2 ") {
558 let fields = record.splitn(10, ' ').collect::<Vec<_>>();
559 if fields.len() < 10 || index >= records.len() {
560 return Err(GitError::Command {
561 operation: "parse status".into(),
562 detail: "Git returned a malformed rename record".into(),
563 });
564 }
565 let xy = fields[1].as_bytes();
566 let original_path = records[index].to_string();
567 index += 1;
568 status.entries.push(GitStatusEntry {
569 path: fields[9].to_string(),
570 original_path: Some(original_path),
571 index_status: xy.first().copied().unwrap_or(b'.') as char,
572 worktree_status: xy.get(1).copied().unwrap_or(b'.') as char,
573 untracked: false,
574 });
575 }
576 }
577 Ok(status)
578}
579
580fn parse_worktrees(output: &str) -> GitResult<Vec<GitWorktree>> {
581 let mut worktrees = Vec::new();
582 let mut current: Option<GitWorktree> = None;
583 for field in output.split('\0') {
584 if field.is_empty() {
585 if let Some(item) = current.take() {
586 worktrees.push(item);
587 }
588 } else if let Some(path) = field.strip_prefix("worktree ") {
589 if let Some(item) = current.take() {
590 worktrees.push(item);
591 }
592 current = Some(GitWorktree {
593 path: PathBuf::from(path),
594 head: None,
595 branch: None,
596 bare: false,
597 detached: false,
598 locked: false,
599 prunable: false,
600 });
601 } else if let Some(item) = current.as_mut() {
602 if let Some(head) = field.strip_prefix("HEAD ") {
603 item.head = Some(head.to_string());
604 } else if let Some(branch) = field.strip_prefix("branch ") {
605 item.branch = Some(branch.trim_start_matches("refs/heads/").to_string());
606 } else {
607 match field.split_whitespace().next().unwrap_or_default() {
608 "bare" => item.bare = true,
609 "detached" => item.detached = true,
610 "locked" => item.locked = true,
611 "prunable" => item.prunable = true,
612 _ => {}
613 }
614 }
615 }
616 }
617 if let Some(item) = current {
618 worktrees.push(item);
619 }
620 if worktrees
621 .iter()
622 .any(|item| item.path.as_os_str().is_empty())
623 {
624 return Err(GitError::Command {
625 operation: "parse worktrees".into(),
626 detail: "Git returned an empty worktree path".into(),
627 });
628 }
629 Ok(worktrees)
630}
631
632fn validate_paths(paths: &[String]) -> GitResult<Vec<String>> {
633 if paths.is_empty() || paths.len() > 1024 {
634 return Err(GitError::InvalidInput(
635 "Git path operations require 1..=1024 paths".into(),
636 ));
637 }
638 paths
639 .iter()
640 .map(|path| validate_relative_path(path))
641 .collect()
642}
643
644fn validate_relative_path(path: &str) -> GitResult<String> {
645 let candidate = Path::new(path);
646 let rooted = candidate.components().any(|part| {
647 matches!(
648 part,
649 std::path::Component::Prefix(_) | std::path::Component::RootDir
650 )
651 });
652 if path.is_empty()
653 || path.len() > 4096
654 || rooted
655 || candidate
656 .components()
657 .any(|part| matches!(part, std::path::Component::ParentDir))
658 {
659 return Err(GitError::InvalidInput(format!(
660 "Git path must be relative and remain in the repository: {path}"
661 )));
662 }
663 Ok(path.to_string())
664}
665
666fn validate_ref(reference: &str) -> GitResult<()> {
667 if reference.is_empty()
668 || reference.len() > 1024
669 || reference.starts_with('-')
670 || reference.chars().any(char::is_whitespace)
671 {
672 return Err(GitError::InvalidInput(
673 "Git reference must be non-empty, bounded, contain no whitespace, and not start with '-'"
674 .into(),
675 ));
676 }
677 Ok(())
678}
679
680fn absolute_worktree_path(path: &Path) -> GitResult<PathBuf> {
681 if !path.is_absolute() || path == Path::new("/") {
682 return Err(GitError::InvalidInput(
683 "worktree path must be an explicit absolute path".into(),
684 ));
685 }
686 Ok(path.to_path_buf())
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692 use std::sync::atomic::{AtomicU64, Ordering};
693
694 static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
695
696 fn repository() -> PathBuf {
697 let sequence = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
698 let root = std::env::temp_dir().join(format!(
699 "glass-git-service-{}-{sequence}",
700 std::process::id()
701 ));
702 std::fs::create_dir_all(&root).unwrap();
703 for arguments in [
704 vec!["init", "-q"],
705 vec!["config", "user.name", "Glass Test"],
706 vec!["config", "user.email", "glass@example.invalid"],
707 ] {
708 assert!(
709 Command::new("git")
710 .args(arguments)
711 .current_dir(&root)
712 .status()
713 .unwrap()
714 .success()
715 );
716 }
717 root
718 }
719
720 #[test]
721 fn git_service_tracks_stage_commit_diff_branch_and_blame() {
722 let root = repository();
723 std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
724 let service = GitService::open(&root).unwrap();
725 let status = service.status().unwrap();
726 assert!(status.entries.iter().any(|entry| entry.path == "main.rs"));
727
728 service.stage(&["main.rs".into()]).unwrap();
729 let commit = service.commit("test: initialize fixture").unwrap();
730 assert_eq!(commit.subject, "test: initialize fixture");
731 assert!(
732 service
733 .blame("main.rs", 1, 1)
734 .unwrap()
735 .contains("Glass Test")
736 );
737
738 std::fs::write(root.join("main.rs"), "fn main() { println!(\"ok\"); }\n").unwrap();
739 assert!(
740 service
741 .diff(false, Some("main.rs"))
742 .unwrap()
743 .contains("println")
744 );
745 service.discard(&["main.rs".into()]).unwrap();
746 assert!(
747 !service
748 .diff(false, Some("main.rs"))
749 .unwrap()
750 .contains("println")
751 );
752 service.create_branch("fixture-branch", None).unwrap();
753 assert!(
754 service
755 .branches()
756 .unwrap()
757 .iter()
758 .any(|branch| branch.name == "fixture-branch")
759 );
760 assert!(service.conflicts().unwrap().is_empty());
761 assert_eq!(service.worktrees().unwrap().len(), 1);
762
763 std::fs::remove_dir_all(root).unwrap();
764 }
765
766 #[test]
767 fn git_paths_and_references_fail_closed() {
768 assert!(validate_relative_path("src/main.rs").is_ok());
769 assert!(validate_relative_path("../escape").is_err());
770 assert!(validate_relative_path("/absolute").is_err());
771 assert!(validate_ref("--upload-pack=bad").is_err());
772 let root = repository();
773 let service = GitService::open(&root).unwrap();
774 assert!(service.push(Some("--upload-pack=bad"), None).is_err());
775 assert!(absolute_worktree_path(Path::new("relative")).is_err());
776 std::fs::remove_dir_all(root).unwrap();
777 }
778
779 #[cfg(unix)]
780 #[test]
781 fn worktree_removal_accepts_a_canonical_path_alias() {
782 use std::os::unix::fs::symlink;
783
784 let root = repository();
785 std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
786 let service = GitService::open(&root).unwrap();
787 service.stage(&["main.rs".into()]).unwrap();
788 service.commit("test: initialize fixture").unwrap();
789
790 let worktree = root.with_extension("worktree");
791 let alias = root.with_extension("worktree-alias");
792 service
793 .create_worktree(&worktree, "canonical-alias", true)
794 .unwrap();
795 symlink(&worktree, &alias).unwrap();
796
797 service.remove_worktree(&alias, true).unwrap();
798 assert!(!worktree.exists());
799
800 std::fs::remove_file(alias).unwrap();
801 std::fs::remove_dir_all(root).unwrap();
802 }
803
804 #[test]
805 fn status_parser_handles_branch_untracked_and_rename_records() {
806 let parsed = parse_status(concat!(
807 "# branch.head main\0",
808 "# branch.upstream origin/main\0",
809 "# branch.ab +2 -1\0",
810 "? new.txt\0",
811 "2 R. N... 100644 100644 100644 a b R100 renamed.txt\0old.txt\0",
812 ))
813 .unwrap();
814 assert_eq!(parsed.branch.as_deref(), Some("main"));
815 assert_eq!(parsed.upstream.as_deref(), Some("origin/main"));
816 assert_eq!((parsed.ahead, parsed.behind), (2, 1));
817 assert_eq!(parsed.entries.len(), 2);
818 assert_eq!(parsed.entries[1].original_path.as_deref(), Some("old.txt"));
819 }
820}