nb-api 0.4.0

Typed Rust interface to the nb note-taking CLI (subprocess wrapper: escaping, validation, output parsing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
//! Hermetic test fixtures for integration tests that exercise the `nb`
//! CLI.
//!
//! This module is gated behind the `testing` Cargo feature so that
//! test-only dependencies (notably [`tempfile`]) do not enter the
//! build graph of normal consumers. Enable with
//! `--features testing`; add `--features testing-tokio` to also reach
//! the async helpers ([`NbTestEnv::configure_tokio`],
//! [`NbTestEnv::nb_command_async`]).
//!
//! # Quick start
//!
//! ```no_run
//! # #[cfg(feature = "testing")]
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use nb_api::testing::NbTestEnv;
//!
//! let env = NbTestEnv::new()?;
//! let mut command = env.nb_command();
//! command.arg("notebooks");
//! let output = command.output()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Hermeticity
//!
//! The fixture owns an isolated [`NB_DIR`] (the data store where `nb`
//! writes notebooks) and a separate [`NbTestEnv::working_dir`]
//! (the execution cwd for spawned `nb` processes). Neither inherits
//! the caller's project-root CWD by default, though
//! [`NbTestEnvBuilder::working_directory`] can supply a caller-owned
//! path (the fixture then does not delete it on `Drop`). Cleanup
//! happens on `Drop`.
//!
//! Inherited `GIT_*` routing vars (`GIT_DIR`, `GIT_INDEX_FILE`,
//! `GIT_COMMON_DIR`, `GIT_WORK_TREE`, `GIT_OBJECT_DIRECTORY`,
//! `GIT_ALTERNATE_OBJECT_DIRECTORIES`) are stripped via
//! [`crate::git_env::scrub_git_env`] (or its `std` sibling) before
//! any intentional fixture overrides apply. See `nb-api:issues/3`.
//!
//! [`NB_DIR`]: https://github.com/xwmx/nb#environment-variables
//!
//! # `nb` binary resolution
//!
//! The fixture spawns the `nb` CLI during initialization via an
//! **absolute path** discovered once per process (see
//! [`nb_binary`]). Child processes receive a **safe `PATH`** that
//! always includes system directories so `#!/usr/bin/env bash` on
//! the `nb` script can resolve `bash` even when a concurrent test
//! has poisoned the parent process `PATH` (see `nb-api:issues/api/7`).
//!
//! The repository's `qa` workflow installs `nb` (pinned to the
//! `7.24.0` tag) before running tests. Override discovery with
//! `NB_API_TEST_NB` when needed.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Command as StdCommand, ExitStatus, Stdio};
use std::sync::OnceLock;

use crate::git_env::scrub_git_env_std;
use crate::nb_program::nb_candidate_names;

#[cfg(feature = "testing-tokio")]
use tokio::process::Command as TokioCommand;

const DEFAULT_NOTEBOOK: &str = "scratch";

const GIT_AUTHOR_NAME: &str = "nb-api tests";
const GIT_AUTHOR_EMAIL: &str = "nb-api@localhost";

/// Deterministic git configuration applied to every fixture-spawned git
/// command, on top of the signing overrides. Forces `core.autocrlf=false`
/// so notebook repos are byte-identical across platforms: Git-for-Windows
/// defaults `autocrlf=true`, which renormalizes committed files to CRLF on
/// checkout and makes a fresh nb init commit appear dirty to the
/// transaction's baseline check (`nb-api:todos/api/9`, Windows CI finding).
///
/// Uses the `GIT_CONFIG_COUNT` mechanism so no global/`HOME` config file
/// is needed (the fixture HOME is a tempdir anyway).
fn apply_git_config_env(cmd: &mut impl GitEnvSetter) {
    cmd.env("GIT_CONFIG_COUNT", "4");
    cmd.env("GIT_CONFIG_KEY_0", "commit.gpgsign");
    cmd.env("GIT_CONFIG_VALUE_0", "false");
    cmd.env("GIT_CONFIG_KEY_1", "tag.gpgsign");
    cmd.env("GIT_CONFIG_VALUE_1", "false");
    cmd.env("GIT_CONFIG_KEY_2", "core.autocrlf");
    cmd.env("GIT_CONFIG_VALUE_2", "false");
    cmd.env("GIT_CONFIG_KEY_3", "core.eol");
    cmd.env("GIT_CONFIG_VALUE_3", "lf");
}

/// Minimal surface shared by [`StdCommand`] and [`TokioCommand`] so the
/// fixture's deterministic git-config env can be applied to both.
trait GitEnvSetter {
    fn env<K, V>(&mut self, key: K, value: V)
    where
        K: AsRef<std::ffi::OsStr>,
        V: AsRef<std::ffi::OsStr>;
}

impl GitEnvSetter for StdCommand {
    fn env<K, V>(&mut self, key: K, value: V)
    where
        K: AsRef<std::ffi::OsStr>,
        V: AsRef<std::ffi::OsStr>,
    {
        StdCommand::env(self, key, value);
    }
}

#[cfg(feature = "testing-tokio")]
impl GitEnvSetter for TokioCommand {
    fn env<K, V>(&mut self, key: K, value: V)
    where
        K: AsRef<std::ffi::OsStr>,
        V: AsRef<std::ffi::OsStr>,
    {
        TokioCommand::env(self, key, value);
    }
}

/// System / platform directories always injected into fixture child
/// `PATH` so shebang interpreters (`env bash`) and common `nb`
/// install locations resolve under PATH poison tests.
///
/// Includes Apple Silicon Homebrew (`/opt/homebrew/bin`) and
/// Intel Homebrew / manual prefixes (`/usr/local/bin`).
const SAFE_PATH_DIRS: &[&str] = &[
    "/opt/homebrew/bin",
    "/opt/homebrew/sbin",
    "/usr/local/bin",
    "/usr/local/sbin",
    "/usr/bin",
    "/bin",
    "/usr/sbin",
    "/sbin",
];

static NB_BINARY: OnceLock<PathBuf> = OnceLock::new();
static CHILD_PATH: OnceLock<OsString> = OnceLock::new();

/// Absolute canonical path to the `nb` executable used by fixtures.
///
/// Resolution order: absolute `NB_API_TEST_NB`, fixed install
/// locations (incl. Homebrew), login-home `~/.local/bin/nb` (macOS
/// `id -P` / `dscl`, then `/etc/passwd`), then absolute non-poisoned
/// `PATH` entries. Relative override/PATH candidates are rejected.
/// Concurrent tests may poison process `PATH` (`issues/api/7`);
/// discovery does not rely on it alone.
pub fn nb_binary() -> &'static Path {
    NB_BINARY.get_or_init(discover_nb_binary).as_path()
}

