standout-input 10.0.0

Declarative input collection for CLI applications
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
use std::collections::{BTreeMap, HashSet};

use super::definition::{child_segment, path_join, Questionnaire};
use super::render::{FINGERPRINT_PREFIX, FORMAT_LINE, QUESTIONNAIRE_PREFIX, TAG_OPEN};

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RawAnswers {
    values: BTreeMap<String, String>,
    occurrences: BTreeMap<String, usize>,
    warnings: Vec<AnswerSheetDiagnostic>,
}

impl RawAnswers {
    #[cfg(feature = "simple-prompts")]
    pub(crate) fn from_parts(
        values: BTreeMap<String, String>,
        occurrences: BTreeMap<String, usize>,
    ) -> Self {
        Self {
            values,
            occurrences,
            warnings: Vec::new(),
        }
    }

    pub fn get(&self, path: &str) -> Option<&str> {
        self.values.get(path).map(String::as_str)
    }

    pub fn occurrence_count(&self, group_path: &str) -> usize {
        self.occurrences.get(group_path).copied().unwrap_or(0)
    }

    pub fn warnings(&self) -> &[AnswerSheetDiagnostic] {
        &self.warnings
    }

    pub fn set(&mut self, path: impl Into<String>, answer: impl Into<String>) {
        self.values.insert(path.into(), answer.into());
    }

    pub fn set_occurrence_count(&mut self, group_path: impl Into<String>, count: usize) {
        self.occurrences.insert(group_path.into(), count);
    }

    pub fn push_warning(&mut self, warning: AnswerSheetDiagnostic) {
        self.warnings.push(warning);
    }
}

/// How the bytes behind `--answers` become [`RawAnswers`]; the default is [`StandoutAnswerSheet`].
pub trait AnswerSheetFormat {
    fn parse(
        &self,
        questionnaire: &Questionnaire,
        text: &str,
    ) -> Result<RawAnswers, Vec<AnswerSheetDiagnostic>>;
}

/// The preamble/fingerprint sheet `questions` renders.
pub struct StandoutAnswerSheet;

impl AnswerSheetFormat for StandoutAnswerSheet {
    fn parse(
        &self,
        questionnaire: &Questionnaire,
        text: &str,
    ) -> Result<RawAnswers, Vec<AnswerSheetDiagnostic>> {
        questionnaire.parse_answer_sheet(text)
    }
}

#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum AnswerSheetDiagnostic {
    #[error("{message}")]
    Incompatible { message: String },

    #[error("Line {line}: {message}")]
    Tag { line: usize, message: String },

    #[error("Line {line}: warning: the answer for '{path}' contains '<id:'. A tag only marks a question when it ends its line; if this was meant to be a question line, remove everything after the tag — if it is ordinary prose, ignore this warning.")]
    SuspectedTagInAnswer { path: String, line: usize },

    #[error("Could not read the answer sheet: {detail}")]
    UnreadableDocument { detail: String },
}

impl AnswerSheetDiagnostic {
    fn incompatible(message: impl Into<String>) -> Self {
        Self::Incompatible {
            message: message.into(),
        }
    }

    fn tag(line: usize, message: impl Into<String>) -> Self {
        Self::Tag {
            line,
            message: message.into(),
        }
    }

    fn malformed_preamble(line: usize, detail: impl std::fmt::Display) -> Self {
        Self::incompatible(format!(
            "Line {line}: malformed answer-sheet preamble: {detail}. Render a fresh answer sheet and copy your answers into it."
        ))
    }
}

struct OpenAnswer {
    path: Option<String>,
    lines: Vec<(usize, String)>,
}

impl OpenAnswer {
    fn flush_into(
        self,
        values: &mut BTreeMap<String, String>,
        warnings: &mut Vec<AnswerSheetDiagnostic>,
    ) {
        let Some(path) = self.path else {
            return;
        };
        for (index, line) in &self.lines {
            if line.contains(TAG_OPEN) {
                warnings.push(AnswerSheetDiagnostic::SuspectedTagInAnswer {
                    path: path.clone(),
                    line: index + 1,
                });
            }
        }
        let text = self
            .lines
            .into_iter()
            .map(|(_, line)| line)
            .collect::<Vec<_>>()
            .join("\n");
        values.insert(path, text.trim().to_string());
    }
}

struct Scope {
    group_id: String,
    def_prefix: String,
    path_prefix: String,
    discard: bool,
}

fn terminal_tag(line: &str) -> Option<&str> {
    let before_close = line.trim_end().strip_suffix('>')?;
    let open = before_close.rfind(TAG_OPEN)?;
    let id = &before_close[open + TAG_OPEN.len()..];
    let valid = !id.is_empty()
        && id
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'));
    valid.then_some(id)
}

