#![deny(unsafe_code)]
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use crate::plat::{path as ppath, Platform};
pub trait Fs {
fn is_file(&self, path: &Path) -> bool;
fn is_dir(&self, path: &Path) -> bool;
fn read(&self, path: &Path) -> Result<String, String>;
}
pub struct RealFs;
impl Fs for RealFs {
fn is_file(&self, path: &Path) -> bool {
path.is_file()
}
fn is_dir(&self, path: &Path) -> bool {
path.is_dir()
}
fn read(&self, path: &Path) -> Result<String, String> {
crate::md::sanitize::read_file(path).map_err(|e| format!("{}: {}", path.display(), e))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
Doc {
path: PathBuf,
anchor: Option<String>,
},
Anchor(String),
External(String),
Broken { raw: String, why: String },
}
impl Target {
pub fn describe(&self, root: &Path) -> String {
match self {
Target::Doc { path, anchor } => {
let base = rel_to(path, root);
match anchor {
Some(a) => format!("{base}#{a}"),
None => base,
}
}
Target::Anchor(a) => format!("#{a}"),
Target::External(url) => url.clone(),
Target::Broken { raw, why } => format!("{raw}: {why}"),
}
}
pub fn yank_text(&self, root: &Path) -> String {
match self {
Target::External(url) => url.clone(),
Target::Doc { path, .. } => rel_to(path, root),
Target::Anchor(a) => format!("#{a}"),
Target::Broken { raw, .. } => raw.clone(),
}
}
}
pub fn rel_to(path: &Path, root: &Path) -> String {
let rel = ppath::rel_to(
Platform::HOST,
&root.to_string_lossy(),
&path.to_string_lossy(),
);
match ppath::sep(Platform::HOST) {
'/' => rel,
native => rel.replace(native, "/"),
}
}
pub fn within_root(path: &Path, root: &Path) -> bool {
ppath::contains(
Platform::HOST,
&root.to_string_lossy(),
&path.to_string_lossy(),
)
}
pub fn same_path(a: &Path, b: &Path) -> bool {
ppath::same(Platform::HOST, &a.to_string_lossy(), &b.to_string_lossy())
}
fn broken(raw: &str, why: &str) -> Target {
Target::Broken {
raw: raw.to_string(),
why: why.to_string(),
}
}
pub fn resolve(raw: &str, doc_dir: &Path, root: &Path, fs: &dyn Fs) -> Target {
let raw = raw.trim();
if raw.is_empty() {
return broken(raw, "empty link");
}
if let Some(frag) = raw.strip_prefix('#') {
return Target::Anchor(frag.to_string());
}
if scheme_of(raw).is_some() {
return Target::External(raw.to_string());
}
let (path_part, anchor) = split_fragment(raw);
if path_part.is_empty() {
return match anchor {
Some(a) => Target::Anchor(a),
None => broken(raw, "empty link"),
};
}
let decoded = percent_decode(path_part);
let absolute = ppath::markdown_is_rooted(Platform::HOST, &decoded);
let base = if absolute { root } else { doc_dir };
let rel = ppath::markdown_trim_root(Platform::HOST, &decoded);
let joined = match normalize(base, rel) {
Some(p) => p,
None => return broken(raw, "link escapes the index root"),
};
if !within_root(&joined, root) {
return broken(raw, "link escapes the index root");
}
let joined = match fs.is_file(&joined) || fs.is_dir(&joined) {
true => joined,
false => root_named(rel, root, fs).unwrap_or(joined),
};
classify_path(raw, joined, anchor, fs)
}
fn root_named(rel: &str, root: &Path, fs: &dyn Fs) -> Option<PathBuf> {
let name = root.file_name()?.to_str()?;
let rest = rel.strip_prefix(name)?.strip_prefix('/')?;
let path = normalize(root, rest)?;
(fs.is_file(&path) || fs.is_dir(&path)).then_some(path)
}
fn classify_path(raw: &str, path: PathBuf, anchor: Option<String>, fs: &dyn Fs) -> Target {
if fs.is_dir(&path) {
let readme = path.join("README.md");
if fs.is_file(&readme) {
return Target::Doc {
path: readme,
anchor,
};
}
return Target::Doc { path, anchor };
}
if fs.is_file(&path) {
return Target::Doc { path, anchor };
}
if path.extension().is_none() {
let mut with_md = OsString::from(path.as_os_str());
with_md.push(".md");
let candidate = PathBuf::from(with_md);
if fs.is_file(&candidate) {
return Target::Doc {
path: candidate,
anchor,
};
}
}
broken(raw, "no such file")
}
pub fn is_markdown(path: &Path) -> bool {
crate::source::detect::from_path(path) == Some(crate::source::detect::Format::Markdown)
}
pub fn split_fragment(raw: &str) -> (&str, Option<String>) {
match raw.split_once('#') {
Some((p, f)) if !f.is_empty() => (p, Some(f.to_string())),
Some((p, _)) => (p, None),
None => (raw, None),
}
}
pub use crate::url::scheme_of;
pub fn normalize(base: &Path, rel: &str) -> Option<PathBuf> {
ppath::join(Platform::HOST, &base.to_string_lossy(), rel).map(PathBuf::from)
}
pub fn percent_decode(s: &str) -> String {
if !s.contains('%') {
return s.to_string();
}
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Some(b) = hex_byte(bytes[i + 1], bytes[i + 2]) {
out.push(b);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8(out).unwrap_or_else(|_| s.to_string())
}
fn hex_byte(hi: u8, lo: u8) -> Option<u8> {
Some(hex_digit(hi)? << 4 | hex_digit(lo)?)
}
fn hex_digit(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
#[cfg(test)]
mod decode_tests {
use super::*;
#[test]
fn plain_strings_pass_through() {
assert_eq!(percent_decode("models/SAMPLE_MODEL.md"), "models/SAMPLE_MODEL.md");
assert_eq!(percent_decode(""), "");
}
#[test]
fn well_formed_escapes_decode() {
assert_eq!(percent_decode("a%20b.md"), "a b.md");
assert_eq!(percent_decode("%41%42"), "AB");
assert_eq!(percent_decode("%2Fx"), "/x");
assert_eq!(percent_decode("%E2%82%AC.md"), "\u{20ac}.md");
}
#[test]
fn malformed_escapes_are_left_verbatim() {
assert_eq!(percent_decode("100%"), "100%");
assert_eq!(percent_decode("%zz"), "%zz");
assert_eq!(percent_decode("%a"), "%a");
assert_eq!(percent_decode("%"), "%");
}
#[test]
fn a_percent_next_to_a_multibyte_char_does_not_panic() {
assert_eq!(percent_decode("%a\u{20ac}"), "%a\u{20ac}");
assert_eq!(percent_decode("%\u{20ac}"), "%\u{20ac}");
assert_eq!(percent_decode("x%\u{1f600}y"), "x%\u{1f600}y");
assert_eq!(percent_decode("%4\u{20ac}"), "%4\u{20ac}");
assert_eq!(percent_decode("%ff"), "%ff");
}
#[test]
fn resolving_a_percent_encoded_link_is_panic_free() {
struct Nothing;
impl Fs for Nothing {
fn is_file(&self, _p: &Path) -> bool {
false
}
fn is_dir(&self, _p: &Path) -> bool {
false
}
fn read(&self, _p: &Path) -> Result<String, String> {
Err("no".into())
}
}
let root = Path::new("/corpus");
for raw in ["%a\u{20ac}", "%\u{20ac}#frag", "a%2", "%%%", "d%c3%a9j%c3%a0.md"] {
let t = resolve(raw, root, root, &Nothing);
assert!(matches!(t, Target::Broken { .. }), "{raw} -> {t:?}");
}
}
}