use std::{
ops::Range,
path::{Component, Path},
sync::LazyLock,
};
use regex::Regex;
#[cfg(test)]
#[path = "target_tests.rs"]
mod tests;
static TOKEN: LazyLock<Regex> = LazyLock::new(|| {
let pattern = if cfg!(windows) {
r"(?:[A-Za-z]:[\\/])?[\w.\-/\\+@~]+(?::\d+(?:[:-]\d+)?)?"
} else {
r"[\w.\-/+@~]+(?::\d+(?:[:-]\d+)?)?"
};
Regex::new(pattern).expect("the path pattern compiles")
});
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Mention {
pub(super) range: Range<usize>,
pub(super) path_len: usize,
pub(super) path: String,
}
pub(super) fn prose_mentions<'a>(
text: &'a str,
workspace: &'a Path,
) -> impl Iterator<Item = Mention> + 'a {
TOKEN.find_iter(text).filter_map(move |token| {
let at = usize::from(token.as_str().starts_with('@'));
let start = token.start() + at;
let written = token.as_str()[at..].trim_end_matches('.');
mention(written, workspace).map(|(path, path_len)| Mention {
range: start..start + written.len(),
path_len,
path,
})
})
}
pub(super) fn whole_mention(text: &str, workspace: &Path) -> Option<Mention> {
TOKEN
.find(text)
.filter(|token| token.start() == 0 && token.end() == text.len())?;
let (path, path_len) = mention(text, workspace)?;
Some(Mention {
range: 0..text.len(),
path_len,
path,
})
}
fn mention(written: &str, workspace: &Path) -> Option<(String, usize)> {
let drive = drive_len(written);
let path_len = written[drive..]
.find(':')
.map_or(written.len(), |colon| drive + colon);
let path = &written[..path_len];
if path.starts_with('~') {
return None;
}
let relative = if drive > 0 || path.starts_with('/') {
Path::new(path).strip_prefix(workspace).ok()?
} else {
Path::new(path)
};
let mut names: Vec<&str> = Vec::new();
let mut depth = 0usize;
for component in relative.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
depth = depth.checked_sub(1)?;
names.push("..");
}
Component::Normal(name) => {
depth += 1;
names.push(name.to_str()?);
}
Component::RootDir | Component::Prefix(_) => return None,
}
}
let name = *names.last().filter(|name| **name != "..")?;
let has_extension = name
.rsplit_once('.')
.is_some_and(|(_, extension)| extension.chars().any(char::is_alphabetic));
if names.len() < 2 && !has_extension {
return None;
}
Some((names.join("/"), path.len()))
}
fn drive_len(written: &str) -> usize {
match written.as_bytes() {
[letter, b':', b'/' | b'\\', ..] if cfg!(windows) && letter.is_ascii_alphabetic() => 2,
_ => 0,
}
}