2 releases

Uses old Rust 2015

0.2.1 Jun 2, 2022
0.2.0 May 15, 2022

#372 in Filesystem

Download history 24417/week @ 2024-07-21 22815/week @ 2024-07-28 24719/week @ 2024-08-04 26903/week @ 2024-08-11 28519/week @ 2024-08-18 29861/week @ 2024-08-25 21353/week @ 2024-09-01 22978/week @ 2024-09-08 18691/week @ 2024-09-15 21425/week @ 2024-09-22 26705/week @ 2024-09-29 15912/week @ 2024-10-06 27704/week @ 2024-10-13 18977/week @ 2024-10-20 24663/week @ 2024-10-27 14541/week @ 2024-11-03

86,643 downloads per month
Used in 89 crates (14 directly)

MIT/Apache

13KB
164 lines

clean-path

crates.io version docs.rs docs license

clean-path is a safe fork of the path-clean crate.

Installation

cargo add clean-path

Usage

use std::path::{Path, PathBuf};
use clean_path::{clean, Clean};

assert_eq!(clean("foo/../../bar"), PathBuf::from("../bar"));
assert_eq!(Path::new("hello/world/..").clean(), PathBuf::from("hello"));
assert_eq!(
    PathBuf::from("/test/../path/").clean(),
    PathBuf::from("/path")
);

About

This fork aims to provide the same utility as path-clean, without using unsafe. Additionally, the api is improved (clean takes AsRef<Path> instead of just &str) and Clean is implemented on Path in addition to just PathBuf.

The main cleaning procedure is implemented using the methods provided by PathBuf, thus it should bring portability benefits over path-clean w.r.t. correctly handling cross-platform filepaths.

Additionally, the original implementation in path-clean is rather inscrutible, and as such if being able to inspect and understand the code is important to you, this crate provides a more readable implementation.

However, the current implementation is not highly-optimized, so if performance is top-priority, consider using path-clean instead.

Specification

The cleaning works as follows:

  1. Reduce multiple slashes to a single slash.
  2. Eliminate . path name elements (the current directory).
  3. Eliminate .. path name elements (the parent directory) and the non-. non-.., element that precedes them.
  4. Eliminate .. elements that begin a rooted path, that is, replace /.. by / at the beginning of a path.
  5. Leave intact .. elements that begin a non-rooted path.

If the result of this process is an empty string, return the string ".", representing the current directory.

This transformation is performed lexically, without touching the filesystem. Therefore it doesn't do any symlink resolution or absolute path resolution. For more information you can see "Getting Dot-Dot Right".

This functionality is exposed in the clean function and Clean trait implemented for std::path::PathBuf and std::path::Path.

License

MIT OR Apache-2.0

No runtime deps