zenquirer 0.1.0

Interactive command-line questionnaires and prompts with async support
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Interactive questionnaire builder for zenq CLI.
//!
//! This module provides the `zenq build` command that allows users to create
//! questionnaires interactively using zenquirer's own backend (dogfooding!).

use std::path::Path;
use zenquirer::{
    ConfirmPrompt, CrosstermBackend, Error, InputPrompt, MultiSelectPrompt, QuestionData,
    QuestionOption, Questionnaire, SelectPrompt, ValidationRule, Validator,
};
use zenquirer_core::question::{QuestionConfig, QuestionType};

/// Output format for questionnaire serialization
#[derive(Debug, Clone, Copy)]
enum OutputFormat {
    Json,
    Yaml,
}

/// Public entry point for the build command
pub fn build_command(output: Option<&Path>, preview: bool) -> Result<(), Error> {
    zenquirer::smol::block_on(async {
        // Build questionnaire interactively
        let backend = CrosstermBackend::new()?;
        backend.clear_screen()?; // Clear screen for clean slate
        let questionnaire = build_workflow(backend).await?;

        // Preview if requested
        if preview {
            preview_questionnaire(&questionnaire)?;

            let backend = CrosstermBackend::new()?;
            let should_save = backend
                .confirm("Save this questionnaire?".into(), None)
                .await?;

            if !should_save {
                eprintln!("Questionnaire discarded.");
                return Ok(());
            }
        }

        // Serialize and save
        match output {
            Some(path) => {
                let format = get_output_format(path)?;
                let content = serialize_questionnaire(&questionnaire, format)?;
                std::fs::write(path, content)?;
                eprintln!("✓ Saved to {}", path.display());
            }
            None => {
                // Default to YAML for stdout
                let content = serialize_questionnaire(&questionnaire, OutputFormat::Yaml)?;
                println!("{content}");
            }
        }

        Ok(())
    })
}

/// Main workflow for building a questionnaire
async fn build_workflow(_backend: CrosstermBackend) -> Result<Questionnaire, Error> {
    let mut questionnaire = Questionnaire::new();

    // Step 1: Collect metadata
    let mut backend = CrosstermBackend::new()?;
    questionnaire.header = {
        let header = backend
            .text_input(
                "Questionnaire title (header)".into(),
                Some("Optional - press Enter to skip".into()),
                None,
                None,
                None,
            )
            .await?;
        if header.is_empty() {
            None
        } else {
            Some(header)
        }
    };

    backend = CrosstermBackend::new()?;
    questionnaire.footer = {
        let footer = backend
            .text_input(
                "Questionnaire footer".into(),
                Some("Optional - press Enter to skip".into()),
                None,
                None,
                None,
            )
            .await?;
        if footer.is_empty() {
            None
        } else {
            Some(footer)
        }
    };

    // Step 2: Add questions loop
    add_question_loop(backend, &mut questionnaire).await?;

    Ok(questionnaire)
}

/// Interactive loop for adding questions
async fn add_question_loop(
    _backend: CrosstermBackend,
    questionnaire: &mut Questionnaire,
) -> Result<(), Error> {
    loop {
        let mut backend = CrosstermBackend::new()?;

        let add_question = backend
            .confirm(
                "Add a question?".into(),
                Some(format!(
                    "Current questions: {}",
                    questionnaire.questions.len()
                )),
            )
            .await?;

        if !add_question {
            break;
        }

        // Get question ID with validation
        backend = CrosstermBackend::new()?;
        let name = backend
            .text_input(
                "Question ID/name".into(),
                Some("e.g., username, email, language".into()),
                Some(
                    Validator::new()
                        .rule(ValidationRule::NotEmpty)
                        .rule(ValidationRule::AlphanumericWithUnderscore)
                        .message("Must be non-empty, alphanumeric with underscores only"),
                ),
                None,
                None,
            )
            .await?;

        // Check for duplicate
        if questionnaire.questions.contains_key(&name) {
            eprintln!("⚠ Question '{name}' already exists. Skipping.");
            continue;
        }

        // Select question type
        backend = CrosstermBackend::new()?;
        let question_type_answer = backend
            .select(
                "Select question type".into(),
                vec![
                    QuestionOption::new("Input - Free text input"),
                    QuestionOption::new("Select - Single choice"),
                    QuestionOption::new("MultiSelect - Multiple choices"),
                    QuestionOption::new("Confirm - Yes/no"),
                    QuestionOption::new("Number - Numeric input"),
                ],
                None,
                None,
                None,
                None,
            )
            .await?;

        // Extract question type from selection
        let question_type = question_type_answer
            .value
            .split(" - ")
            .next()
            .unwrap_or("Input");

        // Configure and add question
        backend = CrosstermBackend::new()?;
        let question_data = configure_question(backend, question_type, name.clone()).await?;

        questionnaire.insert(name, question_data);
        eprintln!("✓ Question added");
    }

    Ok(())
}

