oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
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
//! Declarative version-key paths for [`super::json`] edits (ADR-0033).
//!
//! Segments are dotted. A bare name is an object key; a digit-only segment is
//! an array index; `{field=value}` selects the unique array element whose
//! `field` string equals `value`.

use std::fmt;

use jsonc_parser::cst::{CstArray, CstRootNode};

use super::json::{
    descend, jsonc_options, named_props, push_segment, replace_in, Cursor, JsonEditError,
};

/// One segment of a declared `key`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeySegment {
    /// Object property name, or a numeric array index as a string of digits.
    Name(String),
    /// Unique array element where `field` is the string `value`.
    Match { field: String, value: String },
}

/// Parse `plugins.{name=review-cycle}.version` into segments.
///
/// # Errors
///
/// Empty input, empty segments, malformed `{field=value}`, or a trailing dot.
pub fn parse_key_path(key: &str) -> Result<Vec<KeySegment>, KeyPathError> {
    if key.is_empty() {
        return Err(KeyPathError::Empty);
    }
    let mut segments = Vec::new();
    let mut rest = key;
    while !rest.is_empty() {
        if rest.starts_with('.') {
            return Err(KeyPathError::EmptySegment);
        }
        if rest.starts_with('{') {
            let Some(end) = rest.find('}') else {
                return Err(KeyPathError::UnclosedMatch);
            };
            let inner = &rest[1..end];
            let Some((field, value)) = inner.split_once('=') else {
                return Err(KeyPathError::BadMatch {
                    text: inner.to_owned(),
                });
            };
            if field.is_empty() || value.is_empty() {
                return Err(KeyPathError::BadMatch {
                    text: inner.to_owned(),
                });
            }
            if field.contains('{')
                || field.contains('}')
                || value.contains('{')
                || value.contains('}')
            {
                return Err(KeyPathError::BadMatch {
                    text: inner.to_owned(),
                });
            }
            segments.push(KeySegment::Match {
                field: field.to_owned(),
                value: value.to_owned(),
            });
            rest = &rest[end + 1..];
            if rest.is_empty() {
                break;
            }
            if !rest.starts_with('.') {
                return Err(KeyPathError::ExpectedDot);
            }
            rest = &rest[1..];
            continue;
        }
        let (name, after) = match rest.find('.') {
            Some(i) => {
                let after = &rest[i + 1..];
                if after.is_empty() {
                    return Err(KeyPathError::EmptySegment);
                }
                (&rest[..i], after)
            }
            None => (rest, ""),
        };
        if name.is_empty() {
            return Err(KeyPathError::EmptySegment);
        }
        if name.contains('{') || name.contains('}') {
            return Err(KeyPathError::BadName {
                text: name.to_owned(),
            });
        }
        segments.push(KeySegment::Name(name.to_owned()));
        rest = after;
    }
    if segments.is_empty() {
        return Err(KeyPathError::Empty);
    }
    Ok(segments)
}

/// Parse a key that must resolve to a replaceable string leaf (ADR-0033).
///
/// # Errors
///
/// Same as [`parse_key_path`], plus [`KeyPathError::MatchAsLeaf`] when the last
/// segment is `{field=value}`.
pub fn parse_write_key_path(key: &str) -> Result<Vec<KeySegment>, KeyPathError> {
    let segments = parse_key_path(key)?;
    if matches!(segments.last(), Some(KeySegment::Match { .. })) {
        return Err(KeyPathError::MatchAsLeaf);
    }
    Ok(segments)
}

#[cfg(test)]
fn resolve_json_key_path(text: &str, key: &str) -> Result<Vec<String>, KeyPathError> {
    resolve_in(&parse(text)?, key)
}

fn parse(text: &str) -> Result<CstRootNode, KeyPathError> {
    CstRootNode::parse(text, &jsonc_options()).map_err(|err| JsonEditError::from(err).into())
}

/// Resolve match segments against `root`, returning a path of bare names and
/// indexes for [`replace_in`]: missing paths, or zero or several matches, refuse.
fn resolve_in(root: &CstRootNode, key: &str) -> Result<Vec<String>, KeyPathError> {
    let segments = parse_write_key_path(key)?;
    let Some(root_obj) = root.object_value() else {
        return Err(JsonEditError::RootNotObject.into());
    };
    let mut cursor = Cursor::Object(root_obj);
    let mut resolved = Vec::new();
    let mut walked = String::new();
    let last = segments.len() - 1;
    for (i, segment) in segments.iter().enumerate() {
        let is_last = i == last;
        match segment {
            KeySegment::Name(name) => {
                if !is_last {
                    cursor = descend(cursor, name, &walked)?;
                    push_segment(&mut walked, name);
                }
                resolved.push(name.clone());
            }
            KeySegment::Match { field, value } => {
                if is_last {
                    return Err(KeyPathError::MatchAsLeaf);
                }
                let Cursor::Array(arr) = cursor else {
                    return Err(KeyPathError::MatchNotOnArray {
                        path: walked.clone(),
                    });
                };
                let index = match_index(&arr, field, value, &walked)?;
                let index_s = index.to_string();
                cursor = descend(Cursor::Array(arr), &index_s, &walked)?;
                push_segment(&mut walked, &index_s);
                resolved.push(index_s);
            }
        }
    }
    Ok(resolved)
}

