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/// Concise porcelain status for recovery errors.
162pub fn notebook_status_porcelain(
163    notebook_root: &Path,
164) -> Result<String, NbError> {
165    git_capture(
166        notebook_root,
167        &["status".into(), "--porcelain".into(), "-uall".into()],
168    )
169    .map(|s| s.trim().to_string())
170}
171
172/// Stage paths and create one commit. Returns `Ok(true)` if a commit was
173/// created, `Ok(false)` if there was nothing to commit (pure no-op tree).
174///
175/// `force_paths` are always `git add -f`'d so transaction-owned outputs that
176/// match ignore rules (e.g. `.gitkeep`, new ignored filenames) enter the
177/// checkpoint. Pre-existing ignored mutators must be rejected before calling.
178///
179/// When the `testing` feature is enabled, `NB_API_FAIL_AFTER_STAGE=1` makes
180/// this return an error after staging (for rollback isolation regressions).
181pub fn notebook_commit_all(
182    notebook_root: &Path,
183    message: &str,
184    force_paths: &[String],
185) -> Result<bool, NbError> {
186    git_capture(notebook_root, &["add".into(), "-A".into()])?;
187    for rel in force_paths {
188        // `-f` stages ignored paths; missing paths are skipped (delete cases).
189        let abs = notebook_root.join(rel);
190        if abs.is_file() {
191            git_capture(
192                notebook_root,
193                &["add".into(), "-f".into(), "--".into(), rel.clone()],
194            )?;
195        }
196    }
197    #[cfg(feature = "testing")]
198    if std::env::var_os("NB_API_FAIL_AFTER_STAGE").is_some() {
199        return Err(NbError::CommandFailed {
200            command: "nb-api://fail-after-stage".into(),
201            stderr: "injected staging failure for rollback tests".into(),
202            exit_code: Some(1),
203        });
204    }
205    // Detect empty commit: diff --cached --quiet exits 1 when there are staged changes.
206    let mut command = Command::new("git");
207    crate::git_env::scrub_git_env_std(&mut command);
208    command.current_dir(notebook_root);
209    command.args(["diff", "--cached", "--quiet"]);
210    let status = command.status().map_err(|e| NbError::Io {
211        path: notebook_root.to_path_buf(),
212        source: e.into(),
213    })?;
214    // exit 0 = no staged diff; exit 1 = has staged changes; other = error
215    match status.code() {
216        Some(0) => Ok(false),
217        Some(1) => {
218            git_capture(
219                notebook_root,
220                &[
221                    "commit".into(),
222                    "-m".into(),
223                    message.to_string(),
224                    "--no-gpg-sign".into(),
225                ],
226            )?;
227            Ok(true)
228        },
229        _ => Err(NbError::CommandFailed {
230            command: "git diff --cached --quiet".into(),
231            stderr: format!("unexpected exit {status}"),
232            exit_code: status.code(),
233        }),
234    }
235}
236
237/// Hard-reset worktree/index to `revision` and remove untracked files.
238pub fn notebook_reset_clean(
239    notebook_root: &Path,
240    revision: &str,
241) -> Result<(), NbError> {
242    git_capture(
243        notebook_root,
244        &["reset".into(), "--hard".into(), revision.to_string()],
245    )?;
246    git_capture(notebook_root, &["clean".into(), "-fd".into()])?;
247    Ok(())
248}
249
250/// List tracked + untracked (non-ignored) notebook-relative paths, excluding `.git`.
251pub fn list_notebook_paths(
252    notebook_root: &Path,
253) -> Result<Vec<String>, NbError> {
254    let mut paths = Vec::new();
255    let tracked =
256        git_capture(notebook_root, &["ls-files".into(), "-z".into()])?;
257    for p in tracked.split('\0') {
258        if !p.is_empty() {
259            paths.push(p.to_string());
260        }
261    }
262    let untracked = git_capture(
263        notebook_root,
264        &[
265            "ls-files".into(),
266            "--others".into(),
267            "--exclude-standard".into(),
268            "-z".into(),
269        ],
270    )?;
271    for p in untracked.split('\0') {
272        if !p.is_empty() && !paths.iter().any(|e| e == p) {
273            paths.push(p.to_string());
274        }
275    }
276    // Also include empty directories that exist on disk (folders).
277    fn walk_dirs(
278        base: &Path,
279        rel: &Path,
280        out: &mut Vec<String>,
281    ) -> Result<(), NbError> {
282        let entries = std::fs::read_dir(base).map_err(|e| NbError::Io {
283            path: base.to_path_buf(),
284            source: e.into(),
285        })?;
286        for entry in entries {
287            let entry = entry.map_err(|e| NbError::Io {
288                path: base.to_path_buf(),
289                source: e.into(),
290            })?;
291            let name = entry.file_name();
292            if name == ".git" {
293                continue;
294            }
295            let file_type = entry.file_type().map_err(|e| NbError::Io {
296                path: entry.path(),
297                source: e.into(),
298            })?;
299            if file_type.is_dir() {
300                let child_rel = rel.join(&name);
301                let rel_str = child_rel.to_string_lossy().replace('\\', "/");
302                if !out.iter().any(|p| {
303                    p == &rel_str || p.starts_with(&format!("{rel_str}/"))
304                }) {
305                    out.push(rel_str);
306                }
307                walk_dirs(&entry.path(), &child_rel, out)?;
308            }
309        }
310        Ok(())
311    }
312    walk_dirs(notebook_root, Path::new(""), &mut paths)?;
313    Ok(paths)
314}
315
316/// Existing ignored paths on disk (not part of the editable virtual tree).
317pub fn list_ignored_paths(
318    notebook_root: &Path,
319) -> Result<Vec<String>, NbError> {
320    let ignored = git_capture(
321        notebook_root,
322        &[
323            "ls-files".into(),
324            "--others".into(),
325            "--ignored".into(),
326            "--exclude-standard".into(),
327            "-z".into(),
328        ],
329    )?;
330    let mut paths = Vec::new();
331    for p in ignored.split('\0') {
332        if !p.is_empty() {
333            paths.push(p.to_string());
334        }
335    }
336    Ok(paths)
337}