face-core 0.1.0

Core grouping, clustering, and paging primitives for the face CLI.
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
//! Integration tests for the `ClusterId` public surface (§6 of `docs/design.md`).
//!
//! These tests pin the canonical-string and structured parsing rules,
//! quoting/escaping behavior, the error matrix, and serde round-trips
//! for the `face_core::ClusterId` newtype. The contract under test is the
//! architect's locked surface — see the test-writer brief and §6.1 of
//! `docs/design.md`.

use face_core::{ClusterId, ClusterIdError, ClusterIdSegment};

/// Test helper: build a segment from two string slices.
fn seg(axis: &str, value: &str) -> ClusterIdSegment {
    ClusterIdSegment::new(axis, value)
}

/// Test helper: build a `ClusterId` from a list of `(axis, value)` pairs.
fn id(pairs: &[(&str, &str)]) -> ClusterId {
    ClusterId::new(pairs.iter().map(|(a, v)| seg(a, v)).collect())
}

mod parse_canonical {
    //! §6.1 canonical-form parsing — comma-separated `axis:value` pairs.

    use super::*;

    /// Bare single-axis values have no `:`. The architect contract is
    /// that such a segment parses with an empty axis name; the CLI fills
    /// the axis at bind-time. **CONTRACT CONFLICT NOTE:** the developer's
    /// implementation rejects this with `MissingSeparator { segment: 0 }`.
    /// This test asserts the architect-spec'd behavior; if it fails, the
    /// orchestrator must reconcile the contract before merging.
    #[test]
    fn single_axis_bare() {
        let parsed = ClusterId::parse_canonical("excellent").expect("bare single-axis must parse");
        assert_eq!(parsed.segments(), [seg("", "excellent")]);
        assert_eq!(parsed.depth(), 1);
    }

    #[test]
    fn two_axis_bare() {
        let parsed = ClusterId::parse_canonical("file:src/cli.rs,score:excellent")
            .expect("two-axis bare must parse");
        assert_eq!(
            parsed.segments(),
            [seg("file", "src/cli.rs"), seg("score", "excellent")]
        );
        assert_eq!(parsed.depth(), 2);
    }

    #[test]
    fn three_axis_bare() {
        let parsed = ClusterId::parse_canonical("repo:oops-rs,file:src/cli.rs,score:excellent")
            .expect("three-axis bare must parse");
        assert_eq!(
            parsed.segments(),
            [
                seg("repo", "oops-rs"),
                seg("file", "src/cli.rs"),
                seg("score", "excellent"),
            ]
        );
    }

