1use std::{
2 borrow::Cow,
3 ffi::OsStr,
4 path::{Component, Path, PathBuf, Prefix},
5};
6
7use keepcalm::SharedGlobalMut;
8use serde::Serialize;
9use tempfile::TempDir;
10
11static CANONICAL_TEMP_DIR: SharedGlobalMut<PathBuf> = SharedGlobalMut::new_lazy(|| {
12 let tmp = if cfg!(target_vendor = "apple") {
13 Path::new("/tmp").to_owned()
14 } else {
15 std::env::temp_dir()
16 };
17 match dunce::canonicalize(&tmp) {
18 Ok(canonical) => canonical,
19 Err(_) => tmp,
20 }
21});
22
23static CANONICAL_CWD: SharedGlobalMut<Option<PathBuf>> = SharedGlobalMut::new_lazy(|| {
24 let cwd = std::env::current_dir().ok()?;
25 match dunce::canonicalize(&cwd) {
26 Ok(canonical) => Some(canonical),
27 Err(_) => Some(cwd),
28 }
29});
30
31static CANONICAL_HOME_DIR: SharedGlobalMut<Option<PathBuf>> = SharedGlobalMut::new_lazy(|| {
32 dirs::home_dir().map(|home| dunce::canonicalize(&home).unwrap_or(home))
33});
34
35#[derive(Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
36pub struct NicePathBuf {
37 path: PathBuf,
38}
39
40impl serde::Serialize for NicePathBuf {
41 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
42 where
43 S: serde::Serializer,
44 {
45 serializer.serialize_str(&self.path.display().to_string())
46 }
47}
48
49impl<'de> serde::Deserialize<'de> for NicePathBuf {
50 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
51 where
52 D: serde::Deserializer<'de>,
53 {
54 let s = String::deserialize(deserializer)?;
55 Ok(Self::new(&s))
56 }
57}
58
59impl From<&'_ NicePathBuf> for NicePathBuf {
60 fn from(path: &NicePathBuf) -> Self {
61 path.clone()
62 }
63}
64
65impl From<&'_ Path> for NicePathBuf {
66 fn from(path: &Path) -> Self {
67 NicePathBuf::new(path)
68 }
69}
70
71impl AsRef<Path> for NicePathBuf {
72 fn as_ref(&self) -> &Path {
73 &self.path
74 }
75}
76
77impl NicePathBuf {
78 pub fn new(path: impl AsRef<Path>) -> Self {
79 Self {
80 path: path.as_ref().to_path_buf(),
81 }
82 }
83
84 pub fn exists(&self) -> std::io::Result<bool> {
85 std::fs::exists(&self.path)
86 }
87
88 pub fn join(&self, other: impl AsRef<Path>) -> Self {
89 Self {
90 path: self.path.join(other.as_ref()),
91 }
92 }
93
94 pub fn create_dir_all(&self) -> std::io::Result<()> {
95 std::fs::create_dir_all(&self.path)
96 }
97
98 pub fn remove_dir_all(&self) -> std::io::Result<()> {
99 std::fs::remove_dir_all(&self.path)
100 }
101
102 pub fn parent(&self) -> Option<NicePathBuf> {
103 self.path.parent().map(NicePathBuf::new)
104 }
105
106 pub fn cwd() -> NicePathBuf {
107 let cwd = std::env::current_dir().expect("Couldn't get current directory");
108 cwd.into()
109 }
110
111 pub fn env_string(&self) -> String {
117 let path = &self.path;
118 let canonical = canonicalize_path(path);
119 if cfg!(target_vendor = "apple") {
120 if let Ok(tmp) = canonical.strip_prefix(CANONICAL_TEMP_DIR.read()) {
121 format!("/tmp/{}", tmp.display())
122 } else {
123 canonical.display().to_string()
124 }
125 } else {
126 canonical.display().to_string()
127 }
128 }
129}
130
131impl From<PathBuf> for NicePathBuf {
132 fn from(path: PathBuf) -> Self {
133 Self { path }
134 }
135}
136
137impl From<String> for NicePathBuf {
138 fn from(path: String) -> Self {
139 Self {
140 path: PathBuf::from(path),
141 }
142 }
143}
144
145impl std::fmt::Display for NicePathBuf {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 write_pretty_path(false, &self.path, f)
148 }
149}
150
151impl std::fmt::Debug for NicePathBuf {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 write_pretty_path(true, &self.path, f)
154 }
155}
156
157pub struct NiceTempDir {
158 path: TempDir,
159}
160
161impl Default for NiceTempDir {
162 fn default() -> Self {
163 Self::new()
164 }
165}
166
167impl NiceTempDir {
168 pub fn new() -> Self {
169 let path = if cfg!(target_vendor = "apple") {
170 tempfile::Builder::new()
171 .tempdir_in("/tmp")
172 .expect("Couldn't create tempdir")
173 } else {
174 tempfile::tempdir().expect("Couldn't create tempdir")
175 };
176 debug_assert!(path.path().is_absolute());
177 debug_assert!(matches!(std::fs::exists(path.path()), Ok(true)));
178 Self { path }
179 }
180
181 pub fn exists(&self) -> Result<bool, std::io::Error> {
182 std::fs::exists(self.path.path())
183 }
184
185 pub fn remove_dir_all(self) -> std::io::Result<()> {
186 self.path.close()
187 }
188
189 pub fn join(&self, other: impl AsRef<Path>) -> NicePathBuf {
190 NicePathBuf::new(self.path.path().join(other.as_ref()))
191 }
192
193 pub fn file_name(&self) -> Option<&OsStr> {
194 self.path.path().file_name()
195 }
196
197 pub fn env_string(&self) -> String {
198 NicePathBuf::from(self).env_string()
199 }
200}
201
202impl std::fmt::Display for NiceTempDir {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 write!(f, "{}", NicePathBuf::new(self.path.path()))
205 }
206}
207
208impl From<&'_ NiceTempDir> for NicePathBuf {
209 fn from(tempdir: &NiceTempDir) -> Self {
210 NicePathBuf::new(tempdir.path.path())
211 }
212}
213
214fn canonicalize_path(path: &Path) -> Cow<Path> {
216 if let Ok(path) = dunce::canonicalize(path) {
217 return path.into();
218 }
219
220 let components = path.components();
221 let Some(last) = components.last() else {
222 return path.into();
223 };
224
225 let mut rest = PathBuf::from(last.as_os_str());
226
227 let mut path = path;
230 while let Some(parent) = path.parent() {
231 if let Ok(mut path) = dunce::canonicalize(parent) {
232 for component in rest.components() {
233 match component {
234 Component::ParentDir => {
235 if let Some(parent) = path.parent() {
236 path = parent.to_path_buf();
237 }
238 }
239 Component::CurDir => {}
240 _ => {
241 path = path.join(component.as_os_str());
242 }
243 }
244 }
245 return path.into();
246 }
247
248 path = parent;
249 let components = path.components();
250 let Some(last) = components.last() else {
251 return path.into();
252 };
253
254 rest = PathBuf::from(last.as_os_str()).join(rest);
255 }
256
257 path.into()
258}
259
260fn write_pretty_path(
261 debug: bool,
262 path: &Path,
263 f: &mut std::fmt::Formatter<'_>,
264) -> std::fmt::Result {
265 let tmp = &*CANONICAL_TEMP_DIR.read();
266 let home = &*CANONICAL_HOME_DIR.read();
267 let cwd = &*CANONICAL_CWD.read();
268
269 let mut canon_path = canonicalize_path(path);
270
271 if cfg!(target_vendor = "apple") && canon_path.is_absolute() {
273 if let Ok(without_private) = canon_path.strip_prefix("/private") {
274 canon_path = Path::new("/").join(without_private).into();
275 }
276 }
277
278 if let Some(cwd) = cwd {
281 if let Ok(path) = canon_path.strip_prefix(cwd) {
282 if debug {
283 write_debug_path(f, path)?;
284 } else {
285 write!(f, "{}", path.display())?;
286 }
287 return Ok(());
288 }
289 }
290
291 if !cfg!(unix) && !cfg!(windows) {
293 if debug {
294 write_debug_path(f, path)?;
295 } else {
296 write!(f, "{}", path.display())?;
297 }
298 return Ok(());
299 }
300
301 if let Ok(path) = canon_path.strip_prefix(tmp) {
303 if cfg!(unix) {
304 let path = Path::new("/tmp").join(path);
305 if debug {
306 write_debug_path(f, &path)?;
307 } else {
308 write!(f, "{}", path.display())?;
309 }
310 } else if cfg!(windows) {
311 let path = Path::new("%TEMP%").join(path);
312 if debug {
313 write_debug_path(f, &path)?;
314 } else {
315 write!(f, "{}", path.display())?;
316 }
317 }
318 return Ok(());
319 }
320
321 if debug {
323 if cfg!(windows) {
325 if let Some(Component::Prefix(prefix)) = canon_path.components().next() {
326 if let Prefix::VerbatimDisk(_) = prefix.kind() {
328 return f
329 .write_str(&format!("<{}>", canon_path.display()).replace(r"\\?\", ""));
330 }
331 }
332 }
333
334 write_debug_path(f, &canon_path)?;
335 return Ok(());
336 }
337
338 if let Some(home) = home {
340 if let Ok(path) = canon_path.strip_prefix(home) {
341 if cfg!(unix) {
342 write!(f, "~/{}", path.display())?;
343 } else if cfg!(windows) {
344 write!(f, "%USERPROFILE%\\{}", path.display())?;
345 }
346 return Ok(());
347 }
348 }
349
350 if cfg!(windows) {
352 if let Some(Component::Prefix(prefix)) = canon_path.components().next() {
353 if let Prefix::VerbatimDisk(_) = prefix.kind() {
354 return write!(
355 f,
356 "{}",
357 canon_path.display().to_string().replace(r"\\?\", "")
358 );
359 }
360 }
361 }
362
363 write!(f, "{}", canon_path.display())
364}
365
366fn write_debug_path(f: &mut std::fmt::Formatter<'_>, path: &Path) -> std::fmt::Result {
367 if cfg!(windows) {
368 write!(f, "<{}>", path.display())
369 } else {
370 write!(f, "{path:?}")
371 }
372}
373
374#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, derive_more::Error, derive_more::Display)]
375pub enum ShellParseError {
376 #[display("unmatched quote ({_0})")]
377 UnmatchedQuote(#[error(not(source))] char),
378}
379
380#[derive(derive_more::Debug, Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
382pub enum ShellBit {
383 #[debug("{_0:?}")]
386 Literal(String),
387 #[debug("{_0:?}")]
390 Quoted(String),
391}
392
393impl PartialEq<str> for ShellBit {
394 fn eq(&self, other: &str) -> bool {
395 match self {
396 ShellBit::Literal(s) => s == other,
397 ShellBit::Quoted(s) => s == other,
398 }
399 }
400}
401
402impl PartialEq<&'_ str> for ShellBit {
403 fn eq(&self, other: &&str) -> bool {
404 match self {
405 ShellBit::Literal(s) => s == other,
406 ShellBit::Quoted(s) => s == other,
407 }
408 }
409}
410
411impl ShellBit {
412 pub fn to_string(&self) -> String {
413 match self {
414 ShellBit::Literal(s) => s.clone(),
415 ShellBit::Quoted(s) => s.clone(),
416 }
417 }
418}
419
420impl Serialize for ShellBit {
421 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
422 where
423 S: serde::Serializer,
424 {
425 match self {
427 ShellBit::Literal(s) => serializer.serialize_str(s),
428 ShellBit::Quoted(s) => serializer.serialize_str(s),
429 }
430 }
431}
432
433pub fn shell_split(input: &str) -> Result<Vec<ShellBit>, ShellParseError> {
435 let mut result = Vec::new();
436 let mut in_string = None;
437 let mut in_escape = false;
438 let mut accum = String::new();
439
440 for c in input.chars() {
441 if let Some(string_char) = in_string {
442 if string_char == '\'' {
443 if c == string_char {
444 in_string = None;
445 result.push(ShellBit::Literal(std::mem::take(&mut accum)));
446 } else {
447 accum.push(c);
448 }
449 } else if in_escape {
450 in_escape = false;
451 accum.push('\\');
452 accum.push(c);
453 } else if c == '\\' {
454 in_escape = true;
455 } else if c == string_char {
456 in_string = None;
457 if c == '"' {
458 result.push(ShellBit::Quoted(std::mem::take(&mut accum)));
459 }
460 } else {
461 accum.push(c);
462 }
463 } else if c == '\\' {
464 in_escape = true;
465 } else if in_escape {
466 in_escape = false;
467 accum.push('\\');
468 accum.push(c);
469 } else if c == '"' || c == '\'' {
470 in_string = Some(c);
471 } else if c == ' ' {
472 if accum.is_empty() {
473 continue;
474 }
475 result.push(ShellBit::Quoted(std::mem::take(&mut accum)));
476 } else {
477 accum.push(c);
478 }
479 }
480 if let Some(string_char) = in_string {
481 return Err(ShellParseError::UnmatchedQuote(string_char));
482 }
483
484 if !accum.is_empty() {
485 result.push(ShellBit::Quoted(std::mem::take(&mut accum)));
486 }
487
488 Ok(result)
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[cfg(unix)]
496 #[test]
497 fn test_nice_path_buf_tmp_unix() {
498 let path = NicePathBuf::new(Path::new("/tmp/hello.world"));
499
500 assert_eq!("/tmp/hello.world", format!("{}", path));
501 assert_eq!("\"/tmp/hello.world\"", format!("{:?}", path));
502
503 let path = NicePathBuf::new(Path::new("//tmp//hello.world"));
504
505 assert_eq!("/tmp/hello.world", format!("{}", path));
506 assert_eq!("\"/tmp/hello.world\"", format!("{:?}", path));
507
508 let path = NicePathBuf::new(Path::new("//does-not-exist-anywhere/..//tmp//hello.world"));
509
510 assert_eq!("/tmp/hello.world", format!("{}", path));
511 assert_eq!("\"/tmp/hello.world\"", format!("{:?}", path));
512
513 let path = NicePathBuf::new(
514 Path::new("/tmp")
515 .canonicalize()
516 .unwrap()
517 .join("hello.world"),
518 );
519
520 assert_eq!("/tmp/hello.world", format!("{}", path));
521 assert_eq!("\"/tmp/hello.world\"", format!("{:?}", path));
522
523 let temp_dir = NiceTempDir::new();
525 let path = temp_dir.join("a/b/c/d");
526
527 let name = temp_dir.file_name().unwrap().to_string_lossy();
528
529 assert_eq!(format!("/tmp/{name}/a/b/c/d"), format!("{}", path));
530 assert_eq!(format!("\"/tmp/{name}/a/b/c/d\""), format!("{:?}", path));
531 }
532
533 #[cfg(windows)]
534 #[test]
535 fn test_nice_path_buf_tmp_windows() {
536 let tmp = std::env::temp_dir();
537 let tmp = tmp.join("hello.world");
538
539 let path = NicePathBuf::new(&tmp);
540
541 assert_eq!(r"%TEMP%\hello.world", format!("{}", path));
542 assert_eq!(r"<%TEMP%\hello.world>", format!("{:?}", path));
543
544 let path = NicePathBuf::new(
545 &std::env::temp_dir()
546 .canonicalize()
547 .unwrap()
548 .join("hello.world"),
549 );
550
551 assert_eq!(r"%TEMP%\hello.world", format!("{}", path));
552 assert_eq!(r"<%TEMP%\hello.world>", format!("{:?}", path));
553
554 let path = NicePathBuf::new(r#"C:\directory"#);
555
556 assert_eq!(r"C:\directory", format!("{}", path));
557 assert_eq!(r"<C:\directory>", format!("{:?}", path));
558 }
559
560 #[test]
561 fn test_shell_split() {
562 assert_eq!(format!("{:?}", shell_split("").unwrap()), r#"[]"#);
563 assert_eq!(format!("{:?}", shell_split("a").unwrap()), r#"["a"]"#);
564 assert_eq!(
565 format!("{:?}", shell_split("a b").unwrap()),
566 r#"["a", "b"]"#
567 );
568 assert_eq!(
569 format!("{:?}", shell_split("a b c").unwrap()),
570 r#"["a", "b", "c"]"#
571 );
572 assert_eq!(
573 format!("{:?}", shell_split("a 'b' c").unwrap()),
574 r#"["a", "b", "c"]"#
575 );
576 assert_eq!(
577 format!("{:?}", shell_split("a 'b c' d").unwrap()),
578 r#"["a", "b c", "d"]"#
579 );
580 assert_eq!(
581 format!("{:?}", shell_split(r#"a "b" c"#).unwrap()),
582 r#"["a", "b", "c"]"#
583 );
584 assert_eq!(
585 format!("{:?}", shell_split(r#"a "b c" d"#).unwrap()),
586 r#"["a", "b c", "d"]"#
587 );
588 assert_eq!(
589 format!("{:?}", shell_split(r#"a "b\'c" d"#).unwrap()),
590 r#"["a", "b\\'c", "d"]"#
591 );
592 assert_eq!(
593 format!("{:?}", shell_split(r#"a "a\\b" d"#).unwrap()),
594 r#"["a", "a\\\\b", "d"]"#
595 );
596 assert_eq!(
597 format!("{:?}", shell_split(r#"a 'a\\b' d"#).unwrap()),
598 r#"["a", "a\\\\b", "d"]"#
599 );
600 }
601
602 #[test]
603 fn test_shell_split_errors() {
604 assert_eq!(
605 shell_split("a 'b").unwrap_err(),
606 ShellParseError::UnmatchedQuote('\'')
607 );
608 assert_eq!(
609 shell_split("a \"b c").unwrap_err(),
610 ShellParseError::UnmatchedQuote('"')
611 );
612 assert_eq!(
613 shell_split("a '").unwrap_err(),
614 ShellParseError::UnmatchedQuote('\'')
615 );
616 }
617}