/// `PATH` value applied to every fixture-spawned child.
pub fn fixture_child_path() -> &'static OsString {
    CHILD_PATH.get_or_init(|| {
        let nb = nb_binary();
        let mut dirs: Vec<PathBuf> = Vec::new();
        if let Some(parent) = nb.parent() {
            dirs.push(parent.to_path_buf());
        }
        for d in SAFE_PATH_DIRS {
            let p = PathBuf::from(d);
            if !dirs.iter().any(|x| x == &p) {
                dirs.push(p);
            }
        }
        std::env::join_paths(dirs).unwrap_or_else(|_| OsString::from("/usr/bin:/bin"))
    })
}

fn discover_nb_binary() -> PathBuf {
    if let Some(explicit) = std::env::var_os("NB_API_TEST_NB") {
        return resolve_nb_override(Path::new(&explicit)).unwrap_or_else(|reason| {
            panic!("nb-api testing: invalid NB_API_TEST_NB: {reason}");
        });
    }

    // Candidate file names per directory. On Windows this is the PATHEXT
    // set (`nb.cmd`, `nb.exe`, …) because CreateProcess cannot spawn an
    // extensionless bash script; on Unix it is the bare `nb`.
    let names = nb_candidate_names();

    let mut candidates: Vec<PathBuf> = Vec::new();
    for d in SAFE_PATH_DIRS {
        for name in &names {
            candidates.push(PathBuf::from(d).join(name));
        }
    }

    if let Some(home) = login_home_dir() {
        for name in &names {
            candidates.push(home.join(".local/bin").join(name));
        }
    }

    if let Some(path_var) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path_var) {
            if path_dir_looks_poisoned(&dir) || !dir.is_absolute() {
                continue;
            }
            for name in &names {
                candidates.push(dir.join(name));
            }
        }
    }

    let mut tried = Vec::new();
    for c in &candidates {
        tried.push(c.clone());
        if let Some(abs) = canonicalize_executable(c) {
            return abs;
        }
    }

    panic!(
        "nb-api testing: could not locate an executable `nb` binary. \
         Install nb 7.24.0 or set NB_API_TEST_NB to its absolute path. \
         candidates tried: {tried:?}"
    );
}

/// Validate `NB_API_TEST_NB`: must be absolute, exist, be executable,
/// and is returned in canonical form.
fn resolve_nb_override(path: &Path) -> Result<PathBuf, String> {
    if !path.is_absolute() {
        return Err(format!(
            "path must be absolute (got relative {:?}); \
             relative overrides break after fixture current_dir changes",
            path
        ));
    }
    canonicalize_executable(path).ok_or_else(|| {
        format!(
            "path is not an executable file after canonicalize: {:?}",
            path
        )
    })
}

/// Canonical absolute executable, or `None` if `path` is relative,
/// missing, or not executable.
fn canonicalize_executable(path: &Path) -> Option<PathBuf> {
    if !path.is_absolute() {
        return None;
    }
    let canonical = path.canonicalize().ok()?;
    if !is_executable_file(&canonical) {
        return None;
    }
    Some(canonical)
}

