use std::io::Write;
use std::path::PathBuf;
pub(super) fn named_project_root(args: &[String]) -> Option<&str> {
let runtime = args.first().map(String::as_str) == Some("runtime");
args.windows(2)
.find(|pair| pair[0] == "--project-root" || (runtime && pair[0] == "--project"))
.map(|pair| pair[1].as_str())
}
pub(super) fn scope_root(root: &str) -> PathBuf {
std::fs::canonicalize(root).unwrap_or_else(|_| PathBuf::from(root))
}
pub(super) fn operation_word(args: &[String]) -> &str {
args.first()
.map(String::as_str)
.filter(|word| {
!word.is_empty()
&& word.len() <= 64
&& word.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
})
.unwrap_or("engine")
}
pub(super) struct EngineCall<'a, E> {
pub(super) project_root: Option<PathBuf>,
pub(super) run: Box<dyn FnOnce() -> Result<String, E> + 'a>,
}
#[derive(Debug)]
pub(super) enum DeliveryFailure<E> {
Operation(E),
ReceiptNotPersisted,
Write(std::io::Error),
}
pub(super) fn deliver_engine_document<E>(
operation: &str,
call: EngineCall<'_, E>,
out: &mut dyn Write,
) -> Result<(), DeliveryFailure<E>> {
use lean_ctx::core::context_admission::capture::ADMISSIONS;
use lean_ctx::core::context_admission::receipt_store::{
frame::FrameCall,
observed, roots,
trace::{Channel, Delivery},
};
let EngineCall { project_root, run } = call;
let index = project_root
.as_deref()
.map(|root| root.to_string_lossy().into_owned());
let scoped = move || -> Result<(), DeliveryFailure<E>> {
let frame = FrameCall::open(operation);
let output = ADMISSIONS
.sync_scope(Some(frame.capture()), run)
.map_err(DeliveryFailure::Operation)?;
let document = format!("{output}\n");
let prepared = frame
.seal(
index.as_deref().unwrap_or(roots::ENGINE_KEY),
document.as_bytes(),
false,
Delivery::engine_interface,
)
.map_err(|_missing| DeliveryFailure::ReceiptNotPersisted)?;
if let Some(prepared) = prepared {
prepared.await_write();
}
observed::write_observed(out, Channel::Stdout, document.as_bytes(), None)
.map_err(DeliveryFailure::Write)
};
match project_root {
Some(root) => lean_ctx::core::policy::runtime::REQUEST_PROJECT
.sync_scope(std::cell::RefCell::new(Some(root)), scoped),
None => scoped(),
}
}
const RECEIPT_NOT_PERSISTED: &str = "receipt_not_persisted";
pub(super) fn exit_unless_delivered<E>(
label: &str,
delivered: Result<(), DeliveryFailure<E>>,
code: impl FnOnce(E) -> String,
) {
let (message, status) = match delivered {
Ok(()) => return,
Err(DeliveryFailure::Operation(error)) => (format!("{label}: {}", code(error)), 2),
Err(DeliveryFailure::ReceiptNotPersisted) => {
(format!("{label}: {RECEIPT_NOT_PERSISTED}"), 2)
}
Err(DeliveryFailure::Write(error)) => {
(format!("lean-ctx: output could not be written: {error}"), 1)
}
};
eprintln!("{message}");
std::process::exit(status);
}