canonical-path-2.0.2/Cargo.toml.orig010064400007650000024000000013171347203736400155150ustar0000000000000000[package] name = "canonical-path" description = "Path and PathBuf-like types for representing canonical filesystem paths" version = "2.0.2" # Also update html_root_url in lib.rs when bumping this authors = ["Tony Arcieri "] license = "Apache-2.0" edition = "2018" homepage = "https://github.com/iqlusioninc/crates/" repository = "https://github.com/iqlusioninc/crates/tree/develop/canonical-path" readme = "README.md" categories = ["filesystem"] keywords = ["filesystem", "path", "canonicalization"] [badges] maintenance = { status = "passively-maintained" } travis-ci = { repository = "iqlusioninc/crates", branch = "develop" } [dev-dependencies] tempfile = "3" canonical-path-2.0.2/Cargo.toml0000644000000022030000000000000117500ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "canonical-path" version = "2.0.2" authors = ["Tony Arcieri "] description = "Path and PathBuf-like types for representing canonical filesystem paths" homepage = "https://github.com/iqlusioninc/crates/" readme = "README.md" keywords = ["filesystem", "path", "canonicalization"] categories = ["filesystem"] license = "Apache-2.0" repository = "https://github.com/iqlusioninc/crates/tree/develop/canonical-path" [dev-dependencies.tempfile] version = "3" [badges.maintenance] status = "passively-maintained" [badges.travis-ci] branch = "develop" repository = "iqlusioninc/crates" canonical-path-2.0.2/CHANGES.md010064400007650000024000000014051347203741700142150ustar0000000000000000## [2.0.2] (2019-05-24) - Test all crates on Rust 1.35.0 ([#206]) ## [2.0.1] (2019-05-22) - Canonicalize `current_exe()` ([#198]) ## [2.0.0] (2019-05-20) - Clean up and modernize ([#193]) - Update to 2018 edition ([#138]) ## 1.0.0 (2018-10-03) - Initial 1.0 release ## 0.1.1 (2018-04-09) - Fix link to CircleCI badge in `Cargo.toml` ## 0.1.0 (2018-04-09) - Initial release [2.0.2]: https://github.com/iqlusioninc/crates/pull/207 [#206]: https://github.com/iqlusioninc/crates/pull/206 [2.0.1]: https://github.com/iqlusioninc/crates/pull/199 [#198]: https://github.com/iqlusioninc/crates/pull/198 [2.0.0]: https://github.com/iqlusioninc/crates/pull/194 [#193]: https://github.com/iqlusioninc/crates/pull/193 [#138]: https://github.com/iqlusioninc/crates/pull/138 canonical-path-2.0.2/README.md010064400007650000024000000036431347203706400141060ustar0000000000000000# canonical-path.rs [![Crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Apache 2.0 Licensed][license-image]][license-link] ![Rust 1.35+][rustc-image] [![Build Status][build-image]][build-link] `std::fs::Path` and `PathBuf`-like types for representing canonical filesystem paths. In the same way a `str` "guarantees" a `&[u8]` contains only valid UTF-8 data, `CanonicalPath` and `CanonicalPathBuf` guarantee that the paths they represent are canonical, or at least, were canonical at the time they were created. [Documentation][docs-link] ## Requirements - Rust 1.35+ ## License Copyright © 2018-2019 iqlusion Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/canonical-path.svg [crate-link]: https://crates.io/crates/canonical-path [docs-image]: https://docs.rs/canonical-path/badge.svg [docs-link]: https://docs.rs/canonical-path/ [license-image]: https://img.shields.io/badge/license-Apache2.0-blue.svg [license-link]: https://github.com/iqlusioninc/crates/blob/develop/LICENSE [rustc-image]: https://img.shields.io/badge/rustc-1.35+-blue.svg [build-image]: https://travis-ci.com/iqlusioninc/crates.svg?branch=develop [build-link]: https://travis-ci.com/iqlusioninc/crates/ canonical-path-2.0.2/src/lib.rs010064400007650000024000000320131347203737600145310ustar0000000000000000//! Path newtypes which are always guaranteed to be canonical //! //! In the same way a `str` "guarantees" a `&[u8]` contains only valid UTF-8 data, //! `CanonicalPath` and `CanonicalPathBuf` guarantee that the paths they represent //! are canonical, or at least, were canonical at the time they were created. #![deny( warnings, missing_docs, trivial_numeric_casts, unused_import_braces, unused_qualifications )] #![doc(html_root_url = "https://docs.rs/canonical-path/2.0.2")] use std::{ borrow::Borrow, env, ffi::{OsStr, OsString}, fs::{Metadata, ReadDir}, io::{Error, ErrorKind, Result}, path::{Components, Display, Iter, Path, PathBuf}, }; /// Common methods of `CanonicalPath` and `CanonicalPathBuf` macro_rules! impl_path { () => { /// Return a `Path` reference. #[inline] pub fn as_path(&self) -> &Path { self.0.as_ref() } /// Return an `OsStr` reference. #[inline] pub fn as_os_str(&self) -> &OsStr { self.0.as_os_str() } /// Yields a `&str` slice if the path is valid unicode. #[inline] pub fn to_str(&self) -> Option<&str> { self.0.to_str() } /// Return a canonical parent path of this path, or `io::Error` if the /// path is the root directory or another canonicalization error occurs. pub fn parent(&self) -> Result { CanonicalPathBuf::new(&self.0 .parent() .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "can't get parent of '/'"))?) } /// Returns the final component of the path, if there is one. #[inline] pub fn file_name(&self) -> Option<&OsStr> { self.0.file_name() } /// Determines whether base is a prefix of self. #[inline] pub fn starts_with>(&self, base: P) -> bool { self.0.starts_with(base) } /// Determines whether child is a suffix of self. #[inline] pub fn ends_with>(&self, child: P) -> bool { self.0.ends_with(child) } /// Extracts the stem (non-extension) portion of `self.file_name`. #[inline] pub fn file_stem(&self) -> Option<&OsStr> { self.0.file_stem() } /// Extracts the extension of `self.file_name`, if possible. #[inline] pub fn extension(&self) -> Option<&OsStr> { self.0.extension() } /// Creates an owned `CanonicalPathBuf` like self but with the given file name. #[inline] pub fn with_file_name>(&self, file_name: S) -> Result { CanonicalPathBuf::new(&self.0.with_file_name(file_name)) } /// Creates an owned `CanonicalPathBuf` like self but with the given extension. #[inline] pub fn with_extension>(&self, extension: S) -> Result { CanonicalPathBuf::new(&self.0.with_extension(extension)) } /// Produces an iterator over the `Component`s of a path #[inline] pub fn components(&self) -> Components { self.0.components() } /// Produces an iterator over the path's components viewed as /// `OsStr` slices. #[inline] pub fn iter(&self) -> Iter { self.0.iter() } /// Returns an object that implements `Display` for safely printing /// paths that may contain non-Unicode data. #[inline] pub fn display(&self) -> Display { self.0.display() } /// Queries the file system to get information about a file, directory, etc. /// /// Unlike the `std` version of this method, it will not follow symlinks, /// since as a canonical path we should be symlink-free. #[inline] pub fn metadata(&self) -> Result { // Counterintuitively this is the version of this method which // does not traverse symlinks self.0.symlink_metadata() } /// Join a path onto a canonical path, returning a `CanonicalPathBuf`. #[inline] pub fn join>(&self, path: P) -> Result { CanonicalPathBuf::new(&self.0.join(path)) } /// Returns an iterator over the entries within a directory. /// /// The iterator will yield instances of io::Result. New /// errors may be encountered after an iterator is initially /// constructed. /// /// This is an alias to fs::read_dir. #[inline] pub fn read_dir(&self) -> Result { self.0.read_dir() } /// Does this path exist? #[inline] pub fn exists(&self) -> bool { self.0.exists() } /// Is this path a file? #[inline] pub fn is_file(&self) -> bool { self.0.is_file() } /// Is this path a directory? #[inline] pub fn is_dir(&self) -> bool { self.0.is_file() } } } /// An owned path on the filesystem which is guaranteed to be canonical. /// /// More specifically: it is at least guaranteed to be canonical at /// the time it is created. There are potential TOCTTOU problems if the /// underlying filesystem structure changes after path canonicalization. #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct CanonicalPathBuf(PathBuf); impl CanonicalPathBuf { /// Create a canonical path by first canonicalizing the given path. pub fn canonicalize

