ctgen 0.1.6

Code Generator based on Handlebars Templates and Database Reflection
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use anyhow::Result;
use clap::{Parser, Subcommand};
use console::style;
use ctgen::consts::CONFIG_NAME_DEFAULT;
use ctgen::error::CtGenError;
use ctgen::profile::{CtGenProfile, CtGenProfileConfigOverrides};
use ctgen::task::prompt::CtGenTaskPrompt;
use ctgen::CtGen;
use database_reflection::adapter::reflection_adapter::ReflectionAdapter;
use dialoguer::theme::ColorfulTheme;
use dialoguer::{Confirm, Input, MultiSelect, Select, Sort};
#[allow(unused_imports)]
use log::{debug, error, info, log_enabled, Level};
use serde_json::Value;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::Display;
use std::path::Path;

#[derive(Parser, Debug)]
#[command(author = "Cytec BG", version, about = "Code Template Generator", long_about = None)]
pub struct Args {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Manage code template config profiles
    Config {
        #[command(subcommand)]
        op: CommandConfig,
    },
    /// Run code template generator
    Run {
        #[arg(long, default_value = "default")]
        /// Config profile to use for this run
        profile: Option<String>,

        #[arg(long, conflicts_with = "dsn")]
        /// Override profile env-file directive
        env_file: Option<String>,

        #[arg(long, conflicts_with = "dsn")]
        /// Override profile env-var directive
        env_var: Option<String>,

        #[arg(long)]
        /// Override profile DSN directive
        dsn: Option<String>,

        #[arg(long)]
        /// Override profile target-dir directive
        target_dir: Option<String>,

        #[arg(long, value_parser = parse_prompt_key_val::<String, String>, number_of_values = 1)]
        /// Prompt answer override, for example --prompt "dummy=1"
        prompt: Option<Vec<(String, String)>>,

        /// Database table name to generate code templates for
        table: Option<String>,
    },
    /// Init a new profile
    Init {
        #[arg(long)]
        /// Add config profile with specific name
        name: Option<String>,

        #[arg(default_value = ".")]
        path: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum CommandConfig {
    /// Add a config profile. If no name is given, template name from toml file will be used
    Add {
        #[arg(long, conflicts_with = "name")]
        /// Add config as default
        default: bool,
        #[arg(long)]
        /// Add config with specific name
        name: Option<String>,

        #[arg(default_value = ".")]
        /// Path to Ctgen.toml file
        path: String,
    },
    /// List all saved config profiles
    #[command(alias = "ls")]
    List,
    /// Remove a config profile
    Rm {
        /// Config profile name to remove
        name: String,
    },
}

pub fn parse_prompt_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
where
    T: std::str::FromStr,
    T::Err: Error + Send + Sync + 'static,
    U: std::str::FromStr,
    U::Err: Error + Send + Sync + 'static,
{
    let pos = s.find('=').ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;

    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}

#[tokio::main]
#[allow(unreachable_code)]
async fn main() -> Result<()> {
    env_logger::init();

    let args = Args::parse();

    let mut ctgen = CtGen::new().await?;

    match args.command {
        Commands::Config { op } => match op {
            CommandConfig::Add { default, name, path } => {
                let profile_name = if let Some(n) = name.as_deref() {
                    n
                } else if default {
                    CONFIG_NAME_DEFAULT
                } else {
                    ""
                };

                let profile = ctgen.add_profile(profile_name, &path).await?;

                print_info(format!("Added profile {}", style(profile.name()).cyan()));

                Ok(())
            }
            CommandConfig::List => {
                list_profiles(&ctgen).await;

                Ok(())
            }
            CommandConfig::Rm { name } => {
                ctgen.remove_profile(&name).await?;

                print_info(format!("Removed profile {}", style(name).cyan()));

                Ok(())
            }
        },
        Commands::Run {
            profile,
            env_file,
            env_var,
            dsn,
            target_dir,
            prompt,
            table,
        } => {
            let profile_name = if let Some(p) = profile.as_deref() { p } else { CONFIG_NAME_DEFAULT };

            print_info(format!("Loading profile {}", style(profile_name).cyan()));

            ctgen.set_current_profile(profile_name).await?;

            let mut profile_overrides: Option<CtGenProfileConfigOverrides> = None;

            if env_file.is_some() || env_var.is_some() || dsn.is_some() || target_dir.is_some() {
                print_info("Overriding profile parameters");
                profile_overrides = Some(CtGenProfileConfigOverrides::new(env_file, env_var, dsn, target_dir));
            }

            let context_dir = CtGen::get_realpath(&CtGen::get_current_working_dir()?).await?;

            print_info("Creating ctgen task");

            let mut task = ctgen.create_task(&context_dir, table.as_deref(), profile_overrides).await?;

            // set pre-defined prompt answer
            if let Some(prompts) = prompt {
                print_info("Overriding prompt responses");
                let unanswered_prompts = task.prompts_unanswered(); // TODO clone not great

                for (answered_prompt_id, answered_prompt_answer) in prompts {
                    if let Some(unanswered_prompt) = unanswered_prompts.iter().find(|p| {
                        if let CtGenTaskPrompt::PromptGeneric { prompt_id, prompt_data: _ } = p {
                            return prompt_id == &answered_prompt_id;
                        }
                        false
                    }) {
                        // TODO unless prompts_unanswered is a cloned set we wouldn't be able to call mutable method

                        if answered_prompt_answer.contains(',') {
                            task.set_prompt_answer(
                                unanswered_prompt,
                                Value::from(answered_prompt_answer.split(',').map(str::to_string).collect::<Vec<String>>()),
                            )
                            .await?;
                        } else {
                            task.set_prompt_answer(unanswered_prompt, Value::from(answered_prompt_answer))
                                .await?;
                        }
                    }
                }
            }

            // ask prompts to prepare context
            loop {
                let unanswered_prompts = task.prompts_unanswered(); // TODO clone not great

                if unanswered_prompts.is_empty() {
                    break;
                }

                print_info("Preparing prompts");

                for unanswered_prompt in unanswered_prompts {
                    match unanswered_prompt.clone() {
                        CtGenTaskPrompt::PromptDatabase => {
                            let options = Value::from(task.reflection_adapter().list_database_names().await?);

                            let answer = ask_prompt("Enter database name:", Some(&options), false, false).await?;

                            task.set_prompt_answer(&unanswered_prompt, answer).await?;
                        }
                        CtGenTaskPrompt::PromptTable => {
                            let options = Value::from(task.reflection_adapter().list_table_names().await?);

                            let answer = ask_prompt("Enter table name:", Some(&options), false, false).await?;

                            task.set_prompt_answer(&unanswered_prompt, answer).await?;
                        }
                        CtGenTaskPrompt::PromptGeneric { prompt_id: _, prompt_data } => {
                            let rendered_prompt = task.render_prompt(&prompt_data)?;

                            // TODO handle enumerations

                            let mut answer = Value::from("");
                            if rendered_prompt.should_ask() {
                                answer = ask_prompt(
                                    rendered_prompt.prompt(),
                                    Some(rendered_prompt.options()),
                                    rendered_prompt.multiple(),
                                    rendered_prompt.ordered(),
                                )
                                .await?;
                            }

                            task.set_prompt_answer(&unanswered_prompt, answer).await?;
                        }
                    }
                }
            }

            //println!("{}", serde_json::to_string(&task.context())?);

            // run
            print_info("Running ctgen task");
            Ok(task.run().await?)
        }
        Commands::Init { name, path } => {
            let name = if let Some(name) = name {
                name
            } else {
                //CONFIG_NAME_DEFAULT.to_string()
                let default_name = if ctgen.get_profiles().contains_key(CONFIG_NAME_DEFAULT) {
                    // there's already a default profile, so we better suggest something else, like for example the path, if it's alphanumeric, or the base directory name of the CWD
                    if CtGen::get_name_regex()?.is_match(&path) {
                        path.clone()
                    } else {
                        Path::new(&CtGen::get_current_working_dir()?)
                            .file_name()
                            .and_then(OsStr::to_str)
                            .unwrap_or_default()
                            .to_string()
                    }
                } else {
                    CONFIG_NAME_DEFAULT.to_string()
                };

                loop {
                    let answer = ask_prompt("Enter profile name:", Some(&Value::String(default_name.clone())), false, false).await;

                    if answer.as_ref().is_ok_and(|v| v.as_str().is_some_and(|s| !s.is_empty())) {
                        break answer.unwrap().as_str().unwrap().to_string();
                    }
                }
            };

            print_info(format!("Creating profile {}", style(&name).cyan()));

            let _profile = ctgen.init_profile(&path, &name).await?;

            print_info(format!("Created and registered profile {}", style(&name).cyan()));

            Ok(())
        }
    }
}

/// Print info label
fn print_info(label: impl Display) {
    println!("{} {}", style("".to_string()).for_stderr().green(), label);
}

/// Print fail label
fn print_fail(label: impl Display) {
    println!("{} {}", style("?".to_string()).for_stderr().yellow(), label);
}

/// List profiles
async fn list_profiles(ctgen: &CtGen) {
    if !ctgen.get_profiles().is_empty() {
        print_info("Installed profiles:");

        let total = ctgen.get_profiles().len();
        for (idx, (profile_name, profile_file)) in ctgen.get_profiles().iter().enumerate() {
            let idx_label = format!("[{}/{}]", (idx + 1), total);

            let profile_name_label = if CtGenProfile::load(profile_file, profile_name).await.is_ok() {
                if profile_name == CONFIG_NAME_DEFAULT {
                    style(profile_name).cyan().bold()
                } else {
                    style(profile_name).cyan()
                }
            } else {
                style(profile_name).red().blink()
            };

            println!(
                "{}\t{}\t{}",
                style(idx_label).dim(),
                profile_name_label,
                style(profile_file).underlined()
            );
        }
    } else {
        print_fail("No profiles found.");
    }
}

/// Ask prompt
async fn ask_prompt(prompt_text: &str, options: Option<&Value>, multiple: bool, ordered: bool) -> Result<Value> {
    return if let Some(options) = options {
        if options.is_string() {
            //input with default suggestion

            let input: String = Input::with_theme(&ColorfulTheme::default())
                .with_prompt(prompt_text)
                .default(options.as_str().unwrap().to_string())
                .report(true)
                .interact_text()
                .unwrap();

            return Ok(Value::from(input));
        } else if !options.is_object() && !options.is_array() {
            Err(CtGenError::RuntimeError("Invalid prompt options".to_string()).into())
        } else if multiple {
            //multi-select + sort?

            let multiselected = if options.is_object() {
                options
                    .as_object()
                    .unwrap()
                    .values()
                    .map(|v| v.as_str().unwrap().to_string())
                    .collect::<Vec<String>>()
            } else {
                options
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|v| v.as_str().unwrap().to_string())
                    .collect::<Vec<String>>()
            };

            print_info(format!("Note: Use {} before {}.", style("SPACE").cyan(), style("ENTER").cyan()));

            let selections = MultiSelect::with_theme(&ColorfulTheme::default())
                .with_prompt(prompt_text)
                .items(&multiselected[..])
                .max_length(20)
                .report(true)
                .interact()
                .unwrap();

            let (multiselected, selections) = if ordered
                && selections.len() > 1
                && Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt("Would you like to sort this selection?")
                    .wait_for_newline(true)
                    .report(true)
                    .interact()
                    .unwrap()
            {
                let subset = multiselected
                    .iter()
                    .enumerate()
                    .filter(|(idx, _v)| selections.contains(idx))
                    .map(|(_k, v)| v.clone())
                    .collect::<Vec<String>>();

                print_info(format!("Note: Use {} before {}.", style("SPACE").cyan(), style("ENTER").cyan()));

                let subset_sort = Sort::with_theme(&ColorfulTheme::default())
                    .with_prompt("Sort the selected items:")
                    .items(&subset[..])
                    .interact()
                    .unwrap();

                (subset, subset_sort)
            } else {
                (multiselected, selections)
            };

            if options.is_object() {
                let mut results: Vec<String> = Vec::new();
                for selection in selections {
                    let value = multiselected[selection].clone();

                    let key = options
                        .as_object()
                        .unwrap()
                        .iter()
                        .find_map(|(k, v)| if v.as_str().unwrap() == value { Some(k.clone()) } else { None })
                        .unwrap_or(String::from(""));

                    results.push(key.clone());
                }

                Ok(Value::from(results))
            } else {
                let mut results: Vec<String> = Vec::new();
                for selection in selections {
                    results.push(multiselected[selection].clone());
                }

                Ok(Value::from(results))
            }
        } else if options.is_object() && options.as_object().unwrap().keys().all(|e| ["0", "1"].contains(&e.as_str())) {
            // confirm

            if Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt(prompt_text)
                .wait_for_newline(true)
                .report(true)
                .interact()
                .unwrap()
            {
                Ok(Value::from("1"))
            } else {
                Ok(Value::from("0"))
            }
        } else {
            // select

            let selections = if options.is_object() {
                options
                    .as_object()
                    .unwrap()
                    .values()
                    .map(|v| v.as_str().unwrap().to_string())
                    .collect::<Vec<String>>()
            } else {
                options
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|v| v.as_str().unwrap().to_string())
                    .collect::<Vec<String>>()
            };

            let selection = Select::with_theme(&ColorfulTheme::default())
                .with_prompt(prompt_text)
                .max_length(20)
                .items(&selections[..])
                .report(true)
                .interact()
                .unwrap();

            if options.is_object() {
                let value = selections.get(selection).unwrap();
                let key = options
                    .as_object()
                    .unwrap()
                    .iter()
                    .find_map(|(k, v)| if v == value { Some(k.clone()) } else { None })
                    .unwrap_or(String::from(""));

                Ok(Value::from(key.clone()))
            } else {
                Ok(Value::from(selections.get(selection).unwrap().clone()))
            }
        }
    } else {
        //input

        let input: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt(prompt_text)
            .interact_text()
            .unwrap();

        Ok(Value::from(input))
    };

    //Ok(Value::from(""))

    // println!("Prompt: {}", prompt_text);
    //
    // if let Some(options) = options {
    //     if options.is_string() {
    //         println!("Options: {}", options.as_str().unwrap());
    //     } else if options.is_array() {
    //         for option in options.as_array().unwrap() {
    //             println!("Option: {}", option);
    //         }
    //     } else if options.is_object() {
    //         for (option_key, option_val) in options.as_object().unwrap() {
    //             println!("Option: {} = {}", option_key, option_val);
    //         }
    //     }
    // }
    //
    // let mut input_lines = BufReader::new(tokio::io::stdin()).lines();
    //
    // if let Some(line) = input_lines.next_line().await? {
    //     if multiple {
    //         return Ok(Value::from(line.split(',').map(str::to_string).collect::<Vec<String>>()));
    //     } else {
    //         return Ok(Value::from(line));
    //     }
    // }
    //
    // Ok(Value::from(""))
}