Skip to main content

nb_api/
git.rs

1//! Git repository detection and notebook-repo helpers.
2//!
3//! Consumed by `nb-api` directly and by downstream tools (e.g.,
4//! `nb-mcp-server`'s `paths.rs`) via the published crate.
5
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use crate::error::NbError;
10
11/// Derive the notebook name from the current Git repository.
12///
13/// Returns the directory name of the master repository (not the worktree).
14/// Used as a fallback when no explicit notebook name is configured.
15pub fn derive_git_notebook_name() -> Option<String> {
16    let current_root = git_rev_parse(&["--show-toplevel"])?;
17    let git_common_dir = git_rev_parse(&["--git-common-dir"])?;
18    let git_common_dir = if git_common_dir.is_relative() {
19        current_root.join(&git_common_dir)
20    } else {
21        git_common_dir
22    };
23    let git_common_dir = git_common_dir.canonicalize().ok()?;
24    let master_root = if git_common_dir.file_name().is_some_and(|n| n == ".git") {
25        git_common_dir.parent()?.to_path_buf()
26    } else {
27        return None;
28    };
29    master_root
30        .file_name()
31        .and_then(|name| name.to_str())
32        .map(|name| name.to_string())
33}
34
35/// Run `git rev-parse` with the given arguments and return the output as a path.
36///
37/// Returns `None` if git is not available, the command fails, or the output is empty.
38///
39/// Strips inherited `GIT_*` routing vars before spawning so the git
40/// invocation resolves the repository from its own cwd/args, not from
41/// the parent hook or CI environment. See `nb-api:issues/3`.
42pub fn git_rev_parse(args: &[&str]) -> Option<PathBuf> {
43    git_rev_parse_in(Path::new("."), args)
44}
45
46/// `git rev-parse` with an explicit working directory.
47pub fn git_rev_parse_in(cwd: &Path, args: &[&str]) -> Option<PathBuf> {
48    let output = git_capture(cwd, &{
49        let mut v = vec!["rev-parse".to_string()];
50        v.extend(args.iter().map(|s| (*s).to_string()));
51        v
52    })
53    .ok()?;
54    let value = output.trim();
55    if value.is_empty() {
56        return None;
57    }
58    Some(PathBuf::from(value))
59}
60
61/// Run git in `cwd` with scrubbed `GIT_*` routing vars. Returns stdout on success.
62pub fn git_capture(cwd: &Path, args: &[String]) -> Result<String, NbError> {
63    let mut command = Command::new("git");
64    crate::git_env::scrub_git_env_std(&mut command);
65    // Preserve fixture git identity / signing overrides after scrub.
66    if let Ok(v) = std::env::var("GIT_AUTHOR_NAME") {
67        command.env("GIT_AUTHOR_NAME", v);
68    }
69    if let Ok(v) = std::env::var("GIT_AUTHOR_EMAIL") {
70        command.env("GIT_AUTHOR_EMAIL", v);
71    }
72    if let Ok(v) = std::env::var("GIT_COMMITTER_NAME") {
73        command.env("GIT_COMMITTER_NAME", v);
74    }
75    if let Ok(v) = std::env::var("GIT_COMMITTER_EMAIL") {
76        command.env("GIT_COMMITTER_EMAIL", v);
77    }
78    command.current_dir(cwd);
79    command.args(args);
80    let joined = format!("git {}", args.join(" "));
81    let output = command.output().map_err(|e| {
82        if e.kind() == std::io::ErrorKind::NotFound {
83            NbError::ExecutableNotFound {
84                path: "git".to_string(),
85            }
86        } else {
87            NbError::Io {
88                path: cwd.to_path_buf(),
89                source: e.into(),
90            }
91        }
92    })?;
93    if output.status.success() {
94        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
95    } else {
96        let stderr = String::from_utf8_lossy(&output.stderr);
97        let stdout = String::from_utf8_lossy(&output.stdout);
98        let stderr_text = if stderr.is_empty() {
99            stdout.into_owned()
100        } else {
101            stderr.into_owned()
102        };
103        Err(NbError::CommandFailed {
104            command: joined,
105            stderr: stderr_text,
106            exit_code: output.status.code(),
107        })
108    }
109}
110
111/// HEAD revision (`git rev-parse HEAD`) for a notebook worktree.
112pub fn notebook_head(notebook_root: &Path) -> Result<String, NbError> {
113    let out = git_capture(notebook_root, &["rev-parse".into(), "HEAD".into()])?;
114    let rev = out.trim().to_string();
115    if rev.is_empty() {
116        return Err(NbError::CommandFailed {
117            command: "git rev-parse HEAD".into(),
118            stderr: "empty HEAD".into(),
119            exit_code: None,
120        });
121    }
122    Ok(rev)
123}
124
125/// True when `git status --porcelain` is non-empty (any dirty state).
126pub fn notebook_is_dirty(notebook_root: &Path) -> Result<bool, NbError> {
127    let out = git_capture(
128        notebook_root,
129        &[
130            "status".into(),
131            "--porcelain".into(),
132            "-uall".into(),
133            "--ignored=no".into(),
134        ],
135    )?;
136    if !out.trim().is_empty() {
137        return Ok(true);
138    }
139    // Belt-and-suspenders: unstaged or staged diffs against HEAD.
140    let mut command = Command::new("git");
141    crate::git_env::scrub_git_env_std(&mut command);
142    command.current_dir(notebook_root);
143    command.args(["diff-index", "--quiet", "HEAD", "--"]);
144    let status = command.status().map_err(|e| NbError::Io {
145        path: notebook_root.to_path_buf(),
146        source: e.into(),
147    })?;
148    match status.code() {
149        Some(0) => Ok(false),
150        Some(1) => Ok(true),
151        _ => Err(NbError::CommandFailed {
152            command: "git diff-index --quiet HEAD --".into(),
153            stderr: format!("unexpected exit {status}"),
154            exit_code: status.code(),
155        }),
156    }
157}
158
159/// Concise porcelain status for recovery errors.
160pub fn notebook_status_porcelain(notebook_root: &Path) -> Result<String, NbError> {
161    git_capture(
162        notebook_root,
163        &["status".into(), "--porcelain".into(), "-uall".into()],
164    )
165    .map(|s| s.trim().to_string())
166}
167
168/// Stage paths and create one commit. Returns `Ok(true)` if a commit was
169/// created, `Ok(false)` if there was nothing to commit (pure no-op tree).
170///
171/// `force_paths` are always `git add -f`'d so transaction-owned outputs that
172/// match ignore rules (e.g. `.gitkeep`, new ignored filenames) enter the
173/// checkpoint. Pre-existing ignored mutators must be rejected before calling.
174///
175/// When the `testing` feature is enabled, `NB_API_FAIL_AFTER_STAGE=1` makes
176/// this return an error after staging (for rollback isolation regressions).
177pub fn notebook_commit_all(
178    notebook_root: &Path,
179    message: &str,
180    force_paths: &[String],
181) -> Result<bool, NbError> {
182    git_capture(notebook_root, &["add".into(), "-A".into()])?;
183    for rel in force_paths {
184        // `-f` stages ignored paths; missing paths are skipped (delete cases).
185        let abs = notebook_root.join(rel);
186        if abs.is_file() {
187            git_capture(
188                notebook_root,
189                &["add".into(), "-f".into(), "--".into(), rel.clone()],
190            )?;
191        }
192    }
193    #[cfg(feature = "testing")]
194    if std::env::var_os("NB_API_FAIL_AFTER_STAGE").is_some() {
195        return Err(NbError::CommandFailed {
196            command: "nb-api://fail-after-stage".into(),
197            stderr: "injected staging failure for rollback tests".into(),
198            exit_code: Some(1),
199        });
200    }
201    // Detect empty commit: diff --cached --quiet exits 1 when there are staged changes.
202    let mut command = Command::new("git");
203    crate::git_env::scrub_git_env_std(&mut command);
204    command.current_dir(notebook_root);
205    command.args(["diff", "--cached", "--quiet"]);
206    let status = command.status().map_err(|e| NbError::Io {
207        path: notebook_root.to_path_buf(),
208        source: e.into(),
209    })?;
210    // exit 0 = no staged diff; exit 1 = has staged changes; other = error
211    match status.code() {
212        Some(0) => Ok(false),
213        Some(1) => {
214            git_capture(
215                notebook_root,
216                &[
217                    "commit".into(),
218                    "-m".into(),
219                    message.to_string(),
220                    "--no-gpg-sign".into(),
221                ],
222            )?;
223            Ok(true)
224        }
225        _ => Err(NbError::CommandFailed {
226            command: "git diff --cached --quiet".into(),
227            stderr: format!("unexpected exit {status}"),
228            exit_code: status.code(),
229        }),
230    }
231}
232
233/// Hard-reset worktree/index to `revision` and remove untracked files.
234pub fn notebook_reset_clean(notebook_root: &Path, revision: &str) -> Result<(), NbError> {
235    git_capture(
236        notebook_root,
237        &["reset".into(), "--hard".into(), revision.to_string()],
238    )?;
239    git_capture(notebook_root, &["clean".into(), "-fd".into()])?;
240    Ok(())
241}
242
243/// List tracked + untracked (non-ignored) notebook-relative paths, excluding `.git`.
244pub fn list_notebook_paths(notebook_root: &Path) -> Result<Vec<String>, NbError> {
245    let mut paths = Vec::new();
246    let tracked = git_capture(notebook_root, &["ls-files".into(), "-z".into()])?;
247    for p in tracked.split('\0') {
248        if !p.is_empty() {
249            paths.push(p.to_string());
250        }
251    }
252    let untracked = git_capture(
253        notebook_root,
254        &[
255            "ls-files".into(),
256            "--others".into(),
257            "--exclude-standard".into(),
258            "-z".into(),
259        ],
260    )?;
261    for p in untracked.split('\0') {
262        if !p.is_empty() && !paths.iter().any(|e| e == p) {
263            paths.push(p.to_string());
264        }
265    }
266    // Also include empty directories that exist on disk (folders).
267    fn walk_dirs(base: &Path, rel: &Path, out: &mut Vec<String>) -> Result<(), NbError> {
268        let entries = std::fs::read_dir(base).map_err(|e| NbError::Io {
269            path: base.to_path_buf(),
270            source: e.into(),
271        })?;
272        for entry in entries {
273            let entry = entry.map_err(|e| NbError::Io {
274                path: base.to_path_buf(),
275                source: e.into(),
276            })?;
277            let name = entry.file_name();
278            if name == ".git" {
279                continue;
280            }
281            let file_type = entry.file_type().map_err(|e| NbError::Io {
282                path: entry.path(),
283                source: e.into(),
284            })?;
285            if file_type.is_dir() {
286                let child_rel = rel.join(&name);
287                let rel_str = child_rel.to_string_lossy().replace('\\', "/");
288                if !out
289                    .iter()
290                    .any(|p| p == &rel_str || p.starts_with(&format!("{rel_str}/")))
291                {
292                    out.push(rel_str);
293                }
294                walk_dirs(&entry.path(), &child_rel, out)?;
295            }
296        }
297        Ok(())
298    }
299    walk_dirs(notebook_root, Path::new(""), &mut paths)?;
300    Ok(paths)
301}
302
303/// Existing ignored paths on disk (not part of the editable virtual tree).
304pub fn list_ignored_paths(notebook_root: &Path) -> Result<Vec<String>, NbError> {
305    let ignored = git_capture(
306        notebook_root,
307        &[
308            "ls-files".into(),
309            "--others".into(),
310            "--ignored".into(),
311            "--exclude-standard".into(),
312            "-z".into(),
313        ],
314    )?;
315    let mut paths = Vec::new();
316    for p in ignored.split('\0') {
317        if !p.is_empty() {
318            paths.push(p.to_string());
319        }
320    }
321    Ok(paths)
322}