• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

getdozer / dozer / 5829357348

pending completion
5829357348

Pull #1839

github

aaryaattrey
typo
Pull Request #1839: load config from stdin

37 of 37 new or added lines in 4 files covered. (100.0%)

45551 of 59108 relevant lines covered (77.06%)

39686.65 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

24.29
/dozer-cli/src/cli/helper.rs
1
use crate::config_helper::combine_config;
2
use crate::errors::CliError;
3
use crate::errors::CliError::{ConfigurationFilePathNotProvided, FailedToFindConfigurationFiles};
4
use crate::errors::ConfigCombineError::CannotReadConfig;
5
use crate::errors::OrchestrationError;
6
use crate::simple::SimpleOrchestrator as Dozer;
7
use atty::Stream;
8
use dozer_types::models::config::default_cache_max_map_size;
9
use dozer_types::prettytable::{row, Table};
10
use dozer_types::{models::config::Config, serde_yaml};
11
use handlebars::Handlebars;
12
use std::collections::BTreeMap;
13
use std::io::{self, Read};
14
use std::path::PathBuf;
15
use std::sync::Arc;
×
16
use tokio::runtime::Runtime;
×
17

×
18
pub fn init_dozer(
×
19
    config_paths: Vec<String>,
×
20
    config_token: Option<String>,
×
21
    config_overrides: Vec<(String, serde_json::Value)>,
×
22
) -> Result<Dozer, CliError> {
×
23
    let runtime = Runtime::new().map_err(CliError::FailedToCreateTokioRuntime)?;
×
24
    let mut config = runtime.block_on(load_config(config_paths, config_token))?;
×
25

×
26
    config = apply_overrides(&config, config_overrides)?;
×
27

×
28
    let cache_max_map_size = config
×
29
        .cache_max_map_size
×
30
        .unwrap_or_else(default_cache_max_map_size);
×
31
    let page_size = page_size::get() as u64;
×
32
    config.cache_max_map_size = Some(cache_max_map_size / page_size * page_size);
×
33

×
34
    Ok(Dozer::new(config, Arc::new(runtime)))
×
35
}
×
36

×
37
pub fn list_sources(
×
38
    config_paths: Vec<String>,
×
39
    config_token: Option<String>,
×
40
    config_overrides: Vec<(String, serde_json::Value)>,
×
41
    filter: Option<String>,
×
42
) -> Result<(), OrchestrationError> {
×
43
    let dozer = init_dozer(config_paths, config_token, config_overrides)?;
×
44
    let connection_map = dozer.list_connectors()?;
×
45
    let mut table_parent = Table::new();
×
46
    for (connection_name, (tables, schemas)) in connection_map {
×
47
        let mut first_table_found = false;
×
48

×
49
        for (table, schema) in tables.into_iter().zip(schemas) {
×
50
            let name = table.schema.map_or(table.name.clone(), |schema_name| {
×
51
                format!("{schema_name}.{}", table.name)
×
52
            });
×
53

×
54
            if filter
×
55
                .as_ref()
×
56
                .map_or(true, |name_part| name.contains(name_part))
×
57
            {
×
58
                if !first_table_found {
×
59
                    table_parent.add_row(row!["Connection", "Table", "Columns"]);
×
60
                    first_table_found = true;
×
61
                }
×
62
                let schema_table = schema.schema.print();
×
63

×
64
                table_parent.add_row(row![connection_name, name, schema_table]);
×
65
            }
×
66
        }
×
67

×
68
        if first_table_found {
×
69
            table_parent.add_empty_row();
×
70
        }
×
71
    }
×
72
    table_parent.printstd();
×
73
    Ok(())
×
74
}
×
75

×
76
async fn load_config(
×
77
    config_url_or_paths: Vec<String>,
×
78
    config_token: Option<String>,
×
79
) -> Result<Config, CliError> {
×
80
    let mut is_pipe = false;
×
81
    if atty::isnt(Stream::Stdin) {
×
82
        is_pipe = true;
×
83
    }
×
84
    let first_config_path = config_url_or_paths.get(0);
×
85
    match first_config_path {
×
86
        None => Err(ConfigurationFilePathNotProvided),
×
87
        Some(path) => {
×
88
            if path.starts_with("https://") || path.starts_with("http://") {
×
89
                load_config_from_http_url(path, config_token).await
×
90
            } else if is_pipe && std::env::var("ENABLE_PIPES").is_err() {
×
91
                load_config_from_file(config_url_or_paths, true)
×
92
            } else {
×
93
                load_config_from_file(config_url_or_paths, false)
×
94
            }
×
95
        }
×
96
    }
×
97
}
×
98

×
99
async fn load_config_from_http_url(
×
100
    config_url: &str,
×
101
    config_token: Option<String>,
×
102
) -> Result<Config, CliError> {
×
103
    let client = reqwest::Client::new();
×
104
    let mut get_request = client.get(config_url);
×
105
    if let Some(token) = config_token {
×
106
        get_request = get_request.bearer_auth(token);
×
107
    }
×
108
    let response: reqwest::Response = get_request.send().await?.error_for_status()?;
×
109
    let contents = response.text().await?;
×
110
    parse_config(&contents)
×
111
}
×
112