/// Replace the string at `key` in `text` (ADR-0033). A missing final key is an error.
///
/// # Errors
///
/// When `key` does not parse, the document cannot be walked to a unique leaf,
/// or the leaf is not a replaceable string.
pub fn replace_json_at_key(text: &str, key: &str, next: &str) -> Result<String, KeyPathError> {
    let root = parse(text)?;
    let path = resolve_in(&root, key)?;
    let refs: Vec<&str> = path.iter().map(String::as_str).collect();
    replace_in(&root, &refs, next)?;
    Ok(root.to_string())
}

fn match_index(
    arr: &CstArray,
    field: &str,
    value: &str,
    walked: &str,
) -> Result<usize, KeyPathError> {
    let path = if walked.is_empty() {
        format!("{{{field}={value}}}")
    } else {
        format!("{walked}/{{{field}={value}}}")
    };
    let mut hits = Vec::new();
    for (index, elem) in arr.elements().into_iter().enumerate() {
        let Some(obj) = elem.as_object() else {
            continue;
        };
        let named = named_props(&obj, field);
        let prop = match named.as_slice() {
            [] => continue,
            [only] => only,
            _ => {
                return Err(JsonEditError::Duplicate {
                    path: format!("{path}[{index}]"),
                }
                .into());
            }
        };
        let Some(value_node) = prop.value() else {
            continue;
        };
        let Some(lit) = value_node.as_string_lit() else {
            continue;
        };
        let Ok(decoded) = lit.decoded_value() else {
            continue;
        };
        if decoded == value {
            hits.push(index);
        }
    }
    match hits.as_slice() {
        [only] => Ok(*only),
        [] => Err(KeyPathError::NoMatch { path }),
        _ => Err(KeyPathError::AmbiguousMatch { path }),
    }
}

#[derive(Debug)]
pub enum KeyPathError {
    Empty,
    EmptySegment,
    UnclosedMatch,
    ExpectedDot,
    BadMatch { text: String },
    BadName { text: String },
    MatchNotOnArray { path: String },
    NoMatch { path: String },
    AmbiguousMatch { path: String },
    MatchAsLeaf,
    Json(JsonEditError),
}

impl From<JsonEditError> for KeyPathError {
    fn from(err: JsonEditError) -> Self {
        Self::Json(err)
    }
}

impl fmt::Display for KeyPathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("extra-files key must not be empty"),
            Self::EmptySegment => f.write_str("extra-files key has an empty segment"),
            Self::UnclosedMatch => f.write_str("extra-files key has an unclosed `{field=value}`"),
            Self::ExpectedDot => f.write_str("extra-files key needs `.` after `}`"),
            Self::BadMatch { text } => {
                write!(f, "extra-files key has a bad match `{{{text}}}`")
            }
            Self::BadName { text } => write!(f, "extra-files key has a bad segment `{text}`"),
            Self::MatchNotOnArray { path } => {
                write!(
                    f,
                    "extra-files match at `{path}` requires an array to select from"
                )
            }
            Self::NoMatch { path } => write!(f, "extra-files match `{path}` found no element"),
            Self::AmbiguousMatch { path } => {
                write!(f, "extra-files match `{path}` found more than one element")
            }
            Self::MatchAsLeaf => f.write_str("extra-files key cannot end with `{field=value}`"),
            Self::Json(err) => write!(f, "{err}"),
        }
    }
}

impl std::error::Error for KeyPathError {}

#[cfg(test)]
mod tests {
    use super::{
        parse_key_path, parse_write_key_path, replace_json_at_key, resolve_json_key_path,
        KeySegment,
    };

    #[test]
    fn parse_dotted_and_match() {
        assert_eq!(
            parse_key_path("version").expect("parse"),
            vec![KeySegment::Name(String::from("version"))]
        );
        assert_eq!(
            parse_key_path("plugins.{name=review-cycle}.version").expect("parse"),
            vec![
                KeySegment::Name(String::from("plugins")),
                KeySegment::Match {
                    field: String::from("name"),
                    value: String::from("review-cycle"),
                },
                KeySegment::Name(String::from("version")),
            ]
        );
    }

