docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Rustc style error display.
//!
//! A [`Diagnostic`] shows an error next to the template text that caused it,
//! with a caret under the offending span. Line numbers count paragraphs, so a
//! placement error points at a paragraph a person can find in the document
//! instead of at a byte offset.
//!
//! ```no_run
//! # fn example() -> docx_templating::Result<()> {
//! let bytes = std::fs::read("broken.docx")?;
//!
//! if let Err(error) = docx_templating::Template::from_bytes(bytes.clone()) {
//!     eprintln!("{}", docx_templating::diagnose(&bytes, &error));
//! }
//! # Ok(())
//! # }
//! ```
//!
//! The output looks like a compiler message:
//!
//! ```text
//! error: unclosed block in word/document.xml at 0..23
//!  --> word/document.xml:1:1
//!   |
//! 1 | {% for item in items %}
//!   | ^^^^^^^^^^^^^^^^^^^^^^^ this block is never closed
//!   |
//!   = help: add the matching closing tag before the enclosing block ends
//! ```

use std::fmt;
use std::ops::Range;

use crate::adapters::docx::parse_part;
use crate::domain::binding::text_view;
use crate::package::{PackageSource, ZipPackageSource};
use crate::{BindingError, Error, RenderError};

/// A multi line, compiler style rendering of an error.
///
/// Build one with [`diagnose`] for a template that failed to load, or with
/// [`Template::diagnostic`](crate::Template::diagnostic) for a template that
/// loaded but failed to render. The [`Display`](fmt::Display) implementation
/// is meant for a terminal or a log line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    message: String,
    part: Option<String>,
    line: Option<usize>,
    column: Option<usize>,
    snippet: Option<String>,
    caret: usize,
    label: Option<String>,
    help: Option<String>,
}

impl Diagnostic {
    /// The error message, without the snippet or the help line.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The DOCX part the error refers to, when the error names one.
    #[must_use]
    pub fn part(&self) -> Option<&str> {
        self.part.as_deref()
    }

    /// The one based line the caret points at, when a span was known.
    ///
    /// Lines count paragraphs in the rendered part, not text lines inside a
    /// paragraph.
    #[must_use]
    pub fn line(&self) -> Option<usize> {
        self.line
    }

    /// The one based character column of the caret, when a span was known.
    #[must_use]
    pub fn column(&self) -> Option<usize> {
        self.column
    }

    /// A hint on how to fix the error, when one is known.
    #[must_use]
    pub fn help(&self) -> Option<&str> {
        self.help.as_deref()
    }

    /// Build a diagnostic without a snippet.
    pub(crate) fn from_error(error: &Error) -> Self {
        Self::build(error, None)
    }

    /// Build a diagnostic against the template text.
    pub(crate) fn with_view(error: &Error, view: &View) -> Self {
        Self::build(error, Some(view))
    }

    fn build(error: &Error, view: Option<&View>) -> Self {
        let detail = Detail::of(error);
        let mut diagnostic = Self {
            message: message_of(error),
            part: detail.part.clone(),
            line: None,
            column: None,
            snippet: None,
            caret: 1,
            label: detail.label.map(str::to_owned),
            help: detail.help.clone(),
        };

        if let Some(view) = view
            && Some(view.part()) == detail.part.as_deref()
            && let Some(span) = detail.span.as_ref()
            && let Some(placed) = view.locate(span)
        {
            diagnostic.line = Some(placed.line);
            diagnostic.column = Some(placed.column);
            diagnostic.snippet = Some(placed.text);
            diagnostic.caret = placed.caret;
        }

        diagnostic
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = format!("error: {}", self.message);

        if let (Some(part), Some(line), Some(column)) =
            (self.part.as_deref(), self.line, self.column)
        {
            out.push_str(&format!("\n  --> {part}:{line}:{column}"));
        }

        if let (Some(snippet), Some(line), Some(column)) =
            (self.snippet.as_deref(), self.line, self.column)
        {
            let number = line.to_string();
            let pad = " ".repeat(number.len());
            let indent = " ".repeat(column.saturating_sub(1));
            let carets = "^".repeat(self.caret.max(1));

            out.push_str(&format!("\n{pad} |"));
            out.push_str(&format!("\n{number} | {snippet}"));
            out.push_str(&format!("\n{pad} | {indent}{carets}"));
            if let Some(label) = &self.label {
                out.push(' ');
                out.push_str(label);
            }
            out.push_str(&format!("\n{pad} |"));
            if let Some(help) = &self.help {
                out.push_str(&format!("\n{pad} = help: {help}"));
            }
        } else if let Some(help) = &self.help {
            out.push_str(&format!("\n   = help: {help}"));
        }

        f.write_str(&out)
    }
}

