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: Add environment variables to init --import #3083

Merged
merged 3 commits into from
Feb 10, 2025
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
44 changes: 44 additions & 0 deletions crates/pixi_utils/src/conda_environment_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use miette::{Context, Diagnostic, IntoDiagnostic, NamedSource, SourceSpan};
use pixi_config::Config;
use rattler_conda_types::{MatchSpec, NamedChannelOrUrl, ParseStrictness::Lenient};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;
use std::{io::BufRead, path::Path, str::FromStr};
use thiserror::Error;
Expand Down Expand Up @@ -56,6 +57,8 @@ pub struct CondaEnvFile {
#[serde(default)]
channels: Vec<NamedChannelOrUrl>,
dependencies: Vec<CondaEnvDep>,
#[serde(default)]
variables: HashMap<String, String>,
}

#[derive(Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -84,6 +87,10 @@ impl CondaEnvFile {
&self.dependencies
}

pub fn variables(&self) -> HashMap<String, String> {
self.variables.clone()
}

pub fn from_path(path: &Path) -> miette::Result<Self> {
let file = fs_err::File::open(path).into_diagnostic()?;
let reader = std::io::BufReader::new(file);
Expand Down Expand Up @@ -321,6 +328,7 @@ mod tests {
file.write_all(example_conda_env_file.as_bytes()).unwrap();

let conda_env_file_data = CondaEnvFile::from_path(path).unwrap();
let vars = conda_env_file_data.variables();
let (conda_deps, pip_deps, _) =
parse_dependencies(conda_env_file_data.dependencies().clone()).unwrap();

Expand All @@ -333,5 +341,41 @@ mod tests {
pip_deps,
vec![pep508_rs::Requirement::from_str("requests").unwrap()]
);

let empty_map = HashMap::<String, String>::new();

assert_eq!(vars, empty_map);
}

#[test]
fn test_parse_conda_env_file_with_variables() {
let example_conda_env_file = r#"
name: pixi_example_project
channels:
- conda-forge
dependencies:
- pip==24.0
variables:
MY_VAR: my_value
MY_OTHER_VAR: 123
MY_EMPTY_VAR:
"#;

let f = tempfile::NamedTempFile::new().unwrap();
let path = f.path();
let mut file = fs_err::File::create(path).unwrap();
file.write_all(example_conda_env_file.as_bytes()).unwrap();

let conda_env_file_data = CondaEnvFile::from_path(path).unwrap();
let vars = conda_env_file_data.variables();

assert_eq!(
vars,
HashMap::from([
("MY_VAR".to_string(), "my_value".to_string()),
("MY_OTHER_VAR".to_string(), "123".to_string()),
("MY_EMPTY_VAR".to_string(), "".to_string())
])
);
}
}
40 changes: 26 additions & 14 deletions src/cli/init.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{
cmp::PartialEq,
collections::HashMap,
fs,
io::{ErrorKind, Write},
path::{Path, PathBuf},
Expand Down Expand Up @@ -85,6 +86,12 @@ version = "{{ version }}"

[dependencies]

{%- if env_vars %}

[activation]
env = { {{ env_vars }} }
{%- endif %}

"#;

/// The pyproject.toml template
Expand Down Expand Up @@ -223,6 +230,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
.unwrap_or(default_name.clone().as_str())
.to_string();

let env_vars = env_file.variables();
// TODO: Improve this:
// - Use .condarc as channel config
let (conda_deps, pypi_deps, channels) = env_file.to_manifest(&config)?;
Expand All @@ -235,6 +243,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
&platforms,
None,
&vec![],
Some(&env_vars),
);
let mut workspace =
WorkspaceMut::from_template(pixi_manifest_path, rendered_workspace_template)?;
Expand Down Expand Up @@ -434,6 +443,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
&platforms,
index_url.as_ref(),
&extra_index_urls,
None,
);
save_manifest_file(&pixi_manifest_path, rv)?;
};
Expand Down Expand Up @@ -472,21 +482,23 @@ fn render_project(
platforms: &Vec<String>,
index_url: Option<&Url>,
extra_index_urls: &Vec<Url>,
env_vars: Option<&HashMap<String, String>>,
) -> String {
env.render_named_str(
consts::PROJECT_MANIFEST,
PROJECT_TEMPLATE,
context! {
name,
version,
author,
channels,
platforms,
index_url,
extra_index_urls,
},
)
.expect("should be able to render the template")
let ctx = context! {
name,
version,
author,
channels,
platforms,
index_url,
extra_index_urls,
env_vars => {if let Some(env_vars) = env_vars {
env_vars.iter().map(|(k, v)| format!("{} = \"{}\"", k, v)).collect::<Vec<String>>().join(", ")
} else {String::new()}},
};

env.render_named_str(consts::PROJECT_MANIFEST, PROJECT_TEMPLATE, ctx)
.expect("should be able to render the template")
}

/// Save the rendered template to a file, and print a message to the user.
Expand Down
Loading