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(compile): support --env #24166

Merged
merged 25 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
33cc111
fix: Added support for --env for the compile subcommand
HasanAlrimawi Jun 10, 2024
c72851e
update: repetitive code wrapped into a function to be reused without …
HasanAlrimawi Jun 11, 2024
4b48e42
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 12, 2024
57c2a76
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 23, 2024
3dbf249
lint-fix: replaced eprintln with log::info & initialized logging syst…
HasanAlrimawi Jun 24, 2024
5ee011b
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 24, 2024
a6be904
removed unsused import
HasanAlrimawi Jun 24, 2024
92d2967
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 25, 2024
d1c5efb
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 25, 2024
64cc593
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 26, 2024
b3be35f
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 26, 2024
1f8c1a6
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 27, 2024
6ec532a
Merge branch 'main' into compile-env-support
HasanAlrimawi Jun 30, 2024
fa99ddd
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 1, 2024
8df79fa
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 2, 2024
97c1f01
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 3, 2024
9b3ad26
fix: append env file variables into executable
HasanAlrimawi Jul 3, 2024
49b42ad
fix: added log and updated test .out file
HasanAlrimawi Jul 3, 2024
d6065ac
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 3, 2024
04e4b3e
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 4, 2024
6d2ec5c
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 7, 2024
65111fd
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 8, 2024
c1f9440
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 9, 2024
e33d836
Merge branch 'main' into compile-env-support
HasanAlrimawi Jul 9, 2024
670067c
Updates
dsherret Jul 9, 2024
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
35 changes: 22 additions & 13 deletions cli/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,19 +793,7 @@ impl CliOptions {
)
.with_context(|| "Resolving node_modules folder.")?;

if let Some(env_file_name) = &flags.env_file {
match from_filename(env_file_name) {
Ok(_) => (),
Err(error) => {
match error {
dotenvy::Error::LineParse(line, index)=> log::info!("{} Parsing failed within the specified environment file: {} at index: {} of the value: {}",colors::yellow("Warning"), env_file_name, index, line),
dotenvy::Error::Io(_)=> log::info!("{} The `--env` flag was used, but the environment file specified '{}' was not found.",colors::yellow("Warning"),env_file_name),
dotenvy::Error::EnvVar(_)=>log::info!("{} One or more of the environment variables isn't present or not unicode within the specified environment file: {}",colors::yellow("Warning"),env_file_name),
_ => log::info!("{} Unknown failure occurred with the specified environment file: {}", colors::yellow("Warning"), env_file_name),
}
}
}
}
load_env_variables_from_env_file(flags.env_file.as_ref());

let disable_deprecated_api_warning = flags.log_level
== Some(log::Level::Error)
Expand Down Expand Up @@ -1118,6 +1106,10 @@ impl CliOptions {
}
}

pub fn env_file_name(&self) -> Option<&String> {
self.flags.env_file.as_ref()
}

pub fn enable_future_features(&self) -> bool {
*DENO_FUTURE
}
Expand Down Expand Up @@ -1873,6 +1865,23 @@ pub fn config_to_deno_graph_workspace_member(
})
}

fn load_env_variables_from_env_file(filename: Option<&String>) {
let Some(env_file_name) = filename else {
return;
};
match from_filename(env_file_name) {
Ok(_) => (),
Err(error) => {
match error {
dotenvy::Error::LineParse(line, index)=> log::info!("{} Parsing failed within the specified environment file: {} at index: {} of the value: {}",colors::yellow("Warning"), env_file_name, index, line),
dotenvy::Error::Io(_)=> log::info!("{} The `--env` flag was used, but the environment file specified '{}' was not found.",colors::yellow("Warning"),env_file_name),
dotenvy::Error::EnvVar(_)=> log::info!("{} One or more of the environment variables isn't present or not unicode within the specified environment file: {}",colors::yellow("Warning"),env_file_name),
_ => log::info!("{} Unknown failure occurred with the specified environment file: {}", colors::yellow("Warning"), env_file_name),
}
}
}
}

#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
Expand Down
11 changes: 11 additions & 0 deletions cli/mainrt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub use deno_runtime::UNSTABLE_GRANULAR_FLAGS;
use deno_terminal::colors;

use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::env::current_exe;

Expand Down Expand Up @@ -70,6 +71,14 @@ fn unwrap_or_exit<T>(result: Result<T, AnyError>) -> T {
}
}