impl Questionnaire {
    pub fn parse_answer_sheet(&self, text: &str) -> Result<RawAnswers, Vec<AnswerSheetDiagnostic>> {
        let lines: Vec<&str> = text.lines().collect();
        let body_start = self.check_preamble(&lines)?;
        self.parse_body(&lines, body_start)
    }

    pub fn parse_answer_sheet_body(
        &self,
        text: &str,
    ) -> Result<RawAnswers, Vec<AnswerSheetDiagnostic>> {
        let lines: Vec<&str> = text.lines().collect();
        self.parse_body(&lines, 0)
    }

    fn parse_body(
        &self,
        lines: &[&str],
        body_start: usize,
    ) -> Result<RawAnswers, Vec<AnswerSheetDiagnostic>> {
        let mut diagnostics: Vec<AnswerSheetDiagnostic> = Vec::new();
        let mut warnings: Vec<AnswerSheetDiagnostic> = Vec::new();
        let mut values: BTreeMap<String, String> = BTreeMap::new();
        let mut occurrences: BTreeMap<String, usize> = BTreeMap::new();
        let mut seen_sections: HashSet<String> = HashSet::new();
        let mut stack: Vec<Scope> = Vec::new();
        let mut open: Option<OpenAnswer> = None;

        for (index, line) in lines.iter().enumerate().skip(body_start) {
            let Some(id) = terminal_tag(line) else {
                if let Some(current) = open.as_mut() {
                    current.lines.push((index, line.to_string()));
                }
                continue;
            };

            if let Some(previous) = open.take() {
                previous.flush_into(&mut values, &mut warnings);
            }
            let is_group = self.node_meta(id).is_some_and(|meta| meta.group);
            if is_group {
                self.open_group(
                    id,
                    index,
                    &mut stack,
                    &mut occurrences,
                    &mut seen_sections,
                    &mut diagnostics,
                );
            } else {
                let path = self.open_field(id, index, &mut stack, &values, &mut diagnostics);
                open = Some(OpenAnswer {
                    path,
                    lines: Vec::new(),
                });
            }
        }
        if let Some(last) = open {
            last.flush_into(&mut values, &mut warnings);
        }

        if diagnostics.is_empty() {
            Ok(RawAnswers {
                values,
                occurrences,
                warnings,
            })
        } else {
            Err(diagnostics)
        }
    }

    fn open_field(
        &self,
        id: &str,
        line_index: usize,
        stack: &mut Vec<Scope>,
        values: &BTreeMap<String, String>,
        diagnostics: &mut Vec<AnswerSheetDiagnostic>,
    ) -> Option<String> {
        let line = line_index + 1;
        let Some(meta) = self.node_meta(id) else {
            diagnostics.push(AnswerSheetDiagnostic::tag(
                line,
                format!("unknown question tag '<id:{id}>'. This questionnaire does not define that ID; if the line is prose, add any character after the tag, otherwise render a fresh answer sheet."),
            ));
            return None;
        };
        let Some(keep) = resolve_scope(stack, meta.parent.as_deref()) else {
            diagnostics.push(AnswerSheetDiagnostic::tag(
                line,
                format!("misplaced '<id:{id}>'. That ID is not valid at this point of the sheet; keep each question inside its own group block, or render a fresh answer sheet to restore the structure."),
            ));
            return None;
        };
        stack.truncate(keep);
        let (def_prefix, path_prefix, discard) = match stack.last() {
            Some(scope) => (
                scope.def_prefix.as_str(),
                scope.path_prefix.as_str(),
                scope.discard,
            ),
            None => ("", "", false),
        };
        if discard {
            return None;
        }
        let path = path_join(path_prefix, child_segment(def_prefix, id));
        if values.contains_key(&path) {
            diagnostics.push(AnswerSheetDiagnostic::tag(
                line,
                format!("duplicate question '<id:{path}>'. Each question may be answered once per occurrence; remove the extra question line or copy the complete group block instead."),
            ));
            return None;
        }
        Some(path)
    }

