loopsmith-core 1.0.0

Config model and validation for loopsmith loops
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
//! Markdown document → `serde_yaml::Value` → `LoopConfig`.
//!
//! The parser is deliberately ignorant of the config model. It produces a
//! generic value tree and lets serde do the typing, so a new section needs an
//! entry in [`super::section_shape`] at most, and usually nothing at all.

use super::{heading_to_key, section_path, section_shape, SECTION_PATHS};
use crate::{CoreError, LoopConfig};
use serde_yaml::{Mapping, Value};

/// Walk to a dotted path inside `root`, creating intermediate mappings.
///
/// Sections live one level down now that the config is bundled — `## Goals`
/// writes `intent.goals` — so every place that used to reach for a top-level
/// key goes through here instead.
fn slot_at<'a>(root: &'a mut Mapping, path: &str) -> Result<&'a mut Value, String> {
    let mut parts = path.split('.').peekable();
    let mut cursor = root;
    loop {
        let part = parts.next().expect("a path has at least one segment");
        let key = Value::from(part);
        if parts.peek().is_none() {
            return Ok(cursor
                .entry(key)
                .or_insert(Value::Mapping(Mapping::new())));
        }
        let slot = cursor
            .entry(key)
            .or_insert_with(|| Value::Mapping(Mapping::new()));
        let Value::Mapping(next) = slot else {
            return Err(format!("`{path}` runs through a value that is not a section"));
        };
        cursor = next;
    }
}

/// The headings a `##` may carry, for an error message worth reading.
fn known_headings() -> String {
    SECTION_PATHS
        .iter()
        .map(|(_, _, heading)| *heading)
        .collect::<Vec<_>>()
        .join(", ")
}

#[derive(Debug)]
enum Tok {
    H1(String),
    H2(String),
    H3(String),
    Bullet { indent: usize, text: String },
}

/// Parse a markdown config.
pub fn parse_md(text: &str, origin: &str) -> Result<LoopConfig, CoreError> {
    parse_md_reporting(text, origin).map(|(cfg, _)| cfg)
}

/// [`parse_md`], additionally reporting which 0.3 keys were relocated.
pub fn parse_md_reporting(
    text: &str,
    origin: &str,
) -> Result<(LoopConfig, Vec<crate::config::legacy::Moved>), CoreError> {
    let toks = tokenize(text);
    let value = build_document(&toks).map_err(|e| CoreError::Parse {
        path: origin.to_string(),
        yaml: e,
        json: "not attempted: the file was read as markdown".into(),
    })?;
    // A legacy heading builds the 0.3 shape; this is what turns it into the
    // 1.0 one. It also picks up the per-key repairs — a bare trigger gaining
    // its `on:` wrapper, a node's `isolated: true` becoming an isolation
    // level — so the markdown path and the YAML path cannot disagree.
    let (value, moved) = crate::config::legacy::migrate(&value);
    serde_yaml::from_value::<LoopConfig>(value)
        .map(|cfg| (cfg, moved))
        .map_err(|e| CoreError::Parse {
            path: origin.to_string(),
            yaml: e.to_string(),
            json: "not attempted: the file was read as markdown".into(),
        })
}

/// Split the document into headings and bullets, folding indented
/// continuation lines into the bullet above them.
///
/// Anything else — paragraphs, tables, fenced blocks at the left margin — is
/// documentation and is dropped. That is the feature: the config explains
/// itself in the same file.
fn tokenize(text: &str) -> Vec<Tok> {
    let mut out: Vec<Tok> = Vec::new();
    let mut fenced = false;
    let mut last_bullet_indent: Option<usize> = None;
    let mut after_blank = false;

    for raw in text.lines() {
        let trimmed = raw.trim_start();
        let indent = raw.len() - trimmed.len();

        if trimmed.starts_with("```") && indent == 0 {
            fenced = !fenced;
            last_bullet_indent = None;
            continue;
        }
        if fenced {
            continue;
        }
        if trimmed.is_empty() {
            after_blank = true;
            continue;
        }

        if indent == 0 {
            if let Some(rest) = trimmed.strip_prefix("### ") {
                out.push(Tok::H3(rest.trim().to_string()));
                last_bullet_indent = None;
                after_blank = false;
                continue;
            }
            if let Some(rest) = trimmed.strip_prefix("## ") {
                out.push(Tok::H2(rest.trim().to_string()));
                last_bullet_indent = None;
                after_blank = false;
                continue;
            }
            if let Some(rest) = trimmed.strip_prefix("# ") {
                out.push(Tok::H1(rest.trim().to_string()));
                last_bullet_indent = None;
                after_blank = false;
                continue;
            }
        }

        if let Some(rest) = trimmed.strip_prefix("- ") {
            out.push(Tok::Bullet {
                indent,
                text: rest.trim_end().to_string(),
            });
            last_bullet_indent = Some(indent);
            after_blank = false;
            continue;
        }

        // A non-bullet line indented past the bullet above it, with no blank
        // line in between, continues that bullet's value. This is how a long
        // `instruction` spans several lines without becoming prose.
        if let Some(bi) = last_bullet_indent {
            if !after_blank && indent > bi {
                if let Some(Tok::Bullet { text, .. }) = out.last_mut() {
                    text.push('\n');
                    text.push_str(trimmed.trim_end());
                    continue;
                }
            }
        }

        // Anything else is prose.
        last_bullet_indent = None;
        after_blank = false;
    }
    out
}

