Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/pixi/tests/integration_rust/add_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

This file was deleted.

12 changes: 6 additions & 6 deletions crates/pixi_api/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<I: Interface> {
Expand Down Expand Up @@ -481,7 +481,7 @@ impl<I: Interface> WorkspaceContext<I> {
spec_type: SpecType,
dep_options: DependencyOptions,
git_options: GitOptions,
) -> miette::Result<(Option<UpdateDeps>, Vec<SkippedPackage>)> {
) -> Result<(Option<UpdateDeps>, Vec<SkippedPackage>), AddError> {
Box::pin(crate::workspace::add::add_conda_dep(
self.workspace_mut()?,
specs,
Expand All @@ -497,7 +497,7 @@ impl<I: Interface> WorkspaceContext<I> {
pypi_deps: PypiDeps,
editable: bool,
options: DependencyOptions,
) -> miette::Result<(Option<UpdateDeps>, Vec<SkippedPackage>)> {
) -> Result<(Option<UpdateDeps>, Vec<SkippedPackage>), AddError> {
Box::pin(crate::workspace::add::add_pypi_dep(
self.workspace_mut()?,
pypi_deps,
Expand Down
202 changes: 178 additions & 24 deletions crates/pixi_api/src/workspace/add/mod.rs
Original file line number Diff line number Diff line change
@@ -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<UpdateDependenciesError>,
},
}

pub async fn add_conda_dep(
mut workspace: WorkspaceMut,
specs: IndexMap<PackageName, MatchSpec>,
spec_type: SpecType,
dep_options: DependencyOptions,
git_options: GitOptions,
) -> miette::Result<(Option<UpdateDeps>, Vec<SkippedPackage>)> {
) -> Result<(Option<UpdateDeps>, Vec<SkippedPackage>), AddError> {
sanity_check_workspace(workspace.workspace()).await?;

// Resolve the requested platforms, accepting bare subdirs as subdir
Expand Down Expand Up @@ -55,19 +105,15 @@ 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 {
let subdirectory = git_options
.subdir
.clone()
.map(Subdirectory::try_from)
.transpose()
.into_diagnostic()?
.transpose()?
.unwrap_or_default();
source_specs = passed_specs
.iter()
Expand Down Expand Up @@ -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<Output = AddError> {
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('\\', "/")
}
Expand All @@ -134,7 +196,7 @@ pub async fn add_pypi_dep(
pypi_deps: PypiDeps,
editable: bool,
options: DependencyOptions,
) -> miette::Result<(Option<UpdateDeps>, Vec<SkippedPackage>)> {
) -> Result<(Option<UpdateDeps>, Vec<SkippedPackage>), AddError> {
sanity_check_workspace(workspace.workspace()).await?;

// Resolve the requested platforms, accepting bare subdirs as subdir
Expand Down Expand Up @@ -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<PackageName, MatchSpec> {
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));
}
}
2 changes: 1 addition & 1 deletion crates/pixi_api/src/workspace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions crates/pixi_api/src/workspace/platforms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,7 +30,7 @@ use rattler_conda_types::Subdir;
pub fn resolve_platforms(
workspace_platforms: &IndexSet<PixiPlatform>,
names: &[PixiPlatformName],
) -> miette::Result<Vec<PixiPlatform>> {
) -> Result<Vec<PixiPlatform>, PlatformEditError> {
names
.iter()
.map(|name| {
Expand All @@ -40,7 +40,7 @@ pub fn resolve_platforms(
name.as_str()
.parse::<Subdir>()
.map(PixiPlatform::from_subdir)
.map_err(|_| miette::miette!("workspace does not define a platform named '{name}'"))
.map_err(|_| PlatformEditError::NotFound(name.clone()))
})
.collect()
}
Loading
Loading