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
//! zenq - CLI tool for running questionnaires from YAML/JSON files
//!
//! This tool allows you to run interactive questionnaires without writing any Rust code.
//! Simply create a YAML or JSON configuration file and run it with zenq.

mod builder;

use clap::{Parser, Subcommand, ValueEnum};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use zenquirer::{Answers, CrosstermBackend, Error, Questionnaire, QuestionnaireExt};

#[derive(Parser)]
#[command(name = "zenq")]
#[command(version, about = "Interactive command-line questionnaires from YAML/JSON", long_about = None)]
#[command(arg_required_else_help = true)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Path to questionnaire file (shortcut for `zenq run <file>`)
    #[arg(value_name = "FILE")]
    file: Option<PathBuf>,

    /// Pre-fill answers from JSON/YAML file
    #[arg(long)]
    override_file: Option<PathBuf>,

    /// Output file (default: stdout)
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Output format (json or yaml)
    #[arg(long, default_value = "json")]
    format: OutputFormat,
}

#[derive(Subcommand)]
enum Commands {
    /// Run a questionnaire interactively
    Run {
        /// Path to questionnaire file (JSON or YAML)
        file: PathBuf,

        /// Pre-fill answers from JSON/YAML file
        #[arg(long)]
        override_file: Option<PathBuf>,

        /// Output file (default: stdout)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Output format (json or yaml)
        #[arg(long, default_value = "json")]
        format: OutputFormat,
    },

    /// Validate questionnaire syntax
    Validate {
        /// Path to questionnaire file
        file: PathBuf,
    },

    /// Convert between JSON and YAML formats
    Convert {
        /// Input file
        input: PathBuf,

        /// Output file
        output: PathBuf,
    },

    /// Display questionnaire metadata
    Info {
        /// Path to questionnaire file
        file: PathBuf,
    },

    /// Interactively build a questionnaire
    Build {
        /// Output file path (JSON/YAML based on extension, or stdout if omitted)
        output: Option<PathBuf>,

        /// Preview questionnaire before saving
        #[arg(short, long)]
        preview: bool,
    },
}

#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)]
enum OutputFormat {
    Json,
    Yaml,
}

enum CliAction {
    Run {
        file: PathBuf,
        override_file: Option<PathBuf>,
        output: Option<PathBuf>,
        format: OutputFormat,
    },
    Validate {
        file: PathBuf,
    },
    Convert {
        input: PathBuf,
        output: PathBuf,
    },
    Info {
        file: PathBuf,
    },
    Build {
        output: Option<PathBuf>,
        preview: bool,
    },
}

