use std::path::{Path, PathBuf};
use crate::error::NbError;
use walk::{ItemOutcome, program_opaque_reason, walk_item};
mod walk;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum NbrcSelection {
Assign(String),
Fallback(&'static str),
Absent,
}
pub(crate) fn select_nb_dir(input: &str, home: &Path) -> NbrcSelection {
let normalized = input.replace("\r\n", "\n");
let options = brush_parser::ParserOptions::default();
let mut parser =
brush_parser::Parser::new(normalized.as_bytes(), &options);
let program = match parser.parse_program() {
Ok(program) => program,
Err(_) => return NbrcSelection::Fallback("unparseable rc"),
};
let mut scan_state: Option<String> = None;
if let Some(reason) =
program_opaque_reason(&program, home, &mut scan_state)
{
return NbrcSelection::Fallback(reason);
}
let mut nb_dir: Option<String> = None;
let mut selected: Option<String> = None;
let mut undetermined: Option<&'static str> = None;
for complete in &program.complete_commands {
for item in &complete.0 {
match walk_item(item, home, &mut nb_dir) {
ItemOutcome::Assign(value) => {
selected =
if value.is_empty() { None } else { Some(value) };
},
ItemOutcome::Clear => {
selected = None;
},
ItemOutcome::Undetermined(reason) => {
if undetermined.is_none() {
undetermined = Some(reason);
}
},
ItemOutcome::Ignore => {},
}
}
}
if let Some(reason) = undetermined {
NbrcSelection::Fallback(reason)
} else if let Some(value) = selected {
NbrcSelection::Assign(value)
} else if let Some(value) = nb_dir.clone().filter(|v| !v.is_empty()) {
NbrcSelection::Assign(value)
} else {
NbrcSelection::Absent
}
}
pub(crate) fn resolve_store_dir(strict: bool) -> Result<PathBuf, NbError> {
let nb_dir = std::env::var_os("NB_DIR");
let home = std::env::var_os("HOME");
let nbrc_path = std::env::var_os("NBRC_PATH");
if let Some(dir) = nb_dir.as_ref().filter(|v| !v.is_empty()) {
tracing::debug!("notebook store from explicit NB_DIR");
return Ok(PathBuf::from(dir));
}
if strict {
return Err(NbError::ValidationError {
reason: "notebook store is not configured (`NB_DIR` is unset) and strict resolution refuses the file default"
.to_string(),
location: None,
});
}
let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
NbError::ValidationError {
reason: "home directory is not available, so the default notebook store cannot be resolved"
.to_string(),
location: None,
}
})?;
let home_path = PathBuf::from(home);
let rc_path = match nbrc_path.as_ref().filter(|v| !v.is_empty()) {
Some(custom) => {
let path = PathBuf::from(custom);
if !path.is_absolute() {
return Err(NbError::ValidationError {
reason: "`NBRC_PATH` must be absolute when set"
.to_string(),
location: None,
});
}
path
},
None => home_path.join(".nbrc"),
};
let store = match std::fs::read_to_string(&rc_path) {
Ok(text) => match select_nb_dir(&text, &home_path) {
NbrcSelection::Assign(raw) => PathBuf::from(raw),
NbrcSelection::Fallback(reason) => {
tracing::warn!(
"notebook rc `{}` is ambiguous ({}); falling back to the default store",
rc_path.display(),
reason
);
home_path.join(".nb")
},
NbrcSelection::Absent => {
tracing::debug!(
"notebook store from default ~/.nb (no NB_DIR in rc)"
);
home_path.join(".nb")
},
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("notebook store from default ~/.nb (no rc file)");
home_path.join(".nb")
},
Err(e) => {
return Err(NbError::Io {
path: rc_path.clone(),
source: e.into(),
});
},
};
if !store.is_absolute() {
return Err(NbError::ValidationError {
reason: format!(
"notebook store from `{}` must be absolute, got `{}`",
rc_path.display(),
store.display()
),
location: None,
});
}
tracing::debug!(
"notebook store `{}` selected via {}",
store.display(),
rc_path.display()
);
Ok(store)
}
#[cfg(test)]
mod tests;