(path: P) -> Result where P: AsRef, { Ok(CanonicalPathBuf(path.as_ref().canonicalize()?)) } /// Create a canonical path, returning error if the supplied path is not canonical. // TODO: rename this to `from_path` or `try_new` to satisfy clippy? (breaking API change) #[allow(clippy::new_ret_no_self)] pub fn new

(path: P) -> Result where P: AsRef, { let p = path.as_ref(); let canonical_path_buf = Self::canonicalize(p)?; if canonical_path_buf.as_path() != p { return Err(Error::new( ErrorKind::InvalidInput, format!("non-canonical input path: {}", p.display()), )); } Ok(canonical_path_buf) } /// Return a `CanonicalPath` reference. #[inline] pub fn as_canonical_path(&self) -> &CanonicalPath { unsafe { CanonicalPath::from_path_unchecked(&self.0) } } /// Updates `self`'s filename ala the same method on `PathBuf` pub fn set_file_name>(&mut self, file_name: S) { self.0.set_file_name(file_name); } /// Updates `self.extension` to extension. /// /// Returns `false` and does nothing if `self.file_name` is `None`, /// returns `true` and updates the extension otherwise. /// If `self.extension` is `None`, the extension is added; otherwise it is replaced. pub fn set_extension>(&mut self, extension: S) -> bool { self.0.set_extension(extension) } /// Consumes the `CanonicalPathBuf`, yielding its internal `PathBuf` storage. pub fn into_path_buf(self) -> PathBuf { self.0 } /// Consumes the `CanonicalPathBuf`, yielding its internal `OsString` storage. pub fn into_os_string(self) -> OsString { self.0.into_os_string() } impl_path!(); } impl AsRef for CanonicalPathBuf { fn as_ref(&self) -> &Path { self.as_path() } } impl AsRef for CanonicalPathBuf { fn as_ref(&self) -> &CanonicalPath { self.as_canonical_path() } } impl AsRef for CanonicalPathBuf { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl Borrow for CanonicalPathBuf { fn borrow(&self) -> &CanonicalPath { self.as_canonical_path() } } /// A reference type for a canonical filesystem path /// /// More specifically: it is at least guaranteed to be canonical at /// the time it is created. There are potential TOCTTOU problems if the /// underlying filesystem structure changes after path canonicalization. #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct CanonicalPath(Path); impl CanonicalPath { /// Create a canonical path, returning error if the supplied path is not canonical pub fn new

