Skip to content

Commit fa24f84

Browse files
committed
Correct error handling and document Mode enum
Signed-off-by: James Rhodes <jarhodes314@gmail.com>
1 parent 0d62c76 commit fa24f84

File tree

3 files changed

+49
-9
lines changed

3 files changed

+49
-9
lines changed

crates/common/tedge_config/src/tedge_toml/error.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ pub enum TEdgeConfigError {
3535

3636
#[error(transparent)]
3737
FromAtomFileError(#[from] tedge_utils::fs::AtomFileError),
38+
39+
#[error(transparent)]
40+
Anyhow(#[from] anyhow::Error),
3841
}
3942

4043
pub type ConfigSettingResult<T> = Result<T, ConfigSettingError>;

crates/common/tedge_config/src/tedge_toml/tedge_config_location.rs

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::TEdgeConfig;
66
use crate::TEdgeConfigDto;
77
use crate::TEdgeConfigError;
88
use crate::TEdgeConfigReader;
9+
use anyhow::Context;
910
use camino::Utf8Path;
1011
use camino::Utf8PathBuf;
1112
use serde::Deserialize as _;
@@ -183,7 +184,7 @@ impl TEdgeConfigLocation {
183184
}
184185

185186
if Sources::INCLUDE_ENVIRONMENT {
186-
update_with_environment_variables(&mut dto, &mut warnings);
187+
update_with_environment_variables(&mut dto, &mut warnings)?;
187188
}
188189

189190
Ok((dto, warnings))
@@ -218,7 +219,7 @@ impl TEdgeConfigLocation {
218219
}
219220

220221
if Sources::INCLUDE_ENVIRONMENT {
221-
update_with_environment_variables(&mut dto, &mut warnings);
222+
update_with_environment_variables(&mut dto, &mut warnings)?;
222223
}
223224

224225
Ok((dto, warnings))
@@ -309,7 +310,10 @@ impl UnusedValueWarnings {
309310
}
310311
}
311312

312-
fn update_with_environment_variables(dto: &mut TEdgeConfigDto, warnings: &mut UnusedValueWarnings) {
313+
fn update_with_environment_variables(
314+
dto: &mut TEdgeConfigDto,
315+
warnings: &mut UnusedValueWarnings,
316+
) -> anyhow::Result<()> {
313317
for (key, value) in std::env::vars() {
314318
let tedge_key = match key.strip_prefix("TEDGE_") {
315319
Some("CONFIG_DIR") => continue,
@@ -344,13 +348,16 @@ fn update_with_environment_variables(dto: &mut TEdgeConfigDto, warnings: &mut Un
344348
}
345349
}
346350
if value.is_empty() {
347-
if let Err(e) = dto.try_unset_key(&tedge_key) {
348-
warnings.push(format!("Failed to process {key}: {e}"))
349-
}
350-
} else if let Err(e) = dto.try_update_str(&tedge_key, &value) {
351-
warnings.push(format!("Failed to process {key}: {e}"))
351+
dto.try_unset_key(&tedge_key).with_context(|| {
352+
format!("Failed to reset value for {tedge_key} from environment variable {key}")
353+
})?;
354+
} else {
355+
dto.try_update_str(&tedge_key, &value).with_context(|| {
356+
format!("Failed to set value for {tedge_key} to {value:?} from environment variable {key}")
357+
})?;
352358
}
353359
}
360+
Ok(())
354361
}
355362

356363
fn deserialize_toml(
@@ -679,6 +686,30 @@ type = "a-service-type""#;
679686
assert_eq!(warnings.0, ["Unknown configuration field \"unknown_value\" from environment variable TEDGE_UNKNOWN_VALUE"]);
680687
}
681688

689+
#[tokio::test]
690+
async fn unsetting_configuration_for_unknown_profile_does_not_warn_or_error() {
691+
let (_dir, t) = create_temp_tedge_config("").unwrap();
692+
let mut env = EnvSandbox::new().await;
693+
env.set_var("TEDGE_C8Y_PROFILES_TEST_URL", "");
694+
let (_config, warnings) = t
695+
.load_dto_with_warnings::<FileAndEnvironment>()
696+
.await
697+
.unwrap();
698+
assert_eq!(warnings.0, &[] as &[&'static str]);
699+
}
700+
701+
#[tokio::test]
702+
async fn environment_variable_causes_error_if_its_value_cannot_be_parsed() {
703+
let (_dir, t) = create_temp_tedge_config("").unwrap();
704+
let mut env = EnvSandbox::new().await;
705+
env.set_var("TEDGE_SUDO_ENABLE", "yes");
706+
let err = t
707+
.load_dto_with_warnings::<FileAndEnvironment>()
708+
.await
709+
.unwrap_err();
710+
assert!(dbg!(err.to_string()).contains("TEDGE_SUDO_ENABLE"));
711+
}
712+
682713
#[tokio::test]
683714
async fn environment_variables_are_ignored_in_file_only_mode() {
684715
let (_dir, t) = create_temp_tedge_config("sudo.enable = true").unwrap();

crates/common/tedge_config_macros/impl/src/query.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,6 @@ fn generate_string_writers(paths: &[VecDeque<&FieldOrGroup>]) -> TokenStream {
770770
.#convert_to_field_ty
771771
.map_err(|e| WriteError::ParseValue(Box::new(e)))?),
772772
},
773-
// TODO can we really do this with write_segments?
774773
parse_quote_spanned! {ty.span()=>
775774
WritableKey::#match_variant => self.#(#write_segments).* = other.#(#write_segments).*.take(),
776775
},
@@ -1022,6 +1021,13 @@ fn enum_variant(segments: &VecDeque<&FieldOrGroup>) -> ConfigurationKey {
10221021
}
10231022
}
10241023

1024+
/// Which type (`TEdgeConfigDto`/`TEdgeConfigReader`) we should generate a key
1025+
/// enum for
1026+
///
1027+
/// For the CLI, we allow keys based on the reader, so values like
1028+
/// `config.version` aren't configured by or visible to the user. For detecting
1029+
/// unknown keys in the TOML file however, we need to generate keys from the
1030+
/// DTO since `config.version` is allowed in the TOML file.
10251031
#[derive(Debug, Clone, Copy)]
10261032
enum Mode {
10271033
Dto,

0 commit comments

Comments
 (0)