use mlua::{Lua, Table, Value};
pub fn is_windows_style(path: &str) -> bool {
path.contains('\\') || (!path.contains('/') && drive(path).is_some())
}
fn restyle(canonical: String, windows: bool) -> String {
if windows {
canonical.replace('/', "\\")
} else {
canonical
}
}
fn drive(path: &str) -> Option<usize> {
let mut chars = path.chars();
(chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':'))
.then_some(2)
}
pub fn split_root(path: &str) -> (String, String) {
let canonical = path.replace('\\', "/");
let root_len = if canonical.starts_with("//") {
2
} else {
match drive(&canonical) {
Some(d) if canonical[d..].starts_with('/') => d + 1,
Some(d) => d,
None if canonical.starts_with('/') => 1,
None => 0,
}
};
let (root, rest) = canonical.split_at(root_len);
(root.to_string(), rest.to_string())
}
fn components(rest: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for segment in rest.split('/') {
if segment.is_empty() || (segment == "." && !parts.is_empty()) {
continue;
}
parts.push(segment);
}
parts
}
fn root_is_anchor(root: &str) -> bool {
!root.is_empty() && !(root.len() == 2 && root.ends_with(':'))
}
pub fn is_absolute(path: &str) -> bool {
root_is_anchor(&split_root(path).0)
}
pub fn basename(path: &str) -> String {
let (_, rest) = split_root(path);
match components(&rest).last() {
Some(name) if *name != "." && *name != ".." => (*name).to_string(),
_ => String::new(),
}
}
pub fn dirname(path: &str) -> String {
let windows = is_windows_style(path);
let (root, rest) = split_root(path);
let parts = components(&rest);
let out = match parts.split_last() {
Some((_, parent)) if parent.is_empty() && root.is_empty() => ".".into(),
Some((_, parent)) => format!("{root}{}", parent.join("/")),
None if root.is_empty() => ".".into(),
None => root,
};
restyle(out, windows)
}
fn extension(path: &str) -> Option<String> {
match basename(path).rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() => Some(ext.to_string()),
_ => None,
}
}
pub fn join(segments: &[String]) -> String {
let windows = segments
.iter()
.find(|s| !s.is_empty())
.is_some_and(|s| is_windows_style(s));
let mut out = String::new();
for segment in segments {
if segment.is_empty() {
continue;
}
let canonical = segment.replace('\\', "/");
if out.is_empty() {
out.push_str(&canonical);
} else {
let bare_drive = out.len() == 2 && drive(&out).is_some();
if !out.ends_with('/') && !bare_drive {
out.push('/');
}
out.push_str(canonical.trim_start_matches('/'));
}
}
restyle(out, windows)
}
pub fn normalize(path: &str) -> String {
let windows = is_windows_style(path);
let (root, rest) = split_root(path);
let rooted = !root.is_empty();
let anchored = root_is_anchor(&root);
let mut parts: Vec<&str> = Vec::new();
for segment in components(&rest) {
match segment {
"." => {}
".." => {
if parts.last().is_some_and(|p| *p != "..") {
parts.pop();
} else if !anchored {
parts.push("..");
}
}
other => parts.push(other),
}
}
let joined = parts.join("/");
let out = match (rooted, joined.is_empty()) {
(true, _) => format!("{root}{joined}"),
(false, true) => ".".into(),
(false, false) if !split_root(&joined).0.is_empty() => format!("./{joined}"),
(false, false) => joined,
};
restyle(out, windows)
}
pub(crate) fn create_path_table(lua: &Lua) -> mlua::Result<Table> {
let path = lua.create_table()?;
path.set(
"join",
lua.create_function(|_, segments: mlua::Variadic<String>| Ok(join(&segments)))?,
)?;
path.set(
"basename",
lua.create_function(|_, path: String| Ok(basename(&path)))?,
)?;
path.set(
"dirname",
lua.create_function(|_, path: String| Ok(dirname(&path)))?,
)?;
path.set(
"extension",
lua.create_function(|lua, path: String| match extension(&path) {
Some(ext) => Ok(Value::String(lua.create_string(ext)?)),
None => Ok(Value::Nil),
})?,
)?;
path.set(
"normalize",
lua.create_function(|_, path: String| Ok(normalize(&path)))?,
)?;
path.set(
"is_absolute",
lua.create_function(|_, path: String| Ok(is_absolute(&path)))?,
)?;
Ok(path)
}
#[cfg(test)]
mod tests;