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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/pixi_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ fancy_display = { workspace = true }
fs-err = { workspace = true }
futures = { workspace = true }
hex = { workspace = true }
indexmap = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
itertools = { workspace = true }
miette = { workspace = true }
minijinja = { workspace = true }
pep508_rs = { workspace = true }
pixi_config = { workspace = true }
pixi_consts = { workspace = true }
pixi_core = { workspace = true }
pixi_global = { workspace = true }
pixi_install_pypi = { workspace = true }
pixi_manifest = { workspace = true }
pixi_progress = { workspace = true }
Expand Down
41 changes: 41 additions & 0 deletions crates/pixi_api/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use pixi_pypi_spec::{PixiPypiSpec, PypiPackageName};
use pixi_spec::PixiSpec;
use rattler_conda_types::{Channel, MatchSpec, NamedChannelOrUrl, PackageName, Subdir};

use crate::global::{GlobalEnvironment, ListError};
use crate::interface::Interface;
use crate::workspace::add::GitOptions;
use crate::workspace::{
Expand Down Expand Up @@ -50,6 +51,42 @@ impl<I: Interface> DefaultContext<I> {
}
}

pub struct GlobalContext<I: Interface> {
_interface: I,
project: pixi_global::Project,
}

impl<I: Interface> GlobalContext<I> {
pub fn new(interface: I, project: pixi_global::Project) -> Self {
Self {
_interface: interface,
project,
}
}

pub fn project(&self) -> &pixi_global::Project {
&self.project
}

pub fn manifest_path(&self) -> std::path::PathBuf {
self.project.manifest.path.clone()
}

pub async fn list_environments(
&self,
regex: Option<String>,
) -> Result<Vec<GlobalEnvironment>, ListError> {
crate::global::list::list(&self.project, regex).await
}

pub async fn get_environment(
&self,
name: &pixi_global::EnvironmentName,
) -> Result<GlobalEnvironment, ListError> {
crate::global::list::get(&self.project, name).await
}
}

