From 1a6a7103d912af080aa4c5b37e9d51a7967d3385 Mon Sep 17 00:00:00 2001 From: Jiahao XU <30436523+NobodyXu@users.noreply.github.com> Date: Sun, 6 Oct 2024 21:43:22 +1100 Subject: [PATCH] Environment variables: For one accepting boolean, treat "0", "false" and empty env as false (#1238) * Add getenv_boolean * Update Build methods to use getenv_boolean And update getenv_boolean, to treat "false" as false. * Fix Build::getenv_Boolean and treat empty env as false * Env CC_ENABLE_DEBUG_OUTPUT: treat "false" or empty str as false * Fix Build::getenv_boolean * Fix clippy --- src/command_helpers.rs | 2 +- src/lib.rs | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/command_helpers.rs b/src/command_helpers.rs index 0def5fea..9f83e38c 100644 --- a/src/command_helpers.rs +++ b/src/command_helpers.rs @@ -45,7 +45,7 @@ impl CargoOutput { warnings: true, output: OutputKind::Forward, debug: match std::env::var_os("CC_ENABLE_DEBUG_OUTPUT") { - Some(v) => v != "0", + Some(v) => v != "0" && v != "false" && v != "", None => false, }, checked_dbg_var: Arc::new(AtomicBool::new(false)), diff --git a/src/lib.rs b/src/lib.rs index bdd437a6..d69dcc07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1857,7 +1857,7 @@ impl Build { let mut cmd = self.get_base_compiler()?; // Disable default flag generation via `no_default_flags` or environment variable - let no_defaults = self.no_default_flags || self.getenv("CRATE_CC_NO_DEFAULTS").is_some(); + let no_defaults = self.no_default_flags || self.getenv_boolean("CRATE_CC_NO_DEFAULTS"); if !no_defaults { self.add_default_flags(&mut cmd, &target, &opt_level)?; @@ -3668,15 +3668,12 @@ impl Build { } fn get_debug(&self) -> bool { - self.debug.unwrap_or_else(|| match self.getenv("DEBUG") { - Some(s) => &*s != "false", - None => false, - }) + self.debug.unwrap_or_else(|| self.getenv_boolean("DEBUG")) } fn get_shell_escaped_flags(&self) -> bool { self.shell_escaped_flags - .unwrap_or_else(|| self.getenv("CC_SHELL_ESCAPED_FLAGS").is_some()) + .unwrap_or_else(|| self.getenv_boolean("CC_SHELL_ESCAPED_FLAGS")) } fn get_dwarf_version(&self) -> Option { @@ -3752,6 +3749,14 @@ impl Build { r } + /// get boolean flag that is either true or false + fn getenv_boolean(&self, v: &str) -> bool { + match self.getenv(v) { + Some(s) => &*s != "0" && &*s != "false" && !s.is_empty(), + None => false, + } + } + fn getenv_unwrap(&self, v: &str) -> Result, Error> { match self.getenv(v) { Some(s) => Ok(s),