fn path_dir_looks_poisoned(dir: &Path) -> bool {
    let s = dir.to_string_lossy();
    s.contains("poisoned")
        || s.contains("nb-shim-")
        || s == "/nonexistent"
        || s.starts_with("/nonexistent")
}

fn is_executable_file(path: &Path) -> bool {
    let Ok(meta) = std::fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        meta.permissions().mode() & 0o111 != 0
    }
    #[cfg(windows)]
    {
        // CreateProcess cannot spawn an extensionless bash script; only
        // accept files with a PATHEXT-style executable extension
        // (nb.cmd, nb.exe, nb.bat, nb.com). See `nb-api:todos/api/9`.
        has_spawnable_windows_extension(path)
    }
    #[cfg(not(any(unix, windows)))]
    {
        true
    }
}

/// True when `path`'s file name carries a CreateProcess-spawnable
/// extension from the PATHEXT set (case-insensitive).
#[cfg(windows)]
fn has_spawnable_windows_extension(path: &Path) -> bool {
    path.extension().is_some_and(|ext| {
        let ext = ext.to_string_lossy().to_ascii_lowercase();
        matches!(ext.as_str(), "com" | "exe" | "bat" | "cmd")
    })
}

/// Login home for the current user (ignores env `HOME`, which tests
/// overwrite with fixture tempdirs).
///
/// Order (Unix):
/// 1. macOS `id -P` passwd-style line (Open Directory–backed accounts)
/// 2. macOS `dscl` `NFSHomeDirectory` for the current user name
/// 3. `/etc/passwd` by UID (Linux and legacy macOS local files)
///
/// External tools are invoked by absolute path so a poisoned process
/// `PATH` cannot block discovery.
fn login_home_dir() -> Option<PathBuf> {
    #[cfg(unix)]
    {
        if let Some(home) = home_from_id_p() {
            return Some(home);
        }
        if let Some(home) = home_from_dscl() {
            return Some(home);
        }
        home_from_etc_passwd_uid()
    }
    #[cfg(not(unix))]
    {
        std::env::var_os("USERPROFILE")
            .or_else(|| std::env::var_os("HOME"))
            .map(PathBuf::from)
    }
}

