1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::collections::BTreeMap;
use log::debug;
use crate::processors::Processor;
use crate::Template;

pub fn generate_cargo(template: &Template, core_path: Option<String>) -> String {
    debug!("Generating Cargo.toml");
    CARGO_TOML
        .replace(PROJECT_NAME, &template.name
            .replace(' ', "-")
            .to_lowercase(),
        )
        .replace(CORE_VERSION, &core_path
            .map(|path| format!("{{ path = \"{path}\" }}"))
            .unwrap_or_else(|| "\"0.1.2\"".to_string())
        )
}

pub fn generate_main(streams: BTreeMap<(String, String), Vec<Processor>>) -> String {
    debug!("Generating main.rs");
    let streams_config: String = streams.iter()
        .map(|((input_topic, output_topic), processors)| {
            let processor_list: String = processors.iter()
                .map(|processor| format!("&{}, ", processor.function_name))
                .collect();

            SINGLE_STREAM
                .replace(INPUT_TOPIC, input_topic)
                .replace(OUTPUT_TOPIC, output_topic)
                .replace(PROCESSORS, &processor_list)
        })
        .collect();

    let function_names: String =  streams.iter()
        .flat_map(|(_, processors)| {
            processors.iter()
                .map(|p| format!("{}, ",p.function_name))
        })
        .collect();

    let functions: String = streams.into_iter()
        .flat_map(|(_, processors)| {
            processors.into_iter()
                .map(|p| p.function_body)
        })
        .collect();

    format!("{}{}{}",
            MAIN.replace(STREAMS, &streams_config),
            functions,
            SIMULATIONS
                .replace(FUNCTION_IMPORTS, &function_names)
                .replace(STREAMS, &streams_config)
    )
}

const CARGO_TOML: &str = r##"[package]
name = "%%PROJECT_NAME%%"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
log = "0.4.17"
env_logger = "0.9.0"
serde_json = "1.0.83"
kafka_json_processor_core = %%CORE_VERSION%%
lazy_static = "1.4.0"
regex = "1.7.0"
"##;

const PROJECT_NAME: &str = "%%PROJECT_NAME%%";
const CORE_VERSION: &str = "%%CORE_VERSION%%";

const MAIN: &str = r##"#![allow(unused_variables, unused_imports)]

use std::collections::HashMap;
use log::{LevelFilter, trace, debug, error, info, warn};
use serde_json::Value;
use kafka_json_processor_core::processor::{ObjectKey, ObjectTree, OutputMessage};
use kafka_json_processor_core::error::{ProcessingError, ErrorKind};
use kafka_json_processor_core::{run_processor, Stream};
use kafka_json_processor_core::processor::ObjectKey::{Key, Index};
use lazy_static::lazy_static;

fn main() {
    env_logger::builder()
        .init();

    let mut streams = HashMap::new();
%%STREAMS%%

    run_processor(streams);
}
"##;

const STREAMS: &str = "%%STREAMS%%";

const SINGLE_STREAM: &str = r##"
    streams.insert("%%INPUT_TOPIC%%_%%OUTPUT_TOPIC%%".to_string(), Stream {
        source_topic: "%%INPUT_TOPIC%%".to_string(),
        target_topic: "%%OUTPUT_TOPIC%%".to_string(),
        processors: &[%%PROCESSORS%%],
    });"##;

const INPUT_TOPIC: &str = "%%INPUT_TOPIC%%";
const OUTPUT_TOPIC: &str = "%%OUTPUT_TOPIC%%";
const PROCESSORS: &str = "%%PROCESSORS%%";

const SIMULATIONS: &str = r##"

#[cfg(test)]
mod simulations {
    use std::collections::HashMap;
    use log::LevelFilter;
    use kafka_json_processor_core::simulation::simulate_streams_from_default_folder;
    use kafka_json_processor_core::Stream;
    use crate::{%%FUNCTION_IMPORTS%%};

