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

getdozer / dozer / 5830305245

pending completion
5830305245

Pull #1839

github

aaryaattrey
ignore pipe logic
Pull Request #1839: load config from stdin

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

45529 of 59112 relevant lines covered (77.02%)

39481.44 hits per line

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

24.17
/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
    ignore_pipe: bool,
×
23
) -> Result<Dozer, CliError> {
×
24
    let runtime = Runtime::new().map_err(CliError::FailedToCreateTokioRuntime)?;
×
25
    let mut config = runtime.block_on(load_config(config_paths, config_token, ignore_pipe))?;
×
26

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

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

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

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

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

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

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

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

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

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

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

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

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

×
143
    let mut data = BTreeMap::new();
×
144

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

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

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

×
156
    Ok(config)
×
157
}
×
158

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

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

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

×
180
    Ok(config)
2✔
181
}
2✔
182

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

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

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

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

×
200
    use super::*;
×
201

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

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