use crate::util::{MediaMarkerKind, UnwrapPoison};
use base64::{
Engine as _,
engine::general_purpose::{STANDARD, URL_SAFE, URL_SAFE_NO_PAD},
};
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::OsString;
use std::io::Cursor;
use std::path::{Component, Path, PathBuf};
use std::sync::{LazyLock, Mutex};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MediaTarget {
LocalImage,
RemoteUrl,
Invalid,
}
pub(crate) const MAX_DATA_URI_ENCODED_BYTES: usize = 20 * 1024 * 1024;
pub(crate) const RASTER_DECODE_MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024;
pub(crate) const RASTER_DECODE_MAX_DIMENSION_PX: u32 = 16384;
#[must_use]
pub(crate) fn raster_decode_limits() -> image::Limits {
let mut limits = image::Limits::default();
limits.max_alloc = Some(RASTER_DECODE_MAX_ALLOC_BYTES);
limits.max_image_width = Some(RASTER_DECODE_MAX_DIMENSION_PX);
limits.max_image_height = Some(RASTER_DECODE_MAX_DIMENSION_PX);
limits
}
#[must_use]
pub(crate) fn classify_media_image_target(target: &str) -> MediaTarget {
let trimmed = target.trim();
if is_valid_remote_url(trimmed) {
MediaTarget::RemoteUrl
} else if is_decodable_local_raster(trimmed) {
MediaTarget::LocalImage
} else {
MediaTarget::Invalid
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MarkerTarget {
NotAReference,
Inline,
Remote,
Local(PathBuf),
}
#[must_use]
pub(crate) fn resolve_marker_target(target: &str, roots: &[PathBuf]) -> MarkerTarget {
let target = target.trim();
if is_inline_payload(target) {
return MarkerTarget::Inline;
}
if crate::util::is_http_url(target) {
return MarkerTarget::Remote;
}
let raw = Path::new(target);
if raw.is_absolute() {
return MarkerTarget::Local(raw.to_path_buf());
}
if let Some(joined) = roots
.iter()
.map(|root| root.join(raw))
.find(|candidate| candidate.exists())
{
return MarkerTarget::Local(joined);
}
if !names_a_reference(target) {
return MarkerTarget::NotAReference;
}
MarkerTarget::Local(
roots
.first()
.map_or_else(|| raw.to_path_buf(), |root| root.join(raw)),
)
}
const REPAIR_MARGIN: usize = 2;
#[must_use]
pub(crate) fn repaired_local_target(path: &Path) -> Option<PathBuf> {
if !path.is_absolute() || path.to_string_lossy().ends_with(['/', '\\']) || !is_missing(path) {
return None;
}
let components: Vec<Component<'_>> = path.components().collect();
let mut prefix = PathBuf::new();
let missing = components.iter().position(|component| {
prefix.push(component);
is_missing(&prefix)
})?;
if !matches!(components[missing], Component::Normal(_))
|| missing + 1 == components.len()
|| components[missing + 1..].contains(&Component::ParentDir)
{
return None;
}
let name = components[missing].as_os_str().to_str()?;
let directory: PathBuf = components[..missing].iter().collect();
let candidate = unique_near_directory(&directory, name)?;
let repaired = directory
.join(candidate)
.join(components[missing + 1..].iter().collect::<PathBuf>());
std::fs::metadata(&repaired).is_ok().then_some(repaired)
}
fn is_missing(path: &Path) -> bool {
matches!(
std::fs::symlink_metadata(path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound
)
}
fn unique_near_directory(directory: &Path, name: &str) -> Option<OsString> {
let written: Vec<char> = crate::util::caseless_name_key(name).chars().collect();
let limit = (written.len() / 2).max(1);
let mut best: Option<(usize, OsString)> = None;
let mut runner_up = usize::MAX;
for entry in std::fs::read_dir(directory).ok()?.flatten() {
if !entry.metadata().is_ok_and(|meta| meta.is_dir()) {
continue;
}
let candidate = entry.file_name();
let Some(text) = candidate.to_str() else {
continue;
};
let lowered: Vec<char> = crate::util::caseless_name_key(text).chars().collect();
let Some(distance) = edit_distance_within(&written, &lowered, limit) else {
continue;
};
match &best {
Some((best_distance, _)) if *best_distance <= distance => {
runner_up = runner_up.min(distance);
}
_ => {
if let Some((best_distance, _)) = best.replace((distance, candidate)) {
runner_up = runner_up.min(best_distance);
}
}
}
}
let (distance, candidate) = best?;
(runner_up >= distance + REPAIR_MARGIN).then_some(candidate)
}
fn edit_distance_within(a: &[char], b: &[char], limit: usize) -> Option<usize> {
if a.len().abs_diff(b.len()) > limit {
return None;
}
let mut previous: Vec<usize> = (0..=b.len()).collect();
let mut current = vec![0_usize; b.len() + 1];
for (row, from) in a.iter().enumerate() {
current[0] = row + 1;
let mut row_best = current[0];
for (column, to) in b.iter().enumerate() {
current[column + 1] = (previous[column + 1] + 1)
.min(current[column] + 1)
.min(previous[column] + usize::from(from != to));
row_best = row_best.min(current[column + 1]);
}
if row_best > limit {
return None;
}
std::mem::swap(&mut previous, &mut current);
}
(previous[b.len()] <= limit).then_some(previous[b.len()])
}
#[must_use]
pub(crate) fn is_inline_payload(target: &str) -> bool {
target.starts_with("data:") || target.starts_with(crate::util::DATA_URI_OMITTED_PREFIX)
}
#[must_use]
pub(crate) fn target_file_key(target: &str, roots: &[PathBuf]) -> Option<PathBuf> {
let MarkerTarget::Local(path) = resolve_marker_target(target, roots) else {
return None;
};
let path = repaired_local_target(&path).unwrap_or(path);
Some(file_key(&path))
}
#[must_use]
pub(crate) fn file_key(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn names_a_reference(target: &str) -> bool {
target.contains('/')
|| target.contains('\\')
|| target
.rsplit_once('.')
.is_some_and(|(stem, extension)| !stem.is_empty() && !extension.is_empty())
}
pub(crate) enum RemoteMarker {
Deliverable,
Refused(&'static str),
}
#[must_use]
pub(crate) fn remote_marker(kind: MediaMarkerKind, target: &str) -> RemoteMarker {
let reason = match kind {
MediaMarkerKind::File => FILE_URL_REASON,
MediaMarkerKind::Image if !is_valid_remote_url(target) => INVALID_ADDRESS_REASON,
MediaMarkerKind::Image | MediaMarkerKind::Audio | MediaMarkerKind::Video => {
return RemoteMarker::Deliverable;
}
};
RemoteMarker::Refused(reason)
}
#[must_use]
pub(crate) fn inline_marker_refusal(kind: MediaMarkerKind) -> String {
marker_refusal(&kind.noun(), INLINE_PAYLOAD_REASON)
}
#[must_use]
pub(crate) fn local_refusal(kind: MediaMarkerKind, path: &Path) -> Option<&'static str> {
if kind == MediaMarkerKind::Image {
image_target_refusal(path)
} else {
local_target_refusal(path)
}
}
#[must_use]
fn local_target_refusal(path: &Path) -> Option<&'static str> {
if path.is_relative() {
return Some(NO_WORKSPACE_REASON);
}
match std::fs::metadata(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(FILE_NOT_FOUND_REASON),
Err(_) => Some(UNREADABLE_REASON),
Ok(metadata) if metadata.is_dir() => Some(DIRECTORY_REASON),
Ok(metadata) if !metadata.is_file() => Some(NOT_A_FILE_REASON),
Ok(_) => None,
}
}
#[must_use]
fn image_target_refusal(path: &Path) -> Option<&'static str> {
use std::io::Read as _;
if let Some(reason) = local_target_refusal(path) {
return Some(reason);
}
let Ok(mut file) = std::fs::File::open(path) else {
return Some(UNREADABLE_REASON);
};
let mut head = [0_u8; 16];
let Ok(read) = file.read(&mut head) else {
return Some(UNREADABLE_REASON);
};
if matches!(
image::guess_format(&head[..read]),
Ok(image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::WebP)
) {
None
} else {
Some(NOT_AN_IMAGE_REASON)
}
}
pub(crate) const FILE_NOT_FOUND_REASON: &str = "file not found.";
pub(crate) const DIRECTORY_REASON: &str = "it is a directory.";
pub(crate) const NO_WORKSPACE_REASON: &str = "the message's workspace is unknown.";
pub(crate) const UNREADABLE_REASON: &str = "it could not be read.";
pub(crate) const INLINE_PAYLOAD_REASON: &str = "it carries an inline payload, not a file.";
pub(crate) const NOT_AN_IMAGE_REASON: &str = "it is not an image.";
pub(crate) const NOT_A_FILE_REASON: &str = "it is not a regular file.";
pub(crate) const INVALID_ADDRESS_REASON: &str = "it is not a valid address.";
pub(crate) const FILE_URL_REASON: &str = "an address is not a local file.";
#[must_use]
pub(crate) fn marker_name(target: &str) -> String {
crate::util::truncate(
crate::util::file_name_or_path(without_credentials(target).as_ref()),
60,
)
}
#[must_use]
pub(crate) fn recordable_target(target: &str) -> Option<Cow<'_, str>> {
let target = target.trim();
if target.to_ascii_lowercase().starts_with("data:") {
return None;
}
Some(without_credentials(target))
}
fn without_credentials(target: &str) -> Cow<'_, str> {
let (prefix, rest) = if let Some((scheme, rest)) = target.split_once("://") {
(&target[..scheme.len() + 3], rest)
} else if let Some(rest) = target.strip_prefix("//") {
("//", rest)
} else {
return Cow::Borrowed(target);
};
let without_value = rest.split(['?', '#']).next().unwrap_or(rest);
let (authority, path) = without_value.split_once('/').unwrap_or((without_value, ""));
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
Cow::Owned(format!("{prefix}{host}/{path}"))
}
#[must_use]
pub(crate) fn marker_refusal(name: &str, reason: &str) -> String {
format!("Could not send \"{name}\": {reason}")
}
#[must_use]
pub(crate) fn marker_refusal_for(target: &str, reason: &str) -> String {
marker_refusal(&marker_name(target), reason)
}
#[must_use]
pub(crate) fn is_valid_remote_url(target: &str) -> bool {
let Some(rest) = target
.strip_prefix("https://")
.or_else(|| target.strip_prefix("http://"))
else {
return false;
};
if rest.chars().any(char::is_whitespace) {
return false;
}
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
if authority.is_empty() || authority.starts_with(':') || authority.contains('@') {
return false;
}
let Some((host, port)) = split_authority_host_port(authority) else {
return false;
};
if !port.is_empty()
&& (!port.bytes().all(|b| b.is_ascii_digit()) || !port.parse::<u16>().is_ok_and(|x| x > 0))
{
return false;
}
if host.starts_with('[') {
host.ends_with(']')
&& host.len() > 2
&& host.matches('[').count() == 1
&& host.matches(']').count() == 1
} else {
!host.is_empty() && !host.contains(':') && !host.contains('[')
}
}
fn split_authority_host_port(authority: &str) -> Option<(&str, &str)> {
if let Some(close) = authority.find(']') {
if !authority.starts_with('[') {
return None;
}
let after = &authority[close + 1..];
if after.is_empty() {
return Some((&authority[..=close], ""));
}
let port = after.strip_prefix(':')?;
if port.is_empty() {
return None; }
Some((&authority[..=close], port))
} else {
match authority.rsplit_once(':') {
Some((host, port)) if !port.is_empty() => Some((host, port)),
Some(_) => None, None => Some((authority, "")),
}
}
}
#[must_use]
pub(crate) fn data_uri_base64_payload(uri: &str) -> Option<&str> {
let rest = uri.strip_prefix("data:")?;
let payload_start = rest.rfind(";base64,")? + ";base64,".len();
let payload = &rest[payload_start..];
(payload.len() <= MAX_DATA_URI_ENCODED_BYTES).then_some(payload)
}
fn declared_data_uri_format(target: &str) -> Option<image::ImageFormat> {
let rest = target.strip_prefix("data:image/")?;
let subtype = rest.split(';').next().unwrap_or("").trim();
let declared = image::ImageFormat::from_extension(subtype)?;
crate::util::image_format_native_label(declared)
.is_some()
.then_some(declared)
}
fn parse_native_data_uri(uri: &str) -> Option<(image::ImageFormat, Vec<u8>)> {
let declared = declared_data_uri_format(uri)?;
let payload = data_uri_base64_payload(uri)?;
let bytes = decode_base64_payload(payload)?;
if image::guess_format(&bytes).ok()? != declared {
return None;
}
Some((declared, bytes))
}
#[must_use]
pub(crate) fn decode_native_data_uri(
uri: &str,
limits: image::Limits,
) -> Option<(u32, u32, Vec<u8>)> {
let (_, bytes) = parse_native_data_uri(uri)?;
decode_raster_bytes(&bytes, limits)
}
#[must_use]
pub(crate) fn is_native_data_uri(target: &str) -> bool {
parse_native_data_uri(target)
.is_some_and(|(_, bytes)| decode_raster(&bytes, raster_decode_limits()).is_some())
}
#[must_use]
fn decode_base64_payload(s: &str) -> Option<Vec<u8>> {
let compact: Cow<'_, [u8]> = if s.as_bytes().iter().any(u8::is_ascii_whitespace) {
Cow::Owned(
s.bytes()
.filter(|b| !b.is_ascii_whitespace())
.collect::<Vec<u8>>(),
)
} else {
Cow::Borrowed(s.as_bytes())
};
if compact.is_empty() {
return None;
}
STANDARD
.decode(compact.as_ref())
.ok()
.or_else(|| URL_SAFE.decode(compact.as_ref()).ok())
.or_else(|| URL_SAFE_NO_PAD.decode(compact.as_ref()).ok())
}
pub(crate) fn decode_raster_image(
bytes: &[u8],
limits: image::Limits,
) -> anyhow::Result<image::DynamicImage> {
let format = image::guess_format(bytes)
.map_err(|e| anyhow::anyhow!("not a recognisable image format ({e})"))?;
if crate::util::image_format_native_label(format).is_none() {
anyhow::bail!(
"{} is not one of the formats this tool decodes (PNG, JPEG, WEBP)",
format
.extensions_str()
.first()
.copied()
.unwrap_or("unknown")
);
}
let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format);
reader.limits(limits);
Ok(reader.decode()?)
}
fn decode_raster(bytes: &[u8], limits: image::Limits) -> Option<image::DynamicImage> {
decode_raster_image(bytes, limits).ok()
}
#[must_use]
pub(crate) fn decode_raster_bytes(
bytes: &[u8],
limits: image::Limits,
) -> Option<(u32, u32, Vec<u8>)> {
let img = decode_raster(bytes, limits)?;
let rgba = img.to_rgba8();
Some((rgba.width(), rgba.height(), rgba.into_raw()))
}
static LOCAL_RASTER_DECODE_CACHE: LazyLock<Mutex<HashMap<(PathBuf, std::time::SystemTime), bool>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
const LOCAL_RASTER_CACHE_MAX_ENTRIES: usize = 4096;
#[must_use]
fn is_decodable_local_raster(target: &str) -> bool {
let path = Path::new(target);
if !path.is_absolute() {
return false;
}
let Ok(meta) = std::fs::metadata(path) else {
return false;
};
if !meta.is_file() || meta.len() > crate::util::INBOUND_IMAGE_MAX_INPUT_BYTES {
return false;
}
let Ok(mtime) = meta.modified() else {
return false;
};
let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let key = (canonical.clone(), mtime);
{
let cache = LOCAL_RASTER_DECODE_CACHE.lock().unwrap_poison();
if let Some(&result) = cache.get(&key) {
return result;
}
}
let result = is_decodable_raster_file(&canonical);
let mut cache = LOCAL_RASTER_DECODE_CACHE.lock().unwrap_poison();
if cache.len() >= LOCAL_RASTER_CACHE_MAX_ENTRIES {
cache.clear();
}
cache.insert(key, result);
result
}
#[must_use]
fn is_decodable_raster_file(path: &Path) -> bool {
std::fs::read(path).is_ok_and(|bytes| decode_raster(&bytes, raster_decode_limits()).is_some())
}
#[cfg(test)]
mod tests {
use super::*;
use base64::engine::general_purpose::STANDARD;
fn write_temp_png(tag: &str) -> std::path::PathBuf {
use std::io::Write;
let path = std::env::temp_dir().join(format!(
"mahbot_media_target_{tag}_{}.png",
std::process::id()
));
let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
let mut buf = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.expect("test PNG must encode");
std::fs::File::create(&path)
.and_then(|mut f| f.write_all(&buf))
.expect("test PNG must write");
path
}
#[test]
fn remote_url_valid_and_malformed() {
assert_eq!(
classify_media_image_target("https://example.com/b.jpg"),
MediaTarget::RemoteUrl
);
assert_eq!(
classify_media_image_target("http://127.0.0.1:8080/img.png"),
MediaTarget::RemoteUrl
);
assert_eq!(classify_media_image_target("http://"), MediaTarget::Invalid);
assert_eq!(
classify_media_image_target("https://exa mple.com/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https:// example.com/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://:8080/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://example.com:99999/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://example.com:/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://[::1/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://user:pass@host/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://user@host/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://[::1]:8080/img.png"),
MediaTarget::RemoteUrl
);
assert_eq!(
classify_media_image_target("https://host:8080:9999/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://[::1]:80:90/img.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://[]/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://[::1]foo:80/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://host[::1]:80/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("https://[::1]/img.png"),
MediaTarget::RemoteUrl
);
assert_eq!(
classify_media_image_target("https://example.com/foo bar.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://host[/x.png"),
MediaTarget::Invalid
);
assert_eq!(
classify_media_image_target("http://host[foo:80"),
MediaTarget::Invalid
);
}
#[test]
fn data_uri_native_and_fake() {
let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
let mut buf = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.expect("test PNG must encode");
let uri = format!("data:image/png;base64,{}", STANDARD.encode(&buf));
assert_eq!(classify_media_image_target(&uri), MediaTarget::Invalid);
assert!(is_native_data_uri(&uri));
assert!(!is_native_data_uri("data:image/png;base64,abcd"));
let truncated = {
let payload = uri
.strip_prefix("data:image/png;base64,")
.expect("tiny png uri");
let bytes = STANDARD
.decode(payload.as_bytes())
.expect("tiny png base64");
let t = &bytes[..bytes.len().min(24)];
format!("data:image/png;base64,{}", STANDARD.encode(t))
};
assert!(!is_native_data_uri(&truncated));
assert!(!is_native_data_uri("data:image/gif;base64,R0lGOD"));
let mut jbuf = Vec::new();
image::RgbImage::from_pixel(1, 1, image::Rgb([255, 0, 0]))
.write_to(
&mut std::io::Cursor::new(&mut jbuf),
image::ImageFormat::Jpeg,
)
.expect("test JPEG must encode");
let mismatched = format!("data:image/png;base64,{}", STANDARD.encode(&jbuf));
assert!(!is_native_data_uri(&mismatched));
}
#[test]
fn data_uri_base64_payload_extracts_and_caps() {
let cases: &[(&str, Option<&str>)] = &[
("data:image/png;base64,AAAA", Some("AAAA")),
("data:image/png;charset=utf-8;base64,BBBB", Some("BBBB")),
("/tmp/photo.png", None),
("https://example.com/img.png", None),
("data:image/png,raw-bytes", None),
("data:image/png;base64,", Some("")),
];
for (uri, expected) in cases {
assert_eq!(data_uri_base64_payload(uri), *expected, "case: {uri}");
}
let over = format!(
"data:image/png;base64,{}",
"A".repeat(MAX_DATA_URI_ENCODED_BYTES + 1)
);
assert_eq!(data_uri_base64_payload(&over), None);
}
#[test]
fn local_targets_classify_by_a_real_decode() {
let png = write_temp_png("valid");
let dir = png.parent().expect("temp path has a parent");
let text = dir.join(format!(
"mahbot_media_target_{}_notimage.txt",
std::process::id()
));
std::fs::write(&text, b"top secret").unwrap();
let corrupt = dir.join(format!(
"mahbot_media_target_{}_trunc.png",
std::process::id()
));
let bytes = std::fs::read(&png).unwrap();
std::fs::write(&corrupt, &bytes[..bytes.len().min(24)]).unwrap();
assert_eq!(
classify_media_image_target(png.to_str().unwrap()),
MediaTarget::LocalImage
);
for invalid in [
"",
" ",
"...",
"photo.png",
"/tmp/definitely_missing_mahbot.png",
text.to_str().unwrap(),
corrupt.to_str().unwrap(),
] {
assert_eq!(
classify_media_image_target(invalid),
MediaTarget::Invalid,
"target: {invalid:?}"
);
}
let _ = std::fs::remove_file(&png);
let _ = std::fs::remove_file(&text);
let _ = std::fs::remove_file(&corrupt);
}
#[test]
fn an_oversized_raster_is_not_refused_as_a_target() {
let png = write_temp_png("oversized");
std::fs::File::options()
.write(true)
.open(&png)
.and_then(|file| file.set_len(crate::util::INBOUND_IMAGE_MAX_INPUT_BYTES + 1))
.expect("a sparse oversized raster");
assert_eq!(local_refusal(MediaMarkerKind::Image, &png), None);
let _ = std::fs::remove_file(&png);
}
#[test]
fn refusal_names_hide_credentials() {
assert_eq!(
marker_name("https://cdn.example.com/a/poster.png?token=s3cret"),
"poster.png"
);
assert_eq!(
marker_name("https://user:pass@cdn.example.com/poster.png"),
"poster.png"
);
assert_eq!(
marker_name("https://user:pass@cdn.example.com#s3cret"),
"cdn.example.com"
);
assert_eq!(marker_name("generated/some-poster.png"), "some-poster.png");
assert_eq!(marker_name("generated/poster#2.png"), "poster#2.png");
assert_eq!(
recordable_target("/tmp/a.png").as_deref(),
Some("/tmp/a.png")
);
assert_eq!(
recordable_target("HTTPS://user:pass@cdn.example.com/a.png?token=s3cret").as_deref(),
Some("HTTPS://cdn.example.com/a.png")
);
assert_eq!(
recordable_target("//user:pass@cdn.example.com/a.png?token=s3cret").as_deref(),
Some("//cdn.example.com/a.png")
);
assert_eq!(recordable_target("data:image/png;base64,AAAA"), None);
assert_eq!(recordable_target("DATA:image/png;base64,AAAA"), None);
}
#[test]
fn a_mistyped_directory_resolves_to_the_file_it_meant() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let generated = root.join("userspaces").join("lyuba").join("generated");
std::fs::create_dir_all(&generated).unwrap();
let png = generated.join("shot.png");
std::fs::write(&png, b"png").unwrap();
let ancestor_typo = root
.join("userseas")
.join("lyuba")
.join("generated")
.join("shot.png");
assert_eq!(repaired_local_target(&ancestor_typo), Some(png.clone()));
let parent_typo = root
.join("userspaces")
.join("lyuba")
.join("generatd")
.join("shot.png");
assert_eq!(repaired_local_target(&parent_typo), Some(png.clone()));
assert_eq!(repaired_local_target(&png), None);
assert_eq!(repaired_local_target(&generated.join("shot.pgn")), None);
assert_eq!(
repaired_local_target(&PathBuf::from(format!("{}/", png.display()))),
None
);
assert_eq!(
repaired_local_target(&root.join("userseas").join("..").join("shot.png")),
None
);
assert_eq!(
repaired_local_target(&root.join("zzzz").join("shot.png")),
None
);
assert_eq!(
repaired_local_target(&root.join("userseas").join("lyuba").join("gone.png")),
None
);
assert_eq!(
repaired_local_target(
&root
.join("userseas")
.join("userspaces")
.join("lyuba")
.join("generated")
.join("shot.png")
),
None
);
std::fs::create_dir_all(root.join("alpha")).unwrap();
std::fs::create_dir_all(root.join("alphb")).unwrap();
assert_eq!(
repaired_local_target(&root.join("alphx").join("shot.png")),
None
);
}
#[test]
fn workspace_files_decide_bare_word_references() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("Makefile"), b"all:").unwrap();
std::fs::write(dir.path().join("poster.thumbnail"), b"x").unwrap();
let roots = [dir.path().to_path_buf()];
for name in ["Makefile", "poster.thumbnail"] {
assert_eq!(
resolve_marker_target(name, &roots),
MarkerTarget::Local(dir.path().join(name)),
"{name} is a file the workspace has"
);
}
assert_eq!(
resolve_marker_target("path", &roots),
MarkerTarget::NotAReference
);
assert_eq!(
resolve_marker_target("plot.png", &roots),
MarkerTarget::Local(dir.path().join("plot.png"))
);
}
}