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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Cluster identifiers (§6.1 of `docs/design.md`).
//!
//! A [`ClusterId`] is an ordered list of `axis:value` segments, comma-separated
//! when rendered. Values containing `,`, `:`, or `"` are quoted with double
//! quotes; embedded `"` is escaped as `""` (CSV-style).
//!
//! Both the canonical comma form and the structured `axis=value` repeat form
//! parse into the same value, and round-trip through [`fmt::Display`].

use std::fmt::{self, Write as _};
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A single `axis:value` pair within a [`ClusterId`].
///
/// `ClusterIdSegment` is `#[non_exhaustive]` — construct values via
/// [`ClusterIdSegment::new`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ClusterIdSegment {
    /// Axis name (e.g. `file`, `score`).
    pub axis: String,
    /// Value within that axis (e.g. `src/cli.rs`, `excellent`).
    pub value: String,
}

impl ClusterIdSegment {
    /// Construct a segment from any types that convert into `String`.
    ///
    /// `ClusterIdSegment` is `#[non_exhaustive]`; downstream callers
    /// (notably integration tests) build segments through this
    /// constructor.
    ///
    /// # Examples
    ///
    /// ```
    /// use face_core::ClusterIdSegment;
    ///
    /// let s = ClusterIdSegment::new("file", "src/cli.rs");
    /// assert_eq!(s.axis, "file");
    /// assert_eq!(s.value, "src/cli.rs");
    /// ```
    pub fn new(axis: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            axis: axis.into(),
            value: value.into(),
        }
    }
}

/// Ordered list of `axis:value` segments identifying a cluster's path
/// from the root.
///
/// The empty id (`ClusterId::default()`) addresses the root, before any
/// axis has been applied.
///
/// # Examples
///
/// ```
/// use face_core::ClusterId;
///
/// let id: ClusterId = "file:src/cli.rs,score:excellent".parse().unwrap();
/// assert_eq!(id.depth(), 2);
/// assert_eq!(id.to_string(), "file:src/cli.rs,score:excellent");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct ClusterId(Vec<ClusterIdSegment>);

impl ClusterId {
    /// Construct a new cluster id from an ordered segment list.
    pub fn new(segments: Vec<ClusterIdSegment>) -> Self {
        Self(segments)
    }

    /// Borrow the underlying segments in nesting order.
    pub fn segments(&self) -> &[ClusterIdSegment] {
        &self.0
    }

    /// Number of segments. The root id has depth `0`.
    pub fn depth(&self) -> usize {
        self.0.len()
    }

    /// `true` when this id has no segments (i.e. addresses the root).
    pub fn is_root(&self) -> bool {
        self.0.is_empty()
    }

    /// Return a new id with the last segment dropped, or `None` if this
    /// id is already the root.
    pub fn parent(&self) -> Option<ClusterId> {
        if self.0.is_empty() {
            None
        } else {
            Some(ClusterId(self.0[..self.0.len() - 1].to_vec()))
        }
    }