/// macOS `id -P`: print the current user as a passwd-style entry
/// (works for Open Directory accounts that are absent from
/// `/etc/passwd`). GNU/Linux `id` typically rejects `-P`.
#[cfg(unix)]
fn home_from_id_p() -> Option<PathBuf> {
    for id_bin in ["/usr/bin/id", "/bin/id"] {
        let output = match StdCommand::new(id_bin).arg("-P").output() {
            Ok(o) => o,
            Err(_) => continue,
        };
        if !output.status.success() {
            continue;
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let line = stdout.lines().next()?;
        if let Some(home) = home_from_passwd_style_line(line) {
            return Some(home);
        }
    }
    None
}

/// macOS Directory Service home lookup for the current user name.
#[cfg(unix)]
fn home_from_dscl() -> Option<PathBuf> {
    let user = current_username()?;
    // Only meaningful on macOS; spawn failure is non-fatal.
    let output = match StdCommand::new("/usr/bin/dscl")
        .args([".", "-read", &format!("/Users/{user}"), "NFSHomeDirectory"])
        .output()
    {
        Ok(o) => o,
        Err(_) => return None,
    };
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    parse_dscl_home(&stdout)
}

#[cfg(unix)]
fn home_from_etc_passwd_uid() -> Option<PathBuf> {
    let uid = current_uid()?;
    let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
    for line in passwd.lines() {
        let mut fields = line.split(':');
        let _name = fields.next()?;
        let _passwd = fields.next()?;
        let file_uid = fields.next()?.parse::<u32>().ok()?;
        if file_uid != uid {
            continue;
        }
        let _gid = fields.next()?;
        let _gecos = fields.next()?;
        let home = fields.next()?;
        if !home.is_empty() {
            return Some(PathBuf::from(home));
        }
    }
    None
}

/// Home directory from a passwd-style colon line.
///
/// Traditional (7 fields): `name:pw:uid:gid:gecos:home:shell` → home @ 5.
/// macOS `id -P` (10 fields):
/// `name:pw:uid:gid:class:change:expire:gecos:home:shell` → home @ 8.
#[cfg_attr(not(unix), allow(dead_code))]
fn home_from_passwd_style_line(line: &str) -> Option<PathBuf> {
    let fields: Vec<&str> = line.trim().split(':').collect();
    let home = if fields.len() >= 10 {
        fields[8]
    } else if fields.len() >= 7 {
        fields[5]
    } else {
        return None;
    };
    if home.is_empty() {
        None
    } else {
        Some(PathBuf::from(home))
    }
}

/// Parse `dscl … NFSHomeDirectory` stdout.
#[cfg_attr(not(unix), allow(dead_code))]
fn parse_dscl_home(stdout: &str) -> Option<PathBuf> {
    for line in stdout.lines() {
        let line = line.trim();
        let Some(rest) = line
            .strip_prefix("NFSHomeDirectory:")
            .or_else(|| line.strip_prefix("dsAttrTypeNative:NFSHomeDirectory:"))
        else {
            continue;
        };
        let home = rest.trim();
        if !home.is_empty() {
            return Some(PathBuf::from(home));
        }
    }
    None
}

#[cfg(unix)]
fn current_username() -> Option<String> {
    for id_bin in ["/usr/bin/id", "/bin/id"] {
        let output = match StdCommand::new(id_bin).arg("-un").output() {
            Ok(o) => o,
            Err(_) => continue,
        };
        if !output.status.success() {
            continue;
        }
        let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !name.is_empty() {
            return Some(name);
        }
    }
    None
}

#[cfg(unix)]
fn current_uid() -> Option<u32> {
    // Absolute id(1) — does not depend on process PATH (may be poisoned).
    for id_bin in ["/usr/bin/id", "/bin/id"] {
        let output = match StdCommand::new(id_bin).arg("-u").output() {
            Ok(o) => o,
            Err(_) => continue,
        };
        if !output.status.success() {
            continue;
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        if let Ok(uid) = stdout.trim().parse::<u32>() {
            return Some(uid);
        }
    }
    // Linux-only fallback when id(1) is unavailable.
    let status = std::fs::read_to_string("/proc/self/status").ok()?;
    for line in status.lines() {
        let Some(rest) = line.strip_prefix("Uid:") else {
            continue;
        };
        return rest.split_whitespace().next()?.parse().ok();
    }
    None
}

#[cfg(test)]
mod nb_resolve_tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn relative_nb_override_is_rejected() {
        let err = resolve_nb_override(Path::new("relative/nb")).unwrap_err();
        assert!(
            err.contains("absolute"),
            "expected absolute-path error, got {err}"
        );
    }

    #[test]
    fn relative_candidate_is_not_canonicalized() {
        assert!(canonicalize_executable(Path::new("nb")).is_none());
        assert!(canonicalize_executable(Path::new("./nb")).is_none());
    }

    #[test]
    fn safe_path_dirs_include_homebrew_prefix() {
        assert!(
            SAFE_PATH_DIRS.contains(&"/opt/homebrew/bin"),
            "Apple Silicon Homebrew must be in SAFE_PATH_DIRS for poisoned-PATH discovery"
        );
    }

    #[test]
    fn parses_macos_id_p_home_field() {
        let line = "me:********:501:20::0:0:Me:/Users/me:/bin/zsh";
        assert_eq!(
            home_from_passwd_style_line(line),
            Some(PathBuf::from("/Users/me"))
        );
    }

    #[test]
    fn parses_traditional_passwd_home_field() {
        let line = "me:x:1000:1000:Me:/home/me:/bin/bash";
        assert_eq!(
            home_from_passwd_style_line(line),
            Some(PathBuf::from("/home/me"))
        );
    }

    #[test]
    fn parses_dscl_nfs_home_directory() {
        assert_eq!(
            parse_dscl_home("NFSHomeDirectory: /Users/me\n"),
            Some(PathBuf::from("/Users/me"))
        );
        assert_eq!(
            parse_dscl_home("dsAttrTypeNative:NFSHomeDirectory: /Users/me\n"),
            Some(PathBuf::from("/Users/me"))
        );
    }

    #[cfg(unix)]
    #[test]
    fn absolute_executable_is_canonicalized() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let bin = dir.path().join("fake-nb");
        fs::write(&bin, b"#!/bin/sh\n").expect("write");
        fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).expect("chmod");
        let abs = bin.canonicalize().expect("canonicalize fixture path");
        let got = canonicalize_executable(&abs).expect("accept absolute executable");
        assert!(got.is_absolute());
        assert_eq!(got, abs);
    }
}

/// A captured `nb` subprocess failure: exit status, stdout, and
/// stderr preserved separately so callers can inspect all three
/// streams when a fixture-initialization command fails.
#[derive(Debug)]
pub struct NbFailure {
    pub status: ExitStatus,
    pub stdout: String,
    pub stderr: String,
}

impl std::fmt::Display for NbFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "exit status: {}\nstdout: {}\nstderr: {}",
            self.status,
            if self.stdout.is_empty() {
                "<empty>"
            } else {
                &self.stdout
            },
            if self.stderr.is_empty() {
                "<empty>"
            } else {
                &self.stderr
            },
        )
    }
}

impl std::error::Error for NbFailure {}

/// Errors raised while building or initializing an [`NbTestEnv`].
#[derive(Debug, thiserror::Error)]
pub enum NbTestError {
    #[error("io error during {context}: {source}")]
    Io {
        context: String,
        #[source]
        source: std::io::Error,
    },

    #[error("nb command failed during {context}: {failure}")]
    Nb {
        context: String,
        #[source]
        failure: NbFailure,
    },
}