fn load_env_vars(env_vars: &HashMap<String, String>) {
env_vars.iter().for_each(|env_var| {
if env::var(env_var.0).is_err() {
std::env::set_var(env_var.0, env_var.1);
}
})
}
HasanAlrimawi marked this conversation as resolved.
Show resolved Hide resolved

fn main() {
let args: Vec<_> = env::args_os().collect();
let current_exe_path = current_exe().unwrap();
Expand All @@ -79,6 +88,8 @@ fn main() {
match standalone {
Ok(Some(future)) => {
let (metadata, eszip) = future.await?;
util::logger::init(metadata.log_level);
load_env_vars(&metadata.env_vars_from_env_file);
let exit_code = standalone::run(eszip, metadata).await?;
std::process::exit(exit_code);
}
Expand Down
26 changes: 26 additions & 0 deletions cli/standalone/binary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::env::current_exe;
use std::ffi::OsString;
Expand Down Expand Up @@ -96,6 +97,7 @@ pub struct Metadata {
pub ca_stores: Option<Vec<String>>,
pub ca_data: Option<Vec<u8>>,
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
pub env_vars_from_env_file: HashMap<String, String>,
pub workspace_resolver: SerializedWorkspaceResolver,
pub entrypoint_key: String,
pub node_modules: Option<NodeModules>,
Expand Down Expand Up @@ -584,6 +586,14 @@ impl<'a> DenoCompileBinaryWriter<'a> {
}
};

let env_vars_from_env_file = match cli_options.env_file_name() {
Some(env_filename) => {
log::info!("{} Environment variables from the file \"{}\" were embedded in the generated executable file", crate::colors::yellow("Warning"), env_filename);
get_file_env_vars(env_filename.to_string())?
}
None => Default::default(),
};

let metadata = Metadata {
argv: compile_flags.args.clone(),
seed: cli_options.seed(),
Expand All @@ -596,6 +606,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
log_level: cli_options.log_level(),
ca_stores: cli_options.ca_stores().clone(),
ca_data,
env_vars_from_env_file,
entrypoint_key: root_dir_url.specifier_key(entrypoint).into_owned(),
workspace_resolver: SerializedWorkspaceResolver {
import_map: self.workspace_resolver.maybe_import_map().map(|i| {
Expand Down Expand Up @@ -757,6 +768,21 @@ impl<'a> DenoCompileBinaryWriter<'a> {
}
}

/// This function returns the environment variables specified
/// in the passed environment file.
fn get_file_env_vars(
filename: String,
) -> Result<HashMap<String, String>, dotenvy::Error> {
let mut file_env_vars = HashMap::new();
for item in dotenvy::from_filename_iter(filename)? {
let Ok((key, val)) = item else {
continue; // this failure will be warned about on load
};
file_env_vars.insert(key, val);
}
Ok(file_env_vars)
}

/// This function sets the subsystem field in the PE header to 2 (GUI subsystem)
/// For more information about the PE header: https://learn.microsoft.com/en-us/windows/win32/debug/pe-format
fn set_windows_binary_to_gui(bin: &mut [u8]) -> Result<(), AnyError> {
Expand Down
14 changes: 14 additions & 0 deletions tests/specs/compile/env_vars_support/__test__.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"tempDir": true,
"steps": [
{
"args": "compile -A --output out --env=environment.env main.ts",
"output": "compile.out"
},
{
"commandName": "./out",
"args": [],
"output": "main.out"
}
]
}
4 changes: 4 additions & 0 deletions tests/specs/compile/env_vars_support/compile.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Warning Parsing failed within the specified environment file: environment.env at index: 3 of the value: c:\path
Check [WILDCARD]main.ts
Compile [WILDCARD]main.ts to out[WILDCARD]
Warning Environment variables from the file "environment.env" were embedded in the generated executable file
4 changes: 4 additions & 0 deletions tests/specs/compile/env_vars_support/environment.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FOO=valid
MULTILINE="First Line
Second Line"
ANOTHER_FOO=c:\path
4 changes: 4 additions & 0 deletions tests/specs/compile/env_vars_support/main.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
valid
undefined
First Line
Second Line
3 changes: 3 additions & 0 deletions tests/specs/compile/env_vars_support/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
console.log(Deno.env.get("FOO"));
console.log(Deno.env.get("ANOTHER_FOO"));
console.log(Deno.env.get("MULTILINE"));