    fn open_group(
        &self,
        id: &str,
        line_index: usize,
        stack: &mut Vec<Scope>,
        occurrences: &mut BTreeMap<String, usize>,
        seen_sections: &mut HashSet<String>,
        diagnostics: &mut Vec<AnswerSheetDiagnostic>,
    ) {
        let line = line_index + 1;
        let group = self
            .group_def(id)
            .expect("caller verified the ID names a group");
        let parent = self
            .node_meta(id)
            .expect("known group has meta")
            .parent
            .clone();

        let discard_scope = |discard: bool| Scope {
            group_id: group.id().to_string(),
            def_prefix: group.def_prefix(),
            path_prefix: String::new(),
            discard,
        };

        let Some(keep) = resolve_scope(stack, parent.as_deref()) else {
            diagnostics.push(AnswerSheetDiagnostic::tag(
                line,
                format!("misplaced '<id:{id}>'. That ID is not valid at this point of the sheet; keep each question inside its own group block, or render a fresh answer sheet to restore the structure."),
            ));
            stack.push(discard_scope(true));
            return;
        };
        stack.truncate(keep);
        let (parent_def, parent_path, parent_discard) = match stack.last() {
            Some(scope) => (
                scope.def_prefix.as_str(),
                scope.path_prefix.as_str(),
                scope.discard,
            ),
            None => ("", "", false),
        };
        if parent_discard {
            stack.push(discard_scope(true));
            return;
        }
        let base = path_join(parent_path, child_segment(parent_def, id));
        let path_prefix = match group.repeat() {
            Some(_) => {
                let count = occurrences.entry(base.clone()).or_insert(0);
                let index = *count;
                *count += 1;
                format!("{base}[{index}]")
            }
            None => {
                if !seen_sections.insert(base.clone()) {
                    diagnostics.push(AnswerSheetDiagnostic::tag(
                        line,
                        format!("duplicate group '<id:{id}>'. This group is answered once; remove the extra block (only repeatable sections take copied blocks)."),
                    ));
                    stack.push(discard_scope(true));
                    return;
                }
                base
            }
        };
        stack.push(Scope {
            group_id: group.id().to_string(),
            def_prefix: group.def_prefix(),
            path_prefix,
            discard: false,
        });
    }

    fn check_preamble(&self, lines: &[&str]) -> Result<usize, Vec<AnswerSheetDiagnostic>> {
        let mut diagnostics = Vec::new();
        let mut i = 0;

        let next_content = |i: &mut usize| -> Option<usize> {
            while *i < lines.len() && lines[*i].trim().is_empty() {
                *i += 1;
            }
            (*i < lines.len()).then(|| {
                let at = *i;
                *i += 1;
                at
            })
        };

        match next_content(&mut i) {
            Some(at) => {
                let line = lines[at].trim();
                if line != FORMAT_LINE {
                    match line.strip_prefix("#! standout-answers ") {
                        Some(version) => {
                            diagnostics.push(AnswerSheetDiagnostic::incompatible(format!(
                                "Unsupported answer-format version '{}' (this release reads only version 1). Render a fresh answer sheet; old sheets are not migrated.",
                                version.trim()
                            )))
                        }
                        None => diagnostics.push(AnswerSheetDiagnostic::malformed_preamble(
                            at + 1,
                            format!("expected '{FORMAT_LINE}'"),
                        )),
                    }
                }
            }
            None => diagnostics.push(AnswerSheetDiagnostic::malformed_preamble(
                lines.len() + 1,
                format!("expected '{FORMAT_LINE}'"),
            )),
        }

        let expect_keyed = |i: &mut usize,
                            prefix: &str,
                            diagnostics: &mut Vec<AnswerSheetDiagnostic>|
         -> Option<String> {
            match next_content(i) {
                Some(at) => match lines[at].trim().strip_prefix(prefix) {
                    Some(value) => Some(value.trim().to_string()),
                    None => {
                        diagnostics.push(AnswerSheetDiagnostic::malformed_preamble(
                            at + 1,
                            format!("expected '{prefix} ...'"),
                        ));
                        None
                    }
                },
                None => {
                    diagnostics.push(AnswerSheetDiagnostic::malformed_preamble(
                        lines.len() + 1,
                        format!("expected '{prefix} ...'"),
                    ));
                    None
                }
            }
        };

        if let Some(found) = expect_keyed(&mut i, QUESTIONNAIRE_PREFIX, &mut diagnostics) {
            if found != self.id() {
                diagnostics.push(AnswerSheetDiagnostic::incompatible(format!(
                    "This answer sheet is for questionnaire '{found}', not '{expected}'. Render a fresh answer sheet for '{expected}'.",
                    expected = self.id()
                )));
            }
        }
        if let Some(found) = expect_keyed(&mut i, FINGERPRINT_PREFIX, &mut diagnostics) {
            if found != self.fingerprint() {
                diagnostics.push(AnswerSheetDiagnostic::incompatible(format!(
                    "This answer sheet was rendered from a different version of questionnaire semantics (fingerprint '{found}', expected '{expected}'). The questionnaire changed since this sheet was rendered; render a fresh answer sheet and copy your answers into it. Answers are not migrated.",
                    expected = self.fingerprint()
                )));
            }
        }

        if diagnostics.is_empty() {
            Ok(i)
        } else {
            Err(diagnostics)
        }
    }
}

fn resolve_scope(stack: &[Scope], parent: Option<&str>) -> Option<usize> {
    match parent {
        None => Some(0),
        Some(parent) => stack
            .iter()
            .rposition(|scope| scope.group_id == parent)
            .map(|found| found + 1),
    }
}