From d00ee5031fd7a5a3587d80d7841bca6022055ce6 Mon Sep 17 00:00:00 2001 From: nicholaslyang Date: Thu, 7 Dec 2023 17:15:37 -0500 Subject: [PATCH] Removing unused code --- Cargo.lock | 11 -- Cargo.toml | 1 - .../src/cache_archive/restore_symlink.rs | 6 +- crates/turborepo-errors/Cargo.toml | 11 -- crates/turborepo-errors/src/lib.rs | 82 ------------ crates/turborepo-lib/Cargo.toml | 1 - crates/turborepo-lib/src/cli/error.rs | 21 +--- crates/turborepo-lib/src/commands/prune.rs | 4 +- crates/turborepo-lib/src/run/error.rs | 19 --- .../turborepo-lib/src/run/graph_visualizer.rs | 4 +- crates/turborepo-lib/src/shim.rs | 73 +++++------ crates/turborepo-paths/Cargo.toml | 1 - .../src/absolute_system_path.rs | 18 +-- .../src/absolute_system_path_buf.rs | 117 +++++++----------- .../src/anchored_system_path.rs | 2 +- .../src/anchored_system_path_buf.rs | 10 +- crates/turborepo-paths/src/lib.rs | 77 +++--------- .../turborepo-paths/src/relative_unix_path.rs | 9 +- .../src/relative_unix_path_buf.rs | 5 +- 19 files changed, 123 insertions(+), 349 deletions(-) delete mode 100644 crates/turborepo-errors/Cargo.toml delete mode 100644 crates/turborepo-errors/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index ff148cc554fbd4..3fa9717ae2843f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10862,7 +10862,6 @@ dependencies = [ "tempdir", "test-case", "thiserror", - "turborepo-errors", "wax", ] @@ -10986,15 +10985,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "turborepo-errors" -version = "0.1.0" -dependencies = [ - "itertools", - "miette 5.10.0", - "serde", -] - [[package]] name = "turborepo-ffi" version = "0.1.0" @@ -11153,7 +11143,6 @@ dependencies = [ "turborepo-cache", "turborepo-ci", "turborepo-env", - "turborepo-errors", "turborepo-filewatch", "turborepo-fs", "turborepo-graph-utils", diff --git a/Cargo.toml b/Cargo.toml index 1cc76f1a5a55d0..771bc6cb13b557 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -147,7 +147,6 @@ turborepo-api-client = { path = "crates/turborepo-api-client" } turborepo-cache = { path = "crates/turborepo-cache" } turborepo-ci = { path = "crates/turborepo-ci" } turborepo-env = { path = "crates/turborepo-env" } -turborepo-errors = { path = "crates/turborepo-errors" } turborepo-ffi = { path = "crates/turborepo-ffi" } turborepo-fs = { path = "crates/turborepo-fs" } turborepo-lib = { path = "crates/turborepo-lib", default-features = false } diff --git a/crates/turborepo-cache/src/cache_archive/restore_symlink.rs b/crates/turborepo-cache/src/cache_archive/restore_symlink.rs index ac4fc3bb07c3b8..2fe952e29c459d 100644 --- a/crates/turborepo-cache/src/cache_archive/restore_symlink.rs +++ b/crates/turborepo-cache/src/cache_archive/restore_symlink.rs @@ -60,7 +60,7 @@ fn actually_restore_symlink<'a>( let link_name = header.link_name()?.expect("have linkname"); let symlink_to = link_name.to_str().ok_or_else(|| { CacheError::PathError( - PathError::InvalidUnicode(link_name.to_string_lossy().to_string(), None), + PathError::InvalidUnicode(link_name.to_string_lossy().to_string()), Backtrace::capture(), ) })?; @@ -93,7 +93,7 @@ pub fn canonicalize_linkname( ) -> Result { let linkname = linkname.try_into().map_err(|_| { CacheError::PathError( - PathError::InvalidUnicode(linkname.to_string_lossy().to_string(), None), + PathError::InvalidUnicode(linkname.to_string_lossy().to_string()), Backtrace::capture(), ) })?; @@ -119,7 +119,7 @@ pub fn canonicalize_linkname( // In order to DAG sort them, however, we do need to canonicalize them. // We canonicalize them as if we're restoring them verbatim. // - match turbopath::categorize(linkname, None) { + match turbopath::categorize(linkname) { // 1. Check to see if the link target is absolute _on the current platform_. // If it is an absolute path it's canonical by rule. UnknownPathType::Absolute(abs) => Ok(abs), diff --git a/crates/turborepo-errors/Cargo.toml b/crates/turborepo-errors/Cargo.toml deleted file mode 100644 index 60ab0c5edd073f..00000000000000 --- a/crates/turborepo-errors/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "turborepo-errors" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -itertools = { workspace = true } -miette = { workspace = true } -serde = { workspace = true, features = ["derive"] } diff --git a/crates/turborepo-errors/src/lib.rs b/crates/turborepo-errors/src/lib.rs deleted file mode 100644 index 453a465696cb9c..00000000000000 --- a/crates/turborepo-errors/src/lib.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Turborepo's library for high quality errors - -use std::{fmt::Display, ops::Deref, sync::Arc}; - -use serde::{Deserialize, Serialize}; - -pub trait Sourced { - fn with_provenance(self, provenance: Option>) -> Self; - - fn provenance(&self) -> Option>; -} - -#[derive(Clone, Debug)] -pub struct WithSource { - value: T, - provenance: Option>, -} - -impl WithSource { - pub fn new(value: T, provenance: Option>) -> Self { - Self { value, provenance } - } -} - -impl Deref for WithSource { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.value - } -} - -impl Sourced for WithSource { - fn with_provenance(self, provenance: Option>) -> Self { - Self::new(self.value, provenance) - } - - fn provenance(&self) -> Option> { - self.provenance.clone() - } -} - -impl Sourced for Result { - fn with_provenance(self, provenance: Option>) -> Self { - match self { - Ok(value) => Ok(value.with_provenance(provenance)), - Err(err) => Err(err.with_provenance(provenance)), - } - } - fn provenance(&self) -> Option> { - match self { - Ok(value) => value.provenance(), - Err(err) => err.provenance(), - } - } -} - -#[derive(Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Provenance { - // TODO: Add line/column numbers - TurboJson, - EnvironmentVariable { name: String }, - Flag { name: String }, -} - -impl Display for Provenance { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Provenance::TurboJson => write!(f, "from turbo.json"), - Provenance::EnvironmentVariable { name } => write!(f, "environment variable {}", name), - Provenance::Flag { name } => { - write!(f, "flag --{}", name) - } - } - } -} - -impl Provenance { - pub fn from_flag(name: impl Into) -> Option> { - Some(Arc::new(Provenance::Flag { name: name.into() })) - } -} diff --git a/crates/turborepo-lib/Cargo.toml b/crates/turborepo-lib/Cargo.toml index 628e234a06ab7a..35b3969d1f8553 100644 --- a/crates/turborepo-lib/Cargo.toml +++ b/crates/turborepo-lib/Cargo.toml @@ -122,7 +122,6 @@ turborepo-api-client = { workspace = true } turborepo-cache = { workspace = true } turborepo-ci = { workspace = true } turborepo-env = { workspace = true } -turborepo-errors = { workspace = true } turborepo-filewatch = { path = "../turborepo-filewatch" } turborepo-lockfiles = { workspace = true } turborepo-scm = { workspace = true } diff --git a/crates/turborepo-lib/src/cli/error.rs b/crates/turborepo-lib/src/cli/error.rs index 3610ce3af8813d..3e83f976634f30 100644 --- a/crates/turborepo-lib/src/cli/error.rs +++ b/crates/turborepo-lib/src/cli/error.rs @@ -1,7 +1,6 @@ -use std::{backtrace, sync::Arc}; +use std::backtrace; use thiserror::Error; -use turborepo_errors::{Provenance, Sourced}; use turborepo_repository::package_graph; use crate::{ @@ -46,21 +45,3 @@ pub enum Error { #[error(transparent)] SerdeJson(#[from] serde_json::Error), } - -impl Sourced for Error { - fn with_provenance(self, provenance: Option>) -> Self { - match self { - Self::Path(e) => Self::Path(e.with_provenance(provenance)), - Self::Run(e) => Self::Run(e.with_provenance(provenance)), - _ => todo!(), - } - } - - fn provenance(&self) -> Option> { - match self { - Self::Path(e) => e.provenance(), - Self::Run(e) => e.provenance(), - _ => todo!(), - } - } -} diff --git a/crates/turborepo-lib/src/commands/prune.rs b/crates/turborepo-lib/src/commands/prune.rs index 3e405557d1ccc9..cbd76caa83076f 100644 --- a/crates/turborepo-lib/src/commands/prune.rs +++ b/crates/turborepo-lib/src/commands/prune.rs @@ -7,7 +7,6 @@ use tracing::trace; use turbopath::{ AbsoluteSystemPathBuf, AnchoredSystemPath, AnchoredSystemPathBuf, RelativeUnixPath, }; -use turborepo_errors::{Provenance, Sourced}; use turborepo_repository::{ package_graph::{self, PackageGraph, WorkspaceName, WorkspaceNode}, package_json::PackageJson, @@ -261,8 +260,7 @@ impl<'a> Prune<'a> { .build() .await?; - let out_directory = AbsoluteSystemPathBuf::from_unknown(&base.repo_root, output_dir) - .with_provenance(Provenance::from_flag("out-dir")); + let out_directory = AbsoluteSystemPathBuf::from_unknown(&base.repo_root, output_dir); let full_directory = match docker { true => out_directory.join_component("full"), diff --git a/crates/turborepo-lib/src/run/error.rs b/crates/turborepo-lib/src/run/error.rs index 2947b080d64ea9..37f53ebe6c29d6 100644 --- a/crates/turborepo-lib/src/run/error.rs +++ b/crates/turborepo-lib/src/run/error.rs @@ -1,8 +1,5 @@ -use std::sync::Arc; - use miette::Diagnostic; use thiserror::Error; -use turborepo_errors::{Provenance, Sourced}; use turborepo_repository::package_graph; use super::graph_visualizer; @@ -52,19 +49,3 @@ pub enum Error { #[error("error registering signal handler: {0}")] SignalHandler(std::io::Error), } - -impl Sourced for Error { - fn with_provenance(self, provenance: Option>) -> Self { - match self { - Self::Path(e) => Self::Path(e.with_provenance(provenance)), - _ => todo!(), - } - } - - fn provenance(&self) -> Option> { - match self { - Self::Path(e) => e.provenance().clone(), - _ => None, - } - } -} diff --git a/crates/turborepo-lib/src/run/graph_visualizer.rs b/crates/turborepo-lib/src/run/graph_visualizer.rs index 419af8b21dfe92..ee64722c412934 100644 --- a/crates/turborepo-lib/src/run/graph_visualizer.rs +++ b/crates/turborepo-lib/src/run/graph_visualizer.rs @@ -6,7 +6,6 @@ use std::{ use thiserror::Error; use turbopath::{AbsoluteSystemPath, AbsoluteSystemPathBuf}; -use turborepo_errors::{Provenance, Sourced}; use turborepo_ui::{cprintln, cwrite, cwriteln, BOLD, BOLD_YELLOW_REVERSE, UI, YELLOW}; use which::which; @@ -142,8 +141,7 @@ fn filename_and_extension( cwd: &AbsoluteSystemPath, raw_filename: &str, ) -> Result<(AbsoluteSystemPathBuf, String), Error> { - let graph_file = AbsoluteSystemPathBuf::from_unknown(cwd, raw_filename) - .with_provenance(Provenance::from_flag("graph")); + let graph_file = AbsoluteSystemPathBuf::from_unknown(cwd, raw_filename); if let Some(extension) = graph_file.extension() { let extension = extension.to_string(); Ok((graph_file, extension)) diff --git a/crates/turborepo-lib/src/shim.rs b/crates/turborepo-lib/src/shim.rs index eeadce1f4b89c8..5ecb359af4e0e1 100644 --- a/crates/turborepo-lib/src/shim.rs +++ b/crates/turborepo-lib/src/shim.rs @@ -20,7 +20,6 @@ use tiny_gradient::{GradientStr, RGB}; use tracing::debug; use turbo_updater::check_for_updates; use turbopath::{AbsoluteSystemPath, AbsoluteSystemPathBuf}; -use turborepo_errors::{Sourced, WithSource}; use turborepo_repository::{ inference::{RepoMode, RepoState}, package_json::PackageJson, @@ -29,25 +28,30 @@ use turborepo_ui::UI; use crate::{cli, get_version, spawn_child, tracing::TurboSubscriber, Payload}; +#[derive(Debug, Error, Diagnostic)] +#[error("cannot have multiple `--cwd` flags in command")] +#[diagnostic(code(turbo::shim::empty_cwd))] +pub struct MultipleCwd { + #[backtrace] + backtrace: Backtrace, + #[source_code] + args_string: String, + #[label("first flag declared here")] + flag1: Option, + #[label("but second flag declared here")] + flag2: Option, + #[label("and here")] + flag3: Option, + // The user should get the idea after the first 4 examples + #[label("and here")] + flag4: Option, +} + #[derive(Debug, Error, Diagnostic)] pub enum Error { - #[error("cannot have multiple `--cwd` flags in command")] - #[diagnostic(code(turbo::shim::empty_cwd))] - MultipleCwd { - #[backtrace] - backtrace: Backtrace, - #[source_code] - args_string: String, - #[label("first flag declared here")] - flag1: Option, - #[label("but second flag declared here")] - flag2: Option, - #[label("and here")] - flag3: Option, - // The user should get the idea after the first 4 examples - #[label("and here")] - flag4: Option, - }, + #[error(transparent)] + #[diagnostic(transparent)] + MultipleCwd(Box), #[error("No value assigned to `--cwd` flag")] #[diagnostic(code(turbo::shim::empty_cwd))] EmptyCwd { @@ -192,14 +196,14 @@ impl ShimArgs { ); let args_string = env::args().skip(1).join(" "); - return Err(Error::MultipleCwd { + return Err(Error::MultipleCwd(Box::new(MultipleCwd { backtrace: Backtrace::capture(), args_string, - flag1: indices.get(0).map(|i| (*i, "--cwd".len()).into()), + flag1: indices.first().map(|i| (*i, "--cwd".len()).into()), flag2: indices.get(1).map(|i| (*i, "--cwd".len()).into()), flag3: indices.get(2).map(|i| (*i, "--cwd".len()).into()), flag4: indices.get(3).map(|i| (*i, "--cwd".len()).into()), - }); + }))); } let invocation_dir = AbsoluteSystemPathBuf::cwd()?; @@ -400,9 +404,7 @@ impl LocalTurboState { // - berry (nodeLinker: "node-modules") // // This also supports people directly depending upon the platform version. - fn generate_hoisted_path( - root_path: WithSource<&AbsoluteSystemPath>, - ) -> Option { + fn generate_hoisted_path(root_path: &AbsoluteSystemPath) -> Option { Some(root_path.join_component("node_modules")) } @@ -410,18 +412,14 @@ impl LocalTurboState { // - `npm install --install-strategy=shallow` (`npm install --global-style`) // - `npm install --install-strategy=nested` (`npm install --legacy-bundling`) // - berry (nodeLinker: "pnpm") - fn generate_nested_path( - root_path: WithSource<&AbsoluteSystemPath>, - ) -> Option { + fn generate_nested_path(root_path: &AbsoluteSystemPath) -> Option { Some(root_path.join_components(&["node_modules", "turbo", "node_modules"])) } // Linked strategy: // - `pnpm install` // - `npm install --install-strategy=linked` - fn generate_linked_path( - root_path: WithSource<&AbsoluteSystemPath>, - ) -> Option { + fn generate_linked_path(root_path: &AbsoluteSystemPath) -> Option { // root_path/node_modules/turbo is a symlink. Canonicalize the symlink to what // it points to. We do this _before_ traversing up to the parent, // because on Windows, if you canonicalize a path that ends with `/..` @@ -436,7 +434,7 @@ impl LocalTurboState { } // The unplugged directory doesn't have a fixed path. - fn get_unplugged_base_path(root_path: WithSource<&AbsoluteSystemPath>) -> Utf8PathBuf { + fn get_unplugged_base_path(root_path: &AbsoluteSystemPath) -> Utf8PathBuf { let yarn_rc_filename = env::var("YARN_RC_FILENAME").unwrap_or_else(|_| String::from(".yarnrc.yml")); let yarn_rc_filepath = root_path.as_path().join(yarn_rc_filename); @@ -449,11 +447,9 @@ impl LocalTurboState { // Unplugged strategy: // - berry 2.1+ - fn generate_unplugged_path( - root_path: WithSource<&AbsoluteSystemPath>, - ) -> Option { + fn generate_unplugged_path(root_path: &AbsoluteSystemPath) -> Option { let platform_package_name = TurboState::platform_package_name(); - let unplugged_base_path = Self::get_unplugged_base_path(root_path.clone()); + let unplugged_base_path = Self::get_unplugged_base_path(root_path); unplugged_base_path .read_dir_utf8() @@ -469,7 +465,6 @@ impl LocalTurboState { unplugged_base_path.join(file_name).join("node_modules"), ) .ok() - .map(|path| path.with_provenance(root_path.clone().provenance())) } else { None } @@ -486,7 +481,7 @@ impl LocalTurboState { // // In spite of that, the only known unsupported local invocation is Yarn/Berry < // 2.1 PnP - pub fn infer(root_path: WithSource<&AbsoluteSystemPath>) -> Option { + pub fn infer(root_path: &AbsoluteSystemPath) -> Option { let platform_package_name = TurboState::platform_package_name(); let binary_name = TurboState::binary_name(); @@ -506,7 +501,7 @@ impl LocalTurboState { // search. for root in search_functions .iter() - .filter_map(|search_function| search_function(root_path.clone())) + .filter_map(|search_function| search_function(root_path)) { // Needs borrow because of the loop. #[allow(clippy::needless_borrow)] @@ -563,7 +558,7 @@ fn run_correct_turbo( subscriber: &TurboSubscriber, ui: UI, ) -> Result { - if let Some(turbo_state) = LocalTurboState::infer(repo_state.root.as_sourced_path()) { + if let Some(turbo_state) = LocalTurboState::infer(&repo_state.root) { try_check_for_updates(&shim_args, &turbo_state.version); if turbo_state.local_is_self() { diff --git a/crates/turborepo-paths/Cargo.toml b/crates/turborepo-paths/Cargo.toml index 64f0995906d001..7b0f8a8782d86f 100644 --- a/crates/turborepo-paths/Cargo.toml +++ b/crates/turborepo-paths/Cargo.toml @@ -18,7 +18,6 @@ path-clean = "1.0.1" # TODO: Make this a crate feature serde = { workspace = true } thiserror = { workspace = true } -turborepo-errors = { workspace = true } wax = { workspace = true } [dev-dependencies] diff --git a/crates/turborepo-paths/src/absolute_system_path.rs b/crates/turborepo-paths/src/absolute_system_path.rs index 29b33c9a6155df..4f6a1e2ecb67d8 100644 --- a/crates/turborepo-paths/src/absolute_system_path.rs +++ b/crates/turborepo-paths/src/absolute_system_path.rs @@ -38,7 +38,7 @@ impl ToOwned for AbsoluteSystemPath { type Owned = AbsoluteSystemPathBuf; fn to_owned(&self) -> Self::Owned { - AbsoluteSystemPathBuf(None, self.0.to_owned()) + AbsoluteSystemPathBuf(self.0.to_owned()) } } @@ -105,7 +105,7 @@ impl AbsoluteSystemPath { /// Errors if `Utf8Path` is relative. fn from_utf8_path(path: &Utf8Path) -> Result<&Self, PathError> { if path.is_relative() { - return Err(PathError::NotAbsolute(path.to_string(), None)); + return Err(PathError::NotAbsolute(path.to_string())); } Ok(Self::new_unchecked(path)) } @@ -199,7 +199,6 @@ impl AbsoluteSystemPath { pub fn join_component(&self, segment: &str) -> AbsoluteSystemPathBuf { debug_assert!(!segment.contains(std::path::MAIN_SEPARATOR)); AbsoluteSystemPathBuf( - None, self.0 .join(segment) .as_std_path() @@ -215,7 +214,6 @@ impl AbsoluteSystemPath { .iter() .any(|segment| segment.contains(std::path::MAIN_SEPARATOR))); AbsoluteSystemPathBuf( - None, self.0 .join(segments.join(std::path::MAIN_SEPARATOR_STR)) .as_std_path() @@ -235,7 +233,6 @@ impl AbsoluteSystemPath { ) -> Result { let tail = unix_path.as_ref().to_system_path_buf(); Ok(AbsoluteSystemPathBuf( - None, self.0.join(tail).as_std_path().clean().try_into()?, )) } @@ -267,7 +264,7 @@ impl AbsoluteSystemPath { pub fn resolve(&self, path: &AnchoredSystemPath) -> AbsoluteSystemPathBuf { let path = self.0.join(path); - AbsoluteSystemPathBuf(None, path) + AbsoluteSystemPathBuf(path) } /// Lexically cleans a path by doing the following: @@ -284,18 +281,15 @@ impl AbsoluteSystemPath { .as_std_path() .clean() .try_into() - .map_err(|_| PathError::InvalidUnicode(self.0.as_str().to_owned(), None))?; + .map_err(|_| PathError::InvalidUnicode(self.0.as_str().to_owned()))?; - Ok(AbsoluteSystemPathBuf(None, cleaned_path)) + Ok(AbsoluteSystemPathBuf(cleaned_path)) } /// Canonicalizes a path. Uses `dunce` to avoid UNC paths when possible. pub fn to_realpath(&self) -> Result { let realpath = dunce::canonicalize(&self.0)?; - Ok(AbsoluteSystemPathBuf( - None, - Utf8PathBuf::try_from(realpath)?, - )) + Ok(AbsoluteSystemPathBuf(Utf8PathBuf::try_from(realpath)?)) } /// Gets metadata on path. diff --git a/crates/turborepo-paths/src/absolute_system_path_buf.rs b/crates/turborepo-paths/src/absolute_system_path_buf.rs index b6c28c88996f6e..51eae84cc2e7c3 100644 --- a/crates/turborepo-paths/src/absolute_system_path_buf.rs +++ b/crates/turborepo-paths/src/absolute_system_path_buf.rs @@ -3,47 +3,18 @@ use std::{ fmt, io, ops::Deref, path::{Path, PathBuf}, - sync::Arc, }; use camino::{Utf8Components, Utf8Path, Utf8PathBuf}; use fs_err as fs; use path_clean::PathClean; use serde::Serialize; -use turborepo_errors::{Provenance, Sourced, WithSource}; use crate::{AbsoluteSystemPath, AnchoredSystemPathBuf, PathError}; -#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize)] -pub struct AbsoluteSystemPathBuf( - #[serde(skip)] pub(crate) Option>, - pub(crate) Utf8PathBuf, -); +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize)] +pub struct AbsoluteSystemPathBuf(pub(crate) Utf8PathBuf); -impl TryFrom for AbsoluteSystemPathBuf { - type Error = PathError; - - fn try_from(path: PathBuf) -> Result { - Self::new(Utf8PathBuf::try_from(path)?) - } -} - -impl TryFrom<&Path> for AbsoluteSystemPathBuf { - type Error = PathError; - - fn try_from(path: &Path) -> Result { - let utf8_path: &Utf8Path = path.try_into()?; - Self::new(utf8_path.to_owned()) - } -} - -impl TryFrom<&str> for AbsoluteSystemPathBuf { - type Error = PathError; - - fn try_from(value: &str) -> Result { - Self::new(Utf8PathBuf::from(value)) - } -} impl Borrow for AbsoluteSystemPathBuf { fn borrow(&self) -> &AbsoluteSystemPath { let path = self.as_path(); @@ -65,17 +36,6 @@ impl Deref for AbsoluteSystemPathBuf { } } -impl Sourced for AbsoluteSystemPathBuf { - fn with_provenance(mut self, provenance: Option>) -> Self { - self.0 = provenance; - self - } - - fn provenance(&self) -> Option> { - self.0.clone() - } -} - impl AbsoluteSystemPathBuf { /// Create a new AbsoluteSystemPathBuf from `unchecked_path`. /// Confirms that `unchecked_path` is absolute. Does *not* convert @@ -110,9 +70,9 @@ impl AbsoluteSystemPathBuf { pub fn new(unchecked_path: impl Into) -> Result { let unchecked_path = unchecked_path.into(); if !Path::new(&unchecked_path).is_absolute() { - return Err(PathError::NotAbsolute(unchecked_path, None)); + return Err(PathError::NotAbsolute(unchecked_path)); } - Ok(AbsoluteSystemPathBuf(None, unchecked_path.into())) + Ok(AbsoluteSystemPathBuf(unchecked_path.into())) } /// Takes in a system path of unknown type. If it's absolute, returns the @@ -121,10 +81,9 @@ impl AbsoluteSystemPathBuf { // we have an absolute system path and an unknown kind of system path. let unknown: Utf8PathBuf = unknown.into(); if unknown.is_absolute() { - Self(None, unknown) + Self(unknown) } else { Self( - None, base.as_path() .join(unknown) .as_std_path() @@ -142,7 +101,7 @@ impl AbsoluteSystemPathBuf { pub fn cwd() -> Result { // TODO(errors): Unwrap current_dir() - Ok(Self(None, Utf8PathBuf::try_from(std::env::current_dir()?)?)) + Ok(Self(Utf8PathBuf::try_from(std::env::current_dir()?)?)) } /// Anchors `path` at `self`. @@ -182,32 +141,27 @@ impl AbsoluteSystemPathBuf { } pub fn as_path(&self) -> &Utf8Path { - self.1.as_path() - } - - pub fn as_sourced_path(&self) -> WithSource<&AbsoluteSystemPath> { - let provenance = self.provenance(); - WithSource::new(&self, provenance) + self.0.as_path() } pub fn components(&self) -> Utf8Components<'_> { - self.1.components() + self.0.components() } pub fn parent(&self) -> Option<&AbsoluteSystemPath> { - self.1.parent().map(AbsoluteSystemPath::new_unchecked) + self.0.parent().map(AbsoluteSystemPath::new_unchecked) } pub fn starts_with>(&self, base: P) -> bool { - self.1.starts_with(base.as_ref()) + self.0.starts_with(base.as_ref()) } pub fn ends_with>(&self, child: P) -> bool { - self.1.ends_with(child.as_ref()) + self.0.ends_with(child.as_ref()) } pub fn ensure_dir(&self) -> Result<(), io::Error> { - if let Some(parent) = self.1.parent() { + if let Some(parent) = self.0.parent() { fs::create_dir_all(parent) } else { Ok(()) @@ -215,58 +169,83 @@ impl AbsoluteSystemPathBuf { } pub fn create_dir_all(&self) -> Result<(), io::Error> { - fs::create_dir_all(self.1.as_path()) + fs::create_dir_all(self.0.as_path()) } pub fn remove(&self) -> Result<(), io::Error> { - fs::remove_file(self.1.as_path()) + fs::remove_file(self.0.as_path()) } pub fn set_readonly(&self) -> Result<(), PathError> { let metadata = fs::symlink_metadata(self)?; let mut perms = metadata.permissions(); perms.set_readonly(true); - fs::set_permissions(self.1.as_path(), perms)?; + fs::set_permissions(self.0.as_path(), perms)?; Ok(()) } pub fn is_readonly(&self) -> Result { - Ok(self.1.symlink_metadata()?.permissions().readonly()) + Ok(self.0.symlink_metadata()?.permissions().readonly()) } pub fn as_str(&self) -> &str { - self.1.as_str() + self.0.as_str() } pub fn file_name(&self) -> Option<&str> { - self.1.file_name() + self.0.file_name() } pub fn try_exists(&self) -> Result { // try_exists is an experimental API and not yet in fs_err - Ok(std::fs::try_exists(&self.1)?) + Ok(std::fs::try_exists(&self.0)?) } pub fn extension(&self) -> Option<&str> { - self.1.extension() + self.0.extension() + } +} + +impl TryFrom for AbsoluteSystemPathBuf { + type Error = PathError; + + fn try_from(path: PathBuf) -> Result { + Self::new(Utf8PathBuf::try_from(path)?) + } +} + +impl TryFrom<&Path> for AbsoluteSystemPathBuf { + type Error = PathError; + + fn try_from(path: &Path) -> Result { + let utf8_path: &Utf8Path = path.try_into()?; + Self::new(utf8_path.to_owned()) + } +} + +impl TryFrom<&str> for AbsoluteSystemPathBuf { + type Error = PathError; + + fn try_from(value: &str) -> Result { + Self::new(Utf8PathBuf::from(value)) } } impl From for PathBuf { fn from(path: AbsoluteSystemPathBuf) -> Self { - path.1.into_std_path_buf() + path.0.into_std_path_buf() } } impl fmt::Display for AbsoluteSystemPathBuf { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.1.as_str()) + write!(f, "{}", self.0.as_str()) } } impl AsRef for AbsoluteSystemPathBuf { fn as_ref(&self) -> &Path { - self.1.as_std_path() + self.0.as_std_path() } } diff --git a/crates/turborepo-paths/src/anchored_system_path.rs b/crates/turborepo-paths/src/anchored_system_path.rs index ccfe7f20866301..21444a45ed112f 100644 --- a/crates/turborepo-paths/src/anchored_system_path.rs +++ b/crates/turborepo-paths/src/anchored_system_path.rs @@ -53,7 +53,7 @@ impl AnchoredSystemPath { let path_str = path.as_ref(); let path = Path::new(path_str); if path.is_absolute() { - return Err(PathError::NotRelative(path_str.to_string(), None)); + return Err(PathError::NotRelative(path_str.to_string())); } Ok(unsafe { &*(path as *const Path as *const Self) }) diff --git a/crates/turborepo-paths/src/anchored_system_path_buf.rs b/crates/turborepo-paths/src/anchored_system_path_buf.rs index 9f3cac7889a2ba..6147be0461ac22 100644 --- a/crates/turborepo-paths/src/anchored_system_path_buf.rs +++ b/crates/turborepo-paths/src/anchored_system_path_buf.rs @@ -20,7 +20,7 @@ impl TryFrom<&str> for AnchoredSystemPathBuf { fn try_from(path: &str) -> Result { let path = Utf8Path::new(path); if path.is_absolute() { - return Err(PathError::NotRelative(path.to_string(), None)); + return Err(PathError::NotRelative(path.to_string())); } Ok(AnchoredSystemPathBuf(path.into())) @@ -53,7 +53,7 @@ impl TryFrom<&Path> for AnchoredSystemPathBuf { fn try_from(path: &Path) -> Result { let path = path .to_str() - .ok_or_else(|| PathError::InvalidUnicode(path.to_string_lossy().to_string(), None))?; + .ok_or_else(|| PathError::InvalidUnicode(path.to_string_lossy().to_string()))?; Self::try_from(path) } @@ -82,7 +82,7 @@ impl AnchoredSystemPathBuf { let stripped_path = path .as_path() .strip_prefix(root.as_path()) - .map_err(|_| PathError::NotParent(root.to_string(), path.to_string(), None))? + .map_err(|_| PathError::NotParent(root.to_string(), path.to_string()))? .into(); Ok(AnchoredSystemPathBuf(stripped_path)) @@ -151,7 +151,7 @@ impl AnchoredSystemPathBuf { pub fn from_system_path(path: &Path) -> Result { let path = path .to_str() - .ok_or_else(|| PathError::InvalidUnicode(path.to_string_lossy().to_string(), None))?; + .ok_or_else(|| PathError::InvalidUnicode(path.to_string_lossy().to_string()))?; #[allow(unused_variables)] let PathValidation { @@ -160,7 +160,7 @@ impl AnchoredSystemPathBuf { } = check_path(path); if !well_formed { - return Err(PathError::MalformedPath(path.to_string(), None)); + return Err(PathError::MalformedPath(path.to_string())); } #[cfg(windows)] diff --git a/crates/turborepo-paths/src/lib.rs b/crates/turborepo-paths/src/lib.rs index 1ba8d6bc253d75..b56b4e15ced6ef 100644 --- a/crates/turborepo-paths/src/lib.rs +++ b/crates/turborepo-paths/src/lib.rs @@ -46,7 +46,7 @@ mod anchored_system_path_buf; mod relative_unix_path; mod relative_unix_path_buf; -use std::{io, sync::Arc}; +use std::io; pub use absolute_system_path::{AbsoluteSystemPath, PathRelation}; pub use absolute_system_path_buf::AbsoluteSystemPathBuf; @@ -57,95 +57,50 @@ use miette::Diagnostic; pub use relative_unix_path::RelativeUnixPath; pub use relative_unix_path_buf::{RelativeUnixPathBuf, RelativeUnixPathBufTestExt}; use thiserror::Error; -use turborepo_errors::{Provenance, Sourced}; // Lets windows know that we're going to be reading this file sequentially #[cfg(windows)] pub const FILE_FLAG_SEQUENTIAL_SCAN: u32 = 0x08000000; -impl From for PathError { - fn from(value: camino::FromPathError) -> Self { - PathError::FromPathError(value, None) - } -} - -impl From for PathError { - fn from(value: camino::FromPathBufError) -> Self { - PathError::FromPathBufError(value, None) - } -} - impl From for PathError { fn from(value: io::Error) -> Self { - PathError::IO(value, None) + PathError::IO(value) } } #[derive(Debug, Error, Diagnostic)] pub enum PathError { #[error("Path is non-UTF-8: {0}")] - InvalidUnicode(String, Option>), + InvalidUnicode(String), #[error("Failed to convert path")] - FromPathBufError(camino::FromPathBufError, Option>), + FromPathBufError(#[from] camino::FromPathBufError), #[error("Failed to convert path")] - FromPathError(camino::FromPathError, Option>), + FromPathError(#[from] camino::FromPathError), #[error("path is malformed: {0}")] - MalformedPath(String, Option>), + MalformedPath(String), #[error("Path is not safe for windows: {0}")] - WindowsUnsafePath(String, Option>), + WindowsUnsafePath(String), #[error("Path is not absolute: {0}")] - NotAbsolute(String, Option>), + NotAbsolute(String), #[error("Path is not relative: {0}")] - NotRelative(String, Option>), + NotRelative(String), #[error("Path {0} is not parent of {1}")] - NotParent(String, String, Option>), + NotParent(String, String), #[error("IO Error {0}")] - IO(io::Error, Option>), + IO(io::Error), #[error("{0} is not a prefix for {1}")] - PrefixError(String, String, Option>), -} - -impl Sourced for PathError { - fn with_provenance(mut self, provenance: Option>) -> Self { - match self { - PathError::InvalidUnicode(_, ref mut p) - | PathError::FromPathBufError(_, ref mut p) - | PathError::FromPathError(_, ref mut p) - | PathError::MalformedPath(_, ref mut p) - | PathError::WindowsUnsafePath(_, ref mut p) - | PathError::NotAbsolute(_, ref mut p) - | PathError::NotRelative(_, ref mut p) - | PathError::NotParent(_, _, ref mut p) - | PathError::IO(_, ref mut p) - | PathError::PrefixError(_, _, ref mut p) => *p = provenance, - } - self - } - fn provenance(&self) -> Option> { - match self { - PathError::InvalidUnicode(_, provenance) - | PathError::FromPathBufError(_, provenance) - | PathError::FromPathError(_, provenance) - | PathError::MalformedPath(_, provenance) - | PathError::WindowsUnsafePath(_, provenance) - | PathError::NotAbsolute(_, provenance) - | PathError::NotRelative(_, provenance) - | PathError::NotParent(_, _, provenance) - | PathError::IO(_, provenance) - | PathError::PrefixError(_, _, provenance) => provenance.clone(), - } - } + PrefixError(String, String), } impl From for PathError { fn from(value: std::string::FromUtf8Error) -> Self { - PathError::InvalidUnicode(value.utf8_error().to_string(), None) + PathError::InvalidUnicode(value.utf8_error().to_string()) } } impl PathError { pub fn is_io_error(&self, kind: io::ErrorKind) -> bool { - matches!(self, PathError::IO(err, _) if err.kind() == kind) + matches!(self, PathError::IO(err) if err.kind() == kind) } } @@ -262,11 +217,11 @@ pub enum UnknownPathType { /// Categorizes a path as either an `AbsoluteSystemPathBuf` or /// an `AnchoredSystemPathBuf` depending on whether it /// is absolute or relative. -pub fn categorize(path: &Utf8Path, provenance: Option>) -> UnknownPathType { +pub fn categorize(path: &Utf8Path) -> UnknownPathType { let path = Utf8PathBuf::try_from(path_clean::clean(path)) .expect("path cleaning should preserve UTF-8"); if path.is_absolute() { - UnknownPathType::Absolute(AbsoluteSystemPathBuf(provenance, path)) + UnknownPathType::Absolute(AbsoluteSystemPathBuf(path)) } else { UnknownPathType::Anchored(AnchoredSystemPathBuf(path)) } diff --git a/crates/turborepo-paths/src/relative_unix_path.rs b/crates/turborepo-paths/src/relative_unix_path.rs index d14615413b9fb8..56150d0b810a03 100644 --- a/crates/turborepo-paths/src/relative_unix_path.rs +++ b/crates/turborepo-paths/src/relative_unix_path.rs @@ -21,7 +21,7 @@ impl RelativeUnixPath { pub fn new<'a, P: AsRef + 'a>(value: P) -> Result<&'a Self, PathError> { let path = value.as_ref(); if path.starts_with('/') { - return Err(PathError::NotRelative(path.to_string(), None)); + return Err(PathError::NotRelative(path.to_string())); } // copied from stdlib path.rs: relies on the representation of // RelativeUnixPath being just a str, the same way Path relies on @@ -60,9 +60,10 @@ impl RelativeUnixPath { &self, prefix: impl AsRef, ) -> Result<&RelativeUnixPath, PathError> { - let stripped_path = self.0.strip_prefix(&prefix.as_ref().0).ok_or_else(|| { - PathError::NotParent(prefix.as_ref().to_string(), self.to_string(), None) - })?; + let stripped_path = self + .0 + .strip_prefix(&prefix.as_ref().0) + .ok_or_else(|| PathError::NotParent(prefix.as_ref().to_string(), self.to_string()))?; // Remove leading '/' if present let stripped_path = stripped_path.strip_prefix('/').unwrap_or(stripped_path); diff --git a/crates/turborepo-paths/src/relative_unix_path_buf.rs b/crates/turborepo-paths/src/relative_unix_path_buf.rs index fbd03f28faa092..ce49d7a9e7d047 100644 --- a/crates/turborepo-paths/src/relative_unix_path_buf.rs +++ b/crates/turborepo-paths/src/relative_unix_path_buf.rs @@ -24,7 +24,7 @@ impl RelativeUnixPathBuf { pub fn new(path: impl Into) -> Result { let path_string = path.into(); if path_string.starts_with('/') || Utf8Path::new(&path_string).is_absolute() { - return Err(PathError::NotRelative(path_string, None)); + return Err(PathError::NotRelative(path_string)); } Ok(Self(path_string)) @@ -53,7 +53,6 @@ impl RelativeUnixPathBuf { return Err(PathError::NotParent( prefix.0.to_string(), self.0.to_string(), - None, )); } @@ -67,7 +66,7 @@ impl RelativeUnixPathBuf { if self.0.as_bytes()[prefix_len] != b'/' { let prefix_str = prefix.0.clone(); let this = self.0.clone(); - return Err(PathError::PrefixError(prefix_str, this, None)); + return Err(PathError::PrefixError(prefix_str, this)); } let tail_slice = &self.0[(prefix_len + 1)..];