/// Builder for [`NbTestEnv`]. Constructed via [`NbTestEnv::builder`].
#[derive(Debug, Default)]
pub struct NbTestEnvBuilder {
    notebook: Option<String>,
    working_directory: Option<PathBuf>,
}

impl NbTestEnvBuilder {
    /// Override the notebook name created during fixture initialization.
    pub fn notebook(mut self, name: impl Into<String>) -> Self {
        self.notebook = Some(name.into());
        self
    }

    /// Use a caller-owned path as the execution cwd of spawned `nb`
    /// processes. The fixture does not delete this path on `Drop`;
    /// the fixture-owned data store under the fixture's root tempdir
    /// is still cleaned up automatically.
    pub fn working_directory(mut self, path: impl Into<PathBuf>) -> Self {
        self.working_directory = Some(path.into());
        self
    }

    /// Build the fixture, initialize its notebook, and return it.
    pub fn build(self) -> Result<NbTestEnv, NbTestError> {
        let root = tempfile::Builder::new()
            .prefix("nb-api-test-")
            .tempdir()
            .map_err(|e| NbTestError::Io {
                context: "create isolated root tempdir".to_string(),
                source: e,
            })?;
        let nb_dir = root.path().join(".nb");
        std::fs::create_dir_all(&nb_dir).map_err(|e| NbTestError::Io {
            context: format!("create nb dir at {}", nb_dir.display()),
            source: e,
        })?;
        let working_dir = match self.working_directory {
            Some(path) => path,
            None => {
                let path = root.path().join("work");
                std::fs::create_dir_all(&path).map_err(|e| NbTestError::Io {
                    context: format!("create working dir at {}", path.display()),
                    source: e,
                })?;
                path
            }
        };
        let home_dir = root.path().join("home");
        std::fs::create_dir_all(&home_dir).map_err(|e| NbTestError::Io {
            context: format!("create fixture HOME at {}", home_dir.display()),
            source: e,
        })?;
        let notebook = self
            .notebook
            .unwrap_or_else(|| DEFAULT_NOTEBOOK.to_string());
        let env = NbTestEnv {
            root,
            nb_dir,
            working_dir,
            home_dir,
            notebook,
        };
        env.initialize_notebook()?;
        Ok(env)
    }
}

/// Hermetic fixture for integration tests that exercise the `nb` CLI.
///
/// Constructed via [`NbTestEnv::new`] for the common case or
/// [`NbTestEnv::builder`] for configuration.
///
/// # Drop semantics
///
/// The fixture-owned root tempdir is removed on `Drop`. A
/// caller-supplied `working_directory` (via [`NbTestEnvBuilder`]) is
/// outside the root and is left intact.
pub struct NbTestEnv {
    /// Held for its `Drop` cleanup of the fixture-owned root
    /// tempdir; never read by name. The fixture's derived paths
    /// (`nb_dir`, `working_dir`) are stored separately so callers
    /// can inspect them without taking the root.
    #[allow(dead_code)]
    root: tempfile::TempDir,
    nb_dir: PathBuf,
    working_dir: PathBuf,
    /// Fixture-owned `$HOME` so `nb`'s `_git_required` global-config
    /// check (`git config --global --includes user.name`) finds a
    /// deterministic `user.name`/`user.email` and never falls into
    /// its interactive prompt. The fixture writes `.gitconfig`
    /// here during [`initialize_notebook`](Self::initialize_notebook).
    home_dir: PathBuf,
    notebook: String,
}

impl NbTestEnv {
    /// Build a fixture with hermetic defaults (isolated root,
    /// default notebook name, separate `nb_dir` and `working_dir`,
    /// scrubbed inherited `GIT_*`, deterministic git identity, signing
    /// disabled).
    pub fn new() -> Result<Self, NbTestError> {
        Self::builder().build()
    }

    /// Begin building a fixture with non-default knobs.
    pub fn builder() -> NbTestEnvBuilder {
        NbTestEnvBuilder::default()
    }

    /// Path of the `NB_DIR` data store where `nb` writes notebooks.
    /// Isolated git repository under the fixture-owned root.
    pub fn nb_dir(&self) -> &Path {
        &self.nb_dir
    }

    /// Path of the execution cwd for spawned `nb` processes. Distinct
    /// from [`nb_dir`](Self::nb_dir) by design.
    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    /// Fixture-owned `$HOME` directory. The fixture writes a
    /// deterministic `.gitconfig` here so `nb`'s `_git_required`
    /// global-config check always finds a `user.name`/`user.email`
    /// and never falls into its interactive prompt.
    pub fn home_dir(&self) -> &Path {
        &self.home_dir
    }

    /// Name of the notebook created during fixture initialization.
    pub fn notebook(&self) -> &str {
        &self.notebook
    }