    /// Parse the canonical comma form (§6.1).
    ///
    /// A single-segment bare form (no `:`) is valid — the segment's
    /// axis is left as the empty string and the CLI fills it in at
    /// bind-time. The bare form is allowed only when there is exactly
    /// one segment; mixing bare with multi-segment input is an error.
    ///
    /// # Errors
    ///
    /// Returns [`ClusterIdError`] if the input is empty, mixes bare
    /// and `axis:value` forms, has an explicit empty axis (`:value`),
    /// or contains an unterminated quoted value.
    ///
    /// # Examples
    ///
    /// ```
    /// use face_core::ClusterId;
    ///
    /// let id = ClusterId::parse_canonical("file:src/cli.rs,score:excellent").unwrap();
    /// assert_eq!(id.depth(), 2);
    ///
    /// // Bare single-segment form: axis is empty, CLI fills at bind-time.
    /// let bare = ClusterId::parse_canonical("excellent").unwrap();
    /// assert_eq!(bare.segments()[0].axis, "");
    /// assert_eq!(bare.segments()[0].value, "excellent");
    /// ```
    pub fn parse_canonical(s: &str) -> Result<Self, ClusterIdError> {
        if s.is_empty() {
            return Err(ClusterIdError::Empty);
        }
        let mut segments = Vec::new();
        let mut chars = s.chars().peekable();
        let mut segment_idx = 0usize;

        loop {
            // A leading `"` starts a bare quoted value (no axis).
            if segment_idx == 0 && chars.peek() == Some(&'"') {
                let value = read_value(&mut chars, segment_idx)?;
                segments.push(ClusterIdSegment {
                    axis: String::new(),
                    value,
                });
                match chars.next() {
                    None => break,
                    // Bare form is only allowed when there's exactly
                    // one segment. A trailing `,` means we're mixing
                    // bare with multi-segment.
                    Some(',') => {
                        return Err(ClusterIdError::MissingSeparator { segment: 0 });
                    }
                    Some(other) => {
                        return Err(ClusterIdError::GarbageAfterQuote {
                            segment: segment_idx,
                            ch: other,
                        });
                    }
                }
            }

            let (axis, after_colon) = read_axis(&mut chars, segment_idx)?;

            if !after_colon {
                // No `:` was seen.
                //
                // - At idx 0 with content and end-of-input, it's the
                //   bare single-segment form: store as
                //   { axis: "", value: <axis-buffer> } and we're done.
                // - At idx > 0 with empty input (e.g. trailing comma
                //   leaving nothing to read), it's an empty trailing
                //   segment: surface as `EmptyAxis`.
                // - Anywhere else (mixed bare-with-multi or an axis
                //   without `:` at idx > 0), surface as
                //   `MissingSeparator`.
                if segment_idx == 0 && chars.peek().is_none() && !axis.is_empty() {
                    segments.push(ClusterIdSegment {
                        axis: String::new(),
                        value: axis,
                    });
                    break;
                }
                if axis.is_empty() {
                    return Err(ClusterIdError::EmptyAxis {
                        segment: segment_idx,
                    });
                }
                return Err(ClusterIdError::MissingSeparator {
                    segment: segment_idx,
                });
            }

            // We saw a `:`. An empty axis here means explicit `:value`
            // form, which is not the bare form (bare form has no `:`).
            if axis.is_empty() {
                return Err(ClusterIdError::EmptyAxis {
                    segment: segment_idx,
                });
            }

            let value = read_value(&mut chars, segment_idx)?;
            segments.push(ClusterIdSegment { axis, value });

            match chars.next() {
                None => break,
                Some(',') => {
                    segment_idx += 1;
                    continue;
                }
                Some(other) => {
                    // read_value consumed up to either ',' or end; any
                    // other char here means a stray unquoted character.
                    return Err(ClusterIdError::GarbageAfterQuote {
                        segment: segment_idx,
                        ch: other,
                    });
                }
            }
        }

        Ok(ClusterId(segments))
    }

    /// Parse a list of structured `axis=value` parts (§6.2).
    ///
    /// Each part is a single `axis=value` pair; the order of parts is
    /// preserved as the nesting order.
    ///
    /// # Errors
    ///
    /// Returns [`ClusterIdError::StructuredMissingEquals`] if any part
    /// has no `=` separator, [`ClusterIdError::EmptyAxis`] if a part
    /// has an empty axis side, and [`ClusterIdError::Empty`] if no
    /// parts are supplied.
    pub fn parse_structured<I, S>(parts: I) -> Result<Self, ClusterIdError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut segments = Vec::new();
        for (idx, part) in parts.into_iter().enumerate() {
            let part_str = part.as_ref();
            let Some((axis, value)) = part_str.split_once('=') else {
                return Err(ClusterIdError::StructuredMissingEquals {
                    segment: part_str.to_string(),
                });
            };
            if axis.is_empty() {
                return Err(ClusterIdError::EmptyAxis { segment: idx });
            }
            segments.push(ClusterIdSegment {
                axis: axis.to_string(),
                value: value.to_string(),
            });
        }
        if segments.is_empty() {
            return Err(ClusterIdError::Empty);
        }
        Ok(ClusterId(segments))
    }
}

impl fmt::Display for ClusterId {
    /// Emit the canonical comma form with §6.1 CSV-style quoting:
    /// values containing `,`, `:`, or `"` are wrapped in double quotes;
    /// double quotes inside are escaped as `""`.
    ///
    /// A single-segment id whose axis is empty emits just the value
    /// (no `:` prefix), matching the bare form accepted by
    /// [`Self::parse_canonical`] so that
    /// `parse_canonical(&id.to_string()) == Ok(id)` round-trips.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Bare form: exactly one segment with an empty axis.
        if self.0.len() == 1 && self.0[0].axis.is_empty() {
            return write_value(f, &self.0[0].value);
        }
        for (i, seg) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str(",")?;
            }
            // axis is never quoted in this spec.
            f.write_str(&seg.axis)?;
            f.write_str(":")?;
            write_value(f, &seg.value)?;
        }
        Ok(())
    }
}

impl FromStr for ClusterId {
    type Err = ClusterIdError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_canonical(s)
    }
}

