Skip to main content

rigspark_runtime/
workspace_git.rs

1use crate::workspace::WorkspaceError;
2use std::{path::Path, process::Stdio, time::Duration};
3use tokio::io::AsyncReadExt;
4
5pub struct GitOutput {
6    pub success: bool,
7    pub bytes: Vec<u8>,
8}
9pub trait GitRunner {
10    fn output(&self, root: &Path, mode: &str) -> Result<GitOutput, WorkspaceError>;
11}
12pub struct NativeGitRunner;
13impl GitRunner for NativeGitRunner {
14    fn output(&self, root: &Path, mode: &str) -> Result<GitOutput, WorkspaceError> {
15        if !["status", "diff"].contains(&mode) {
16            return Err(WorkspaceError("invalid git context mode".into()));
17        }
18        let root = root.to_owned();
19        let mode = mode.to_owned();
20        std::thread::spawn(move || {
21            let runtime = tokio::runtime::Builder::new_current_thread()
22                .enable_all()
23                .build()?;
24            runtime.block_on(async {
25                let binary = crate::process_control::resolve_binary("git")
26                    .map_err(|_| WorkspaceError("git unavailable".into()))?;
27                let mut command = tokio::process::Command::new(binary);
28                command.arg("-C").arg(&root).args([
29                    "--no-pager",
30                    "-c",
31                    "core.hooksPath=/dev/null",
32                    "-c",
33                    "core.fsmonitor=false",
34                ]);
35                if mode == "status" {
36                    command.args([
37                        "status",
38                        "--porcelain=v1",
39                        "--untracked-files=all",
40                        "--no-renames",
41                    ]);
42                } else {
43                    command.args(["diff", "--no-color", "--no-ext-diff", "--no-textconv"]);
44                }
45                let mut child = command
46                    .env_clear()
47                    .envs(crate::process_control::minimal_env())
48                    .env("GIT_TERMINAL_PROMPT", "0")
49                    .env("GIT_CONFIG_NOSYSTEM", "1")
50                    .env(
51                        "GIT_CONFIG_GLOBAL",
52                        if cfg!(windows) { "NUL" } else { "/dev/null" },
53                    )
54                    .stdin(Stdio::null())
55                    .stdout(Stdio::piped())
56                    .stderr(Stdio::null())
57                    .kill_on_drop(true)
58                    .spawn()?;
59                let stdout = child
60                    .stdout
61                    .take()
62                    .ok_or_else(|| WorkspaceError("missing git output".into()))?;
63                let operation = async {
64                    let mut bytes = Vec::new();
65                    stdout.take(409601).read_to_end(&mut bytes).await?;
66                    if bytes.len() > 409600 {
67                        let _ = child.start_kill();
68                    }
69                    let status = child.wait().await?;
70                    Ok::<_, WorkspaceError>(GitOutput {
71                        success: status.success(),
72                        bytes,
73                    })
74                };
75                match tokio::time::timeout(Duration::from_secs(5), operation).await {
76                    Ok(result) => result,
77                    Err(_) => {
78                        let _ = child.start_kill();
79                        let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
80                        Err(WorkspaceError("git context timed out".into()))
81                    }
82                }
83            })
84        })
85        .join()
86        .map_err(|_| WorkspaceError("git context task failed".into()))?
87    }
88}