1use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use crate::error::NbError;
10
11pub 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
36pub fn git_rev_parse(args: &[&str]) -> Option<PathBuf> {
44 git_rev_parse_in(Path::new("."), args)
45}
46
47pub 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
62pub 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 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
112pub 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
127pub 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 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
161pub(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 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
204pub 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
219pub 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 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 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 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
284pub 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
297pub 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 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 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
378pub 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}