rototo 0.1.0-alpha.6

Control plane for runtime configuration of your application.
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
use std::collections::BTreeSet;
use std::path::Path;

use serde::Serialize;
use serde_json::Value as JsonValue;

use crate::error::{Result, RototoError};
use crate::model::{
    PackageInspectReport, PackageInspectRequest, QualifierInspectReport, QualifierResolutionTrace,
    RulePathwayInspectReport, VariableInspectReport, VariableResolutionTrace,
};
use crate::resolve::{trace_qualifier_resolution, trace_variable_resolution};
use crate::source::{SourceOptions, stage_package_source};

mod context_factory;
mod render;

use context_factory::ContextFactory;

pub use render::{ContextForm, render_command, render_comment};

#[derive(Clone, Debug, Default)]
pub struct FixtureGenerateSelection {
    pub variables: FixtureTargetSelection,
    pub qualifiers: FixtureTargetSelection,
}

impl FixtureGenerateSelection {
    pub fn all() -> Self {
        Self {
            variables: FixtureTargetSelection::All,
            qualifiers: FixtureTargetSelection::All,
        }
    }

    fn normalized(self) -> Self {
        if self.variables.is_none() && self.qualifiers.is_none() {
            Self::all()
        } else {
            self
        }
    }
}

#[derive(Clone, Debug, Default)]
pub enum FixtureTargetSelection {
    #[default]
    None,
    Some(BTreeSet<String>),
    All,
}

impl FixtureTargetSelection {
    pub fn some(values: impl IntoIterator<Item = String>) -> Self {
        Self::Some(values.into_iter().collect())
    }

    fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }
}

/// A single `rototo resolve` invocation that exercises one behavior case of a
/// variable or qualifier. The CLI renders these into runnable command lines;
/// nothing is persisted to disk.
#[derive(Clone, Debug)]
pub struct ResolveInvocation {
    pub target: ResolveTarget,
    pub case_id: String,
    pub title: String,
    pub because: Option<String>,
    pub context: JsonValue,
    pub expect: ResolveExpectation,
}

#[derive(Clone, Debug)]
pub enum ResolveTarget {
    Variable(String),
    Qualifier(String),
}

impl ResolveTarget {
    /// The `kind:id` label used in headers and JSON output.
    pub fn label(&self) -> String {
        match self {
            Self::Variable(id) => format!("variable:{id}"),
            Self::Qualifier(id) => format!("qualifier:{id}"),
        }
    }

    /// The resolve selector flag that targets this entity.
    pub fn selector_flag(&self) -> &'static str {
        match self {
            Self::Variable(_) => "--variable",
            Self::Qualifier(_) => "--qualifier",
        }
    }

    pub fn id(&self) -> &str {
        match self {
            Self::Variable(id) | Self::Qualifier(id) => id,
        }
    }
}

/// The expected result of a printed invocation, used to annotate each command
/// with its resolution outcome.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ResolveExpectation {
    Variable {
        value: JsonValue,
        matched: MatchedBy,
    },
    Qualifier {
        value: bool,
    },
}

#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum MatchedBy {
    Default,
    Rule { index: usize, condition: String },
}

pub async fn generate_resolve_invocations(
    package_source: impl AsRef<str>,
    source_options: &SourceOptions,
    selection: FixtureGenerateSelection,
) -> Result<Vec<ResolveInvocation>> {
    let package_source = package_source.as_ref();
    let selection = selection.normalized();
    let staged = stage_package_source(package_source.to_owned(), source_options).await?;
    let report =
        crate::inspect_package_report(staged.path(), PackageInspectRequest::default()).await?;

    let variable_ids = selected_variable_ids(&report, &selection.variables)?;
    let qualifier_ids = selected_qualifier_ids(&report, &selection.qualifiers)?;
    let factory = ContextFactory::new(&report);

    let mut invocations = Vec::new();

    for id in qualifier_ids {
        let qualifier = report
            .qualifiers
            .iter()
            .find(|qualifier| qualifier.id == id)
            .expect("selected qualifier id was validated");
        generate_qualifier_invocations(staged.path(), qualifier, &factory, &mut invocations)
            .await?;
    }

    for id in variable_ids {
        let variable = report
            .variables
            .iter()
            .find(|variable| variable.id == id)
            .expect("selected variable id was validated");
        generate_variable_invocations(staged.path(), variable, &factory, &mut invocations).await?;
    }

    Ok(invocations)
}

