Skip to main content

glass_dev/
git.rs

1//! Native bounded Git and worktree service for Glass Dev.
2
3use 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
77impl GitStatus {
78    /// Conflicts first, then unstaged, staged, untracked.
79    pub fn sorted_entries(&self) -> Vec<GitStatusEntry> {
80        let mut entries = self.entries.clone();
81        entries.sort_by(|left, right| {
82            entry_rank(left, &self.conflicts)
83                .cmp(&entry_rank(right, &self.conflicts))
84                .then_with(|| left.path.cmp(&right.path))
85        });
86        entries
87    }
88}
89
90fn entry_rank(entry: &GitStatusEntry, conflicts: &[String]) -> u8 {
91    if conflicts.iter().any(|path| path == &entry.path)
92        || entry.index_status == 'U'
93        || entry.worktree_status == 'U'
94    {
95        0
96    } else if entry.untracked {
97        3
98    } else if entry.worktree_status != ' ' {
99        1
100    } else {
101        2
102    }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
106#[serde(rename_all = "camelCase")]
107pub struct GitBranch {
108    pub name: String,
109    pub current: bool,
110    pub upstream: Option<String>,
111    pub commit: String,
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
115#[serde(rename_all = "camelCase")]
116pub struct GitCommit {
117    pub id: String,
118    pub author: String,
119    pub timestamp: i64,
120    pub subject: String,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
124#[serde(rename_all = "camelCase")]
125pub struct GitWorktree {
126    pub path: PathBuf,
127    pub head: Option<String>,
128    pub branch: Option<String>,
129    pub bare: bool,
130    pub detached: bool,
131    pub locked: bool,
132    pub prunable: bool,
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
136#[serde(rename_all = "camelCase")]
137pub struct GitCommandResult {
138    pub stdout: String,
139    pub stderr: String,
140}
141
142pub struct GitService {
143    root: PathBuf,
144    timeout: Duration,
145}
146
147impl GitService {
148    pub fn open(path: impl AsRef<Path>) -> GitResult<Self> {
149        let path = path.as_ref().canonicalize()?;
150        let probe = run_git_at(
151            &path,
152            &["rev-parse", "--show-toplevel"],
153            DEFAULT_GIT_TIMEOUT,
154            "discover repository",
155        )?;
156        let toplevel = PathBuf::from(probe.stdout.trim());
157        if toplevel.as_os_str().is_empty() || toplevel.canonicalize().is_err() {
158            return Err(GitError::NotRepository(path));
159        }
160        Ok(Self {
161            root: path,
162            timeout: DEFAULT_GIT_TIMEOUT,
163        })
164    }
165
166    pub fn root(&self) -> &Path {
167        &self.root
168    }
169
170    pub fn set_timeout(&mut self, timeout: Duration) -> GitResult<()> {
171        if timeout.is_zero() || timeout > Duration::from_secs(600) {
172            return Err(GitError::InvalidInput(
173                "Git timeout must be between 1 ms and 600 seconds".into(),
174            ));
175        }
176        self.timeout = timeout;
177        Ok(())
178    }
179
180    pub fn status(&self) -> GitResult<GitStatus> {
181        let result = self.run(&["status", "--porcelain=v2", "--branch", "-z"], "status")?;
182        parse_status(&result.stdout)
183    }
184
185    pub fn diff(&self, staged: bool, path: Option<&str>) -> GitResult<String> {
186        let mut arguments = vec!["diff", "--no-ext-diff", "--no-textconv", "--binary"];
187        if staged {
188            arguments.push("--cached");
189        }
190        let validated;
191        if let Some(path) = path {
192            validated = validate_relative_path(path)?;
193            arguments.extend(["--", validated.as_str()]);
194        }
195        Ok(self.run(&arguments, "diff")?.stdout)
196    }
197
198    pub fn stage(&self, paths: &[String]) -> GitResult<()> {
199        let paths = validate_paths(paths)?;
200        let mut arguments = vec!["add", "--"];
201        arguments.extend(paths.iter().map(String::as_str));
202        self.run(&arguments, "stage")?;
203        Ok(())
204    }
205
206    pub fn unstage(&self, paths: &[String]) -> GitResult<()> {
207        let paths = validate_paths(paths)?;
208        let mut arguments = vec!["restore", "--staged", "--"];
209        arguments.extend(paths.iter().map(String::as_str));
210        self.run(&arguments, "unstage")?;
211        Ok(())
212    }
213
214    pub fn discard(&self, paths: &[String]) -> GitResult<()> {
215        let paths = validate_paths(paths)?;
216        let mut arguments = vec!["restore", "--"];
217        arguments.extend(paths.iter().map(String::as_str));
218        self.run(&arguments, "discard working-tree changes")?;
219        Ok(())
220    }
221
222    pub fn fetch(&self, remote: Option<&str>) -> GitResult<()> {
223        let mut arguments = vec!["fetch"];
224        if let Some(remote) = remote {
225            validate_ref(remote)?;
226            arguments.push(remote);
227        }
228        self.run(&arguments, "fetch")?;
229        Ok(())
230    }
231
232    pub fn pull(&self, remote: Option<&str>, branch: Option<&str>) -> GitResult<()> {
233        let mut arguments = vec!["pull"];
234        if let Some(remote) = remote {
235            validate_ref(remote)?;
236            arguments.push(remote);
237        }
238        if let Some(branch) = branch {
239            validate_ref(branch)?;
240            arguments.push(branch);
241        }
242        self.run(&arguments, "pull")?;
243        Ok(())
244    }
245
246    pub fn merge(&self, branch: &str) -> GitResult<()> {
247        validate_ref(branch)?;
248        self.run(&["merge", "--no-edit", branch], "merge")?;
249        Ok(())
250    }
251
252    pub fn rebase(&self, onto: &str) -> GitResult<()> {
253        validate_ref(onto)?;
254        self.run(&["rebase", onto], "rebase")?;
255        Ok(())
256    }
257
258    pub fn push(&self, remote: Option<&str>, branch: Option<&str>) -> GitResult<()> {
259        let mut arguments = vec!["push"];
260        if let Some(remote) = remote {
261            validate_ref(remote)?;
262            arguments.push(remote);
263        }
264        if let Some(branch) = branch {
265            validate_ref(branch)?;
266            arguments.push(branch);
267        }
268        self.run(&arguments, "push")?;
269        Ok(())
270    }
271
272    pub fn branches(&self) -> GitResult<Vec<GitBranch>> {
273        let format = "%(HEAD)%00%(refname:short)%00%(upstream:short)%00%(objectname)%00";
274        let format_argument = format!("--format={format}");
275        let output = self
276            .run(
277                &["for-each-ref", &format_argument, "refs/heads"],
278                "list branches",
279            )?
280            .stdout;
281        let fields = output.split('\0').collect::<Vec<_>>();
282        let mut branches = Vec::new();
283        for row in fields.chunks(4) {
284            if row.len() < 4 || row[1].is_empty() {
285                continue;
286            }
287            branches.push(GitBranch {
288                current: row[0].trim() == "*",
289                name: row[1].to_string(),
290                upstream: (!row[2].is_empty()).then(|| row[2].to_string()),
291                commit: row[3].trim().to_string(),
292            });
293        }
294        Ok(branches)
295    }
296
297    pub fn create_branch(&self, name: &str, start_point: Option<&str>) -> GitResult<()> {
298        validate_ref(name)?;
299        let mut arguments = vec!["branch", name];
300        if let Some(start_point) = start_point {
301            validate_ref(start_point)?;
302            arguments.push(start_point);
303        }
304        self.run(&arguments, "create branch")?;
305        Ok(())
306    }
307
308    pub fn switch_branch(&self, name: &str, create: bool) -> GitResult<()> {
309        validate_ref(name)?;
310        let mut arguments = vec!["switch"];
311        if create {
312            arguments.push("-c");
313        }
314        arguments.push(name);
315        self.run(&arguments, "switch branch")?;
316        Ok(())
317    }
318
319    pub fn commit(&self, message: &str) -> GitResult<GitCommit> {
320        if message.trim().is_empty() || message.len() > 16 * 1024 {
321            return Err(GitError::InvalidInput(
322                "commit message must contain 1..=16384 bytes".into(),
323            ));
324        }
325        self.run(&["commit", "-m", message], "commit")?;
326        self.commit_info("HEAD")
327    }
328
329    pub fn commit_info(&self, revision: &str) -> GitResult<GitCommit> {
330        validate_ref(revision)?;
331        let format = "%H%x00%an <%ae>%x00%ct%x00%s";
332        let format_argument = format!("--format={format}");
333        let output = self
334            .run(
335                &["show", "-s", &format_argument, revision],
336                "inspect commit",
337            )?
338            .stdout;
339        let fields = output.trim_end().splitn(4, '\0').collect::<Vec<_>>();
340        if fields.len() != 4 {
341            return Err(GitError::Command {
342                operation: "inspect commit".into(),
343                detail: "Git returned an invalid commit record".into(),
344            });
345        }
346        Ok(GitCommit {
347            id: fields[0].to_string(),
348            author: fields[1].to_string(),
349            timestamp: fields[2].parse().map_err(|_| GitError::Command {
350                operation: "inspect commit".into(),
351                detail: "Git returned an invalid commit timestamp".into(),
352            })?,
353            subject: fields[3].to_string(),
354        })
355    }
356
357    pub fn blame(&self, path: &str, start_line: u64, end_line: u64) -> GitResult<String> {
358        let path = validate_relative_path(path)?;
359        if start_line == 0 || end_line < start_line || end_line - start_line > 10_000 {
360            return Err(GitError::InvalidInput(
361                "blame lines must be positive, ordered, and span at most 10001 lines".into(),
362            ));
363        }
364        let range = format!("{start_line},{end_line}");
365        Ok(self
366            .run(
367                &["blame", "--line-porcelain", "-L", &range, "--", &path],
368                "blame",
369            )?
370            .stdout)
371    }
372
373    pub fn conflicts(&self) -> GitResult<Vec<String>> {
374        Ok(self
375            .run(
376                &["diff", "--name-only", "--diff-filter=U", "-z"],
377                "list conflicts",
378            )?
379            .stdout
380            .split('\0')
381            .filter(|path| !path.is_empty())
382            .map(str::to_string)
383            .collect())
384    }
385
386    pub fn stash_push(&self, message: &str, include_untracked: bool) -> GitResult<()> {
387        if message.len() > 1024 {
388            return Err(GitError::InvalidInput(
389                "stash message exceeds 1024 bytes".into(),
390            ));
391        }
392        let mut arguments = vec!["stash", "push"];
393        if include_untracked {
394            arguments.push("--include-untracked");
395        }
396        if !message.is_empty() {
397            arguments.extend(["-m", message]);
398        }
399        self.run(&arguments, "stash changes")?;
400        Ok(())
401    }
402
403    pub fn stash_list(&self) -> GitResult<Vec<String>> {
404        Ok(self
405            .run(&["stash", "list", "--format=%gd%x00%s"], "list stashes")?
406            .stdout
407            .lines()
408            .map(str::to_string)
409            .collect())
410    }
411
412    pub fn stash_pop(&self, reference: &str) -> GitResult<()> {
413        validate_ref(reference)?;
414        self.run(&["stash", "pop", reference], "pop stash")?;
415        Ok(())
416    }
417
418    pub fn worktrees(&self) -> GitResult<Vec<GitWorktree>> {
419        let output = self
420            .run(&["worktree", "list", "--porcelain", "-z"], "list worktrees")?
421            .stdout;
422        parse_worktrees(&output)
423    }
424
425    pub fn create_worktree(&self, path: &Path, branch: &str, create_branch: bool) -> GitResult<()> {
426        validate_ref(branch)?;
427        let path = absolute_worktree_path(path)?;
428        let encoded = path
429            .to_str()
430            .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
431        let mut arguments = vec!["worktree", "add"];
432        if create_branch {
433            arguments.extend(["-b", branch]);
434            arguments.push(encoded);
435        } else {
436            arguments.extend([encoded, branch]);
437        }
438        self.run(&arguments, "create worktree")?;
439        Ok(())
440    }
441
442    pub fn remove_worktree(&self, path: &Path, force: bool) -> GitResult<()> {
443        let path = absolute_worktree_path(path)?;
444        let path = path.canonicalize()?;
445        if path == self.root {
446            return Err(GitError::InvalidInput(
447                "cannot remove the primary repository worktree".into(),
448            ));
449        }
450        let known = self.worktrees()?.into_iter().any(|item| {
451            item.path
452                .canonicalize()
453                .is_ok_and(|known_path| known_path == path)
454        });
455        if !known {
456            return Err(GitError::InvalidInput(format!(
457                "path is not an owned repository worktree: {}",
458                path.display()
459            )));
460        }
461        let encoded = path
462            .to_str()
463            .ok_or_else(|| GitError::InvalidInput("worktree path is not UTF-8".into()))?;
464        let mut arguments = vec!["worktree", "remove"];
465        if force {
466            arguments.push("--force");
467        }
468        arguments.push(encoded);
469        self.run(&arguments, "remove worktree")?;
470        Ok(())
471    }
472
473    fn run(&self, arguments: &[&str], operation: &str) -> GitResult<GitCommandResult> {
474        run_git_at(&self.root, arguments, self.timeout, operation)
475    }
476}
477
478pub(crate) fn git_command(root: &Path) -> Command {
479    let mut command = Command::new("git");
480    apply_untrusted_git_isolation(&mut command);
481    command.current_dir(root);
482    command
483}
484
485fn apply_untrusted_git_isolation(command: &mut Command) {
486    command
487        .env("GIT_TERMINAL_PROMPT", "0")
488        .env("GIT_PAGER", "cat")
489        .env("GIT_CONFIG_NOSYSTEM", "1")
490        .env("GIT_CONFIG_GLOBAL", git_null_device());
491}
492
493fn git_null_device() -> &'static str {
494    if cfg!(windows) { "NUL" } else { "/dev/null" }
495}
496
497fn git_safety_overrides(verb: &str) -> Vec<String> {
498    vec![
499        "-c".into(),
500        format!("alias.{verb}="),
501        "-c".into(),
502        format!("core.hooksPath={}", git_null_device()),
503        "-c".into(),
504        "core.fsmonitor=".into(),
505        "-c".into(),
506        "core.fsmonitorHookVersion=".into(),
507        "-c".into(),
508        "diff.external=".into(),
509        "-c".into(),
510        "filter.lfs.smudge=".into(),
511        "-c".into(),
512        "filter.lfs.process=".into(),
513        "-c".into(),
514        "filter.lfs.required=false".into(),
515    ]
516}
517
518fn run_git_at(
519    root: &Path,
520    arguments: &[&str],
521    timeout: Duration,
522    operation: &str,
523) -> GitResult<GitCommandResult> {
524    let mut command = git_command(root);
525    if let Some(verb) = arguments.first() {
526        command.args(git_safety_overrides(verb));
527    }
528    let mut child = command
529        .args(arguments)
530        .stdin(Stdio::null())
531        .stdout(Stdio::piped())
532        .stderr(Stdio::piped())
533        .spawn()?;
534    let stdout = child.stdout.take().ok_or_else(|| GitError::Command {
535        operation: operation.into(),
536        detail: "Git stdout was unavailable".into(),
537    })?;
538    let stderr = child.stderr.take().ok_or_else(|| GitError::Command {
539        operation: operation.into(),
540        detail: "Git stderr was unavailable".into(),
541    })?;
542    let stdout_reader = read_output(stdout);
543    let stderr_reader = read_output(stderr);
544    let deadline = Instant::now() + timeout;
545    let status = loop {
546        if let Some(status) = child.try_wait()? {
547            break status;
548        }
549        if Instant::now() >= deadline {
550            let _ = child.kill();
551            let _ = child.wait();
552            join_output(stdout_reader)?;
553            join_output(stderr_reader)?;
554            return Err(GitError::Timeout(operation.into()));
555        }
556        std::thread::sleep(Duration::from_millis(10));
557    };
558    let stdout = join_output(stdout_reader)?;
559    let stderr = join_output(stderr_reader)?;
560    command_result(status, stdout, stderr, operation)
561}
562
563type OutputReader = JoinHandle<std::io::Result<(Vec<u8>, bool)>>;
564
565fn read_output(mut stream: impl Read + Send + 'static) -> OutputReader {
566    std::thread::spawn(move || {
567        let mut retained = Vec::new();
568        let mut truncated = false;
569        let mut chunk = [0_u8; 8192];
570        loop {
571            let read = stream.read(&mut chunk)?;
572            if read == 0 {
573                break;
574            }
575            let remaining = MAX_GIT_OUTPUT_BYTES.saturating_sub(retained.len());
576            retained.extend_from_slice(&chunk[..read.min(remaining)]);
577            truncated |= read > remaining;
578        }
579        Ok((retained, truncated))
580    })
581}
582
583fn join_output(reader: OutputReader) -> GitResult<(Vec<u8>, bool)> {
584    let output = reader.join().map_err(|_| GitError::Command {
585        operation: "read output".into(),
586        detail: "Git output reader panicked".into(),
587    })??;
588    Ok(output)
589}
590
591fn command_result(
592    status: ExitStatus,
593    stdout: (Vec<u8>, bool),
594    stderr: (Vec<u8>, bool),
595    operation: &str,
596) -> GitResult<GitCommandResult> {
597    if stdout.1 || stderr.1 {
598        return Err(GitError::OutputLimit(operation.into()));
599    }
600    let stdout = String::from_utf8_lossy(&stdout.0).into_owned();
601    let stderr = String::from_utf8_lossy(&stderr.0).into_owned();
602    if !status.success() {
603        return Err(GitError::Command {
604            operation: operation.into(),
605            detail: stderr.trim().to_string(),
606        });
607    }
608    Ok(GitCommandResult { stdout, stderr })
609}
610
611fn parse_status(output: &str) -> GitResult<GitStatus> {
612    let mut status = GitStatus {
613        branch: None,
614        upstream: None,
615        ahead: 0,
616        behind: 0,
617        entries: Vec::new(),
618        conflicts: Vec::new(),
619    };
620    let records = output.split('\0').collect::<Vec<_>>();
621    let mut index = 0;
622    while index < records.len() {
623        let record = records[index];
624        index += 1;
625        if let Some(branch) = record.strip_prefix("# branch.head ") {
626            status.branch = (branch != "(detached)").then(|| branch.to_string());
627        } else if let Some(upstream) = record.strip_prefix("# branch.upstream ") {
628            status.upstream = Some(upstream.to_string());
629        } else if let Some(ab) = record.strip_prefix("# branch.ab ") {
630            for value in ab.split_whitespace() {
631                if let Some(value) = value.strip_prefix('+') {
632                    status.ahead = value.parse().unwrap_or(0);
633                } else if let Some(value) = value.strip_prefix('-') {
634                    status.behind = value.parse().unwrap_or(0);
635                }
636            }
637        } else if let Some(path) = record.strip_prefix("? ") {
638            status.entries.push(GitStatusEntry {
639                path: path.to_string(),
640                original_path: None,
641                index_status: '?',
642                worktree_status: '?',
643                untracked: true,
644            });
645        } else if record.starts_with("1 ") {
646            let fields = record.splitn(9, ' ').collect::<Vec<_>>();
647            if fields.len() < 9 {
648                return Err(GitError::Command {
649                    operation: "parse status".into(),
650                    detail: "Git returned a malformed status record".into(),
651                });
652            }
653            let xy = fields[1].as_bytes();
654            status.entries.push(GitStatusEntry {
655                path: fields[8].to_string(),
656                original_path: None,
657                index_status: porcelain_flag(xy.first().copied()),
658                worktree_status: porcelain_flag(xy.get(1).copied()),
659                untracked: false,
660            });
661        } else if record.starts_with("u ") {
662            let fields = record.splitn(11, ' ').collect::<Vec<_>>();
663            if fields.len() < 11 {
664                return Err(GitError::Command {
665                    operation: "parse status".into(),
666                    detail: "Git returned a malformed unmerged status record".into(),
667                });
668            }
669            let xy = fields[1].as_bytes();
670            let path = fields[10].to_string();
671            status.conflicts.push(path.clone());
672            status.entries.push(GitStatusEntry {
673                path,
674                original_path: None,
675                index_status: xy.first().copied().unwrap_or(b'.') as char,
676                worktree_status: xy.get(1).copied().unwrap_or(b'.') as char,
677                untracked: false,
678            });
679        } else if record.starts_with("2 ") {
680            let fields = record.splitn(10, ' ').collect::<Vec<_>>();
681            if fields.len() < 10 || index >= records.len() {
682                return Err(GitError::Command {
683                    operation: "parse status".into(),
684                    detail: "Git returned a malformed rename record".into(),
685                });
686            }
687            let xy = fields[1].as_bytes();
688            let original_path = records[index].to_string();
689            index += 1;
690            status.entries.push(GitStatusEntry {
691                path: fields[9].to_string(),
692                original_path: Some(original_path),
693                index_status: porcelain_flag(xy.first().copied()),
694                worktree_status: porcelain_flag(xy.get(1).copied()),
695                untracked: false,
696            });
697        }
698    }
699    Ok(status)
700}
701
702fn porcelain_flag(flag: Option<u8>) -> char {
703    match flag.unwrap_or(b'.') {
704        b'.' => ' ',
705        other => other as char,
706    }
707}
708
709fn parse_worktrees(output: &str) -> GitResult<Vec<GitWorktree>> {
710    let mut worktrees = Vec::new();
711    let mut current: Option<GitWorktree> = None;
712    for field in output.split('\0') {
713        if field.is_empty() {
714            if let Some(item) = current.take() {
715                worktrees.push(item);
716            }
717        } else if let Some(path) = field.strip_prefix("worktree ") {
718            if let Some(item) = current.take() {
719                worktrees.push(item);
720            }
721            current = Some(GitWorktree {
722                path: PathBuf::from(path),
723                head: None,
724                branch: None,
725                bare: false,
726                detached: false,
727                locked: false,
728                prunable: false,
729            });
730        } else if let Some(item) = current.as_mut() {
731            if let Some(head) = field.strip_prefix("HEAD ") {
732                item.head = Some(head.to_string());
733            } else if let Some(branch) = field.strip_prefix("branch ") {
734                item.branch = Some(branch.trim_start_matches("refs/heads/").to_string());
735            } else {
736                match field.split_whitespace().next().unwrap_or_default() {
737                    "bare" => item.bare = true,
738                    "detached" => item.detached = true,
739                    "locked" => item.locked = true,
740                    "prunable" => item.prunable = true,
741                    _ => {}
742                }
743            }
744        }
745    }
746    if let Some(item) = current {
747        worktrees.push(item);
748    }
749    if worktrees
750        .iter()
751        .any(|item| item.path.as_os_str().is_empty())
752    {
753        return Err(GitError::Command {
754            operation: "parse worktrees".into(),
755            detail: "Git returned an empty worktree path".into(),
756        });
757    }
758    Ok(worktrees)
759}
760
761fn validate_paths(paths: &[String]) -> GitResult<Vec<String>> {
762    if paths.is_empty() || paths.len() > 1024 {
763        return Err(GitError::InvalidInput(
764            "Git path operations require 1..=1024 paths".into(),
765        ));
766    }
767    paths
768        .iter()
769        .map(|path| validate_relative_path(path))
770        .collect()
771}
772
773fn validate_relative_path(path: &str) -> GitResult<String> {
774    let candidate = Path::new(path);
775    let rooted = candidate.components().any(|part| {
776        matches!(
777            part,
778            std::path::Component::Prefix(_) | std::path::Component::RootDir
779        )
780    });
781    if path.is_empty()
782        || path.len() > 4096
783        || rooted
784        || candidate
785            .components()
786            .any(|part| matches!(part, std::path::Component::ParentDir))
787    {
788        return Err(GitError::InvalidInput(format!(
789            "Git path must be relative and remain in the repository: {path}"
790        )));
791    }
792    Ok(path.to_string())
793}
794
795fn validate_ref(reference: &str) -> GitResult<()> {
796    if reference.is_empty()
797        || reference.len() > 1024
798        || reference.starts_with('-')
799        || reference.chars().any(char::is_whitespace)
800    {
801        return Err(GitError::InvalidInput(
802            "Git reference must be non-empty, bounded, contain no whitespace, and not start with '-'"
803                .into(),
804        ));
805    }
806    Ok(())
807}
808
809fn absolute_worktree_path(path: &Path) -> GitResult<PathBuf> {
810    if !path.is_absolute() || path == Path::new("/") {
811        return Err(GitError::InvalidInput(
812            "worktree path must be an explicit absolute path".into(),
813        ));
814    }
815    Ok(path.to_path_buf())
816}
817
818#[cfg(test)]
819mod tests {
820    use super::*;
821    use std::sync::atomic::{AtomicU64, Ordering};
822
823    static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
824
825    #[test]
826    fn porcelain_v2_dot_means_unstaged_not_staged() {
827        let status = parse_status(
828            "# branch.head main\x001 .M N... 100644 100644 100644 0 0 notes.txt\x00? extra.rs\x00",
829        )
830        .unwrap();
831        assert_eq!(status.entries[0].index_status, ' ');
832        assert_eq!(status.entries[0].worktree_status, 'M');
833        assert!(!status.entries[0].untracked);
834    }
835
836    #[test]
837    fn sorted_entries_rank_conflicts_before_unstaged_and_untracked() {
838        let status = GitStatus {
839            branch: Some("main".into()),
840            upstream: None,
841            ahead: 0,
842            behind: 0,
843            entries: vec![
844                GitStatusEntry {
845                    path: "new.rs".into(),
846                    original_path: None,
847                    index_status: '?',
848                    worktree_status: '?',
849                    untracked: true,
850                },
851                GitStatusEntry {
852                    path: "staged.rs".into(),
853                    original_path: None,
854                    index_status: 'M',
855                    worktree_status: ' ',
856                    untracked: false,
857                },
858                GitStatusEntry {
859                    path: "conflict.rs".into(),
860                    original_path: None,
861                    index_status: 'U',
862                    worktree_status: 'U',
863                    untracked: false,
864                },
865                GitStatusEntry {
866                    path: "unstaged.rs".into(),
867                    original_path: None,
868                    index_status: ' ',
869                    worktree_status: 'M',
870                    untracked: false,
871                },
872            ],
873            conflicts: vec!["conflict.rs".into()],
874        };
875        let order = status
876            .sorted_entries()
877            .into_iter()
878            .map(|entry| entry.path)
879            .collect::<Vec<_>>();
880        assert_eq!(
881            order,
882            vec!["conflict.rs", "unstaged.rs", "staged.rs", "new.rs"]
883        );
884    }
885
886    fn repository() -> PathBuf {
887        let sequence = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
888        let root = std::env::temp_dir().join(format!(
889            "glass-git-service-{}-{sequence}",
890            std::process::id()
891        ));
892        std::fs::create_dir_all(&root).unwrap();
893        for arguments in [
894            vec!["init", "-q"],
895            vec!["config", "user.name", "Glass Test"],
896            vec!["config", "user.email", "glass@example.invalid"],
897        ] {
898            assert!(
899                Command::new("git")
900                    .args(arguments)
901                    .current_dir(&root)
902                    .status()
903                    .unwrap()
904                    .success()
905            );
906        }
907        root
908    }
909
910    #[test]
911    fn git_service_tracks_stage_commit_diff_branch_and_blame() {
912        let root = repository();
913        std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
914        let service = GitService::open(&root).unwrap();
915        let status = service.status().unwrap();
916        assert!(status.entries.iter().any(|entry| entry.path == "main.rs"));
917
918        service.stage(&["main.rs".into()]).unwrap();
919        let commit = service.commit("test: initialize fixture").unwrap();
920        assert_eq!(commit.subject, "test: initialize fixture");
921        assert!(
922            service
923                .blame("main.rs", 1, 1)
924                .unwrap()
925                .contains("Glass Test")
926        );
927
928        std::fs::write(root.join("main.rs"), "fn main() { println!(\"ok\"); }\n").unwrap();
929        assert!(
930            service
931                .diff(false, Some("main.rs"))
932                .unwrap()
933                .contains("println")
934        );
935        service.discard(&["main.rs".into()]).unwrap();
936        assert!(
937            !service
938                .diff(false, Some("main.rs"))
939                .unwrap()
940                .contains("println")
941        );
942        service.create_branch("fixture-branch", None).unwrap();
943        assert!(
944            service
945                .branches()
946                .unwrap()
947                .iter()
948                .any(|branch| branch.name == "fixture-branch")
949        );
950        assert!(service.conflicts().unwrap().is_empty());
951        assert_eq!(service.worktrees().unwrap().len(), 1);
952
953        std::fs::remove_dir_all(root).unwrap();
954    }
955
956    #[test]
957    fn git_paths_and_references_fail_closed() {
958        assert!(validate_relative_path("src/main.rs").is_ok());
959        assert!(validate_relative_path("../escape").is_err());
960        assert!(validate_relative_path("/absolute").is_err());
961        assert!(validate_ref("--upload-pack=bad").is_err());
962        let root = repository();
963        let service = GitService::open(&root).unwrap();
964        assert!(service.push(Some("--upload-pack=bad"), None).is_err());
965        assert!(absolute_worktree_path(Path::new("relative")).is_err());
966        std::fs::remove_dir_all(root).unwrap();
967    }
968
969    #[cfg(unix)]
970    #[test]
971    fn worktree_removal_accepts_a_canonical_path_alias() {
972        use std::os::unix::fs::symlink;
973
974        let root = repository();
975        std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
976        let service = GitService::open(&root).unwrap();
977        service.stage(&["main.rs".into()]).unwrap();
978        service.commit("test: initialize fixture").unwrap();
979
980        let worktree = root.with_extension("worktree");
981        let alias = root.with_extension("worktree-alias");
982        service
983            .create_worktree(&worktree, "canonical-alias", true)
984            .unwrap();
985        symlink(&worktree, &alias).unwrap();
986
987        service.remove_worktree(&alias, true).unwrap();
988        assert!(!worktree.exists());
989
990        std::fs::remove_file(alias).unwrap();
991        std::fs::remove_dir_all(root).unwrap();
992    }
993
994    #[test]
995    fn status_parser_handles_branch_untracked_and_rename_records() {
996        let parsed = parse_status(concat!(
997            "# branch.head main\0",
998            "# branch.upstream origin/main\0",
999            "# branch.ab +2 -1\0",
1000            "? new.txt\0",
1001            "2 R. N... 100644 100644 100644 a b R100 renamed.txt\0old.txt\0",
1002        ))
1003        .unwrap();
1004        assert_eq!(parsed.branch.as_deref(), Some("main"));
1005        assert_eq!(parsed.upstream.as_deref(), Some("origin/main"));
1006        assert_eq!((parsed.ahead, parsed.behind), (2, 1));
1007        assert_eq!(parsed.entries.len(), 2);
1008        assert_eq!(parsed.entries[1].original_path.as_deref(), Some("old.txt"));
1009    }
1010
1011    #[test]
1012    fn status_parser_keeps_unmerged_conflict_paths() {
1013        let parsed = parse_status(concat!(
1014            "# branch.head main\0",
1015            "u UU N... 100644 100644 100644 100644 a b c conflicted.txt\0",
1016        ))
1017        .unwrap();
1018        assert_eq!(parsed.conflicts, vec!["conflicted.txt"]);
1019        assert_eq!(parsed.entries[0].path, "conflicted.txt");
1020        assert_eq!(parsed.entries[0].index_status, 'U');
1021        assert_eq!(parsed.entries[0].worktree_status, 'U');
1022    }
1023
1024    #[test]
1025    fn git_service_stays_in_the_opened_workspace_directory() {
1026        let root = repository();
1027        std::fs::create_dir_all(root.join("nested")).unwrap();
1028        std::fs::write(root.join("root.rs"), "fn root() {}\n").unwrap();
1029        std::fs::write(root.join("nested/lib.rs"), "fn nested() {}\n").unwrap();
1030        let service = GitService::open(root.join("nested")).unwrap();
1031        assert_eq!(service.root(), root.join("nested").canonicalize().unwrap());
1032        service.stage(&["lib.rs".into()]).unwrap();
1033        let status = service.status().unwrap();
1034        assert!(
1035            status.entries.iter().any(|entry| {
1036                entry.path.contains("lib.rs") && entry.index_status != '?' && !entry.untracked
1037            }),
1038            "Git mutations must apply inside the opened workspace, got {status:?}"
1039        );
1040        std::fs::remove_dir_all(root).unwrap();
1041    }
1042
1043    #[cfg(unix)]
1044    #[test]
1045    fn git_status_does_not_execute_repository_aliases() {
1046        let root = repository();
1047        std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
1048        assert!(
1049            Command::new("git")
1050                .args(["config", "alias.status", "!touch pwned"])
1051                .current_dir(&root)
1052                .status()
1053                .unwrap()
1054                .success()
1055        );
1056        let service = GitService::open(&root).unwrap();
1057        service.status().unwrap();
1058        assert!(
1059            !root.join("pwned").exists(),
1060            "repository Git aliases must not run"
1061        );
1062        std::fs::remove_dir_all(root).unwrap();
1063    }
1064}