(path: &P) -> Result<&Self> where P: AsRef + ?Sized, { let p = path.as_ref(); // TODO: non-allocating check that `P` is canonical // // This seems tricky as realpath(3) is our only real way of checking // that a path is canonical. It's also slightly terrifying in that, // at least in glibc, it is over 200 lines long and full of complex // logic and error handling: // // https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/canonicalize.c;hb=HEAD if p != p.canonicalize()? { return Err(Error::new( ErrorKind::InvalidInput, format!("non-canonical input path: {}", p.display()), )); } Ok(unsafe { Self::from_path_unchecked(p) }) } /// Create a canonical path from a path, skipping the canonicalization check /// /// This uses the same unsafe reference conversion tricks as `std` to /// convert from `AsRef` to `AsRef`, i.e. `&CanonicalPath` /// is a newtype for `&Path` in the same way `&Path` is a newtype for `&OsStr`. pub unsafe fn from_path_unchecked

(path: &P) -> &Self where P: AsRef + ?Sized, { &*(path.as_ref() as *const Path as *const CanonicalPath) } /// Convert a canonical path reference into an owned `CanonicalPathBuf` pub fn to_canonical_path_buf(&self) -> CanonicalPathBuf { CanonicalPathBuf(self.0.to_owned()) } impl_path!(); } impl AsRef for CanonicalPath { fn as_ref(&self) -> &Path { &self.0 } } impl ToOwned for CanonicalPath { type Owned = CanonicalPathBuf; fn to_owned(&self) -> CanonicalPathBuf { self.to_canonical_path_buf() } } /// Returns the full, canonicalized filesystem path of the current running /// executable. pub fn current_exe() -> Result { let p = env::current_exe()?; Ok(CanonicalPathBuf::canonicalize(p)?) } // TODO: test on Windows #[cfg(all(test, not(windows)))] mod tests { use std::fs::File; use std::os::unix::fs; use std::path::PathBuf; use super::{CanonicalPath, CanonicalPathBuf}; use tempfile::TempDir; // We create a test file with this name const CANONICAL_FILENAME: &str = "canonical-file"; // We create a symlink to "canonical-file" with this name const NON_CANONICAL_FILENAME: &str = "non-canonical-file"; /// A directory full of test fixtures struct TestFixtureDir { /// The temporary directory itself (i.e. root directory of our tests) pub tempdir: TempDir, /// Canonical path to the test directory pub base_path: PathBuf, /// Path to a canonical file in our test fixture directory pub canonical_path: PathBuf, /// Path to a symlink in our test fixture directory pub symlink_path: PathBuf, } impl TestFixtureDir { pub fn new() -> Self { let tempdir = TempDir::new().unwrap(); let base_path = tempdir.path().canonicalize().unwrap(); let canonical_path = base_path.join(CANONICAL_FILENAME); File::create(&canonical_path).unwrap(); let symlink_path = base_path.join(NON_CANONICAL_FILENAME); fs::symlink(&canonical_path, &symlink_path).unwrap(); Self { tempdir, base_path, canonical_path, symlink_path, } } } #[test] fn create_canonical_path() { let test_fixtures = TestFixtureDir::new(); let canonical_path = CanonicalPath::new(&test_fixtures.canonical_path).unwrap(); assert_eq!( canonical_path.as_path(), test_fixtures.canonical_path.as_path() ); } #[test] fn create_canonical_path_buf() { let test_fixtures = TestFixtureDir::new(); let canonical_path_buf = CanonicalPathBuf::new(&test_fixtures.canonical_path).unwrap(); assert_eq!( canonical_path_buf.as_path(), test_fixtures.canonical_path.as_path() ); } #[test] fn reject_canonical_path_symlinks() { let test_fixtures = TestFixtureDir::new(); let result = CanonicalPath::new(&test_fixtures.symlink_path); assert!(result.is_err(), "symlinks aren't canonical paths!"); } #[test] fn reject_canonical_path_buf_symlinks() { let test_fixtures = TestFixtureDir::new(); let result = CanonicalPathBuf::new(&test_fixtures.symlink_path); assert!(result.is_err(), "symlinks aren't canonical paths!"); } } canonical-path-2.0.2/.cargo_vcs_info.json0000644000000001120000000000000137470ustar00{ "git": { "sha1": "cb5fbc5b1b2e0b658d45965fed2ee3f85401286c" } }