/// Assemble the token stream into the config mapping.
fn build_document(toks: &[Tok]) -> Result<Value, String> {
    let mut root = Mapping::new();
    // The section currently open, and the entry currently open inside it.
    let mut section: Option<String> = None;
    let mut entry: Option<Mapping> = None;

    let mut i = 0usize;
    while i < toks.len() {
        match &toks[i] {
            Tok::H1(name) => {
                flush_entry(&mut root, &section, &mut entry)?;
                root.insert(Value::from("name"), Value::from(name.clone()));
                i += 1;
            }
            Tok::H2(heading) => {
                flush_entry(&mut root, &section, &mut entry)?;
                let key = heading_to_key(heading);
                // Resolving here rather than letting an unknown key fall
                // through to `deny_unknown_fields` is worth the extra table
                // lookup: serde can only say "unknown field `goles`", while
                // this can say which headings exist.
                let path = section_path(&key).ok_or_else(|| {
                    format!(
                        "`## {heading}` is not a config section. Known sections are: {}",
                        known_headings()
                    )
                })?;
                section = Some(path.to_string());
                i += 1;
            }
            Tok::H3(heading) => {
                flush_entry(&mut root, &section, &mut entry)?;
                let Some(sec) = section.as_deref() else {
                    return Err(format!(
                        "`### {heading}` appears before any `##` section heading"
                    ));
                };
                let shape = section_shape(sec).ok_or_else(|| {
                    format!("section `{sec}` does not take `###` entries; use bullets")
                })?;
                let mut m = Mapping::new();
                // A heading is always a string, never re-interpreted as YAML.
                // `### Recorded the baseline: test count, coverage` would
                // otherwise parse as a one-entry mapping and land on a field
                // that wanted text.
                super::nested_insert(&mut m, shape.key_field, Value::from(heading.to_string()));
                entry = Some(m);
                i += 1;
            }
            Tok::Bullet { indent, .. } => {
                let base = *indent;
                let end = toks[i..]
                    .iter()
                    .position(|t| !matches!(t, Tok::Bullet { .. }))
                    .map(|p| i + p)
                    .unwrap_or(toks.len());
                let block: Vec<(usize, &str)> = toks[i..end]
                    .iter()
                    .map(|t| match t {
                        Tok::Bullet { indent, text } => (*indent, text.as_str()),
                        _ => unreachable!("filtered above"),
                    })
                    .collect();
                let (value, _) = build_block(&block, 0, base)?;

                match (&mut entry, section.as_deref()) {
                    // Bullets inside a `###` entry are that entry's fields.
                    (Some(m), _) => merge_into(m, value)?,
                    // Bullets directly under a `##` section are the section.
                    (None, Some(sec)) => {
                        let slot = slot_at(&mut root, sec)?;
                        match slot {
                            Value::Mapping(m) => merge_into(m, value)?,
                            _ => return Err(format!("section `{sec}` already holds a list")),
                        }
                    }
                    // Bullets before any section are top-level fields.
                    (None, None) => merge_into(&mut root, value)?,
                }
                i = end;
            }
        }
    }
    flush_entry(&mut root, &section, &mut entry)?;
    Ok(Value::Mapping(root))
}