/// Configure a question based on its type
async fn configure_question(
    backend: CrosstermBackend,
    question_type: &str,
    name: String,
) -> Result<QuestionData, Error> {
    match question_type {
        "Input" => configure_input_question(backend, name).await,
        "Select" => configure_select_question(backend, name, false).await,
        "MultiSelect" => configure_select_question(backend, name, true).await,
        "Confirm" => configure_confirm_question(backend, name).await,
        "Number" => configure_number_question(backend, name).await,
        _ => Err(Error::Validation(format!(
            "Unknown question type: {question_type}"
        ))),
    }
}

/// Configure an Input question
async fn configure_input_question(
    _backend: CrosstermBackend,
    _name: String,
) -> Result<QuestionData, Error> {
    let mut backend = CrosstermBackend::new()?;
    let prompt = backend
        .text_input(
            "Question prompt".into(),
            Some("e.g., What's your name?".into()),
            Some(Validator::not_empty()),
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let hint = backend
        .text_input(
            "Hint text (optional)".into(),
            Some("Press Enter to skip".into()),
            None,
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let validator = add_validators(backend, "input").await?;

    Ok(QuestionData {
        question_type: QuestionType::Input,
        prompt,
        config: QuestionConfig::Input {
            default_value: None,
        },
        hint: if hint.is_empty() { None } else { Some(hint) },
        validator,
        formatter: None,
    })
}

/// Configure a Select or MultiSelect question
async fn configure_select_question(
    _backend: CrosstermBackend,
    _name: String,
    is_multi: bool,
) -> Result<QuestionData, Error> {
    let mut backend = CrosstermBackend::new()?;
    let prompt = backend
        .text_input(
            "Question prompt".into(),
            Some("e.g., Choose your language".into()),
            Some(Validator::not_empty()),
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let raw_options = backend
        .text_input(
            "Enter options (comma-separated)".into(),
            Some("e.g., Rust, Python, Go, JavaScript".into()),
            Some(Validator::not_empty()),
            None,
            None,
        )
        .await?;

    // Parse options
    let options: Vec<String> = raw_options
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    if options.is_empty() {
        return Err(Error::Validation(
            "Must provide at least one option".to_string(),
        ));
    }

    backend = CrosstermBackend::new()?;
    let hint = backend
        .text_input(
            "Hint text (optional)".into(),
            Some("Press Enter to skip".into()),
            None,
            None,
            None,
        )
        .await?;

    let (min_selections, max_selections) =
        if is_multi {
            backend = CrosstermBackend::new()?;
            let min_str = backend
                .text_input(
                    "Minimum selections (optional)".into(),
                    Some("Press Enter for no minimum".into()),
                    None,
                    None,
                    None,
                )
                .await?;

            backend = CrosstermBackend::new()?;
            let max_str = backend
                .text_input(
                    "Maximum selections (optional)".into(),
                    Some("Press Enter for no maximum".into()),
                    None,
                    None,
                    None,
                )
                .await?;

            let min =
                if min_str.is_empty() {
                    None
                } else {
                    Some(min_str.parse().map_err(|_| {
                        Error::Validation("Minimum must be a valid number".to_string())
                    })?)
                };

            let max =
                if max_str.is_empty() {
                    None
                } else {
                    Some(max_str.parse().map_err(|_| {
                        Error::Validation("Maximum must be a valid number".to_string())
                    })?)
                };

            (min, max)
        } else {
            (None, None)
        };

    let config = if is_multi {
        QuestionConfig::MultiSelect {
            options,
            min_selections,
            max_selections,
        }
    } else {
        QuestionConfig::Select { options }
    };

    Ok(QuestionData {
        question_type: if is_multi {
            QuestionType::MultiSelect
        } else {
            QuestionType::Select
        },
        prompt,
        config,
        hint: if hint.is_empty() { None } else { Some(hint) },
        validator: None,
        formatter: None,
    })
}

/// Configure a Confirm question
async fn configure_confirm_question(
    _backend: CrosstermBackend,
    _name: String,
) -> Result<QuestionData, Error> {
    let mut backend = CrosstermBackend::new()?;
    let prompt = backend
        .text_input(
            "Question prompt".into(),
            Some("e.g., Subscribe to newsletter?".into()),
            Some(Validator::not_empty()),
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let hint = backend
        .text_input(
            "Hint text (optional)".into(),
            Some("Press Enter to skip".into()),
            None,
            None,
            None,
        )
        .await?;

    Ok(QuestionData {
        question_type: QuestionType::Confirm,
        prompt,
        config: QuestionConfig::Confirm,
        hint: if hint.is_empty() { None } else { Some(hint) },
        validator: None,
        formatter: None,
    })
}

/// Configure a Number question
async fn configure_number_question(
    _backend: CrosstermBackend,
    _name: String,
) -> Result<QuestionData, Error> {
    let mut backend = CrosstermBackend::new()?;
    let prompt = backend
        .text_input(
            "Question prompt".into(),
            Some("e.g., Enter your age".into()),
            Some(Validator::not_empty()),
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let hint = backend
        .text_input(
            "Hint text (optional)".into(),
            Some("Press Enter to skip".into()),
            None,
            None,
            None,
        )
        .await?;

    backend = CrosstermBackend::new()?;
    let validator = add_validators(backend, "number").await?;

    Ok(QuestionData {
        question_type: QuestionType::Number,
        prompt,
        config: QuestionConfig::Number {
            default_value: None,
        },
        hint: if hint.is_empty() { None } else { Some(hint) },
        validator,
        formatter: None,
    })
}

/// Add validators to a question
async fn add_validators(
    _backend: CrosstermBackend,
    _question_type: &str,
) -> Result<Option<Validator>, Error> {
    let mut backend = CrosstermBackend::new()?;
    let add_validation = backend.confirm("Add validation?".into(), None).await?;

    if !add_validation {
        return Ok(None);
    }

    // Select validation category
    backend = CrosstermBackend::new()?;
    let category = backend
        .select(
            "Select validation category".into(),
            vec![
                QuestionOption::new("String Validation"),
                QuestionOption::new("Numeric Validation"),
                QuestionOption::new("Network Validation"),
                QuestionOption::new("Path Validation"),
                QuestionOption::new("Security"),
            ],
            None,
            None,
            None,
            None,
        )
        .await?;

    // Select rules from category
    backend = CrosstermBackend::new()?;
    let rules = select_validation_rules(backend, &category.value).await?;

    if rules.is_empty() {
        return Ok(None);
    }

    // Ask for custom error message
    backend = CrosstermBackend::new()?;
    let custom_message = backend
        .text_input(
            "Custom error message (optional)".into(),
            Some("Press Enter for default messages".into()),
            None,
            None,
            None,
        )
        .await?;

    let mut validator = Validator::new();
    for rule in rules {
        validator = validator.rule(rule);
    }

    if !custom_message.is_empty() {
        validator = validator.message(custom_message);
    }

    Ok(Some(validator))
}

/// Select validation rules from a category
async fn select_validation_rules(
    backend: CrosstermBackend,
    category: &str,
) -> Result<Vec<ValidationRule>, Error> {
    let rules_for_category = match category {
        "String Validation" => vec![
            ("Not empty", ValidationRule::NotEmpty),
            ("Minimum length (3)", ValidationRule::MinLength(3)),
            ("Maximum length (100)", ValidationRule::MaxLength(100)),
            ("Lowercase only", ValidationRule::Lowercase),
            ("Uppercase only", ValidationRule::Uppercase),
            ("Alphanumeric only", ValidationRule::AlphanumericOnly),
            (
                "Alphanumeric with underscore",
                ValidationRule::AlphanumericWithUnderscore,
            ),
            ("No whitespace", ValidationRule::NoWhitespace),
        ],
        "Numeric Validation" => vec![
            ("Must be numeric", ValidationRule::Numeric),
            ("Must be integer", ValidationRule::Integer),
            (
                "Range (0-100)",
                ValidationRule::Range {
                    min: Some(0.0),
                    max: Some(100.0),
                },
            ),
            ("Greater than 0", ValidationRule::GreaterThan(0.0)),
        ],
        "Network Validation" => vec![
            #[cfg(feature = "validators-regex")]
            ("Email address", ValidationRule::EmailRegex),
            #[cfg(feature = "validators-regex")]
            ("URL", ValidationRule::UrlRegex),
            #[cfg(feature = "validators-regex")]
            ("IP address", ValidationRule::IpAddress),
            ("Port number", ValidationRule::Port),
            #[cfg(feature = "validators-regex")]
            ("Hostname", ValidationRule::Hostname),
        ],
        "Path Validation" => vec![
            ("Path exists", ValidationRule::PathExists),
            ("File exists", ValidationRule::FileExists),
            ("Directory exists", ValidationRule::DirectoryExists),
        ],
        "Security" => vec![(
            "Strong password",
            ValidationRule::PasswordStrength {
                min_length: 8,
                require_uppercase: true,
                require_lowercase: true,
                require_digit: true,
                require_special: true,
            },
        )],
        _ => vec![],
    };

    if rules_for_category.is_empty() {
        return Ok(vec![]);
    }

    let options: Vec<QuestionOption> = rules_for_category
        .iter()
        .map(|(label, _)| QuestionOption::new(*label))
        .collect();

    let selected = backend
        .multi_select(
            format!("Select {category} rules (multiple)"),
            options,
            None,
            None,
            None,
            None,
        )
        .await?;

    let rules: Vec<ValidationRule> = selected
        .iter()
        .filter_map(|s| {
            rules_for_category
                .iter()
                .find(|(label, _)| *label == s.value)
                .map(|(_, rule)| rule.clone())
        })
        .collect();

    Ok(rules)
}

/// Determine output format from file extension
fn get_output_format(path: &Path) -> Result<OutputFormat, Error> {
    match path.extension().and_then(|s| s.to_str()) {
        Some("json") => Ok(OutputFormat::Json),
        Some("yaml") | Some("yml") => Ok(OutputFormat::Yaml),
        None => Ok(OutputFormat::Yaml), // Default to YAML
        Some(ext) => Err(Error::Validation(format!(
            "Unsupported extension '{ext}'. Use .json, .yaml, or .yml"
        ))),
    }
}

/// Serialize questionnaire to string
fn serialize_questionnaire(q: &Questionnaire, format: OutputFormat) -> Result<String, Error> {
    match format {
        OutputFormat::Json => serde_json::to_string_pretty(q).map_err(Error::Json),
        OutputFormat::Yaml => serde_yaml::to_string(q).map_err(Error::Yaml),
    }
}

/// Preview questionnaire structure
fn preview_questionnaire(q: &Questionnaire) -> Result<(), Error> {
    println!("\n═══════════════════════════════════════");
    println!("  QUESTIONNAIRE PREVIEW");
    println!("═══════════════════════════════════════\n");

    if let Some(header) = &q.header {
        println!("Header: {header}\n");
    }

    println!("Questions ({}):", q.questions.len());
    for (i, (name, data)) in q.questions.iter().enumerate() {
        println!("\n{}. {} [{:?}]", i + 1, name, data.question_type);
        println!("   Prompt: {}", data.prompt);

        match &data.config {
            QuestionConfig::Select { options } | QuestionConfig::MultiSelect { options, .. } => {
                println!("   Options: {}", options.join(", "));
            }
            _ => {}
        }

        if data.validator.is_some() {
            println!("   ✓ Has validation");
        }

        if let Some(hint) = &data.hint {
            println!("   Hint: {hint}");
        }
    }

    if let Some(footer) = &q.footer {
        println!("\nFooter: {footer}");
    }

    println!("\n═══════════════════════════════════════\n");
    Ok(())
}