This commit is contained in:
Sebastian Moser
2026-10-23 15:27:31 +02:00
parent 9141fc5441
commit 37cb94d1d4
11 changed files with 482 additions and 63 deletions

View File

@@ -56,7 +56,7 @@ pub fn opt(name: &str) -> crate::config::ConfigOptId {
let mut opts = mize.config_opts.lock().unwrap();
let id = cur_part.join(name).unwrap();
let opt = ConfigOpt {
name: name.to_owned(),
name: id.dot(),
val: None,
fun: None,
deps: Vec::new(),
@@ -65,13 +65,49 @@ pub fn opt(name: &str) -> crate::config::ConfigOptId {
ConfigOptId { id }
}
pub fn method<F: Fn(ItemData) -> MizeResult<ItemData>>(_name: &str, _fun: F) {
pub fn method<F: Fn(ItemData) -> MizeResult<ItemData>>(name: &str, fun: F) -> ConfigOptId {
let mize = get_global_mize().unwrap();
let mut cur_part = mize.cur_eval_part.lock().unwrap().clone().unwrap();
let mut opts = mize.config_opts.lock().unwrap();
let id = cur_part.join(name).unwrap();
let opt = ConfigOpt {
name: id.dot(),
val: Some(ItemData::from_native(fun)?),
fun: None,
deps: Vec::new(),
};
opts.insert(id.clone(), opt);
ConfigOptId { id }
}
pub fn effect<F: Fn(ItemData) -> MizeResult<ItemData>>(_name: &str, _fun: F) {
pub fn effect<F: Fn(ItemData) -> MizeResult<ItemData>>(_name: &str, _fun: F) -> ConfigOptId {
let mize = get_global_mize().unwrap();
let mut cur_part = mize.cur_eval_part.lock().unwrap().clone().unwrap();
let mut opts = mize.config_opts.lock().unwrap();
let id = cur_part.join(name).unwrap();
let opt = ConfigOpt {
name: id.dot(),
val: Some(ItemData::from_native(fun)?),
fun: None,
deps: Vec::new(),
};
opts.insert(id.clone(), opt);
ConfigOptId { id }
}
pub fn thread<F: Fn(ItemData) -> MizeResult<ItemData>>(_name: &str, _fun: F) {
pub fn thread<F: Fn(ItemData) -> MizeResult<ItemData>>(_name: &str, _fun: F) -> ConfigOptId {
let mize = get_global_mize().unwrap();
let mut cur_part = mize.cur_eval_part.lock().unwrap().clone().unwrap();
let mut opts = mize.config_opts.lock().unwrap();
let id = cur_part.join(name).unwrap();
let opt = ConfigOpt {
name: id.dot(),
val: Some(ItemData::from_native(fun)?),
fun: None,
deps: Vec::new(),
};
opts.insert(id.clone(), opt);
ConfigOptId { id }
}
type CFun = unsafe extern "C" fn (*mut ItemData) -> *mut ItemData;

View File

@@ -32,6 +32,14 @@ pub trait IntoMizeId {
}
impl MizeId {
pub fn dot(&self) -> String {
let path = self.path();
let mut new_path = Vec::new();
for el in path.iter() {
new_path.push(el.to_owned());
}
new_path.join(".")
}
pub fn join(&mut self, to_add: &str) -> MizeResult<MizeId> {
let path = self.path();
let mut new_path = Vec::new();

View File

@@ -235,7 +235,7 @@ impl Mize {
}
pub fn has_part(&mut self, name: &str) -> MizeResult<bool> {
let id = self.id_new_dots(name)?;
Ok(self.parts.lock().unwrap().contains_key(&id))
Ok(self.config_opts.lock().unwrap().contains_key(&id))
}
pub fn add_listener(
&mut self,
@@ -249,9 +249,6 @@ impl Mize {
Ok(())
}
fn part_names(&mut self) -> Vec<&'static str> {
self.part_names.lock().unwrap().clone()
}
pub fn init(&mut self) -> MizeResult<()> {
@@ -834,10 +831,11 @@ impl Mize {
}
pub fn dyn_call(&mut self, part_id: MizeId, method: &str, args: ItemData) -> MizeResult<ItemData> {
let mut parts = self.parts.lock()?;
let _part = parts.get_mut(&part_id).ok_or(mize_err!("part {part_id} is not loaded"))?;
println!("would be dyn_call ing from part, {:?}, {method}, {:?}", part_id, args);
Ok(ItemData::new())
let mut opts = self.config_opts.lock()?;
let part = opts.get_mut(&part_id).ok_or(mize_err!("part {} is not loaded", part_id.dot()))?;
let fun = part.val.ok_or(mize_err!("fun has no val"))?.native::<Fn(ItemData) -> MizeResult<ItemData>>()?;
println!("dyn_call ing from part, {:?}, {method}, {:?}", part_id, args);
fun(args)
}
pub fn get_part_gen<T: MizePart + Send + Sync + 'static>(

View File

@@ -356,8 +356,7 @@ impl ItemData {
/// The native value must have been stored via from_native().
/// Returns a guard that holds the lock on the native_values registry.
pub fn native<T: Any + Send + Sync + 'static>(&self) -> MizeResult<NativeRefGuard<T>> {
let mize_arc = crate::GLOBAL_MIZE.get().ok_or(mize_err!("No global Mize"))?;
let mize = mize_arc.lock().map_err(|_| mize_err!("Failed to lock global Mize"))?;
let mize = get_global_mize()?;
let native_values = mize.native_values.lock().map_err(|_| mize_err!("Failed to lock native_values"))?;
let id_data = self.get_path("_native")
@@ -389,8 +388,7 @@ impl ItemData {
/// The native value must have been stored via from_native().
/// Returns a guard that holds the lock on the native_values registry.
pub fn native_mut<T: Any + Send + Sync + 'static>(&self) -> MizeResult<NativeMutRefGuard<T>> {
let mize_arc = crate::GLOBAL_MIZE.get().ok_or(mize_err!("No global Mize"))?;
let mize = mize_arc.lock().map_err(|_| mize_err!("Failed to lock global Mize"))?;
let mize = get_global_mize()?;
let mut native_values = mize.native_values.lock().map_err(|_| mize_err!("Failed to lock native_values"))?;
let id_data = self.get_path("_native")
@@ -418,11 +416,18 @@ impl ItemData {
})
}
/// Get a clone of the native value stored in this ItemData.
/// The native value must have been stored via from_native().
/// This is useful when you need to pass the value by ownership (e.g., as a function argument).
pub fn native_clone<T: Any + Send + Sync + Clone + 'static>(&self) -> MizeResult<T> {
let guard = self.native::<T>()?;
Ok(guard.clone())
}
/// Take the native value from this ItemData, removing it from the registry.
/// The native value must have been stored via from_native().
pub fn native_take<T: Any + Send + Sync + 'static>(&self) -> MizeResult<T> {
let mize_arc = crate::GLOBAL_MIZE.get().ok_or(mize_err!("No global Mize"))?;
let mize = mize_arc.lock().map_err(|_| mize_err!("Failed to lock global Mize"))?;
let mize = get_global_mize()?;
let mut native_values = mize.native_values.lock().map_err(|_| mize_err!("Failed to lock native_values"))?;
let id_data = self.get_path("_native")

View File

@@ -21,6 +21,57 @@ pub fn write_to_mize_stdout(args: std::fmt::Arguments) -> MizeResult<()> {
Ok(())
}
/// Mize Shell (msh) macro - wraps command execution with nixpkgs executable resolution.
///
/// If the executable is given as a bare name (identifier), it is resolved via
/// [`msh_get_nix_bin`] to a nixpkgs store path. If it is given as a string literal
/// containing `/`, it is treated as a path and used as-is.
///
/// # Examples
/// ```ignore
/// msh!(git status)?; // resolves `git` from nixpkgs
/// msh!(curl https://example.com)?;
/// msh!("/usr/bin/git" status)?; // uses path directly
/// ```
#[macro_export]
macro_rules! msh {
// First token is a string literal — check if it's a path at runtime
($cmd:literal $($rest:tt)*) => {{
let cmd_str: &str = $cmd;
let resolved: String = if cmd_str.contains('/') {
cmd_str.to_string()
} else {
$crate::msh_get_nix_bin(cmd_str)
};
let mut cmd = ::std::process::Command::new(resolved);
$(cmd.arg(::std::stringify!($rest));)*
let status = cmd.status()?;
if status.success() {
::std::result::Result::Ok(())
} else {
::std::result::Result::Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
::std::format!("msh: command exited with {}", status),
))
}
}};
// First token is an identifier — always resolve via nixpkgs
($cmd:ident $($rest:tt)*) => {{
let resolved: String = $crate::msh_get_nix_bin(::std::stringify!($cmd));
let mut cmd = ::std::process::Command::new(resolved);
$(cmd.arg(::std::stringify!($rest));)*
let status = cmd.status()?;
if status.success() {
::std::result::Result::Ok(())
} else {
::std::result::Result::Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
::std::format!("msh: command exited with {}", status),
))
}
}};
}
pub mod prelude {
pub use super::*;
pub use instance::Mize;
@@ -97,6 +148,99 @@ pub extern "C" fn mize_rust_hack_set_global(mize: Arc<Mutex<Mize>>) {
let _ = GLOBAL_MIZE.set(mize);
}
/// Resolve an executable name to its full path in the nixpkgs store.
///
/// Reads `nix.pkgs.ref` (nixpkgs commit hash) and `nix.bin` (path to the `nix`
/// binary) from the Mize config, then runs:
///
/// ```text
/// <nix.bin> eval --raw nixpkgs/<hash>#<pkg>
/// ```
///
/// and returns `<outPath>/bin/<executable>`.
///
/// Certain executable names are mapped to different nixpkgs attribute names
/// via a hardcoded match (e.g. `npm` → `nodejs`).
///
/// # Panics
/// Panics if the global Mize instance is not set, the config values are missing,
/// or `nix eval` fails.
pub fn msh_get_nix_bin(name: &str) -> String {
// Hardcoded mapping of executable names to nixpkgs attribute names
let pkg = match name {
"npm" => "nodejs",
"node" => "nodejs",
"yarn" => "yarn",
"pnpm" => "nodePackages.pnpm",
_ => name,
};
let mut mize = get_global_mize().expect("msh_get_nix_bin: no global Mize instance set");
let nixpkgs_ref = mize
.get_config("nix.pkgs.ref")
.expect("msh_get_nix_bin: failed to get config nix.pkgs.ref")
.value_string()
.expect("msh_get_nix_bin: nix.pkgs.ref is not a string");
let nix_bin = mize
.get_config("nix.bin")
.expect("msh_get_nix_bin: failed to get config nix.bin")
.value_string()
.expect("msh_get_nix_bin: nix.bin is not a string");
// Run: nix eval --raw nixpkgs/<hash>#<pkg>
// --raw outputs just the store path without quotes
let attr = format!("nixpkgs/{}#{}", nixpkgs_ref, pkg);
let output = std::process::Command::new(&nix_bin)
.args(["eval", "--raw", &attr])
.output()
.expect("msh_get_nix_bin: failed to spawn nix eval");
if !output.status.success() {
panic!(
"msh_get_nix_bin: nix eval failed for {}: {}",
attr,
String::from_utf8_lossy(&output.stderr)
);
}
let out_path = String::from_utf8(output.stdout)
.expect("msh_get_nix_bin: nix eval output is not valid UTF-8")
.trim()
.to_string();
format!("{}/bin/{}", out_path, name)
}
/// Run a command with Mize Shell executable resolution.
///
/// This is the function-based equivalent of the [`msh!`] macro, with proper
/// argument handling (no `stringify!` limitations).
///
/// If `cmd` contains `/` it is treated as a path and used as-is.
/// Otherwise it is resolved via [`msh_get_nix_bin`].
///
/// Returns `Ok(())` if the command exits successfully, or an `io::Error` otherwise.
pub fn msh_run(cmd: &str, args: &[&str]) -> std::io::Result<()> {
let resolved = if cmd.contains('/') {
cmd.to_string()
} else {
msh_get_nix_bin(cmd)
};
let mut command = std::process::Command::new(resolved);
command.args(args);
let status = command.status()?;
if status.success() {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("msh: command exited with {}", status),
))
}
}
// platform specific stuff
pub mod platform {
use crate::{Mize, MizeResult};