fn main() {
    if let Err(e) = run() {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

fn run() -> Result<(), Error> {
    let cli = Cli::parse();
    let action = resolve_cli_action(cli)?;

    match action {
        CliAction::Run {
            file,
            override_file,
            output,
            format,
        } => run_command(&file, override_file.as_deref(), output.as_deref(), format),
        CliAction::Validate { file } => validate_command(&file),
        CliAction::Convert { input, output } => convert_command(&input, &output),
        CliAction::Info { file } => info_command(&file),
        CliAction::Build { output, preview } => builder::build_command(output.as_deref(), preview),
    }
}

fn resolve_cli_action(cli: Cli) -> Result<CliAction, Error> {
    match cli.command {
        Some(Commands::Run {
            file,
            override_file,
            output,
            format,
        }) => Ok(CliAction::Run {
            file,
            override_file,
            output,
            format,
        }),
        Some(Commands::Validate { file }) => Ok(CliAction::Validate { file }),
        Some(Commands::Convert { input, output }) => Ok(CliAction::Convert { input, output }),
        Some(Commands::Info { file }) => Ok(CliAction::Info { file }),
        Some(Commands::Build { output, preview }) => Ok(CliAction::Build { output, preview }),
        None => {
            let file = cli.file.ok_or_else(|| {
                Error::Validation(
                    "Expected a subcommand or questionnaire file (.json, .yaml, .yml)".to_string(),
                )
            })?;

            if !is_questionnaire_file(&file) {
                let message = "Shortcut form only supports .json, .yaml, or .yml questionnaire \
                    files; use `zenq run <file>` for explicit run semantics";
                return Err(Error::Validation(message.to_string()));
            }

            Ok(CliAction::Run {
                file,
                override_file: cli.override_file,
                output: cli.output,
                format: cli.format,
            })
        }
    }
}

fn is_questionnaire_file(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .map(|extension| {
            matches!(
                extension.to_ascii_lowercase().as_str(),
                "json" | "yaml" | "yml"
            )
        })
        .unwrap_or(false)
}

fn run_command(
    file: &Path,
    override_file: Option<&Path>,
    output: Option<&Path>,
    format: OutputFormat,
) -> Result<(), Error> {
    // Load questionnaire
    let questionnaire = load_questionnaire(file)?;

    // Load override answers if provided
    let override_answers = if let Some(path) = override_file {
        Some(load_answers(path)?)
    } else {
        None
    };

    // Check if we can run in interactive mode
    // With stderr-based rendering, we just need stdin to be a TTY
    let stdin_is_tty = std::io::stdin().is_terminal();

    let answers = if stdin_is_tty {
        // Interactive mode: UI renders on stderr
        zenquirer::smol::block_on(async {
            let backend = CrosstermBackend::new()?;
            backend.clear_screen()?;
            questionnaire
                .ask_all_async(backend, override_answers.as_ref())
                .await
        })?
    } else {
        // Non-interactive mode: Require override answers
        match &override_answers {
            Some(overrides) => {
                // Validate all questions have answers
                for (key, _) in &questionnaire.questions {
                    if !overrides.contains_key(key) {
                        return Err(Error::Validation(format!(
                            "Missing answer for question '{key}' in override file (stderr is not a TTY)"
                        )));
                    }
                }
                overrides.clone()
            }
            None => {
                return Err(Error::Validation(
                    "Non-interactive mode (stderr is not a TTY) requires --override-file with all answers".to_string()
                ));
            }
        }
    };

    // Serialize answers
    let output_str = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&answers)?,
        OutputFormat::Yaml => serde_yaml::to_string(&answers)?,
    };

    // Write to file or stdout
    if let Some(path) = output {
        std::fs::write(path, output_str)?;
    } else {
        println!("{output_str}");
    }

    Ok(())
}

fn validate_command(file: &Path) -> Result<(), Error> {
    // Try to load and parse the questionnaire
    let questionnaire = load_questionnaire(file)?;

    // Validation successful
    eprintln!("✓ Valid questionnaire");
    eprintln!("  Questions: {}", questionnaire.questions.len());

    // Count question types
    let mut type_counts = std::collections::HashMap::new();
    for question in questionnaire.questions.values() {
        let type_name = format!("{:?}", question.question_type);
        *type_counts.entry(type_name).or_insert(0) += 1;
    }

    let types_str = type_counts
        .iter()
        .map(|(t, c)| format!("{t} ({c})"))
        .collect::<Vec<_>>()
        .join(", ");

    if !types_str.is_empty() {
        eprintln!("  Types: {types_str}");
    }

    Ok(())
}

fn convert_command(input: &Path, output: &Path) -> Result<(), Error> {
    // Load questionnaire (auto-detect input format)
    let questionnaire = load_questionnaire(input)?;

    // Determine output format from extension
    let output_ext = output.extension().and_then(|s| s.to_str()).ok_or_else(|| {
        Error::Validation("Output file must have .json, .yaml, or .yml extension".to_string())
    })?;

    // Serialize to output format
    let output_str = match output_ext {
        "json" => serde_json::to_string_pretty(&questionnaire)?,
        "yaml" | "yml" => serde_yaml::to_string(&questionnaire)?,
        _ => {
            return Err(Error::Validation(format!(
                "Unsupported output extension: {output_ext}"
            )));
        }
    };

    std::fs::write(output, output_str)?;
    eprintln!("✓ Converted {} → {}", input.display(), output.display());

    Ok(())
}

fn info_command(file: &Path) -> Result<(), Error> {
    let questionnaire = load_questionnaire(file)?;

    println!("Questionnaire: {}", file.display());

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

    if let Some(footer) = &questionnaire.footer {
        println!("Footer: {footer}");
    }

    println!("Questions: {}", questionnaire.questions.len());

    // Count question types
    let mut type_counts = std::collections::HashMap::new();
    for question in questionnaire.questions.values() {
        *type_counts
            .entry(format!("{:?}", question.question_type))
            .or_insert(0) += 1;
    }

    if !type_counts.is_empty() {
        println!("Types:");
        for (qtype, count) in type_counts {
            println!("  {qtype} ({count})");
        }
    }

    // Count validators
    let validator_count = questionnaire
        .questions
        .values()
        .filter(|q| q.validator.is_some())
        .count();

    if validator_count > 0 {
        println!("Validators: {validator_count} questions with validation");
    }

    Ok(())
}

