use std::ops::IndexMut;
use itertools::Itertools;
use serde::Serialize;
use crate::dumping::SerializeConfig;
use crate::{ConfigError, ParamPrivacy};
pub fn get_config_presentation<T: Serialize + SerializeConfig>(
config: &T,
include_private_parameters: bool,
) -> Result<serde_json::Value, ConfigError> {
let mut config_presentation = serde_json::to_value(config)?;
if include_private_parameters {
return Ok(config_presentation);
}
for (param_path, serialized_param) in config.dump() {
match serialized_param.privacy {
ParamPrivacy::Public => continue,
ParamPrivacy::TemporaryValue => continue,
ParamPrivacy::Private => remove_path_from_json(¶m_path, &mut config_presentation)?,
}
}
Ok(config_presentation)
}
fn remove_path_from_json(
param_path: &str,
json: &mut serde_json::Value,
) -> Result<(), ConfigError> {
let mut path_to_entry = param_path.split('.').collect_vec();
let Some(entry_to_remove) = path_to_entry.pop() else {
return Ok(()); };
let mut inner_json = json;
for path in &path_to_entry {
if !inner_json.is_object() {
return Ok(()); }
inner_json = inner_json.index_mut(path);
}
if let Some(obj) = inner_json.as_object_mut() {
obj.remove(entry_to_remove);
}
Ok(())
}