/// The error message without the top level wrapper.
///
/// `Error::Placement` displays as `template placement error: ...`, which reads
/// as noise under the `error:` prefix of a diagnostic.
fn message_of(error: &Error) -> String {
    match error {
        Error::Placement(inner) => inner.to_string(),
        Error::Render(inner) => inner.to_string(),
        other => other.to_string(),
    }
}

/// Render an error against the DOCX package it came from.
///
/// Use this after loading fails: [`Template::from_bytes`](crate::Template::from_bytes)
/// returns an error without a template, so
/// [`Template::diagnostic`](crate::Template::diagnostic) is not available. The
/// diagnostic reads `word/document.xml` from `source` and points at the
/// paragraph that failed.
///
/// When the package or the part cannot be read, the error message is returned
/// without a snippet.
///
/// # Examples
///
/// ```no_run
/// # fn example() -> docx_templating::Result<()> {
/// let bytes = std::fs::read("broken.docx")?;
///
/// if let Err(error) = docx_templating::Template::from_bytes(bytes.clone()) {
///     eprintln!("{}", docx_templating::diagnose(&bytes, &error));
/// }
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn diagnose(source: impl AsRef<[u8]>, error: &Error) -> Diagnostic {
    match part_view(source.as_ref(), Detail::of(error).part.as_deref()) {
        Some(view) => Diagnostic::with_view(error, &view),
        None => Diagnostic::from_error(error),
    }
}

/// Read the failing part from a package and build a view of its text.
fn part_view(source: &[u8], part: Option<&str>) -> Option<View> {
    let part = part?;
    let package = ZipPackageSource::from_bytes(source.to_vec()).ok()?;
    let bytes = package.read_part(part).ok()??;
    let document = parse_part(&bytes, part).ok()?;
    let (text, paragraphs) = text_view(&document, part);
    Some(View::new(part, &text, &paragraphs))
}

/// The template text of one part, split into paragraphs.
pub(crate) struct View {
    part: String,
    lines: Vec<ViewLine>,
}

struct ViewLine {
    span: Range<usize>,
    text: String,
}

impl View {
    /// Build a view from the concatenated text and one range per paragraph.
    pub(crate) fn new(part: &str, text: &str, paragraphs: &[Range<usize>]) -> Self {
        let lines = paragraphs
            .iter()
            .map(|span| ViewLine {
                span: span.clone(),
                text: text.get(span.clone()).unwrap_or_default().to_owned(),
            })
            .collect();
        Self {
            part: part.to_owned(),
            lines,
        }
    }

    /// The part this view was built from.
    pub(crate) fn part(&self) -> &str {
        &self.part
    }

    /// Place a span on a line, in characters, with a caret width.
    fn locate(&self, span: &Range<usize>) -> Option<Placed> {
        let index = self
            .lines
            .iter()
            .position(|line| line.span.contains(&span.start))
            .or_else(|| {
                self.lines
                    .iter()
                    .position(|line| line.span.end == span.start && !line.span.is_empty())
            })?;
        let line = self.lines.get(index)?;
        let offset = span.start.checked_sub(line.span.start)?;
        let before = line.text.get(..offset)?;
        let remaining = line.text.len().saturating_sub(offset);
        let width = span.len().min(remaining).max(1);
        let caret = line
            .text
            .get(offset..offset + width)
            .map_or(1, |text| text.chars().count().max(1));

        Some(Placed {
            line: index + 1,
            column: before.chars().count() + 1,
            text: line.text.clone(),
            caret,
        })
    }
}

/// Where a span lands in a view.
struct Placed {
    line: usize,
    column: usize,
    text: String,
    caret: usize,
}

/// The parts of an error a diagnostic can show.
#[derive(Default)]
struct Detail {
    part: Option<String>,
    span: Option<Range<usize>>,
    label: Option<&'static str>,
    help: Option<String>,
}