fn load_questionnaire(path: &Path) -> Result<Questionnaire, Error> {
    let content = std::fs::read_to_string(path).map_err(Error::IO)?;

    match normalized_extension(path).as_deref() {
        Some("json") => serde_json::from_str(&content).map_err(Error::Json),
        Some("yaml") | Some("yml") => serde_yaml::from_str(&content).map_err(Error::Yaml),
        _ => Err(Error::Validation(
            "File must have .json, .yaml, or .yml extension".to_string(),
        )),
    }
}

fn load_answers(path: &Path) -> Result<Answers, Error> {
    let content = std::fs::read_to_string(path).map_err(Error::IO)?;

    match normalized_extension(path).as_deref() {
        Some("json") => serde_json::from_str(&content).map_err(Error::Json),
        Some("yaml") | Some("yml") => serde_yaml::from_str(&content).map_err(Error::Yaml),
        _ => Err(Error::Validation(
            "Override file must have .json, .yaml, or .yml extension".to_string(),
        )),
    }
}

fn normalized_extension(path: &Path) -> Option<String> {
    path.extension()
        .and_then(|extension| extension.to_str())
        .map(|extension| extension.to_ascii_lowercase())
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    fn parse_action(args: &[&str]) -> Result<CliAction, Error> {
        let cli = Cli::try_parse_from(args).expect("CLI arguments should parse");
        resolve_cli_action(cli)
    }

    #[test]
    fn shortcut_runs_questionnaire_files() {
        let action = parse_action(&["zenq", "survey.yaml"]).unwrap();

        match action {
            CliAction::Run {
                file,
                override_file,
                output,
                format,
            } => {
                assert_eq!(file, PathBuf::from("survey.yaml"));
                assert_eq!(override_file, None);
                assert_eq!(output, None);
                assert_eq!(format, OutputFormat::Json);
            }
            _ => panic!("Expected shortcut to resolve to run action"),
        }
    }

    #[test]
    fn shortcut_accepts_uppercase_questionnaire_extensions() {
        let action = parse_action(&["zenq", "SURVEY.YAML", "--format", "yaml"]).unwrap();

        match action {
            CliAction::Run { file, format, .. } => {
                assert_eq!(file, PathBuf::from("SURVEY.YAML"));
                assert_eq!(format, OutputFormat::Yaml);
            }
            _ => panic!("Expected shortcut to resolve to run action"),
        }
    }

    #[test]
    fn shortcut_accepts_run_options() {
        let action = parse_action(&[
            "zenq",
            "survey.yaml",
            "--override-file",
            "defaults.yaml",
            "-o",
            "answers.json",
        ])
        .unwrap();

        match action {
            CliAction::Run {
                override_file,
                output,
                ..
            } => {
                assert_eq!(override_file, Some(PathBuf::from("defaults.yaml")));
                assert_eq!(output, Some(PathBuf::from("answers.json")));
            }
            _ => panic!("Expected shortcut to resolve to run action"),
        }
    }

    #[test]
    fn shortcut_rejects_non_questionnaire_extensions() {
        assert!(parse_action(&["zenq", "survey.txt"]).is_err());
        assert!(parse_action(&["zenq", "./validate"]).is_err());
    }

    #[test]
    fn explicit_run_preserves_filename_handling() {
        let action = parse_action(&["zenq", "run", "validate"]).unwrap();

        match action {
            CliAction::Run { file, .. } => {
                assert_eq!(file, PathBuf::from("validate"));
            }
            _ => panic!("Expected explicit run action"),
        }
    }

    #[test]
    fn subcommands_take_precedence_over_shortcut() {
        let action = parse_action(&["zenq", "validate", "survey.yaml"]).unwrap();

        match action {
            CliAction::Validate { file } => {
                assert_eq!(file, PathBuf::from("survey.yaml"));
            }
            _ => panic!("Expected validate action"),
        }
    }
}