impl Serialize for ClusterId {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for ClusterId {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

/// Errors returned while parsing a [`ClusterId`].
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClusterIdError {
    /// The input was the empty string (or empty structured-parts list).
    #[error("empty cluster id")]
    Empty,
    /// A segment had an axis but no `:` separator before the value.
    #[error("missing `:` separator at segment {segment}")]
    MissingSeparator {
        /// Zero-based index of the offending segment.
        segment: usize,
    },
    /// A quoted value did not have a closing `"`.
    #[error("unterminated quoted value at segment {segment}")]
    UnterminatedQuote {
        /// Zero-based index of the offending segment.
        segment: usize,
    },
    /// A segment had an empty axis side.
    #[error("empty axis at segment {segment}")]
    EmptyAxis {
        /// Zero-based index of the offending segment.
        segment: usize,
    },
    /// A character other than `,` followed a closing quote.
    #[error("unexpected character `{ch}` after closing quote at segment {segment}")]
    GarbageAfterQuote {
        /// Zero-based index of the offending segment.
        segment: usize,
        /// The unexpected character.
        ch: char,
    },
    /// A structured-form part lacked the required `=` separator.
    #[error("structured segment `{segment}` missing `=` separator")]
    StructuredMissingEquals {
        /// The offending part as supplied by the caller.
        segment: String,
    },
}

// ---------- private helpers ----------

/// Read an axis up to the first `:`. Returns the collected axis and
/// whether a `:` was actually consumed (i.e. not end-of-input or `,`).
fn read_axis(
    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    segment_idx: usize,
) -> Result<(String, bool), ClusterIdError> {
    let mut axis = String::new();
    while let Some(&c) = chars.peek() {
        match c {
            ':' => {
                chars.next();
                return Ok((axis, true));
            }
            ',' => {
                // axis with no `:` — surface a missing-separator error.
                return Err(ClusterIdError::MissingSeparator {
                    segment: segment_idx,
                });
            }
            _ => {
                axis.push(c);
                chars.next();
            }
        }
    }
    Ok((axis, false))
}

/// Read a value starting at the current position. Stops at the first
/// unquoted `,` or end-of-input. Handles `"..."` quoted values with
/// `""` escapes.
fn read_value(
    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    segment_idx: usize,
) -> Result<String, ClusterIdError> {
    let mut value = String::new();
    if chars.peek() == Some(&'"') {
        chars.next(); // consume opening quote
        loop {
            match chars.next() {
                None => {
                    return Err(ClusterIdError::UnterminatedQuote {
                        segment: segment_idx,
                    });
                }
                Some('"') => {
                    if chars.peek() == Some(&'"') {
                        chars.next();
                        value.push('"');
                    } else {
                        // closing quote consumed; caller decides what
                        // follows (must be ',' or end-of-input).
                        return Ok(value);
                    }
                }
                Some(c) => value.push(c),
            }
        }
    } else {
        while let Some(&c) = chars.peek() {
            if c == ',' {
                break;
            }
            value.push(c);
            chars.next();
        }
        Ok(value)
    }
}

/// Write `value` with §6.1 quoting rules.
fn write_value(f: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result {
    let needs_quote = value.contains([',', ':', '"']);
    if !needs_quote {
        return f.write_str(value);
    }
    f.write_str("\"")?;
    for c in value.chars() {
        if c == '"' {
            f.write_str("\"\"")?;
        } else {
            f.write_char(c)?;
        }
    }
    f.write_str("\"")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_two_axis_canonical() {
        let id = ClusterId::parse_canonical("file:src/cli.rs,score:excellent").unwrap();
        assert_eq!(id.depth(), 2);
        assert_eq!(id.segments()[0].axis, "file");
        assert_eq!(id.segments()[0].value, "src/cli.rs");
        assert_eq!(id.segments()[1].axis, "score");
        assert_eq!(id.segments()[1].value, "excellent");
    }

    #[test]
    fn round_trips_via_display() {
        let s = "file:src/cli.rs,score:excellent";
        let id: ClusterId = s.parse().unwrap();
        assert_eq!(id.to_string(), s);
    }

    #[test]
    fn quotes_values_with_special_chars() {
        let id = ClusterId::new(vec![ClusterIdSegment {
            axis: "file".into(),
            value: "a,b:c\"d".into(),
        }]);
        let rendered = id.to_string();
        assert_eq!(rendered, "file:\"a,b:c\"\"d\"");
        let round: ClusterId = rendered.parse().unwrap();
        assert_eq!(round, id);
    }

    #[test]
    fn parses_structured_form() {
        let id = ClusterId::parse_structured(["file=src/cli.rs", "score=excellent"]).unwrap();
        assert_eq!(id.depth(), 2);
        assert_eq!(id.segments()[1].value, "excellent");
    }

    #[test]
    fn rejects_empty_string() {
        let err = ClusterId::parse_canonical("").unwrap_err();
        assert_eq!(err, ClusterIdError::Empty);
    }

    #[test]
    fn parses_bare_single_segment() {
        let id = ClusterId::parse_canonical("excellent").unwrap();
        assert_eq!(id.segments().len(), 1);
        assert_eq!(id.segments()[0].axis, "");
        assert_eq!(id.segments()[0].value, "excellent");
        assert_eq!(id.to_string(), "excellent");
    }

    #[test]
    fn rejects_mixed_bare_with_multi() {
        let err = ClusterId::parse_canonical("excellent,file:src/cli.rs").unwrap_err();
        assert_eq!(err, ClusterIdError::MissingSeparator { segment: 0 });
    }
}