diff --git a/crates/pixi/tests/integration_rust/add_tests.rs b/crates/pixi/tests/integration_rust/add_tests.rs index 641d1c1735..298f9bc926 100644 --- a/crates/pixi/tests/integration_rust/add_tests.rs +++ b/crates/pixi/tests/integration_rust/add_tests.rs @@ -1498,7 +1498,10 @@ platforms = ["linux-64"] let error = result.unwrap_err(); // Use insta to snapshot test the full error message format including help text - insta::assert_debug_snapshot!("git_dependency_without_preview_error", error); + insta::assert_snapshot!(pixi_test_utils::format_diagnostic(error.as_ref()), @" + × conda source dependencies are not allowed without enabling the 'pixi-build' preview flag + help: Run `pixi workspace preview add pixi-build` to enable the preview flag + "); } #[tokio::test] diff --git a/crates/pixi/tests/integration_rust/snapshots/integration_rust__add_tests__git_dependency_without_preview_error.snap b/crates/pixi/tests/integration_rust/snapshots/integration_rust__add_tests__git_dependency_without_preview_error.snap deleted file mode 100644 index 12c19f1803..0000000000 --- a/crates/pixi/tests/integration_rust/snapshots/integration_rust__add_tests__git_dependency_without_preview_error.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: crates/pixi/tests/integration_rust/add_tests.rs -expression: error ---- -MietteDiagnostic { - message: "conda source dependencies are not allowed without enabling the 'pixi-build' preview flag", - code: None, - severity: None, - help: Some( - "Run `pixi workspace preview add pixi-build` to enable the preview flag", - ), - url: None, - labels: None, -} diff --git a/crates/pixi_api/src/context.rs b/crates/pixi_api/src/context.rs index 068bad0226..10f76c72aa 100644 --- a/crates/pixi_api/src/context.rs +++ b/crates/pixi_api/src/context.rs @@ -19,10 +19,10 @@ use rattler_conda_types::{Channel, MatchSpec, NamedChannelOrUrl, PackageName, Su use crate::interface::Interface; use crate::workspace::add::GitOptions; use crate::workspace::{ - ChannelError, ChannelOptions, DependencyOptions, EditActivationError, EnvironmentError, - InitError, InitOptions, Package, PlatformError, PreviewFlagsError, ReinstallOptions, - RemoveError, RemoveFeatureError, RunOptions, SetDescriptionError, SetNameError, ShellError, - ShellOptions, + AddError, ChannelError, ChannelOptions, DependencyOptions, EditActivationError, + EnvironmentError, InitError, InitOptions, Package, PlatformError, PreviewFlagsError, + ReinstallOptions, RemoveError, RemoveFeatureError, RunOptions, SetDescriptionError, + SetNameError, ShellError, ShellOptions, }; pub struct DefaultContext { @@ -481,7 +481,7 @@ impl WorkspaceContext { spec_type: SpecType, dep_options: DependencyOptions, git_options: GitOptions, - ) -> miette::Result<(Option, Vec)> { + ) -> Result<(Option, Vec), AddError> { Box::pin(crate::workspace::add::add_conda_dep( self.workspace_mut()?, specs, @@ -497,7 +497,7 @@ impl WorkspaceContext { pypi_deps: PypiDeps, editable: bool, options: DependencyOptions, - ) -> miette::Result<(Option, Vec)> { + ) -> Result<(Option, Vec), AddError> { Box::pin(crate::workspace::add::add_pypi_dep( self.workspace_mut()?, pypi_deps, diff --git a/crates/pixi_api/src/workspace/add/mod.rs b/crates/pixi_api/src/workspace/add/mod.rs index fb79dbd493..d09d2750c6 100644 --- a/crates/pixi_api/src/workspace/add/mod.rs +++ b/crates/pixi_api/src/workspace/add/mod.rs @@ -1,28 +1,78 @@ +use std::path::PathBuf; + +use futures::FutureExt; use indexmap::IndexMap; -use miette::IntoDiagnostic; +use miette::Diagnostic; use pixi_core::{ - environment::sanity_check_workspace, - workspace::{PypiDeps, SkippedPackage, UpdateDeps, WorkspaceMut}, + environment::{SanityCheckError, sanity_check_workspace}, + workspace::{PypiDeps, SkippedPackage, UpdateDependenciesError, UpdateDeps, WorkspaceMut}, }; use pixi_manifest::{ - DependencyOverwriteBehavior, FeatureName, HasWorkspaceManifest, KnownPreviewFlag, SpecType, + DependencyOverwriteBehavior, FeatureName, HasWorkspaceManifest, KnownPreviewFlag, + LoadManifestsError, PlatformEditError, SpecType, }; -use pixi_spec::{GitSpec, PathSourceSpec, SourceSpec, Subdirectory}; +use pixi_spec::{GitSpec, PathSourceSpec, SourceSpec, Subdirectory, SubdirectoryError}; use rattler_conda_types::{MatchSpec, PackageName}; +use thiserror::Error; -use crate::workspace::platforms::resolve_platforms; +use crate::workspace::{ + platforms::resolve_platforms, + workspace::{SaveManifestError, save}, +}; mod options; pub use options::{DependencyOptions, GitOptions}; +#[derive(Debug, Error, Diagnostic)] +pub enum AddError { + #[error(transparent)] + #[diagnostic(transparent)] + LoadWorkspace(#[from] LoadManifestsError), + + #[error(transparent)] + #[diagnostic(transparent)] + SanityCheck(#[from] SanityCheckError), + + #[error(transparent)] + #[diagnostic(transparent)] + Platform(#[from] PlatformEditError), + + #[error( + "conda source dependencies are not allowed without enabling the 'pixi-build' preview flag" + )] + #[diagnostic(help("Run `pixi workspace preview add pixi-build` to enable the preview flag"))] + PixiBuildNotEnabled, + + #[error(transparent)] + Subdirectory(#[from] SubdirectoryError), + + #[error(transparent)] + #[diagnostic(transparent)] + UpdateDependencies(#[from] UpdateDependenciesError), + + #[error(transparent)] + #[diagnostic(transparent)] + Save(#[from] SaveManifestError), + + /// Restoring the manifest after `update` failed also failed. + #[error("failed to restore '{}'", .path.display())] + RestoreManifest { + path: PathBuf, + #[source] + source: std::io::Error, + #[related] + update: Vec, + }, +} + pub async fn add_conda_dep( mut workspace: WorkspaceMut, specs: IndexMap, spec_type: SpecType, dep_options: DependencyOptions, git_options: GitOptions, -) -> miette::Result<(Option, Vec)> { +) -> Result<(Option, Vec), AddError> { sanity_check_workspace(workspace.workspace()).await?; // Resolve the requested platforms, accepting bare subdirs as subdir @@ -55,10 +105,7 @@ pub async fn add_conda_dep( .preview() .is_enabled(KnownPreviewFlag::PixiBuild) { - return Err(miette::miette!( - help = "Run `pixi workspace preview add pixi-build` to enable the preview flag", - "conda source dependencies are not allowed without enabling the 'pixi-build' preview flag" - )); + return Err(AddError::PixiBuildNotEnabled); } if let Some(git) = &git_options.git { @@ -66,8 +113,7 @@ pub async fn add_conda_dep( .subdir .clone() .map(Subdirectory::try_from) - .transpose() - .into_diagnostic()? + .transpose()? .unwrap_or_default(); source_specs = passed_specs .iter() @@ -113,18 +159,34 @@ pub async fn add_conda_dep( { Ok(result) => { // Write the updated manifest - workspace.save().await.into_diagnostic()?; + save(workspace).await?; result } - Err(e) => { - workspace.revert().await.into_diagnostic()?; - return Err(e.into()); - } + Err(e) => return Err(revert(workspace, e).await), }; Ok((update_deps, skipped)) } +/// Reverts `workspace` after `update` failed, keeping `update` if reverting +/// fails too. +/// +/// Not `async`, for the same reason as [`save`]. +fn revert( + workspace: WorkspaceMut, + update: UpdateDependenciesError, +) -> impl Future { + let path = workspace.workspace().workspace.provenance.path.clone(); + workspace.revert().map(move |result| match result { + Ok(_) => update.into(), + Err(source) => AddError::RestoreManifest { + path, + source, + update: vec![update], + }, + }) +} + fn manifest_path_string(path: &std::path::Path) -> String { path.to_string_lossy().replace('\\', "/") } @@ -134,7 +196,7 @@ pub async fn add_pypi_dep( pypi_deps: PypiDeps, editable: bool, options: DependencyOptions, -) -> miette::Result<(Option, Vec)> { +) -> Result<(Option, Vec), AddError> { sanity_check_workspace(workspace.workspace()).await?; // Resolve the requested platforms, accepting bare subdirs as subdir @@ -170,14 +232,106 @@ pub async fn add_pypi_dep( { Ok(result) => { // Write the updated manifest - workspace.save().await.into_diagnostic()?; + save(workspace).await?; result } - Err(e) => { - workspace.revert().await.into_diagnostic()?; - return Err(e.into()); - } + Err(e) => return Err(revert(workspace, e).await), }; Ok((update_deps, skipped)) } + +#[cfg(test)] +mod tests { + use pixi_core::{Workspace, environment::LockFileUsage}; + use pixi_manifest::PixiPlatformName; + use pixi_spec::GitReference; + use rattler_conda_types::{ParseMatchSpecOptions, RepodataRevision}; + + use super::*; + + fn workspace_mut() -> WorkspaceMut { + // The workspace re-reads its manifest from disk during `modify()`, so + // we write the TOML to a temp dir and load from that path. The dir is + // intentionally leaked for the duration of the test. + let tmp = tempfile::TempDir::new().unwrap().keep(); + let path = tmp.join("pixi.toml"); + fs_err::write( + &path, + r#" +[workspace] +name = "test" +channels = [] +platforms = ["linux-64"] +"#, + ) + .unwrap(); + Workspace::from_path(&path) + .expect("failed to load workspace") + .modify() + .unwrap() + } + + fn options(platforms: &[&str]) -> DependencyOptions { + DependencyOptions { + feature: FeatureName::Default, + platforms: platforms + .iter() + .map(|p| PixiPlatformName::try_from(*p).unwrap()) + .collect(), + no_install: true, + lock_file_usage: LockFileUsage::Frozen, + } + } + + fn git_options(path: Option<&str>) -> GitOptions { + GitOptions { + git: None, + path: path.map(PathBuf::from), + reference: GitReference::DefaultBranch, + subdir: None, + } + } + + fn specs(name: &str) -> IndexMap { + let spec = MatchSpec::from_str( + name, + ParseMatchSpecOptions::lenient().with_repodata_revision(RepodataRevision::V3), + ) + .unwrap(); + IndexMap::from([(spec.name.as_exact().unwrap().clone(), spec)]) + } + + #[tokio::test] + async fn unknown_platform() { + let err = add_conda_dep( + workspace_mut(), + specs("ruff"), + SpecType::Run, + options(&["nope"]), + git_options(None), + ) + .await + .err() + .expect("add should fail"); + assert!(matches!( + err, + AddError::Platform(PlatformEditError::NotFound(name)) if name.as_str() == "nope" + )); + } + + #[tokio::test] + async fn source_dependency_needs_pixi_build() { + let err = add_conda_dep( + workspace_mut(), + specs("foo"), + SpecType::Run, + options(&[]), + git_options(Some("foo")), + ) + .await + .err() + .expect("add should fail"); + assert!(matches!(err, AddError::PixiBuildNotEnabled)); + } +} diff --git a/crates/pixi_api/src/workspace/mod.rs b/crates/pixi_api/src/workspace/mod.rs index 03df5384ac..a380f0895e 100644 --- a/crates/pixi_api/src/workspace/mod.rs +++ b/crates/pixi_api/src/workspace/mod.rs @@ -3,7 +3,7 @@ pub mod platforms; pub(crate) mod add; -pub use add::{DependencyOptions, GitOptions}; +pub use add::{AddError, DependencyOptions, GitOptions}; pub(crate) mod remove; pub use remove::RemoveError; diff --git a/crates/pixi_api/src/workspace/platforms.rs b/crates/pixi_api/src/workspace/platforms.rs index 446cb8b095..ec48fe763c 100644 --- a/crates/pixi_api/src/workspace/platforms.rs +++ b/crates/pixi_api/src/workspace/platforms.rs @@ -15,7 +15,7 @@ //! just use the returned `Vec` and leave the manifest alone. use indexmap::IndexSet; -use pixi_manifest::{PixiPlatform, PixiPlatformName}; +use pixi_manifest::{PixiPlatform, PixiPlatformName, PlatformEditError}; use rattler_conda_types::Subdir; /// Resolve each requested platform name against the workspace's declared @@ -30,7 +30,7 @@ use rattler_conda_types::Subdir; pub fn resolve_platforms( workspace_platforms: &IndexSet, names: &[PixiPlatformName], -) -> miette::Result> { +) -> Result, PlatformEditError> { names .iter() .map(|name| { @@ -40,7 +40,7 @@ pub fn resolve_platforms( name.as_str() .parse::() .map(PixiPlatform::from_subdir) - .map_err(|_| miette::miette!("workspace does not define a platform named '{name}'")) + .map_err(|_| PlatformEditError::NotFound(name.clone())) }) .collect() } diff --git a/crates/pixi_api/src/workspace/remove/mod.rs b/crates/pixi_api/src/workspace/remove/mod.rs index 42fd04c2ca..a7cbc51f72 100644 --- a/crates/pixi_api/src/workspace/remove/mod.rs +++ b/crates/pixi_api/src/workspace/remove/mod.rs @@ -2,7 +2,7 @@ use indexmap::IndexMap; use miette::Diagnostic; use pixi_core::{ InstallFilter, UpdateLockFileOptions, - environment::{LockFileUsage, get_update_lock_file_and_prefix}, + environment::{LockFileAndPrefixesError, LockFileUsage, get_update_lock_file_and_prefix}, lock_file::{ReinstallPackages, UpdateMode}, workspace::{PypiDeps, WorkspaceMut}, }; @@ -12,17 +12,18 @@ use pixi_manifest::{ use rattler_conda_types::{MatchSpec, PackageName}; use thiserror::Error; -use crate::workspace::DependencyOptions; +use crate::workspace::{ + DependencyOptions, + workspace::{SaveManifestError, save}, +}; #[derive(Debug, Error, Diagnostic)] pub enum RemoveError { - #[error("dependency `{name}` was not found")] + #[error("dependency '{name}' was not found")] NotFound { name: String }, - #[error( - "Cannot remove Python while PyPI dependencies exist. Please remove these PyPI dependencies first: {}", - .pypi_deps.join(", ") - )] + #[error("cannot remove 'python' while PyPI dependencies exist")] + #[diagnostic(help("Remove these PyPI dependencies first: {}.", .pypi_deps.join(", ")))] PythonHasPypiDependencies { pypi_deps: Vec }, #[error(transparent)] @@ -34,12 +35,13 @@ pub enum RemoveError { #[diagnostic(transparent)] Manifest(RemoveDependencyError), - #[error("failed to save the manifest")] - Save(#[source] std::io::Error), + #[error(transparent)] + #[diagnostic(transparent)] + Save(#[from] SaveManifestError), #[error(transparent)] #[diagnostic(transparent)] - LockFileUpdate(Box), + LockFileAndPrefixes(#[from] LockFileAndPrefixesError), } impl From for RemoveError { @@ -86,7 +88,7 @@ pub async fn remove_conda_deps( )?; } let progress = workspace.progress().cloned(); - let workspace = workspace.save().await.map_err(RemoveError::Save)?; + let workspace = save(workspace).await?; // TODO: update all environments touched by this feature defined. // updating prefix after removing from toml @@ -104,8 +106,7 @@ pub async fn remove_conda_deps( ReinstallPackages::default(), &InstallFilter::default(), ) - .await - .map_err(|e| RemoveError::LockFileUpdate(e.into()))?; + .await?; } Ok(()) @@ -123,7 +124,7 @@ pub async fn remove_pypi_deps( } let progress = workspace.progress().cloned(); - let workspace = workspace.save().await.map_err(RemoveError::Save)?; + let workspace = save(workspace).await?; // TODO: update all environments touched by this feature defined. // updating prefix after removing from toml @@ -141,8 +142,7 @@ pub async fn remove_pypi_deps( ReinstallPackages::default(), &InstallFilter::default(), ) - .await - .map_err(|e| RemoveError::LockFileUpdate(e.into()))?; + .await?; } Ok(()) @@ -213,7 +213,13 @@ requests = "*" insta::assert_snapshot!( format_diagnostic(&err), - @" × Cannot remove Python while PyPI dependencies exist. Please remove these PyPI dependencies first: requests" + @" + × cannot remove 'python' while PyPI dependencies exist + help: Remove these PyPI dependencies first: requests. + " + ); + assert!( + matches!(err, RemoveError::PythonHasPypiDependencies { pypi_deps } if pypi_deps == ["requests"]) ); } @@ -242,7 +248,7 @@ ruff = "*" insta::assert_snapshot!( format_diagnostic(&err), - @" × dependency `fizzbuzz` was not found" + @" × dependency 'fizzbuzz' was not found" ); assert!(matches!(err, RemoveError::NotFound { name } if name == "fizzbuzz")); } diff --git a/crates/pixi_api/src/workspace/workspace/mod.rs b/crates/pixi_api/src/workspace/workspace/mod.rs index 6501317f29..88479a2e8a 100644 --- a/crates/pixi_api/src/workspace/workspace/mod.rs +++ b/crates/pixi_api/src/workspace/workspace/mod.rs @@ -27,7 +27,9 @@ pub struct SaveManifestError { /// doesn't always carry the path. /// /// Not `async`: that would store the `save` future twice, and it is large. -fn save(workspace: WorkspaceMut) -> impl Future> { +pub(crate) fn save( + workspace: WorkspaceMut, +) -> impl Future> { let path = workspace.workspace().workspace.provenance.path.clone(); workspace .save() diff --git a/crates/pixi_core/src/workspace/mod.rs b/crates/pixi_core/src/workspace/mod.rs index dbc85420a3..57375b3ecf 100644 --- a/crates/pixi_core/src/workspace/mod.rs +++ b/crates/pixi_core/src/workspace/mod.rs @@ -77,7 +77,7 @@ use rattler_repodata_gateway::Gateway; pub use registry::{WorkspaceRegistry, WorkspaceRegistryError}; pub use solve_group::SolveGroup; use tokio::sync::{Mutex, Semaphore}; -pub use workspace_mut::{AddSpecsError, WorkspaceMut}; +pub use workspace_mut::{AddSpecsError, UpdateDependenciesError, WorkspaceMut}; use xxhash_rust::xxh3::xxh3_64; static CUSTOM_TARGET_DIR_WARN: OnceCell<()> = OnceCell::new(); diff --git a/crates/pixi_core/src/workspace/workspace_mut.rs b/crates/pixi_core/src/workspace/workspace_mut.rs index b8846abef5..b77e331f7c 100644 --- a/crates/pixi_core/src/workspace/workspace_mut.rs +++ b/crates/pixi_core/src/workspace/workspace_mut.rs @@ -410,11 +410,14 @@ impl WorkspaceMut { let mut workspace = self.workspace.take().expect("workspace is not available"); if let Some(original) = self.original.take() { workspace.workspace.value = original.manifest; - pixi_utils::atomic_write::atomic_write( - &workspace.workspace.provenance.path, - original.source, - ) - .await?; + // Like `Drop`, only touch the file if the changes were written. + if self.modified { + pixi_utils::atomic_write::atomic_write( + &workspace.workspace.provenance.path, + original.source, + ) + .await?; + } workspace.invalidate_environment_hosts(); } @@ -944,3 +947,25 @@ impl Drop for WorkspaceMut { } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Reverting changes that were never saved must not write the manifest. + #[tokio::test] + async fn revert_without_save_leaves_manifest_alone() { + let tmp = tempfile::TempDir::new().unwrap(); + let path = tmp.path().join("pixi.toml"); + fs_err::write( + &path, + "[workspace]\nname = \"test\"\nchannels = []\nplatforms = []\n", + ) + .unwrap(); + let workspace = Workspace::from_path(&path).unwrap().modify().unwrap(); + + fs_err::remove_file(&path).unwrap(); + workspace.revert().await.unwrap(); + assert!(!path.exists()); + } +} diff --git a/scripts/into_diagnostic_baseline.toml b/scripts/into_diagnostic_baseline.toml index d6f78c5dc2..187510702d 100644 --- a/scripts/into_diagnostic_baseline.toml +++ b/scripts/into_diagnostic_baseline.toml @@ -1,5 +1,5 @@ # Generated by `scripts/check_into_diagnostic.py --update`. Crates not listed are pinned at 0. -pixi_api = 15 +pixi_api = 10 pixi_build_backend = 40 pixi_build_cmake = 1 pixi_build_mojo = 2