pub struct WorkspaceContext<I: Interface> {
interface: I,
workspace: Workspace,
Expand Down Expand Up @@ -77,6 +114,10 @@ impl<I: Interface> WorkspaceContext<I> {
&self.workspace
}

pub fn manifest_path(&self) -> std::path::PathBuf {
self.workspace.workspace.provenance.absolute_path()
}

pub fn workspace_mut(&self) -> Result<WorkspaceMut, LoadManifestsError> {
Ok(self.attach_progress(self.workspace.clone().modify()?))
}
Expand Down
159 changes: 159 additions & 0 deletions crates/pixi_api/src/global/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
use fancy_display::FancyDisplay;
use indexmap::IndexSet;
use pixi_consts::consts;
use pixi_global::{
EnvironmentName, Project,
common::{self, CondaMetaError, find_package_records},
project::{ManifestError, ParsedEnvironment},
};
use rattler_conda_types::{NamedChannelOrUrl, PackageName, PrefixRecord, Subdir};
use serde::Serialize;

/// An error from listing the global environments.
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum ListError {
#[error(transparent)]
#[diagnostic(transparent)]
Manifest(#[from] ManifestError),

#[error("invalid regex")]
Regex(#[source] regex::Error),

#[error(transparent)]
#[diagnostic(transparent)]
CondaMeta(#[from] CondaMetaError),
}

/// An executable of a global environment exposed under a name.
#[derive(Debug, Clone, Serialize)]
pub struct GlobalExposedMapping {
pub exposed_name: String,
pub executable: String,
}

/// A dependency of a global environment with its installed version.
#[derive(Debug, Clone, Serialize)]
pub struct GlobalDependency {
pub name: String,
pub version: Option<String>,
}

/// The state of a global environment
#[derive(Debug, Clone, Serialize)]
pub struct GlobalEnvironment {
pub name: EnvironmentName,
pub version: Option<String>,
pub dependencies: Vec<GlobalDependency>,
pub exposed: Vec<GlobalExposedMapping>,
pub shortcuts: IndexSet<PackageName>,
pub channels: Vec<NamedChannelOrUrl>,
pub platform: Option<Subdir>,
pub records: Vec<PrefixRecord>,
}

/// Collect the state of one environment
async fn environment(
project: &Project,
env_name: &EnvironmentName,
env: &ParsedEnvironment,
) -> Result<GlobalEnvironment, ListError> {
let conda_meta = project
.env_root_path()
.join(env_name.as_str())
.join(consts::CONDA_META_DIR);
let records = find_package_records(&conda_meta).await?;

let version = if common::is_single_package_environment(project, env_name) {
common::installed_version(project, env_name).await?
} else {
None
};

let dependencies = env
.dependencies
.specs
.keys()
.map(|name| {
let version = records
.iter()
.find(|rec| {
rec.repodata_record.package_record.name.as_normalized() == name.as_normalized()
})
.map(|rec| {
rec.repodata_record
.package_record
.version
.version()
.to_string()
});
GlobalDependency {
name: name.as_normalized().to_string(),
version,
}
})
.collect();

Ok(GlobalEnvironment {
name: env_name.clone(),
version,
dependencies,
exposed: env
.exposed
.iter()
.map(|mapping| GlobalExposedMapping {
exposed_name: mapping.exposed_name().to_string(),
executable: mapping.executable_relname().to_string(),
})
.collect(),
shortcuts: env.shortcuts.clone().unwrap_or_default(),
channels: env.channels().into_iter().cloned().collect(),
platform: env.platform,
records,
})
}

/// Get a specific global environment
pub async fn get(
project: &Project,
environment_name: &EnvironmentName,
) -> Result<GlobalEnvironment, ListError> {
let env = project
.environments()
.get(environment_name)
.ok_or_else(|| ManifestError::EnvironmentNotFound(environment_name.clone()))?;

environment(project, environment_name, env).await
}

/// List all environments in the global environment, sorted by name
pub async fn list(
project: &Project,
regex: Option<String>,
) -> Result<Vec<GlobalEnvironment>, ListError> {
let mut project_envs = project.environments().clone();
project_envs.sort_by(|a, _, b, _| a.to_string().cmp(&b.to_string()));

project_envs.retain(|env_name, parsed_environment| {
if parsed_environment.dependencies.specs.is_empty() {
tracing::warn!(
"Environment {} doesn't contain dependencies. Skipping.",
env_name.fancy_display()
);
false
} else {
true
}
});

if let Some(regex) = regex {
let regex = regex::Regex::new(&regex).map_err(ListError::Regex)?;
project_envs.retain(|env_name, _| regex.is_match(env_name.as_str()));
}

let mut environments = Vec::with_capacity(project_envs.len());
for (env_name, env) in project_envs.iter() {
environments.push(environment(project, env_name, env).await?);
}

Ok(environments)
}
7 changes: 7 additions & 0 deletions crates/pixi_api/src/global/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//! This module contains everything which is related to pixi global.

pub(crate) mod list;
pub use list::{GlobalDependency, GlobalEnvironment, GlobalExposedMapping, ListError};

// Reexport for pixi_api consumers
pub use pixi_global::*;
3 changes: 2 additions & 1 deletion crates/pixi_api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
pub mod global;
pub mod workspace;

mod context;
pub use context::{DefaultContext, WorkspaceContext};
pub use context::{DefaultContext, GlobalContext, WorkspaceContext};

mod interface;
pub use interface::{Interface, InterfaceError};
Expand Down
4 changes: 2 additions & 2 deletions crates/pixi_cli/src/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use url::Url;

use crate::{
cli_config::{DependencyConfig, LockFileUpdateConfig, NoInstallConfig, ScriptWorkspaceConfig},
cli_interface::{CliInterface, cli_context},
cli_interface::{CliInterface, cli_workspace_context},
has_specs::HasSpecs,
};

Expand Down Expand Up @@ -455,7 +455,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
));
}

let workspace_ctx = cli_context(workspace.clone());
let workspace_ctx = cli_workspace_context(workspace.clone());

let (update_deps, skipped, parsed_names): (_, Vec<SkippedPackage>, Vec<String>) =
match args.dependency_config.dependency_type() {
Expand Down
9 changes: 7 additions & 2 deletions crates/pixi_cli/src/cli_interface.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
use pixi_api::{Interface, InterfaceError, WorkspaceContext};
use pixi_api::{GlobalContext, Interface, InterfaceError, WorkspaceContext, global::Project};
use pixi_core::Workspace;

/// Builds the [`GlobalContext`] every `pixi global` command works through.
pub fn cli_global_context(project: Project) -> GlobalContext<CliInterface> {
GlobalContext::new(CliInterface {}, project)
}

/// Builds the [`WorkspaceContext`] every CLI command works through.
///
/// Attaching the progress reporter here rather than at each call site is what
/// keeps commands like `pixi add` from silently downloading gigabytes: every
/// context method that solves reports through it without the command having to
/// opt in. `search` is the exception, because it builds its own gateway rather
/// than going through the command dispatcher.
pub fn cli_context(workspace: Workspace) -> WorkspaceContext<CliInterface> {
pub fn cli_workspace_context(workspace: Workspace) -> WorkspaceContext<CliInterface> {
WorkspaceContext::new(CliInterface {}, workspace)
.with_progress(pixi_reporters::TopLevelProgress::from_global())
}
Expand Down
Loading
Loading