×
113
pub fn load_config_from_file(
×
114
    config_path: Vec<String>,
×
115
    read_stdin: bool,
×
116
) -> Result<Config, CliError> {
×
117
    let stdin_path = PathBuf::from("<stdin>");
×
118
    let input = if read_stdin {
×
119
        let mut input = String::new();
×
120
        io::stdin()
×
121
            .read_to_string(&mut input)
×
122
            .map_err(|e| CannotReadConfig(stdin_path, e))?;
×
123
        Some(input)
×
124
    } else {
×
125
        None
×
126
    };
×
127

128
    let config_template = combine_config(config_path.clone(), input)?;
×
129
    match config_template {
×
130
        Some(template) => parse_config(&template),
×
131
        None => Err(FailedToFindConfigurationFiles(config_path.join(", "))),
×
132
    }
×
133
}
×
134

135
fn parse_config(config_template: &str) -> Result<Config, CliError> {
×
136
    let mut handlebars = Handlebars::new();
×
137
    handlebars
×
138
        .register_template_string("config", config_template)
×
139
        .map_err(|e| CliError::FailedToParseYaml(Box::new(e)))?;
×
140

141
    let mut data = BTreeMap::new();
×
142

×
143
    for (key, value) in std::env::vars() {
×
144
        data.insert(key, value);
×
145
    }
×
146

147
    let config_str = handlebars
×
148
        .render("config", &data)
×
149
        .map_err(|e| CliError::FailedToParseYaml(Box::new(e)))?;
×
150

×
151
    let config: Config = serde_yaml::from_str(&config_str)
×
152
        .map_err(|e: serde_yaml::Error| CliError::FailedToParseYaml(Box::new(e)))?;
×
153

×
154
    Ok(config)
×
155
}
×
156

×
157
/// Convert `config` to JSON, apply JSON pointer overrides, then convert back to `Config`.
158
fn apply_overrides(
2✔
159
    config: &Config,
2✔
160
    config_overrides: Vec<(String, serde_json::Value)>,
2✔
161
) -> Result<Config, CliError> {
2✔
162
    let mut config_json = serde_json::to_value(config).map_err(CliError::SerializeConfigToJson)?;
2✔
163

164
    for (pointer, value) in config_overrides {
4✔
165
        if let Some(pointee) = config_json.pointer_mut(&pointer) {
2✔
166
            *pointee = value;
2✔
167
        } else {
2✔
168
            return Err(CliError::MissingConfigOverride(pointer));
×
169
        }
170
    }
171

172
    // Directly convert `config_json` to `Config` fails, not sure why.
173
    let config_json_string =
2✔
174
        serde_json::to_string(&config_json).map_err(CliError::SerializeConfigToJson)?;
2✔
175
    let config: Config =
2✔
176
        serde_json::from_str(&config_json_string).map_err(CliError::DeserializeConfigFromJson)?;
2✔
177

×
178
    Ok(config)
2✔
179
}
2✔
180

×
181
pub const LOGO: &str = r"
×
182
.____   ___ __________ ____
×
183
|  _ \ / _ \__  / ____|  _ \
×
184
| | | | | | |/ /|  _| | |_) |
×
185
| |_| | |_| / /_| |___|  _ <
×
186
|____/ \___/____|_____|_| \_\
×
187
";
×
188

×
189
pub const DESCRIPTION: &str = r#"Open-source platform to build, publish and manage blazing-fast real-time data APIs in minutes. 
×
190

×
191
 If no sub commands are passed, dozer will bring up both app and api services.
×
192
"#;
193

×
194
#[cfg(test)]
×
195
mod tests {
×
196
    use dozer_types::models::{api_config::ApiConfig, api_security::ApiSecurity};
×
197

×
198
    use super::*;
×
199

×
200
    #[test]
1✔
201
    fn test_override_top_level() {
1✔
202
        let mut config = Config {
1✔
203
            app_name: "test_override_top_level".to_string(),
1✔
204
            ..Default::default()
1✔
205
        };
1✔
206
        config.sql = Some("sql1".to_string());
1✔
207
        let sql = "sql2".to_string();
1✔
208
        let config = apply_overrides(
1✔
209
            &config,
1✔
210
            vec![("/sql".to_string(), serde_json::to_value(&sql).unwrap())],
1✔
211
        )
1✔
212
        .unwrap();
1✔
213
        assert_eq!(config.sql.unwrap(), sql);
1✔
214
    }
1✔
215

216
    #[test]
1✔
217
    fn test_override_nested() {
1✔
218
        let mut config = Config {
1✔
219
            app_name: "test_override_nested".to_string(),
1✔
220
            ..Default::default()
1✔
221
        };
1✔
222
        config.api = Some(ApiConfig {
1✔
223
            api_security: Some(ApiSecurity::Jwt("secret1".to_string())),
1✔
224
            ..Default::default()
1✔
225
        });
1✔
226
        let api_security = ApiSecurity::Jwt("secret2".to_string());
1✔
227
        let config = apply_overrides(
1✔
228
            &config,
1✔
229
            vec![(
1✔
230
                "/api/api_security".to_string(),
1✔
231
                serde_json::to_value(&api_security).unwrap(),
1✔
232
            )],
1✔
233
        )
1✔
234
        .unwrap();
1✔
235
        assert_eq!(config.api.unwrap().api_security.unwrap(), api_security);
1✔
236
    }
1✔
237
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc