mdbookkit 3.0.0

Support library for mdBook preprocessors in the mdbookkit project
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet},
    fmt::{Debug, Display},
    io::Write,
    ops::Range,
};

pub use annotate_snippets;
use annotate_snippets::{
    Annotation, AnnotationKind, Group, Message, Patch, Renderer, Snippet, renderer::DecorStyle,
};
use bon::Builder;
use tap::{Pipe, Tap};
use tracing::Level;

use crate::{
    emit_debug,
    env::{MDBOOKKIT_TERM_GRAPHICAL, TruthyStr, is_colored, is_logging},
    error::put_severity,
    level_enabled, lexicographic_ordering,
    logging::{EmitCallsite, stderr},
    util::{Lexicographic, LexicographicOrd},
};

#[derive(Builder, Debug)]
#[builder(start_fn = level)]
pub struct IssueReport<'a> {
    #[builder(start_fn)]
    level: IssueLevel,
    #[builder(into)]
    title: Cow<'a, str>,
    #[builder(default)]
    annotations: Vec<Highlight<'a>>,
    #[builder(default)]
    patches: Vec<Suggestion<'a>>,
    #[builder(default)]
    notes: Vec<Note<'a>>,
    #[builder(default)]
    secondary: Vec<IssueReport<'a>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IssueLevel {
    Error,
    Warning,
    Info,
    Help,
    Note,
}

#[derive(Builder, Debug)]
#[builder(start_fn = span)]
pub struct Highlight<'a> {
    #[builder(start_fn)]
    span: Range<usize>,
    kind: AnnotationKind,
    #[builder(into)]
    label: Option<Cow<'a, str>>,
}

#[derive(Builder, Debug)]
#[builder(start_fn = span)]
pub struct Suggestion<'a> {
    #[builder(start_fn)]
    span: Range<usize>,
    #[builder(into)]
    repl: Cow<'a, str>,
}

#[derive(Builder, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[builder(start_fn = level)]
pub struct Note<'a> {
    #[builder(start_fn)]
    level: IssueLevel,
    #[builder(into)]
    message: Cow<'a, str>,
}

#[must_use]
pub struct IssueReporter<'a> {
    pub issues: Vec<IssueReport<'a>>,
    pub source: SourceCode<'a>,
}

#[derive(Clone)]
pub struct SourceCode<'a> {
    pub source_code: &'a str,
    pub source_path: Cow<'a, str>,
}

impl<'a> IssueReporter<'a> {
    pub fn emit(self, emit: EmitCallsite) {
        let source = self.source.clone();
        if let Some(style) = is_graphical() {
            let renderer = if is_colored() {
                Renderer::styled()
            } else {
                Renderer::plain()
            }
            .decor_style(style);
            for report in (self.issues.into_iter())
                // filtering done manually
                .filter(|issue| emit.level_enabled(issue.level.into()))
                .inspect(|issue| put_severity(issue.level.into()))
                .map(|issue| issue_to_report(issue, source.clone()))
            {
                writeln!(stderr(), "{}\n", renderer.render(&report))
                    .or_else(emit_debug!("failed to print to stderr: {:?}"))
                    .ok();
            }
        } else {
            for issue in self.issues {
                // filtering done by tracing
                issue_to_traces(&issue, &source, &emit);
            }
        }
    }
}

fn is_graphical() -> Option<DecorStyle> {
    match MDBOOKKIT_TERM_GRAPHICAL.truthy() {
        None => {
            if is_logging() {
                None
            } else {
                Some(DecorStyle::Unicode)
            }
        }
        Some("ascii") => Some(DecorStyle::Ascii),
        Some(_) => Some(DecorStyle::Unicode),
    }
}

#[must_use]
pub fn issue_to_report<'a>(issue: IssueReport<'a>, source: SourceCode<'a>) -> Vec<Group<'a>> {
    macro_rules! snippet {
        ($items:ident, $kind:ident) => {{
            let mut is_empty = true;
            Snippet::source(source.source_code)
                .path(source.source_path.clone())
                .$kind(($items.$kind.into_iter().map(<_>::into)).inspect(|_| is_empty = false))
                .pipe(|v| if is_empty { None } else { Some(v) })
        }};
    }

    let mut sections = Vec::with_capacity(1 + issue.secondary.len());

    let primary = annotate_snippets::Level::from(issue.level)
        .primary_title(issue.title)
        .elements(snippet!(issue, annotations))
        .elements(snippet!(issue, patches))
        .elements(issue.notes.into_iter().map(Message::from));

    sections.push(primary);

    for issue in issue.secondary {
        let secondary = annotate_snippets::Level::from(issue.level)
            .secondary_title(issue.title)
            .elements(snippet!(issue, annotations))
            .elements(snippet!(issue, patches))
            .elements(issue.notes.into_iter().map(Message::from));

        sections.push(secondary);
    }

    sections
}

pub fn issue_to_traces<'a>(
    issue: &'a IssueReport<'a>,
    source: &'a SourceCode<'a>,
    emit: &EmitCallsite,
) {
    struct IssueFormatter<'a> {
        issue: &'a IssueReport<'a>,
        source: &'a SourceCode<'a>,
    }

    impl<'a> Display for IssueFormatter<'a> {
        fn fmt<'d>(&'d self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let Self { issue, source } = self;

            let IssueReport {
                title, annotations, ..
            } = issue;

            let path = &source.source_path;

            let span_info =
                |span: Option<&'d Highlight<'_>>| -> Option<(usize, usize, Option<&'d str>)> {
                    let Highlight { span, label, .. } = span?;
                    let (line, col) = byte_to_line_col(source.source_code, span.start)?;
                    Some((line, col, label.as_deref()))
                };

            if annotations.len() == 1 {
                if let Some((line, col, label)) = span_info(annotations.iter().next()) {
                    write!(f, "{path}:{line}:{col}: {title}")?;
                    if let Some(label) = label {
                        write!(f, ": {label}")?;
                    }
                } else {
                    write!(f, "{path}: {title}")?;
                }
            } else {
                if let Some((line, col, _)) = span_info(annotations.iter().next()) {
                    write!(f, "{path}:{line}:{col}: {title}")?;
                } else {
                    write!(f, "{path}: {title}")?;
                }
                for (line, col, label) in annotations.iter().filter_map(|span| {
                    let (line, col, label) = span_info(Some(span))?;
                    Some((line, col, label?))
                }) {
                    write!(f, "\n  {path}:{line}:{col}: {label}")?;
                }
            }

            Ok(())
        }
    }

    let level = issue.level;
    let formatter = IssueFormatter { issue, source };

    match level {
        IssueLevel::Error => (emit.error)(format_args!("{formatter}")),
        IssueLevel::Warning => (emit.warn)(format_args!("{formatter}")),
        IssueLevel::Info => (emit.info)(format_args!("{formatter}")),
        IssueLevel::Help => (emit.info)(format_args!("{formatter}")),
        IssueLevel::Note => (emit.debug)(format_args!("{formatter}")),
    }
}

impl<'a> IssueReport<'a> {
    #[inline(always)]
    pub fn if_enabled(level: IssueLevel) -> Option<IssueReportBuilder<'a>> {
        match level {
            IssueLevel::Error => {
                if level_enabled!(Level::ERROR) {
                    Some(Self::level(level))
                } else {
                    None
                }
            }
            IssueLevel::Warning => {
                if level_enabled!(Level::WARN) {
                    Some(Self::level(level))
                } else {
                    None
                }
            }
            IssueLevel::Info => {
                if level_enabled!(Level::INFO) {
                    Some(Self::level(level))
                } else {
                    None
                }
            }
            IssueLevel::Help => {
                if level_enabled!(Level::INFO) {
                    Some(Self::level(level))
                } else {
                    None
                }
            }
            IssueLevel::Note => {
                if level_enabled!(Level::DEBUG) {
                    Some(Self::level(level))
                } else {
                    None
                }
            }
        }
    }

    #[inline]
    pub fn annotations(&mut self, item: Highlight<'a>) -> &mut Self {
        self.annotations.push(item);
        self
    }

    #[inline]
    pub fn secondary(&mut self, item: IssueReport<'a>) -> &mut Self {
        self.secondary.push(item);
        self
    }

    #[inline]
    pub fn note(&mut self, note: Note<'a>) -> &mut Self {
        self.notes.push(note);
        self
    }

    pub fn iter_labels(&self) -> impl Iterator<Item = &str> {
        self.annotations
            .iter()
            .filter_map(|anno| anno.label.as_deref())
    }

    fn append(&mut self, other: &mut Self) -> &mut Self {
        self.annotations = self
            .annotations
            .drain(..)
            .chain(other.annotations.drain(..))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect();

        self.secondary = self
            .secondary
            .drain(..)
            .chain(other.secondary.drain(..))
            .collect::<Vec<_>>()
            .pipe(Self::merged);

        self
    }

    fn merged(mut issues: Vec<Self>) -> Vec<Self> {
        let mut deduped = BTreeMap::<_, Vec<_>>::new();
        for (index, issue) in issues.iter().enumerate() {
            deduped
                .entry(Lexicographic(IssueReportKey(issue)))
                .or_default()
                .push(index);
        }
        let indices = deduped
            .into_values()
            .collect::<Vec<_>>()
            .tap_mut(|indices| indices.sort());

        for indices in indices.iter() {
            let (issues, tail) = issues.split_at_mut(indices[0] + 1);
            let offset = issues.len();
            let head = &mut issues[indices[0]];
            for idx in &indices[1..] {
                head.append(&mut tail[*idx - offset]);
            }
        }

        let mut indices = indices.iter().peekable();
        issues
            .into_iter()
            .enumerate()
            .filter_map(|(idx, item)| {
                if indices.peek()?[0] == idx {
                    indices.next();
                    Some(item)
                } else {
                    None
                }
            })
            .collect()
    }

    fn sort_key(&self) -> impl Ord + use<> {
        let span = self
            .annotations
            .iter()
            .map(|anno| (anno.span.start, anno.span.end))
            .next();
        (self.level, span)
    }
}

impl<'a> IssueReporter<'a> {
    #[inline]
    pub fn sorted(issues: Vec<Self>) -> Vec<Self> {
        let mut sorted = vec![];

        for Self { issues, source } in issues {
            let mut levels = BTreeMap::<_, Vec<_>>::new();
            for issue in issues {
                let level = tracing::Level::from(issue.level);
                levels.entry(level).or_default().push(issue);
            }

            for (level, issues) in levels {
                let mut issues = IssueReport::merged(issues);
                issues.sort_by_key(|issue| issue.sort_key());
                sorted.push((level, issues, source.clone()));
            }
        }

        sorted.sort_by(|(level1, _, _), (level2, _, _)| level2.cmp(level1));

        sorted
            .into_iter()
            .map(|(_, issues, source)| Self { issues, source })
            .collect()
    }
}

impl<'a> Note<'a> {
    pub fn help(message: impl Into<Cow<'a, str>>) -> Self {
        Self::level(IssueLevel::Help).message(message).build()
    }

    #[allow(clippy::self_named_constructors)]
    pub fn note(message: impl Into<Cow<'a, str>>) -> Self {
        Self::level(IssueLevel::Note).message(message).build()
    }
}

impl<'a> Highlight<'a> {
    pub fn primary(span: Range<usize>, text: impl Into<Cow<'a, str>>) -> Self {
        Self::span(span)
            .kind(AnnotationKind::Primary)
            .label(text)
            .build()
    }

    pub fn context(span: Range<usize>, text: impl Into<Cow<'a, str>>) -> Self {
        Self::span(span)
            .kind(AnnotationKind::Context)
            .label(text)
            .build()
    }
}

impl<'a> From<Highlight<'a>> for Annotation<'a> {
    #[inline]
    fn from(this: Highlight<'a>) -> Self {
        let Highlight { span, kind, label } = this;
        let highlight = matches!(this.kind, AnnotationKind::Primary);
        kind.span(span).label(label).highlight_source(highlight)
    }
}

impl<'a> From<Suggestion<'a>> for Patch<'a> {
    #[inline]
    fn from(this: Suggestion<'a>) -> Self {
        Patch::new(this.span, this.repl)
    }
}

impl<'a> From<Note<'a>> for Message<'a> {
    #[inline]
    fn from(this: Note<'a>) -> Self {
        annotate_snippets::Level::from(this.level).message(this.message)
    }
}

impl From<IssueLevel> for annotate_snippets::Level<'static> {
    #[inline]
    fn from(value: IssueLevel) -> Self {
        match value {
            IssueLevel::Error => annotate_snippets::Level::ERROR,
            IssueLevel::Warning => annotate_snippets::Level::WARNING,
            IssueLevel::Info => annotate_snippets::Level::INFO,
            IssueLevel::Note => annotate_snippets::Level::NOTE,
            IssueLevel::Help => annotate_snippets::Level::HELP,
        }
    }
}

impl From<IssueLevel> for tracing::Level {
    #[inline]
    fn from(value: IssueLevel) -> Self {
        match value {
            IssueLevel::Error => tracing::Level::ERROR,
            IssueLevel::Warning => tracing::Level::WARN,
            IssueLevel::Info => tracing::Level::INFO,
            IssueLevel::Note => tracing::Level::DEBUG,
            IssueLevel::Help => tracing::Level::INFO,
        }
    }
}

fn byte_to_line_col(text: &str, byte: usize) -> Option<(usize, usize)> {
    if byte >= text.len() {
        return None;
    }
    let mut scanned = 0;
    for (line, text) in text.split('\n').enumerate() {
        if scanned + text.len() >= byte {
            let mut count = 0;
            for (column, (ch, _)) in text.char_indices().enumerate() {
                if scanned + ch >= byte {
                    return Some((line + 1, column + 1));
                } else {
                    count = ch;
                }
            }
            return Some((line + 1, count + 1));
        } else {
            scanned += text.len() + '\n'.len_utf8();
        }
    }
    None
}

struct IssueReportKey<'a>(&'a IssueReport<'a>);

impl LexicographicOrd for IssueReportKey<'_> {
    fn head(&self) -> impl Ord {
        (
            self.0.level,
            &self.0.title,
            &self.0.patches,
            &self.0.notes,
            (self.0.secondary)
                .iter()
                .map(|item| Lexicographic(Self(item)))
                .collect::<Vec<_>>(),
        )
    }
}

impl LexicographicOrd for &'_ Highlight<'_> {
    fn head(&self) -> impl Ord {
        (range_ord(&self.span), self.kind, &self.label)
    }
}

impl LexicographicOrd for &'_ Suggestion<'_> {
    fn head(&self) -> impl Ord {
        (range_ord(&self.span), &self.repl)
    }
}

lexicographic_ordering!(Highlight<'_>);
lexicographic_ordering!(Suggestion<'_>);

fn range_ord<T: Ord>(range: &Range<T>) -> impl Ord {
    (&range.start, &range.end)
}