impl Detail {
    fn of(error: &Error) -> Self {
        match error {
            Error::Placement(inner) => Self::placement(inner),
            Error::Render(inner) => Self::render(inner),
            _ => Self::default(),
        }
    }

    fn for_part(part: &str) -> Self {
        Self {
            part: Some(part.to_owned()),
            ..Self::default()
        }
    }

    fn for_optional_part(part: Option<&str>) -> Self {
        Self {
            part: part.map(str::to_owned),
            ..Self::default()
        }
    }

    fn span(mut self, span: &Range<usize>) -> Self {
        self.span = Some(span.clone());
        self
    }

    fn label(mut self, label: &'static str) -> Self {
        self.label = Some(label);
        self
    }

    fn help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    fn placement(error: &BindingError) -> Self {
        match error {
            BindingError::Syntax { part, .. } => Self::for_part(part),
            BindingError::TemplateInOpaqueElement {
                part,
                element,
                offset,
            } => Self::for_part(part).help(format!(
                "a template tag inside {element} at byte {offset} is not supported; put it in a paragraph"
            )),
            BindingError::TagSharesContainer {
                part,
                container,
                span,
            } => Self::for_part(part)
                .span(span)
                .label("this tag shares its container with other text")
                .help(format!("put the tag on its own {container}")),
            BindingError::BodyCrossesContainer { part, .. } => Self::for_part(part)
                .help("a block must open and close inside the same container"),
            BindingError::LoopWrapsTable { part, span } => Self::for_part(part)
                .span(span)
                .label("this loop wraps a whole table")
                .help("loop over one table row instead of the whole table"),
            BindingError::UnsupportedInlineLoop { part, .. } => Self::for_part(part).help(
                "put an inline loop inside a table row, or split it across whole paragraphs",
            ),
            BindingError::MultipleTagsInBlock { part, second, .. } => Self::for_part(part)
                .span(second)
                .label("a second structural tag in the same block")
                .help("give each structural tag its own block, or mark it inline"),
            BindingError::UnclosedBlock { part, span } => Self::for_part(part)
                .span(span)
                .label("this block is never closed")
                .help("add the matching closing tag before the enclosing block ends"),
            BindingError::UnexpectedTag { part, span } => Self::for_part(part)
                .span(span)
                .label("no block is open here")
                .help("remove this tag, or open a block before it"),
            BindingError::MismatchedBlock { part, open, close } => Self::for_part(part)
                .span(close)
                .label("this closing tag does not match the open block")
                .help(format!("the open block starts at byte {}", open.start)),
        }
    }

