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 =
25        if git_common_dir.file_name().is_some_and(|n| n == ".git") {
26            git_common_dir.parent()?.to_path_buf()
27        } else {
28            return None;
29        };
30    master_root
31        .file_name()
32        .and_then(|name| name.to_str())
33        .map(|name| name.to_string())
34}
35
36/// Run `git rev-parse` with the given arguments and return the output as a path.
37///
38/// Returns `None` if git is not available, the command fails, or the output is empty.
39///
40/// Strips inherited `GIT_*` routing vars before spawning so the git
41/// invocation resolves the repository from its own cwd/args, not from
42/// the parent hook or CI environment. See `nb-api:issues/3`.
43pub fn git_rev_parse(args: &[&str]) -> Option<PathBuf> {
44    git_rev_parse_in(Path::new("."), args)
45}
46
47/// `git rev-parse` with an explicit working directory.
48pub fn git_rev_parse_in(cwd: &Path, args: &[&str]) -> Option<PathBuf> {
49    let output = git_capture(cwd, &{
50        let mut v = vec!["rev-parse".to_string()];
51        v.extend(args.iter().map(|s| (*s).to_string()));
52        v
53    })
54    .ok()?;
55    let value = output.trim();
56    if value.is_empty() {
57        return None;
58    }
59    Some(PathBuf::from(value))
60}
61
62/// Run git in `cwd` with scrubbed `GIT_*` routing vars. Returns stdout on success.
63pub fn git_capture(cwd: &Path, args: &[String]) -> Result<String, NbError> {
64    let mut command = Command::new("git");
65    crate::git_env::scrub_git_env_std(&mut command);
66    // Preserve fixture git identity / signing overrides after scrub.
67    if let Ok(v) = std::env::var("GIT_AUTHOR_NAME") {
68        command.env("GIT_AUTHOR_NAME", v);
69    }
70    if let Ok(v) = std::env::var("GIT_AUTHOR_EMAIL") {
71        command.env("GIT_AUTHOR_EMAIL", v);
72    }
73    if let Ok(v) = std::env::var("GIT_COMMITTER_NAME") {
74        command.env("GIT_COMMITTER_NAME", v);
75    }
76    if let Ok(v) = std::env::var("GIT_COMMITTER_EMAIL") {
77        command.env("GIT_COMMITTER_EMAIL", v);
78    }
79    command.current_dir(cwd);
80    command.args(args);
81    let joined = format!("git {}", args.join(" "));
82    let output = command.output().map_err(|e| {
83        if e.kind() == std::io::ErrorKind::NotFound {
84            NbError::ExecutableNotFound {
85                path: "git".to_string(),
86            }
87        } else {
88            NbError::Io {
89                path: cwd.to_path_buf(),
90                source: e.into(),
91            }
92        }
93    })?;
94    if output.status.success() {
95        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
96    } else {
97        let stderr = String::from_utf8_lossy(&output.stderr);
98        let stdout = String::from_utf8_lossy(&output.stdout);
99        let stderr_text = if stderr.is_empty() {
100            stdout.into_owned()
101        } else {
102            stderr.into_owned()
103        };
104        Err(NbError::CommandFailed {
105            command: joined,
106            stderr: stderr_text,
107            exit_code: output.status.code(),
108        })
109    }
110}
111
112/// HEAD revision (`git rev-parse HEAD`) for a notebook worktree.
113pub fn notebook_head(notebook_root: &Path) -> Result<String, NbError> {
114    let out =
115        git_capture(notebook_root, &["rev-parse".into(), "HEAD".into()])?;
116    let rev = out.trim().to_string();
117    if rev.is_empty() {
118        return Err(NbError::CommandFailed {
119            command: "git rev-parse HEAD".into(),
120            stderr: "empty HEAD".into(),
121            exit_code: None,
122        });
123    }
124    Ok(rev)
125}
126
127/// True when `git status --porcelain` is non-empty (any dirty state).
128pub fn notebook_is_dirty(notebook_root: &Path) -> Result<bool, NbError> {
129    let out = git_capture(
130        notebook_root,
131        &[
132            "status".into(),
133            "--porcelain".into(),
134            "-uall".into(),
135            "--ignored=no".into(),
136        ],
137    )?;
138    if !out.trim().is_empty() {
139        return Ok(true);
140    }
141    // Belt-and-suspenders: unstaged or staged diffs against HEAD.
142    let mut command = Command::new("git");
143    crate::git_env::scrub_git_env_std(&mut command);
144    command.current_dir(notebook_root);
145    command.args(["diff-index", "--quiet", "HEAD", "--"]);
146    let status = command.status().map_err(|e| NbError::Io {
147        path: notebook_root.to_path_buf(),
148        source: e.into(),
149    })?;
150    match status.code() {
151        Some(0) => Ok(false),
152        Some(1) => Ok(true),
153        _ => Err(NbError::CommandFailed {
154            command: "git diff-index --quiet HEAD --".into(),
155            stderr: format!("unexpected exit {status}"),
156            exit_code: status.code(),
157        }),
158    }
159}
160
161/// True when `git status --porcelain` output shows dirt consisting
162/// solely of tracked `.index` modifications (root or nested).
163///
164/// Reviewer-confirmed safety case, stated verbatim: with porcelain
165/// `-uall --ignored=no` plus the `diff-index` belt-and-suspenders in
166/// `notebook_is_dirty`, index-only dirt implies no uncommitted note
167/// bytes and no untracked files — and the transaction's own
168/// `git add -A` checkpoint absorbs the reconciliation. Tolerated
169/// forms are `M `/` M`/`MM` on paths whose basename is `.index`.
170/// Never tolerated: untracked files (including a live
171/// `.nb-api-index.lock`, whose presence means a concurrent writer
172/// holds the notebook — tolerating it would break mutual
173/// exclusion), deletions, renames, or anything else.
174pub(crate) fn status_is_index_only(status: &str) -> bool {
175    let mut saw_any = false;
176    for line in status.lines() {
177        saw_any = true;
178        // Porcelain v1: two XY columns, a space, then the path.
179        // The three-byte ASCII prefix guarantees index 3 is a
180        // char boundary for the path slice.
181        if line.len() < 4 || line.as_bytes()[2] != b' ' {
182            return false;
183        }
184        let (xy, path) = (&line[..2], line[3..].trim());
185        if xy != "M " && xy != " M" && xy != "MM" {
186            return false;
187        }
188        let path = path.trim();
189        let path = path
190            .strip_prefix('"')
191            .and_then(|p| p.strip_suffix('"'))
192            .unwrap_or(path);
193        if path.is_empty() {
194            return false;
195        }
196        let base = path.rsplit('/').next().unwrap_or(path);
197        if base != ".index" {
198            return false;
199        }
200    }
201    saw_any
202}
203
204/// Concise porcelain status for recovery errors.
205///
206/// Only trailing whitespace is trimmed: leading XY columns are
207/// significant (a leading space marks an unstaged-only entry),
208/// so callers that classify dirt must see them intact.
209pub fn notebook_status_porcelain(
210    notebook_root: &Path,
211) -> Result<String, NbError> {
212    git_capture(
213        notebook_root,
214        &["status".into(), "--porcelain".into(), "-uall".into()],
215    )
216    .map(|s| s.trim_end().to_string())
217}
218
219/// Stage paths and create one commit. Returns `Ok(true)` if a commit was
220/// created, `Ok(false)` if there was nothing to commit (pure no-op tree).
221///
222/// `force_paths` are always `git add -f`'d so transaction-owned outputs that
223/// match ignore rules (e.g. `.gitkeep`, new ignored filenames) enter the
224/// checkpoint. Pre-existing ignored mutators must be rejected before calling.
225///
226/// When the `testing` feature is enabled, `NB_API_FAIL_AFTER_STAGE=1` makes
227/// this return an error after staging (for rollback isolation regressions).
228pub fn notebook_commit_all(
229    notebook_root: &Path,
230    message: &str,
231    force_paths: &[String],
232) -> Result<bool, NbError> {
233    git_capture(notebook_root, &["add".into(), "-A".into()])?;
234    for rel in force_paths {
235        // `-f` stages ignored paths; missing paths are skipped (delete cases).
236        let abs = notebook_root.join(rel);
237        if abs.is_file() {
238            git_capture(
239                notebook_root,
240                &["add".into(), "-f".into(), "--".into(), rel.clone()],
241            )?;
242        }
243    }
244    #[cfg(feature = "testing")]
245    if std::env::var_os("NB_API_FAIL_AFTER_STAGE").is_some() {
246        return Err(NbError::CommandFailed {
247            command: "nb-api://fail-after-stage".into(),
248            stderr: "injected staging failure for rollback tests".into(),
249            exit_code: Some(1),
250        });
251    }
252    // Detect empty commit: diff --cached --quiet exits 1 when there are staged changes.
253    let mut command = Command::new("git");
254    crate::git_env::scrub_git_env_std(&mut command);
255    command.current_dir(notebook_root);
256    command.args(["diff", "--cached", "--quiet"]);
257    let status = command.status().map_err(|e| NbError::Io {
258        path: notebook_root.to_path_buf(),
259        source: e.into(),
260    })?;
261    // exit 0 = no staged diff; exit 1 = has staged changes; other = error
262    match status.code() {
263        Some(0) => Ok(false),
264        Some(1) => {
265            git_capture(
266                notebook_root,
267                &[
268                    "commit".into(),
269                    "-m".into(),
270                    message.to_string(),
271                    "--no-gpg-sign".into(),
272                ],
273            )?;
274            Ok(true)
275        },
276        _ => Err(NbError::CommandFailed {
277            command: "git diff --cached --quiet".into(),
278            stderr: format!("unexpected exit {status}"),
279            exit_code: status.code(),
280        }),
281    }
282}
283
284/// Hard-reset worktree/index to `revision` and remove untracked files.
285pub fn notebook_reset_clean(
286    notebook_root: &Path,
287    revision: &str,
288) -> Result<(), NbError> {
289    git_capture(
290        notebook_root,
291        &["reset".into(), "--hard".into(), revision.to_string()],
292    )?;
293    git_capture(notebook_root, &["clean".into(), "-fd".into()])?;
294    Ok(())
295}
296
297/// List tracked + untracked (non-ignored) notebook-relative paths, excluding `.git`.
298pub fn list_notebook_paths(
299    notebook_root: &Path,
300) -> Result<Vec<String>, NbError> {
301    let mut paths = Vec::new();
302    let tracked =
303        git_capture(notebook_root, &["ls-files".into(), "-z".into()])?;
304    for p in tracked.split('\0') {
305        if !p.is_empty() {
306            paths.push(p.to_string());
307        }
308    }
309    let untracked = git_capture(
310        notebook_root,
311        &[
312            "ls-files".into(),
313            "--others".into(),
314            "--exclude-standard".into(),
315            "-z".into(),
316        ],
317    )?;
318    for p in untracked.split('\0') {
319        if !p.is_empty() && !paths.iter().any(|e| e == p) {
320            paths.push(p.to_string());
321        }
322    }
323    // Also include empty directories that exist on disk (folders).
324    fn walk_dirs(
325        base: &Path,
326        rel: &Path,
327        out: &mut Vec<String>,
328    ) -> Result<(), NbError> {
329        let entries = std::fs::read_dir(base).map_err(|e| NbError::Io {
330            path: base.to_path_buf(),
331            source: e.into(),
332        })?;
333        for entry in entries {
334            let entry = entry.map_err(|e| NbError::Io {
335                path: base.to_path_buf(),
336                source: e.into(),
337            })?;
338            let name = entry.file_name();
339            if name == ".git" {
340                continue;
341            }
342            let file_type = entry.file_type().map_err(|e| NbError::Io {
343                path: entry.path(),
344                source: e.into(),
345            })?;
346            if file_type.is_dir() {
347                let child_rel = rel.join(&name);
348                // Platform-scoped: on Windows the disk form uses
349                // `\` separators, which are normalized here. On
350                // Unix a backslash is an ordinary filename
351                // character (e.g. a literal `a\b` directory) and
352                // must be preserved verbatim.
353                let rel_str = {
354                    let s = child_rel.to_string_lossy();
355                    #[cfg(windows)]
356                    {
357                        s.replace('\\', "/")
358                    }
359                    #[cfg(not(windows))]
360                    {
361                        s.into_owned()
362                    }
363                };
364                if !out.iter().any(|p| {
365                    p == &rel_str || p.starts_with(&format!("{rel_str}/"))
366                }) {
367                    out.push(rel_str);
368                }
369                walk_dirs(&entry.path(), &child_rel, out)?;
370            }
371        }
372        Ok(())
373    }
374    walk_dirs(notebook_root, Path::new(""), &mut paths)?;
375    Ok(paths)
376}
377
378/// Existing ignored paths on disk (not part of the editable virtual tree).
379pub fn list_ignored_paths(
380    notebook_root: &Path,
381) -> Result<Vec<String>, NbError> {
382    let ignored = git_capture(
383        notebook_root,
384        &[
385            "ls-files".into(),
386            "--others".into(),
387            "--ignored".into(),
388            "--exclude-standard".into(),
389            "-z".into(),
390        ],
391    )?;
392    let mut paths = Vec::new();
393    for p in ignored.split('\0') {
394        if !p.is_empty() {
395            paths.push(p.to_string());
396        }
397    }
398    Ok(paths)
399}