hyperlink.rs
This file
Path
src/hyperlink.rs
87 lines · 2.3 KiB · Rust
Last changed by
Merge pull request #1872 from josephadamsdev/fix-1843-windows-hyperlink-slashThayne McCombsbefore adoption1a37650
History of this fileTake it
1use crate::filesystem::absolute_path;2use std::fmt::{self, Formatter, Write};3use std::path::{Path, PathBuf};45pub(crate) struct PathUrl(PathBuf);67impl PathUrl {8 pub(crate) fn new(path: &Path) -> Option<PathUrl> {9 Some(PathUrl(absolute_path(path).ok()?))10 }11}1213impl fmt::Display for PathUrl {14 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {15 write!(f, "file://{}", host())?;16 let bytes = self.0.as_os_str().as_encoded_bytes();17 for &byte in bytes.iter() {18 encode(f, byte)?;19 }20 Ok(())21 }22}2324fn encode(f: &mut Formatter, byte: u8) -> fmt::Result {25 // NOTE:26 // Most terminals can handle non-ascii unicode characters in a file url fine. But on some OSes (notably27 // windows), the encoded bytes of the path may not be valid UTF-8. Since we don't know if a28 // byte >= 128 is part of a valid UTF-8 encoding or not, we just percent encode any non-ascii29 // byte.30 // Percent encoding these bytes is probably safer anyway.31 match byte {32 b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'/' | b':' | b'-' | b'.' | b'_' | b'~' => {33 f.write_char(byte.into())34 }35 #[cfg(windows)]36 b'\\' => f.write_char('/'),37 _ => {38 write!(f, "%{byte:02X}")39 }40 }41}4243#[cfg(unix)]44fn host() -> &'static str {45 use std::sync::OnceLock;4647 static HOSTNAME: OnceLock<String> = OnceLock::new();4849 HOSTNAME50 .get_or_init(|| {51 nix::unistd::gethostname()52 .ok()53 .and_then(|h| h.into_string().ok())54 .unwrap_or_default()55 })56 .as_ref()57}5859#[cfg(not(unix))]60const fn host() -> &'static str {61 "/"62}6364#[cfg(test)]65mod test {66 use super::*;6768 // This allows us to test the encoding without having to worry about the host, or absolute path69 struct Encoded(&'static str);7071 impl fmt::Display for Encoded {72 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {73 for byte in self.0.bytes() {74 encode(f, byte)?;75 }76 Ok(())77 }78 }7980 #[test]81 fn test_unicode_encoding() {82 assert_eq!(83 Encoded("$*\x1bßé/∫😃\x07").to_string(),84 "%24%2A%1B%C3%9F%C3%A9/%E2%88%AB%F0%9F%98%83%07",85 );86 }87}