fn selected_variable_ids(
    report: &PackageInspectReport,
    selection: &FixtureTargetSelection,
) -> Result<Vec<String>> {
    selected_ids(
        selection,
        report.variables.iter().map(|variable| variable.id.as_str()),
        "variable",
    )
}

fn selected_qualifier_ids(
    report: &PackageInspectReport,
    selection: &FixtureTargetSelection,
) -> Result<Vec<String>> {
    selected_ids(
        selection,
        report
            .qualifiers
            .iter()
            .map(|qualifier| qualifier.id.as_str()),
        "qualifier",
    )
}

fn selected_ids<'a>(
    selection: &FixtureTargetSelection,
    available: impl Iterator<Item = &'a str>,
    kind: &str,
) -> Result<Vec<String>> {
    let available = available.map(str::to_owned).collect::<Vec<_>>();
    match selection {
        FixtureTargetSelection::None => Ok(Vec::new()),
        FixtureTargetSelection::All => Ok(available),
        FixtureTargetSelection::Some(ids) => {
            for id in ids {
                if !available.iter().any(|available| available == id) {
                    return Err(RototoError::new(format!("{kind} not found: {kind}://{id}")));
                }
            }
            Ok(available
                .into_iter()
                .filter(|id| ids.contains(id))
                .collect())
        }
    }
}

async fn generate_qualifier_invocations(
    package: &Path,
    qualifier: &QualifierInspectReport,
    factory: &ContextFactory,
    out: &mut Vec<ResolveInvocation>,
) -> Result<()> {
    let target = ResolveTarget::Qualifier(qualifier.id.clone());

    if let Some((context, trace)) =
        sampled_qualifier_context(package, &qualifier.id, true, factory).await?
    {
        out.push(ResolveInvocation {
            target: target.clone(),
            case_id: "matches".to_owned(),
            title: "Matches when the qualifier condition is true".to_owned(),
            because: Some(
                "An evaluation context sample satisfies the qualifier condition.".to_owned(),
            ),
            context,
            expect: ResolveExpectation::Qualifier { value: trace.value },
        });
    }

    if let Some((context, trace)) =
        sampled_qualifier_context(package, &qualifier.id, false, factory).await?
    {
        out.push(ResolveInvocation {
            target,
            case_id: "does-not-match".to_owned(),
            title: "Does not match when the qualifier condition is false".to_owned(),
            because: Some(
                "An evaluation context sample does not satisfy the qualifier condition.".to_owned(),
            ),
            context,
            expect: ResolveExpectation::Qualifier { value: trace.value },
        });
    }

    Ok(())
}