    /// Apply the fixture's environment to a `std::process::Command`:
    /// strip inherited `GIT_*` routing vars, set `NB_DIR`, set a
    /// deterministic git author/committer identity, disable commit
    /// and tag signing, pin a safe child `PATH`, and set `current_dir`
    /// to [`working_dir`](Self::working_dir).
    pub fn configure_std(&self, cmd: &mut StdCommand) {
        scrub_git_env_std(cmd);
        cmd.env("PATH", fixture_child_path());
        cmd.env("NB_DIR", &self.nb_dir);
        cmd.env("HOME", &self.home_dir);
        cmd.env("GIT_AUTHOR_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_AUTHOR_EMAIL", GIT_AUTHOR_EMAIL);
        cmd.env("GIT_COMMITTER_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_COMMITTER_EMAIL", GIT_AUTHOR_EMAIL);
        apply_git_config_env(cmd);
        cmd.current_dir(&self.working_dir);
    }

    /// Async counterpart to [`configure_std`](Self::configure_std).
    /// Available only with the `testing-tokio` Cargo feature.
    #[cfg(feature = "testing-tokio")]
    pub fn configure_tokio(&self, cmd: &mut TokioCommand) {
        crate::git_env::scrub_git_env(cmd);
        cmd.env("PATH", fixture_child_path());
        cmd.env("NB_DIR", &self.nb_dir);
        cmd.env("HOME", &self.home_dir);
        cmd.env("GIT_AUTHOR_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_AUTHOR_EMAIL", GIT_AUTHOR_EMAIL);
        cmd.env("GIT_COMMITTER_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_COMMITTER_EMAIL", GIT_AUTHOR_EMAIL);
        apply_git_config_env(cmd);
        cmd.current_dir(&self.working_dir);
    }

    /// Convenience accessor: a fresh `std::process::Command` for `nb`
    /// with the fixture's environment applied. Uses the absolute
    /// [`nb_binary`] path so parent-process `PATH` poison cannot
    /// prevent executable lookup (`issues/api/7`). Stdin is nulled to
    /// mirror the production [`NbClient::exec`](crate::NbClient) spawn
    /// (prevents TTY hangs / interactive prompts).
    pub fn nb_command(&self) -> StdCommand {
        let mut cmd = StdCommand::new(nb_binary());
        self.configure_std(&mut cmd);
        cmd.stdin(Stdio::null());
        cmd
    }

    /// Async counterpart to [`nb_command`](Self::nb_command). Available
    /// only with the `testing-tokio` Cargo feature.
    #[cfg(feature = "testing-tokio")]
    pub fn nb_command_async(&self) -> TokioCommand {
        let mut cmd = TokioCommand::new(nb_binary());
        self.configure_tokio(&mut cmd);
        cmd.stdin(Stdio::null());
        cmd
    }

    fn initialize_notebook(&self) -> Result<(), NbTestError> {
        // Write `$HOME/.gitconfig` so `nb`'s `_git_required` global
        // check finds a deterministic `user.name`/`user.email` and
        // never falls into its interactive prompt. Without this, the
        // first `nb` invocation hangs on a `read` for Name/Email
        // when stdin is not a TTY.
        let gitconfig = self.home_dir.join(".gitconfig");
        let gitconfig_contents =
            format!("[user]\n\tname = {GIT_AUTHOR_NAME}\n\temail = {GIT_AUTHOR_EMAIL}\n",);
        std::fs::write(&gitconfig, gitconfig_contents).map_err(|e| NbTestError::Io {
            context: format!("write .gitconfig to {}", gitconfig.display()),
            source: e,
        })?;

        // Pre-create a hidden init stub. `nb`'s main loop short-
        // circuits its first-run `_init` (welcome screen and
        // interactive author prompt) when both `NB_DIR` and
        // `NB_NOTEBOOK_PATH` exist. The stub satisfies that check
        // without leaving a phantom `home` notebook: a leading dot
        // hides it from `ls -1` (which `nb notebooks` uses), and
        // `NB_NOTEBOOK_PATH` is pointed at the stub only for the
        // init command. Subsequent commands use `.current` and
        // never resolve through the stub.
        //
        // We use `.init_stub` rather than the conventional
        // `home` so that callers can build a fixture with
        // `notebook("home")` if they want — there is no conflict
        // because the stub is a different name.
        let init_stub = self.nb_dir.join(".init_stub");
        std::fs::create_dir_all(&init_stub).map_err(|e| NbTestError::Io {
            context: format!("create init stub at {}", init_stub.display()),
            source: e,
        })?;

        // Build the init command's env inline rather than via
        // `configure_std`. The init command needs `NB_NOTEBOOK_PATH`
        // pointing at the stub; `configure_std` deliberately does
        // not set `NB_NOTEBOOK_PATH` because subsequent operations
        // must resolve the current notebook through `.current`.
        // Absolute `nb` + safe child PATH: parent PATH may be
        // poisoned by a concurrent harness test (`issues/api/7`).
        let mut cmd = StdCommand::new(nb_binary());
        scrub_git_env_std(&mut cmd);
        cmd.env("PATH", fixture_child_path());
        cmd.env("NB_DIR", &self.nb_dir);
        cmd.env("NB_NOTEBOOK_PATH", &init_stub);
        cmd.env("HOME", &self.home_dir);
        cmd.env("GIT_AUTHOR_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_AUTHOR_EMAIL", GIT_AUTHOR_EMAIL);
        cmd.env("GIT_COMMITTER_NAME", GIT_AUTHOR_NAME);
        cmd.env("GIT_COMMITTER_EMAIL", GIT_AUTHOR_EMAIL);
        apply_git_config_env(&mut cmd);
        cmd.stdin(Stdio::null()); // Prevent TTY hangs (mirrors NbClient::exec)
        cmd.current_dir(&self.working_dir);
        cmd.arg("notebooks").arg("add").arg(&self.notebook);
        let output = cmd.output().map_err(|e| NbTestError::Io {
            context: format!("spawn `nb notebooks add {}`", self.notebook),
            source: e,
        })?;
        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
            return Err(NbTestError::Nb {
                context: format!("`nb notebooks add {}`", self.notebook),
                failure: NbFailure {
                    status: output.status,
                    stdout,
                    stderr,
                },
            });
        }