/// Append a finished `###` entry to its section's list.
fn flush_entry(
    root: &mut Mapping,
    section: &Option<String>,
    entry: &mut Option<Mapping>,
) -> Result<(), String> {
    let Some(m) = entry.take() else {
        return Ok(());
    };
    let sec = section
        .as_deref()
        .ok_or_else(|| "an entry was written outside any section".to_string())?;
    let shape = section_shape(sec).ok_or_else(|| format!("section `{sec}` takes no entries"))?;

    let target = match shape.list_field {
        // e.g. `execution.graph` holds its entries under `…graph.nodes`.
        Some(field) => {
            let slot = slot_at(root, sec)?;
            let Value::Mapping(section_map) = slot else {
                return Err(format!("section `{sec}` should be a mapping"));
            };
            section_map
                .entry(Value::from(field))
                .or_insert(Value::Sequence(vec![]))
        }
        // e.g. `intent.goals` *is* the list.
        None => {
            let slot = slot_at(root, sec)?;
            // `slot_at` creates an empty mapping for a path that did not
            // exist; a list section wants a sequence there instead.
            if slot.as_mapping().is_some_and(|m| m.is_empty()) {
                *slot = Value::Sequence(vec![]);
            }
            slot
        }
    };
    match target {
        Value::Sequence(seq) => seq.push(Value::Mapping(m)),
        _ => return Err(format!("section `{sec}` already holds a mapping")),
    }
    Ok(())
}

fn merge_into(target: &mut Mapping, value: Value) -> Result<(), String> {
    match value {
        Value::Mapping(m) => {
            for (k, v) in m {
                merge_key(target, k, v);
            }
            Ok(())
        }
        _ => Err("expected `- key: value` bullets here, found a bare list".into()),
    }
}

/// Insert one key, merging rather than replacing when both sides are mappings.
///
/// A shallow insert is wrong wherever a `###` heading fills in a nested field.
/// A trigger's heading writes `on.type`, and the `- on:` bullet beneath it then
/// arrives carrying only `expr` — replacing outright would drop the `type` the
/// heading just placed, and the entry fails to parse with `missing field
/// type` pointing at a document that plainly says `### cron`.
fn merge_key(target: &mut Mapping, key: Value, value: Value) {
    if let (Some(Value::Mapping(existing)), Value::Mapping(incoming)) =
        (target.get_mut(&key), &value)
    {
        for (k, v) in incoming.clone() {
            merge_key(existing, k, v);
        }
        return;
    }
    target.insert(key, value);
}

/// Turn one indentation level of bullets into a mapping or a sequence.
///
/// Returns the built value and the index just past the block it consumed.
fn build_block(
    lines: &[(usize, &str)],
    start: usize,
    indent: usize,
) -> Result<(Value, usize), String> {
    let mut map = Mapping::new();
    let mut seq: Vec<Value> = Vec::new();
    let mut i = start;

    while i < lines.len() {
        let (ind, text) = lines[i];
        if ind < indent {
            break;
        }
        if ind > indent {
            return Err(format!("unexpected extra indentation before `- {text}`"));
        }

        match split_field(text) {
            Some((key, "")) => {
                // A key with no value owns the deeper bullets below it.
                let child_indent = lines.get(i + 1).map(|(n, _)| *n).unwrap_or(indent);
                if child_indent > indent {
                    let (child, next) = build_block(lines, i + 1, child_indent)?;
                    map.insert(scalar(key), child);
                    i = next;
                } else {
                    // Nothing below: an explicitly empty value.
                    map.insert(scalar(key), Value::Null);
                    i += 1;
                }
            }
            Some((key, rest)) => {
                map.insert(scalar(key), scalar(rest));
                i += 1;
            }
            None => {
                seq.push(scalar(text));
                i += 1;
            }
        }
    }

    if !map.is_empty() && !seq.is_empty() {
        return Err("a bullet list mixes `key: value` entries with bare items".into());
    }
    if map.is_empty() && !seq.is_empty() {
        return Ok((Value::Sequence(seq), i));
    }
    Ok((Value::Mapping(map), i))
}

/// Split `key: value` when the text really is a field rather than prose.
///
/// The guard on spaces is what keeps `- Never git stash. Never git reset.`
/// from being read as a field named `Never git stash. Never git reset.`.
fn split_field(text: &str) -> Option<(&str, &str)> {
    let (key, rest) = match text.split_once(": ") {
        Some((k, v)) => (k, v.trim()),
        None => (text.strip_suffix(':')?, ""),
    };
    let key = key.trim();
    if key.is_empty() || key.contains(char::is_whitespace) {
        return None;
    }
    Some((key, rest))
}

/// Interpret a scalar the way YAML would, so `12`, `true`, and `[a, b]` arrive
/// as the types they look like. Multi-line values stay verbatim strings —
/// prose with a colon in it is not a mapping.
fn scalar(text: &str) -> Value {
    if text.contains('\n') {
        return Value::from(text.to_string());
    }
    serde_yaml::from_str::<Value>(text).unwrap_or_else(|_| Value::from(text.to_string()))
}