Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow to emit activation environment variables as JSON #1317

Merged
merged 8 commits into from
May 2, 2024
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
3 changes: 3 additions & 0 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,8 @@ This command prints the activation script of an environment.
- `--frozen`: install the environment as defined in the lock file, doesn't update `pixi.lock` if it isn't up-to-date with [manifest file](configuration.md). It can also be controlled by the `PIXI_FROZEN` environment variable (example: `PIXI_FROZEN=true`).
- `--locked`: only install if the `pixi.lock` is up-to-date with the [manifest file](configuration.md)[^1]. It can also be controlled by the `PIXI_LOCKED` environment variable (example: `PIXI_LOCKED=true`). Conflicts with `--frozen`.
- `--environment <ENVIRONMENT> (-e)`: The environment to activate, if none are provided the default environment will be used or a selector will be given to select the right environment.
- `--json`: Print all environment variables that are exported by running the activation script as JSON. When specifying
this option, `--shell` is ignored.

```shell
pixi shell-hook
Expand All @@ -538,6 +540,7 @@ pixi shell-hook --manifest-path ~/myproject/pixi.toml
pixi shell-hook --frozen
pixi shell-hook --locked
pixi shell-hook --environment cuda
pixi shell-hook --json
```

Example use-case, when you want to get rid of the `pixi` executable in a Docker container.
Expand Down
46 changes: 42 additions & 4 deletions src/cli/shell_hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ use rattler_shell::{
activation::{ActivationVariables, PathModificationBehavior},
shell::ShellEnum,
};
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::{default::Default, path::PathBuf};

use crate::{
activation::get_activator,
cli::LockFileUsageArgs,
environment::get_up_to_date_prefix,
project::{manifest::EnvironmentName, Environment},
project::{has_features::HasFeatures, manifest::EnvironmentName, Environment},
Project,
};

Expand All @@ -32,6 +35,15 @@ pub struct Args {
/// The environment to activate in the script
#[arg(long, short)]
environment: Option<String>,

/// Emit the environment variables set by running the activation as JSON
#[clap(long, default_value = "false", conflicts_with = "shell")]
json: bool,
}

#[derive(Serialize)]
struct ShellEnv<'a> {
environment_variables: &'a HashMap<String, String>,
}

/// Generates the activation script.
Expand Down Expand Up @@ -64,6 +76,16 @@ async fn generate_activation_script(
result.script.contents().into_diagnostic()
}

/// Generates a JSON object describing the changes to the shell environment when activating
/// the provided pixi environment.
async fn generate_environment_json(environment: &Environment<'_>) -> miette::Result<String> {
let environment_variables = environment.project().get_env_variables(environment).await?;
let shell_env = ShellEnv {
environment_variables,
};
serde_json::to_string(&shell_env).into_diagnostic()
}

/// Prints the activation script to the stdout.
pub async fn execute(args: Args) -> miette::Result<()> {
let project = Project::load_or_else_discover(args.manifest_path.as_deref())?;
Expand All @@ -82,10 +104,13 @@ pub async fn execute(args: Args) -> miette::Result<()> {
)
.await?;

let script = generate_activation_script(args.shell, &environment).await?;
let output = match args.json {
true => generate_environment_json(&environment).await?,
false => generate_activation_script(args.shell, &environment).await?,
};

// Print the script
println!("{}", script);
// Print the output - either a JSON object or a shell script
println!("{}", output);

Ok(())
}
Expand Down Expand Up @@ -144,4 +169,17 @@ mod tests {
assert!(script.contains("$env.PATH = "));
assert!(script.contains("$env.CONDA_PREFIX = "));
}

#[tokio::test]
async fn test_environment_json() {
let project = Project::discover().unwrap();
let environment = project.default_environment();
let json_env = generate_environment_json(&environment).await.unwrap();
assert!(json_env.contains("\"PIXI_ENVIRONMENT_NAME\":\"default\""));
assert!(json_env.contains("\"CONDA_PREFIX\":"));
#[cfg(not(target_os = "windows"))]
assert!(json_env.contains("\"PATH\":"));
#[cfg(target_os = "windows")]
assert!(json_env.contains("\"Path\":"));
}
}
Loading