From 247bd19f93e11fb037c945ff1dc464a1d1713471 Mon Sep 17 00:00:00 2001 From: mo8it Date: Wed, 4 Sep 2024 02:19:45 +0200 Subject: Canonicalize exercise paths only once --- src/term.rs | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) (limited to 'src/term.rs') diff --git a/src/term.rs b/src/term.rs index 489d658..5b557ec 100644 --- a/src/term.rs +++ b/src/term.rs @@ -1,14 +1,13 @@ -use std::{ - fmt, fs, - io::{self, BufRead, StdoutLock, Write}, -}; - use crossterm::{ cursor::MoveTo, style::{Attribute, Color, SetAttribute, SetForegroundColor}, terminal::{Clear, ClearType}, Command, QueueableCommand, }; +use std::{ + fmt, fs, + io::{self, BufRead, StdoutLock, Write}, +}; pub struct MaxLenWriter<'a, 'b> { pub stdout: &'a mut StdoutLock<'b>, @@ -151,25 +150,29 @@ pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> { stdout.write_all(b"\n") } +/// Canonicalize, convert to string and remove verbatim part on Windows. +pub fn canonicalize(path: &str) -> Option { + fs::canonicalize(path) + .ok()? + .into_os_string() + .into_string() + .ok() + .map(|mut path| { + // Windows itself can't handle its verbatim paths. + if cfg!(windows) && path.as_bytes().starts_with(br"\\?\") { + path.drain(..4); + } + + path + }) +} + pub fn terminal_file_link<'a>( writer: &mut impl CountedWrite<'a>, path: &str, + canonical_path: &str, color: Color, ) -> io::Result<()> { - let canonical_path = fs::canonicalize(path).ok(); - - let Some(canonical_path) = canonical_path.as_deref().and_then(|p| p.to_str()) else { - return writer.write_str(path); - }; - - // Windows itself can't handle its verbatim paths. - #[cfg(windows)] - let canonical_path = if canonical_path.len() > 5 && &canonical_path[0..4] == r"\\?\" { - &canonical_path[4..] - } else { - canonical_path - }; - writer .stdout() .queue(SetForegroundColor(color))? -- cgit v1.2.3