    #[test]
    fn value_with_comma() {
        // Quoting required because the value contains a literal comma.
        let parsed = ClusterId::parse_canonical(r#"file:"src/cli, alt.rs",score:excellent"#)
            .expect("quoted value with comma must parse");
        assert_eq!(
            parsed.segments(),
            [seg("file", "src/cli, alt.rs"), seg("score", "excellent"),]
        );
    }

    #[test]
    fn value_with_colon() {
        // Quoting required because the value contains a literal colon.
        let parsed =
            ClusterId::parse_canonical(r#"key:"a:b""#).expect("quoted value with colon must parse");
        assert_eq!(parsed.segments(), [seg("key", "a:b")]);
    }

    #[test]
    fn value_with_embedded_quote() {
        // CSV-style escaped quote: `""` inside a quoted value is one literal `"`.
        let parsed = ClusterId::parse_canonical(r#"key:"a""b""#)
            .expect("quoted value with embedded quote must parse");
        assert_eq!(parsed.segments(), [seg("key", "a\"b")]);
    }

    #[test]
    fn value_with_all_specials() {
        let parsed = ClusterId::parse_canonical(r#"key:"a,b:c""d""#)
            .expect("quoted value with comma+colon+quote must parse");
        assert_eq!(parsed.segments(), [seg("key", "a,b:c\"d")]);
    }
}

mod parse_structured {
    //! §6.2 structured-form parsing — `axis=value` parts, no quoting needed.

    use super::*;

    #[test]
    fn two_axis() {
        let parsed = ClusterId::parse_structured(["file=src/cli.rs", "score=excellent"])
            .expect("two-axis structured must parse");
        assert_eq!(
            parsed.segments(),
            [seg("file", "src/cli.rs"), seg("score", "excellent"),]
        );
    }

    #[test]
    fn value_with_equals() {
        // Split on the FIRST `=` only: subsequent `=` chars are literal.
        let parsed = ClusterId::parse_structured(["query=a=b"]).expect("value with `=` must parse");
        assert_eq!(parsed.segments(), [seg("query", "a=b")]);
    }

    #[test]
    fn value_with_comma_no_quoting_required() {
        // The structured form has no quoting needs: comma is not a separator here.
        let parsed = ClusterId::parse_structured(["file=src/cli, alt.rs"])
            .expect("value with comma must parse without quoting");
        assert_eq!(parsed.segments(), [seg("file", "src/cli, alt.rs")]);
    }

    // NOTE: the empty-structured-input case (`parse_structured([])`) is
    // intentionally **not** tested here: the orchestrator's contract
    // resolution chose the developer's behavior (returns `Err(Empty)`).
    // Empty-input error coverage lives in `mod errors::empty_input`
    // below for the canonical form; the structured form's empty-input
    // shape is identical and not separately pinned.
}

mod display_round_trip {
    //! For every curated id, `parse_canonical(&id.to_string()) == Ok(id)`.
    //!
    //! These cover bare values, every special char individually and in
    //! combination, the empty value, and multi-axis combinations.

    use super::*;

    fn assert_round_trip(label: &str, original: ClusterId) {
        let serialized = original.to_string();
        let reparsed = ClusterId::parse_canonical(&serialized)
            .unwrap_or_else(|e| panic!("[{label}] reparse of {serialized:?} failed: {e:?}"));
        assert_eq!(
            reparsed, original,
            "[{label}] round-trip mismatch via {serialized:?}",
        );
    }

    #[test]
    fn bare_values() {
        assert_round_trip(
            "two-axis-bare",
            id(&[("file", "src/cli.rs"), ("score", "excellent")]),
        );
    }

    #[test]
    fn value_with_comma() {
        assert_round_trip("comma", id(&[("file", "src/cli, alt.rs")]));
    }

    #[test]
    fn value_with_colon() {
        assert_round_trip("colon", id(&[("key", "a:b")]));
    }

    #[test]
    fn value_with_double_quote() {
        assert_round_trip("dquote", id(&[("key", "a\"b")]));
    }

    #[test]
    fn value_with_already_escaped_pair() {
        // Literal `""` inside the value (i.e. the value is the 2-char string `""`).
        // Round-tripping must preserve it.
        assert_round_trip("escaped-pair", id(&[("key", "\"\"")]));
    }

    #[test]
    fn value_with_all_three_specials() {
        assert_round_trip("all-three", id(&[("key", "a,b:c\"d")]));
    }

    /// Architect contract: `axis:""` represents an explicit empty value
    /// and round-trips. **CONTRACT NOTE:** the developer's parser stops a
    /// bare value at `,` or end-of-input — `axis:` (empty after `:`) is
    /// accepted as an empty value. This test pins that round-trip.
    #[test]
    fn empty_value() {
        // `axis:""` represents an explicit empty value. Round-trip preserves it.
        assert_round_trip("empty-value", id(&[("axis", "")]));
    }

    #[test]
    fn multi_axis_combinations() {
        assert_round_trip(
            "three-axis",
            id(&[
                ("repo", "oops-rs"),
                ("file", "src/cli.rs"),
                ("score", "excellent"),
            ]),
        );
        assert_round_trip(
            "three-axis-with-specials",
            id(&[("repo", "oops-rs, alt"), ("file", "a:b"), ("score", "x\"y")]),
        );
    }

    /// Bare single-segment round-trip: `[("", "excellent")]` displays as
    /// `excellent` (no `:` because the axis is empty) and re-parses back
    /// to the same id. This pins the architect's bare-single-axis form
    /// the developer is responsible for upholding in `parse_canonical`.
    #[test]
    fn single_segment_bare_value() {
        let original = ClusterId::new(vec![seg("", "excellent")]);
        assert_eq!(original.to_string(), "excellent");
        assert_round_trip("single-bare", original);
    }

    /// Bare single-segment with a quote-required value: the value
    /// contains `,`, so the rendered form is `"src/cli, alt.rs"` (no
    /// leading `axis:` because axis is empty), and that re-parses back.
    #[test]
    fn single_segment_bare_with_quote_required_value() {
        let original = ClusterId::new(vec![seg("", "src/cli, alt.rs")]);
        assert_eq!(original.to_string(), r#""src/cli, alt.rs""#);
        assert_round_trip("single-bare-quoted", original);
    }
}

mod errors {
    //! §6.1 / §6.2 error-matrix tests.

    use super::*;

    #[test]
    fn empty_input() {
        let err = ClusterId::parse_canonical("").expect_err("empty input must error");
        assert_eq!(err, ClusterIdError::Empty);
    }

    /// Multi-segment input with no `:` in any segment: e.g. `"abc,def"`.
    /// The first segment lacks a separator, surfaces as
    /// `MissingSeparator { segment: 0 }`.
    #[test]
    fn missing_separator_multi_segment_no_colons() {
        let err = ClusterId::parse_canonical("abc,def")
            .expect_err("comma-separated segments without `:` must error");
        match err {
            ClusterIdError::MissingSeparator { segment } => {
                assert_eq!(segment, 0, "first segment is the offender");
            }
            other => panic!("expected MissingSeparator, got {other:?}"),
        }
    }

    #[test]
    fn unterminated_quote() {
        let err = ClusterId::parse_canonical(r#"file:"src/cli.rs"#)
            .expect_err("unterminated quote must error");
        match err {
            ClusterIdError::UnterminatedQuote { segment } => {
                assert_eq!(segment, 0);
            }
            other => panic!("expected UnterminatedQuote, got {other:?}"),
        }
    }

    #[test]
    fn empty_axis() {
        let err = ClusterId::parse_canonical(":value").expect_err("empty axis must error");
        match err {
            ClusterIdError::EmptyAxis { segment } => {
                assert_eq!(segment, 0);
            }
            other => panic!("expected EmptyAxis, got {other:?}"),
        }
    }

    #[test]
    fn garbage_after_quote() {
        // After a closing `"`, trailing content other than `,` (next sep)
        // is malformed.
        let err = ClusterId::parse_canonical(r#"file:"x"y"#)
            .expect_err("garbage after closing quote must error");
        match err {
            ClusterIdError::GarbageAfterQuote { segment, ch } => {
                assert_eq!(segment, 0);
                assert_eq!(ch, 'y');
            }
            other => panic!("expected GarbageAfterQuote, got {other:?}"),
        }
    }

    /// `parse_structured` part lacking `=` errors. The architect's brief
    /// listed `StructuredMissingEquals { segment }` without pinning the
    /// field type; the developer chose `segment: String` (the offending
    /// part as supplied). This test verifies the error is raised and
    /// the part appears in the carried context, without pinning the
    /// String/usize choice.
    #[test]
    fn structured_missing_equals() {
        let err = ClusterId::parse_structured(["filewithoutequals"])
            .expect_err("structured part lacking `=` must error");
        match err {
            ClusterIdError::StructuredMissingEquals { ref segment } => {
                assert_eq!(
                    segment, "filewithoutequals",
                    "error carries the offending part",
                );
            }
            other => panic!("expected StructuredMissingEquals, got {other:?}"),
        }
    }
}

mod serde {
    //! `ClusterId` serializes as a JSON string equal to `to_string()`.

    use super::*;
    use ::serde::{Deserialize, Serialize};

    #[test]
    fn serialize_to_json_string() {
        let cid = id(&[("file", "src/cli.rs"), ("score", "excellent")]);
        let json = serde_json::to_string(&cid).expect("serialize");
        // String form: a JSON string whose contents equal `to_string()`.
        let expected = format!("\"{}\"", cid);
        assert_eq!(json, expected);
    }

    #[test]
    fn deserialize_from_json_string() {
        let cid = id(&[("file", "src/cli.rs"), ("score", "excellent")]);
        let json = serde_json::to_string(&cid).expect("serialize");
        let back: ClusterId = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, cid);
    }

    #[test]
    fn deserialize_from_quoted_value() {
        // A hand-written JSON string with embedded quoting must deserialize.
        let json = r#""file:\"src/cli, alt.rs\",score:excellent""#;
        let back: ClusterId = serde_json::from_str(json).expect("deserialize quoted value");
        assert_eq!(
            back.segments(),
            [seg("file", "src/cli, alt.rs"), seg("score", "excellent"),]
        );
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct Wrap {
        id: ClusterId,
    }

    #[test]
    fn round_trip_inside_struct() {
        // Mirrors how `ClusterId` rides inside `Cluster`/`FlatCluster`/`Page`.
        let original = Wrap {
            id: id(&[("file", "a,b"), ("score", "x\"y")]),
        };
        let json = serde_json::to_string(&original).expect("serialize wrap");
        let back: Wrap = serde_json::from_str(&json).expect("deserialize wrap");
        assert_eq!(back, original);
    }
}

mod helpers {
    //! `depth`, `is_root`, `parent`, and `FromStr`.

    use super::*;
    use std::str::FromStr;

    #[test]
    fn root_is_root() {
        let root = ClusterId::new(vec![]);
        assert_eq!(root.depth(), 0);
        assert!(root.is_root());
        assert_eq!(root.parent(), None);
    }

    #[test]
    fn parent_of_one_segment_is_root() {
        let one = id(&[("file", "src/cli.rs")]);
        let parent = one.parent().expect("one-segment id has a parent");
        assert!(parent.is_root());
        assert_eq!(parent.depth(), 0);
    }

    #[test]
    fn parent_of_three_segment_strips_last() {
        let three = id(&[
            ("repo", "oops-rs"),
            ("file", "src/cli.rs"),
            ("score", "excellent"),
        ]);
        let parent = three.parent().expect("three-segment id has a parent");
        assert_eq!(parent.depth(), 2);
        assert_eq!(
            parent.segments(),
            [seg("repo", "oops-rs"), seg("file", "src/cli.rs")]
        );
    }

    #[test]
    fn depth_and_is_root_smoke() {
        assert!(ClusterId::new(vec![]).is_root());
        assert!(!id(&[("a", "b")]).is_root());
        assert_eq!(id(&[("a", "b")]).depth(), 1);
        assert_eq!(id(&[("a", "b"), ("c", "d")]).depth(), 2);
    }

    #[test]
    fn from_str_matches_parse_canonical() {
        // `FromStr<Err = ClusterIdError>` is part of the contract.
        let via_from_str =
            ClusterId::from_str("file:src/cli.rs,score:excellent").expect("from_str ok");
        let via_parse = ClusterId::parse_canonical("file:src/cli.rs,score:excellent")
            .expect("parse_canonical ok");
        assert_eq!(via_from_str, via_parse);
    }

    #[test]
    fn from_str_propagates_error() {
        let err = ClusterId::from_str("").expect_err("empty must error");
        assert_eq!(err, ClusterIdError::Empty);
    }
}