    fn render(error: &RenderError) -> Self {
        match error {
            RenderError::MissingValue { path, part } => Self::for_optional_part(part.as_deref())
                .help(format!(
                    "the context has no value at '{path}'; MissingValuePolicy::Empty renders it as empty text"
                )),
            RenderError::ExpectedIterable { path, actual, part } => {
                Self::for_optional_part(part.as_deref())
                    .help(format!("'{path}' holds {actual}; a loop needs an array"))
            }
            RenderError::TypeMismatch {
                path,
                expected,
                actual,
                part,
            } => Self::for_optional_part(part.as_deref()).help(format!(
                "'{path}' holds {actual}; expected {expected}"
            )),
            RenderError::CurrentItemOutsideLoop => {
                Self::default().help("'{{.}}' is only valid inside a loop body")
            }
            RenderError::MetaOutsideLoop { name } => {
                Self::default().help(format!("'{name}' is only valid inside a loop body"))
            }
            RenderError::CannotConvertToText { value_type } => Self::default().help(format!(
                "{value_type} has no text form; render a string, number or boolean instead"
            )),
            RenderError::UnknownFilter { name, part } => Self::for_optional_part(part.as_deref())
                .help(format!(
                    "no filter called '{name}' is registered; register one with TemplateOptions::filter"
                )),
            RenderError::FilterFailed { name, message, part } => {
                Self::for_optional_part(part.as_deref())
                    .help(format!("filter '{name}' reported: {message}"))
            }
            RenderError::InvalidComparison {
                operator,
                left,
                right,
                part,
            } => Self::for_optional_part(part.as_deref()).help(format!(
                "'{operator}' orders numbers and strings; {left} and {right} have no order"
            )),
            RenderError::ArithmeticType {
                operator,
                actual,
                part,
            } => Self::for_optional_part(part.as_deref()).help(format!(
                "'{operator}' works on numbers; the value is {actual}"
            )),
            RenderError::DivisionByZero { operator, part } => {
                Self::for_optional_part(part.as_deref())
                    .help(format!("'{operator}' needs a non zero right operand"))
            }
            RenderError::ArithmeticOverflow { operator, part } => {
                Self::for_optional_part(part.as_deref())
                    .help(format!("'{operator}' produced a number too large to represent"))
            }
            RenderError::InvalidLiteral { literal, part } => {
                Self::for_optional_part(part.as_deref()).help(format!(
                    "'{literal}' is not a number; write an integer or decimal such as 42 or 2.5"
                ))
            }
            RenderError::ExpressionNotSupported { part, .. } => {
                Self::for_optional_part(part.as_deref()).help(
                    "use comparisons and boolean logic in an if condition, not in a value placeholder",
                )
            }
            RenderError::UnsupportedBlockPlacement { part, .. } => {
                Self::for_optional_part(part.as_deref())
                    .help("move the block so it covers whole paragraphs or whole table rows")
            }
            RenderError::TextSpansContainers { part, .. } => Self::for_part(part)
                .help("keep a placeholder inside one run, or outside a hyperlink"),
            RenderError::InvalidPlanTarget { .. } | RenderError::InvalidPlan { .. } => {
                Self::default()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::indexing_slicing
    )]

    use super::*;

    fn view() -> View {
        let text = "Hello {% for item in items %}there{% endfor %}";
        let paragraphs = vec![0..34, 34..46];
        View::new("word/document.xml", text, &paragraphs)
    }

    #[test]
    fn locates_a_span_on_the_first_line() {
        let placed = view().locate(&(6..29)).unwrap();
        assert_eq!(placed.line, 1);
        assert_eq!(placed.column, 7);
        assert_eq!(placed.caret, 23);
        assert_eq!(placed.text, "Hello {% for item in items %}there");
    }

    #[test]
    fn locates_a_span_on_a_later_line() {
        let placed = view().locate(&(36..38)).unwrap();
        assert_eq!(placed.line, 2);
        assert_eq!(placed.column, 3);
        assert_eq!(placed.text, "{% endfor %}");
    }

    #[test]
    fn a_span_past_the_text_has_no_place() {
        assert!(view().locate(&(500..510)).is_none());
    }

    #[test]
    fn displays_a_caret_under_the_span() {
        let error = Error::Placement(BindingError::UnclosedBlock {
            part: "word/document.xml".to_owned(),
            span: 6..29,
        });
        let rendered = Diagnostic::with_view(&error, &view()).to_string();

        assert!(
            rendered.starts_with("error: unclosed block in word/document.xml"),
            "{rendered}"
        );
        assert!(rendered.contains("--> word/document.xml:1:7"), "{rendered}");
        assert!(
            rendered.contains("|       ^^^^^^^^^^^^^^^^^^^^^^^ this block is never closed"),
            "{rendered}"
        );
        assert!(
            rendered.contains("= help: add the matching closing tag"),
            "{rendered}"
        );
    }

    #[test]
    fn displays_a_render_error_without_a_snippet() {
        let error = Error::Render(RenderError::MissingValue {
            path: "user.name".to_owned(),
            part: Some("word/document.xml".to_owned()),
        });
        let diagnostic = Diagnostic::with_view(&error, &view());

        assert_eq!(diagnostic.part(), Some("word/document.xml"));
        assert_eq!(diagnostic.line(), None);
        assert!(diagnostic.help().is_some());

        let rendered = diagnostic.to_string();
        assert!(!rendered.contains("-->"), "{rendered}");
        assert!(rendered.contains("= help:"), "{rendered}");
    }

    #[test]
    fn a_span_from_another_part_is_ignored() {
        let error = Error::Placement(BindingError::UnclosedBlock {
            part: "word/header1.xml".to_owned(),
            span: 6..29,
        });
        let diagnostic = Diagnostic::with_view(&error, &view());

        assert_eq!(diagnostic.part(), Some("word/header1.xml"));
        assert_eq!(diagnostic.line(), None);
        assert_eq!(
            diagnostic.message(),
            "unclosed block in word/header1.xml at 6..29"
        );
    }
}