Files
lucisv/crates/lucisv_server/src/uri.rs
T

151 lines
4.9 KiB
Rust

//! `file:` URI ↔ filesystem path.
//!
//! `lsp-types` 0.97 models a URI as a `fluent_uri::Uri`, which parses and
//! validates but does not know about file paths. The alternative was an
//! `lsp-types` old enough to use `url::Url` (five more packages, see the
//! feature README), so the ~40 lines live here instead.
use std::path::{Path, PathBuf};
use std::str::FromStr;
use lsp_types::Uri;
/// The `file:` URI naming an absolute path, or `None` if the path is not
/// valid UTF-8 or does not parse back as a URI.
pub fn path_to_uri(path: &Path) -> Option<Uri> {
let path = path.to_str()?;
let mut out = String::from("file://");
// A Windows path starts at a drive letter; a POSIX one already starts
// with the `/` that separates the (empty) authority from the path.
if !path.starts_with('/') {
out.push('/');
}
for byte in path.bytes() {
match byte {
b'/' | b'-' | b'.' | b'_' | b'~' => out.push(byte as char),
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' => out.push(byte as char),
// Windows separators become the URI's own.
b'\\' => out.push('/'),
_ => out.push_str(&format!("%{byte:02X}")),
}
}
Uri::from_str(&out).ok()
}
/// The path a `file:` URI names, or `None` for any other scheme.
pub fn uri_to_path(uri: &Uri) -> Option<PathBuf> {
let rest = uri.as_str().strip_prefix("file://")?;
// An authority (`file://host/path`) is skipped; the path starts at the
// first `/`. `file:///path` leaves `rest` already starting with one.
let path = match rest.strip_prefix('/') {
Some(_) => rest,
None => &rest[rest.find('/')?..],
};
let decoded = String::from_utf8(percent_decode(path)).ok()?;
// `file:///C:/x` names `C:/x`, not `/C:/x`. Guarded, because `/C:` is a
// legal POSIX directory name.
if cfg!(windows) {
if let Some(tail) = drive_letter_tail(&decoded) {
return Some(PathBuf::from(tail));
}
}
Some(PathBuf::from(decoded))
}
/// `/C:/x` → `C:/x`, when the leading `/` is a URI artifact and not a root.
fn drive_letter_tail(path: &str) -> Option<&str> {
let tail = path.strip_prefix('/')?;
let mut chars = tail.chars();
match (chars.next(), chars.next()) {
(Some(c), Some(':')) if c.is_ascii_alphabetic() => Some(tail),
_ => None,
}
}
/// Undo percent-encoding. A `%` not followed by two hex digits is kept as
/// written rather than rejected — an editor's URI is not a place to be strict.
fn percent_decode(s: &str) -> Vec<u8> {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
(b'%', Some(&hi), Some(&lo)) => match (hex(hi), hex(lo)) {
(Some(hi), Some(lo)) => {
out.push(hi * 16 + lo);
i += 3;
}
_ => {
out.push(b'%');
i += 1;
}
},
(byte, _, _) => {
out.push(byte);
i += 1;
}
}
}
out
}
fn hex(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip(path: &str) {
let uri = path_to_uri(Path::new(path)).expect("encodable");
assert_eq!(uri_to_path(&uri).as_deref(), Some(Path::new(path)), "for {path}");
}
#[test]
fn a_plain_path_round_trips() {
round_trip("/home/u/rtl/top.sv");
assert_eq!(
path_to_uri(Path::new("/home/u/rtl/top.sv")).map(|u| u.as_str().to_string()),
Some("file:///home/u/rtl/top.sv".to_string())
);
}
#[test]
fn spaces_and_specials_are_percent_encoded() {
let uri = path_to_uri(Path::new("/a b/c#d?e/f.sv")).expect("encodable");
assert_eq!(uri.as_str(), "file:///a%20b/c%23d%3Fe/f.sv");
round_trip("/a b/c#d?e/f.sv");
}
#[test]
fn multi_byte_path_components_round_trip() {
round_trip("/rtl/münchen/✓/top.sv");
let uri = path_to_uri(Path::new("/rtl/é.sv")).expect("encodable");
assert_eq!(uri.as_str(), "file:///rtl/%C3%A9.sv");
}
#[test]
fn a_non_file_scheme_is_rejected() {
let uri = Uri::from_str("untitled:Untitled-1").expect("parses");
assert_eq!(uri_to_path(&uri), None);
}
#[test]
fn an_authority_is_skipped() {
let uri = Uri::from_str("file://localhost/rtl/top.sv").expect("parses");
assert_eq!(uri_to_path(&uri).as_deref(), Some(Path::new("/rtl/top.sv")));
}
#[test]
fn a_stray_percent_is_kept_rather_than_rejected() {
assert_eq!(percent_decode("100%/x"), b"100%/x".to_vec());
assert_eq!(percent_decode("%zz"), b"%zz".to_vec());
}
}