        // Point `nb` at our notebook so subsequent invocations
        // target it via the on-disk `.current` marker that nb
        // reads on every call. The init stub is left in place
        // (hidden, never listed) so the test process can verify
        // `_init` bypass behavior without rebuilding it.
        std::fs::write(self.nb_dir.join(".current"), &self.notebook).map_err(|e| {
            NbTestError::Io {
                context: format!(
                    "write .current to {}",
                    self.nb_dir.join(".current").display()
                ),
                source: e,
            }
        })?;

        // Ensure a clean committed baseline. nb's `_git checkpoint` runs
        // the init commit in a background subshell (`( ... ) &`). When nb
        // is spawned through a `.cmd` launcher (Windows), that orphaned
        // commit is torn down when the wrapper exits, leaving `.index`
        // untracked and every later `Transaction::commit` rejected with
        // `DirtyBaseline`. Run the commit synchronously ourselves with
        // the fixture's deterministic git env so the baseline is identical
        // on Unix and Windows. See `nb-api:todos/api/9`.
        //
        // `git` resolves through the inherited process PATH (as in
        // `crate::git::git_capture`); the fixture child PATH only carries
        // nb's dir + system dirs and would not locate git on Windows.
        // If git cannot spawn (poisoned process PATH, issues/api/7), the
        // baseline is skipped — the poisoned test never runs a
        // transaction, so a missing baseline is harmless there.
        let notebook_root = self.nb_dir.join(&self.notebook);
        let baseline_result: Result<(), NbTestError> = (|| {
            // Write the notebook repo's LOCAL config so every subsequent
            // git invocation (including production `git::git_capture`,
            // which scrubs GIT_CONFIG_* env) sees byte-identical LF
            // handling. The GIT_CONFIG_COUNT env override only reaches
            // fixture-spawned commands; repo-local config persists.
            // See `nb-api:todos/api/9`.
            let mut git_config = StdCommand::new("git");
            scrub_git_env_std(&mut git_config);
            git_config.env("HOME", &self.home_dir);
            apply_git_config_env(&mut git_config);
            git_config.current_dir(&notebook_root);
            git_config.args(["config", "core.autocrlf", "false"]);
            let cfg = git_config.output().map_err(|e| NbTestError::Io {
                context: format!(
                    "fixture baseline `git config core.autocrlf false` in {}",
                    notebook_root.display()
                ),
                source: e,
            })?;
            if !cfg.status.success() {
                let stdout = String::from_utf8_lossy(&cfg.stdout).into_owned();
                let stderr = String::from_utf8_lossy(&cfg.stderr).into_owned();
                return Err(NbTestError::Nb {
                    context: format!(
                        "fixture baseline `git config core.autocrlf false` in {}",
                        notebook_root.display()
                    ),
                    failure: NbFailure {
                        status: cfg.status,
                        stdout,
                        stderr,
                    },
                });
            }
            // nb 7.24.0 fires the notebook's init commit in a background
            // subshell (`( _git_checkpoint_commit ... ) &`). Under the
            // Git Bash `.cmd` launcher on Windows that orphaned git can
            // keep staging `.index` after our synchronous baseline commit,
            // racing the first `Transaction::commit`'s dirty check
            // (intermittent `DirtyBaseline` — see todos/api/9). Settle by
            // re-committing until the worktree/index is verifiably clean.
            // The window is generous (up to ~2.5s) because on Windows the
            // orphaned background git can be delayed by job teardown.
            let mut consecutive_clean = 0u32;
            for _ in 0..50 {
                let mut status = StdCommand::new("git");
                scrub_git_env_std(&mut status);
                status.env("HOME", &self.home_dir);
                apply_git_config_env(&mut status);
                status.current_dir(&notebook_root);
                status.args(["status", "--porcelain", "-uall", "--ignored=no"]);
                let status_out = status.output().map_err(|e| NbTestError::Io {
                    context: format!(
                        "fixture baseline `git status --porcelain` in {}",
                        notebook_root.display()
                    ),
                    source: e,
                })?;
                if !status_out.status.success() {
                    let stdout = String::from_utf8_lossy(&status_out.stdout).into_owned();
                    let stderr = String::from_utf8_lossy(&status_out.stderr).into_owned();
                    return Err(NbTestError::Nb {
                        context: format!(
                            "fixture baseline `git status --porcelain` in {}",
                            notebook_root.display()
                        ),
                        failure: NbFailure {
                            status: status_out.status,
                            stdout,
                            stderr,
                        },
                    });
                }
                let dirty = !String::from_utf8_lossy(&status_out.stdout)
                    .trim()
                    .is_empty();
                if !dirty {
                    // Require two consecutive clean checks so an orphaned
                    // nb background git that has NOT yet staged `.index`
                    // cannot slip in after a single clean observation
                    // (Windows CI DirtyBaseline flake, see todos/api/9).
                    consecutive_clean += 1;
                    if consecutive_clean >= 2 {
                        return Ok(());
                    }
                } else {
                    consecutive_clean = 0;
                }

                let mut git = StdCommand::new("git");
                scrub_git_env_std(&mut git);
                git.env("HOME", &self.home_dir);
                git.env("GIT_AUTHOR_NAME", GIT_AUTHOR_NAME);
                git.env("GIT_AUTHOR_EMAIL", GIT_AUTHOR_EMAIL);
                git.env("GIT_COMMITTER_NAME", GIT_AUTHOR_NAME);
                git.env("GIT_COMMITTER_EMAIL", GIT_AUTHOR_EMAIL);
                apply_git_config_env(&mut git);
                git.current_dir(&notebook_root);
                git.arg("add").arg("-A");
                let add = git.output().map_err(|e| NbTestError::Io {
                    context: format!(
                        "fixture baseline `git add -A` in {}",
                        notebook_root.display()
                    ),
                    source: e,
                })?;
                if !add.status.success() {
                    let stdout = String::from_utf8_lossy(&add.stdout).into_owned();
                    let stderr = String::from_utf8_lossy(&add.stderr).into_owned();
                    return Err(NbTestError::Nb {
                        context: format!(
                            "fixture baseline `git add -A` in {}",
                            notebook_root.display()
                        ),
                        failure: NbFailure {
                            status: add.status,
                            stdout,
                            stderr,
                        },
                    });
                }
                let mut git_commit = StdCommand::new("git");
                scrub_git_env_std(&mut git_commit);
                git_commit.env("HOME", &self.home_dir);
                git_commit.env("GIT_AUTHOR_NAME", GIT_AUTHOR_NAME);
                git_commit.env("GIT_AUTHOR_EMAIL", GIT_AUTHOR_EMAIL);
                git_commit.env("GIT_COMMITTER_NAME", GIT_AUTHOR_NAME);
                git_commit.env("GIT_COMMITTER_EMAIL", GIT_AUTHOR_EMAIL);
                apply_git_config_env(&mut git_commit);
                git_commit.current_dir(&notebook_root);
                git_commit.args(["commit", "-m", "[nb] Initialize"]);
                let commit = git_commit.output().map_err(|e| NbTestError::Io {
                    context: format!(
                        "fixture baseline `git commit` in {}",
                        notebook_root.display()
                    ),
                    source: e,
                })?;
                if !commit.status.success() {
                    // A `nothing to commit` exit is not an error; the
                    // settle loop re-checks status next iteration. Git
                    // may write the message to stdout or stderr.
                    let stdout = String::from_utf8_lossy(&commit.stdout);
                    let stderr = String::from_utf8_lossy(&commit.stderr);
                    if !stdout.contains("nothing to commit")
                        && !stderr.contains("nothing to commit")
                    {
                        return Err(NbTestError::Nb {
                            context: format!(
                                "fixture baseline `git commit` in {}",
                                notebook_root.display()
                            ),
                            failure: NbFailure {
                                status: commit.status,
                                stdout: stdout.into_owned(),
                                stderr: stderr.into_owned(),
                            },
                        });
                    }
                }
                // Let nb's background checkpoint finish before re-checking.
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            Err(NbTestError::Io {
                context: format!(
                    "fixture baseline did not settle clean in {}",
                    notebook_root.display()
                ),
                source: std::io::Error::other("notebook repo never reached a clean baseline"),
            })
        })();
        if let Err(NbTestError::Io { source, .. }) = &baseline_result
            && source.kind() == std::io::ErrorKind::NotFound
        {
            // Poisoned process PATH (issues/api/7): git unresolvable,
            // baseline intentionally skipped.
            tracing::debug!("fixture baseline skipped: git not on process PATH");
        } else {
            baseline_result?;
        }

        Ok(())
    }
}