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

getdozer / dozer / 5817493417

pending completion
5817493417

Pull #1839

github

aaryaattrey
merge fn
Pull Request #1839: load config from stdin

27 of 27 new or added lines in 2 files covered. (100.0%)

45551 of 59106 relevant lines covered (77.07%)

39600.13 hits per line

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

24.64
/dozer-cli/src/cli/helper.rs
1
use crate::errors::CliError;
2
use crate::errors::OrchestrationError;
3
use crate::simple::SimpleOrchestrator as Dozer;
4
use atty::Stream; 
5
use std::io::{self, Read};
6
use crate::config_helper::combine_config;
7
use crate::errors::CliError::{ConfigurationFilePathNotProvided, FailedToFindConfigurationFiles};
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::sync::Arc;
14
use tokio::runtime::Runtime;
15

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

×
24
    config = apply_overrides(&config, config_overrides)?;
×
25

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

×
32
    Ok(Dozer::new(config, Arc::new(runtime)))
×
33
}
×
34

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

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

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

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

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

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

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

×
114
pub fn load_config_from_file(config_path: Vec<String>) -> Result<Config, CliError> {
×
115
    let config_template = combine_config(config_path.clone(),None)?;
×
116
    match config_template {
×
117
        Some(template) => parse_config(&template),
×
118
        None => Err(FailedToFindConfigurationFiles(config_path.join(", "))),
×
119
    }
120
}
×
121

×
122
fn load_config_from_stdin(config_path: Vec<String>) -> Result<Config, CliError>{
×
123
    let mut input = String::new();
×
124
    io::stdin().read_to_string(&mut input).expect("Failed to read input from stdin");
×
125
    let config_template = combine_config(config_path.clone(), Some(input))?;
×
126
    match config_template {
×
127
        Some(template) => parse_config(&template),
×
128
        None => Err(FailedToFindConfigurationFiles(config_path.join(", "))),
×
129
    }
×
130
}
×
131

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

×
138
    let mut data = BTreeMap::new();
×
139

×
140
    for (key, value) in std::env::vars() {
×
141
        data.insert(key, value);
×
142
    }
×
143

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

148
    let config: Config = serde_yaml::from_str(&config_str)
×
149
        .map_err(|e: serde_yaml::Error| CliError::FailedToParseYaml(Box::new(e)))?;
×
150

×
151
    Ok(config)
×
152
}
×
153

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

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

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

175
    Ok(config)
2✔
176
}
2✔
177

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

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

×
188
 If no sub commands are passed, dozer will bring up both app and api services.
×
189
"#;
×
190

×
191
#[cfg(test)]
×
192
mod tests {
193
    use dozer_types::models::{api_config::ApiConfig, api_security::ApiSecurity};
×
194

×
195
    use super::*;
×
196

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

×
213
    #[test]
1✔
214
    fn test_override_nested() {
1✔
215
        let mut config = Config {
1✔
216
            app_name: "test_override_nested".to_string(),
1✔
217
            ..Default::default()
1✔
218
        };
1✔
219
        config.api = Some(ApiConfig {
1✔
220
            api_security: Some(ApiSecurity::Jwt("secret1".to_string())),
1✔
221
            ..Default::default()
1✔
222
        });
1✔
223
        let api_security = ApiSecurity::Jwt("secret2".to_string());
1✔
224
        let config = apply_overrides(
1✔
225
            &config,
1✔
226
            vec![(
1✔
227
                "/api/api_security".to_string(),
1✔
228
                serde_json::to_value(&api_security).unwrap(),
1✔
229
            )],
1✔
230
        )
1✔
231
        .unwrap();
1✔
232
        assert_eq!(config.api.unwrap().api_security.unwrap(), api_security);
1✔
233
    }
1✔
234
}
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

© 2026 Coveralls, Inc