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 = 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
35pub fn git_rev_parse(args: &[&str]) -> Option<PathBuf> {
43 git_rev_parse_in(Path::new("."), args)
44}
45
46pub 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
61pub 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 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
111pub 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
125pub 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 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
159pub 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
168pub 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 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 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 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
233pub 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
243pub 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 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
303pub 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}