async fn generate_variable_invocations(
    package: &Path,
    variable: &VariableInspectReport,
    factory: &ContextFactory,
    out: &mut Vec<ResolveInvocation>,
) -> Result<()> {
    let target = ResolveTarget::Variable(variable.id.clone());

    if let Some(context) = variable_default_context(package, variable, factory).await? {
        let trace = trace_variable_resolution(package, &variable.id, &context).await?;
        if trace.rules.iter().any(|rule| rule.matched) {
            return Err(RototoError::new(format!(
                "generated default fixture matched a rule for variable: {}",
                variable.id
            )));
        }
        out.push(ResolveInvocation {
            target: target.clone(),
            case_id: "default".to_owned(),
            title: "Uses the default value when no rule matches".to_owned(),
            because: Some("Every rule condition is false.".to_owned()),
            context,
            expect: variable_expectation(&trace),
        });
    }

    for rule in &variable.resolve.rules {
        let Some(context) = variable_rule_context(package, variable, rule, factory).await? else {
            continue;
        };
        let trace = trace_variable_resolution(package, &variable.id, &context).await?;
        if !trace
            .rules
            .iter()
            .any(|trace_rule| trace_rule.index == rule.index && trace_rule.matched)
        {
            continue;
        }
        let condition = rule_condition_label(rule);
        let case_id = format!("rule-{}-{}", rule.index, sanitize_id(&condition));
        let title = format!(
            "Rule {} selects {} when {} matches",
            rule.index,
            rule.value
                .as_ref()
                .map(serde_json::Value::to_string)
                .unwrap_or_else(|| "<missing>".to_owned()),
            condition
        );
        out.push(ResolveInvocation {
            target: target.clone(),
            case_id,
            title,
            because: Some("Earlier rule conditions are kept false when possible.".to_owned()),
            context,
            expect: variable_expectation(&trace),
        });
    }

    Ok(())
}

fn variable_expectation(trace: &VariableResolutionTrace) -> ResolveExpectation {
    let matched = trace.rules.iter().find(|rule| rule.matched);
    ResolveExpectation::Variable {
        value: trace.resolution.value.clone(),
        matched: match matched {
            Some(rule) => MatchedBy::Rule {
                index: rule.index,
                condition: rule.condition.clone(),
            },
            None => MatchedBy::Default,
        },
    }
}

fn rule_condition_label(rule: &RulePathwayInspectReport) -> String {
    rule.when
        .as_deref()
        .or(rule.query.as_deref())
        .unwrap_or("<missing>")
        .to_owned()
}

/// The first candidate context that drives `rule` to win for `variable`.
/// Selection is by real resolution, so the rule under test must be the one that
/// actually matches (earlier rules kept false), not merely have a true `when`.
async fn variable_rule_context(
    package: &Path,
    variable: &VariableInspectReport,
    rule: &RulePathwayInspectReport,
    factory: &ContextFactory,
) -> Result<Option<JsonValue>> {
    for context in factory.candidate_contexts() {
        if let Ok(trace) = trace_variable_resolution(package, &variable.id, context).await
            && trace
                .rules
                .iter()
                .any(|trace_rule| trace_rule.index == rule.index && trace_rule.matched)
        {
            return Ok(Some(context.clone()));
        }
    }

    Ok(None)
}

/// The first candidate context under which no rule matches, so `variable`
/// resolves to its default.
async fn variable_default_context(
    package: &Path,
    variable: &VariableInspectReport,
    factory: &ContextFactory,
) -> Result<Option<JsonValue>> {
    for context in factory.candidate_contexts() {
        if let Ok(trace) = trace_variable_resolution(package, &variable.id, context).await
            && trace.rules.iter().all(|rule| !rule.matched)
        {
            return Ok(Some(context.clone()));
        }
    }

    Ok(None)
}

/// The first candidate context that drives `qualifier` to `desired`.
async fn sampled_qualifier_context(
    package: &Path,
    qualifier: &str,
    desired: bool,
    factory: &ContextFactory,
) -> Result<Option<(JsonValue, QualifierResolutionTrace)>> {
    for context in factory.candidate_contexts() {
        if let Ok(trace) = trace_qualifier_resolution(package, qualifier, context).await
            && trace.value == desired
        {
            return Ok(Some((context.clone(), trace)));
        }
    }

    Ok(None)
}

fn sanitize_id(value: &str) -> String {
    let mut sanitized = String::new();
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            sanitized.push(ch.to_ascii_lowercase());
        } else if matches!(ch, '-' | '_' | '.') {
            sanitized.push('-');
        }
    }
    let sanitized = sanitized.trim_matches('-').to_owned();
    if sanitized.is_empty() {
        "fixture".to_owned()
    } else {
        sanitized
    }
}