    #[test]
    fn resolve_match_to_index() {
        let text = r#"{
  "plugins": [
    { "name": "other", "version": "0.1.0" },
    { "name": "review-cycle", "version": "0.14.0" }
  ]
}
"#;
        assert_eq!(
            resolve_json_key_path(text, "plugins.{name=review-cycle}.version").expect("resolve"),
            vec![
                String::from("plugins"),
                String::from("1"),
                String::from("version")
            ]
        );
    }

    #[test]
    fn replace_matched_version() {
        let text = r#"{
  "plugins": [
    { "name": "other", "version": "0.1.0" },
    { "name": "review-cycle", "version": "0.14.0" }
  ]
}
"#;
        let out = replace_json_at_key(text, "plugins.{name=review-cycle}.version", "0.15.0")
            .expect("replace");
        assert!(out.contains("\"version\": \"0.15.0\""));
        assert!(out.contains("\"name\": \"other\""));
        assert!(out.contains("\"version\": \"0.1.0\""));
    }

    #[test]
    fn no_match_and_ambiguous_are_errors() {
        let missing = r#"{ "plugins": [ { "name": "other", "version": "0.1.0" } ] }"#;
        let err = resolve_json_key_path(missing, "plugins.{name=review-cycle}.version")
            .expect_err("none");
        assert!(err.to_string().contains("found no element"), "{err}");
        let dup = r#"{
  "plugins": [
    { "name": "review-cycle", "version": "0.1.0" },
    { "name": "review-cycle", "version": "0.2.0" }
  ]
}"#;
        let err =
            resolve_json_key_path(dup, "plugins.{name=review-cycle}.version").expect_err("dup");
        assert!(err.to_string().contains("more than one element"), "{err}");
    }

    #[test]
    fn trailing_dot_and_match_leaf_are_errors() {
        assert!(parse_key_path("version.").is_err());
        assert!(matches!(
            parse_write_key_path("plugins.{name=review-cycle}"),
            Err(super::KeyPathError::MatchAsLeaf)
        ));
    }

    #[test]
    fn non_string_match_field_is_skipped() {
        let text = r#"{
  "plugins": [
    { "name": 42, "version": "9.9.9" },
    { "name": "review-cycle", "version": "0.14.0" }
  ]
}"#;
        assert_eq!(
            resolve_json_key_path(text, "plugins.{name=review-cycle}.version").expect("resolve"),
            vec![
                String::from("plugins"),
                String::from("1"),
                String::from("version")
            ]
        );
        let only_number = r#"{ "plugins": [ { "name": 42, "version": "0.1.0" } ] }"#;
        let err =
            resolve_json_key_path(only_number, "plugins.{name=42}.version").expect_err("none");
        assert!(err.to_string().contains("found no element"), "{err}");
    }

    #[test]
    fn duplicate_match_field_on_one_element_is_an_error() {
        let text = r#"{
  "plugins": [
    { "name": "review-cycle", "name": "other", "version": "0.14.0" }
  ]
}"#;
        let err =
            resolve_json_key_path(text, "plugins.{name=review-cycle}.version").expect_err("dup");
        assert!(
            err.to_string()
                .contains("JSON path `plugins/{name=review-cycle}[0]` has duplicate keys"),
            "{err}"
        );
    }

    #[test]
    fn match_on_object_is_an_error() {
        let text = r#"{ "plugins": { "name": "review-cycle", "version": "0.1.0" } }"#;
        let err =
            resolve_json_key_path(text, "plugins.{name=review-cycle}.version").expect_err("obj");
        assert!(err.to_string().contains("requires an array"), "{err}");
    }

    #[test]
    fn dotted_match_value_parses() {
        assert_eq!(
            parse_key_path("plugins.{name=foo.bar}.version").expect("parse"),
            vec![
                KeySegment::Name(String::from("plugins")),
                KeySegment::Match {
                    field: String::from("name"),
                    value: String::from("foo.bar"),
                },
                KeySegment::Name(String::from("version")),
            ]
        );
    }

    #[test]
    fn numeric_array_leaf_replaces_string() {
        let out = replace_json_at_key(
            "{\n  \"versions\": [\"0.1.0\", \"9.9.9\"]\n}\n",
            "versions.0",
            "0.2.0",
        )
        .expect("leaf");
        assert!(out.contains("\"0.2.0\""));
        assert!(out.contains("\"9.9.9\""));
    }
}