    #[test]
    fn simulate_streams() {
        env_logger::builder()
            .filter_level(LevelFilter::Trace)
            .init();

        let mut streams: HashMap<String, Stream> = HashMap::new();
%%STREAMS%%

        simulate_streams_from_default_folder(streams);
    }
}
"##;

const FUNCTION_IMPORTS: &str = "%%FUNCTION_IMPORTS%%";


#[cfg(test)]
mod test {
    use std::collections::BTreeMap;
    use crate::processors::Processor;
    use crate::project::{generate_cargo, generate_main};
    use crate::Template;

    #[test]
    fn should_generate_main() {
        let mut streams = BTreeMap::new();
        streams.insert(("abc".to_string(), "def".to_string()), vec![
            Processor {
                function_name: "function_1".to_string(),
                function_body: r##"
fn function_1(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}"##.to_string(),
            },
            Processor {
                function_name: "function_2".to_string(),
                function_body: r##"
fn function_2(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}"##.to_string(),
            },
        ]);

        streams.insert(("topic1".to_string(), "topic2".to_string()), vec![
            Processor {
                function_name: "function_3".to_string(),
                function_body: r##"
fn function_3(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}"##.to_string(),
            },
            Processor {
                function_name: "function_4".to_string(),
                function_body: r##"
fn function_4(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}"##.to_string(),
            },
        ]);

        let main = generate_main(streams);
        assert_eq!(r##"#![allow(unused_variables, unused_imports)]

use std::collections::HashMap;
use log::{LevelFilter, trace, debug, error, info, warn};
use serde_json::Value;
use kafka_json_processor_core::processor::{ObjectKey, ObjectTree, OutputMessage};
use kafka_json_processor_core::error::{ProcessingError, ErrorKind};
use kafka_json_processor_core::{run_processor, Stream};
use kafka_json_processor_core::processor::ObjectKey::{Key, Index};
use lazy_static::lazy_static;

fn main() {
    env_logger::builder()
        .init();

    let mut streams = HashMap::new();

    streams.insert("abc_def".to_string(), Stream {
        source_topic: "abc".to_string(),
        target_topic: "def".to_string(),
        processors: &[&function_1, &function_2, ],
    });
    streams.insert("topic1_topic2".to_string(), Stream {
        source_topic: "topic1".to_string(),
        target_topic: "topic2".to_string(),
        processors: &[&function_3, &function_4, ],
    });

    run_processor(streams);
}

fn function_1(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}
fn function_2(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}
fn function_3(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}
fn function_4(_input: &Value, _message: &mut OutputMessage) -> Result<(), ProcessingError> {
    Ok(())
}

#[cfg(test)]
mod simulations {
    use std::collections::HashMap;
    use log::LevelFilter;
    use kafka_json_processor_core::simulation::simulate_streams_from_default_folder;
    use kafka_json_processor_core::Stream;
    use crate::{function_1, function_2, function_3, function_4, };

    #[test]
    fn simulate_streams() {
        env_logger::builder()
            .filter_level(LevelFilter::Trace)
            .init();

        let mut streams: HashMap<String, Stream> = HashMap::new();

    streams.insert("abc_def".to_string(), Stream {
        source_topic: "abc".to_string(),
        target_topic: "def".to_string(),
        processors: &[&function_1, &function_2, ],
    });
    streams.insert("topic1_topic2".to_string(), Stream {
        source_topic: "topic1".to_string(),
        target_topic: "topic2".to_string(),
        processors: &[&function_3, &function_4, ],
    });

        simulate_streams_from_default_folder(streams);
    }
}
"##, main);
    }

    #[test]
    fn should_generate_cargo() {
        let actual = generate_cargo(&Template {
            name: "sample-project Abcdef".to_string(),
            streams: vec![],
        }, None);

        assert_eq!(r##"[package]
name = "sample-project-abcdef"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
log = "0.4.17"
env_logger = "0.9.0"
serde_json = "1.0.83"
kafka_json_processor_core = "0.1.2"
lazy_static = "1.4.0"
regex = "1.7.0"
"##, actual);
    }
}