changelogging 0.7.0

Building changelogs from fragments.
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! Building changelogs from fragments.

use std::{
    borrow::Cow,
    fs::{read_dir, File},
    io::{read_to_string, Write},
    iter::{once, repeat},
    path::PathBuf,
};

use handlebars::{no_escape, Handlebars, RenderError, TemplateError};
use itertools::Itertools;
use miette::Diagnostic;
use serde::Serialize;
use textwrap::{fill, Options as WrapOptions, WordSeparator, WordSplitter};
use thiserror::Error;
use time::Date;

use crate::{
    config::{Config, Level},
    context::Context,
    fragment::{is_valid_path, Fragment, Fragments, Sections},
    load::load,
    workspace::Workspace,
};

/// Represents errors that can occur during builder initialization.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to initialize the renderer")]
#[diagnostic(
    code(changelogging::builder::init),
    help("make sure the formats configuration is valid")
)]
pub struct InitError(#[from] pub TemplateError);

/// Represents errors that can occur when building titles.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to build the title")]
#[diagnostic(
    code(changelogging::builder::build_title),
    help("make sure the formats configuration is valid")
)]
pub struct BuildTitleError(#[from] pub RenderError);

/// Represents errors that can occur when building fragments.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to build the fragment")]
#[diagnostic(
    code(changelogging::builder::build_fragment),
    help("make sure the formats configuration is valid")
)]
pub struct BuildFragmentError(#[from] pub RenderError);

/// Represents errors that can occur when reading from files.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to read from `{path}`")]
#[diagnostic(
    code(changelogging::builder::read_file),
    help("check whether the file exists and is accessible")
)]
pub struct ReadFileError {
    /// The underlying I/O error.
    pub source: std::io::Error,
    /// The path provided.
    pub path: PathBuf,
}

impl ReadFileError {
    /// Constructs [`Self`].
    pub fn new(source: std::io::Error, path: PathBuf) -> Self {
        Self { source, path }
    }
}

/// Represents errors that can occur when writing to files.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to write to `{path}`")]
#[diagnostic(
    code(changelogging::builder::write_file),
    help("check whether the file exists and is accessible")
)]
pub struct WriteFileError {
    /// The underlying I/O error.
    pub source: std::io::Error,
    /// The path provided.
    pub path: PathBuf,
}

impl WriteFileError {
    /// Constructs [`Self`].
    pub fn new(source: std::io::Error, path: PathBuf) -> Self {
        Self { source, path }
    }
}

/// Represents errors that can occur when opening files.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to open `{path}`")]
#[diagnostic(
    code(changelogging::builder::open_file),
    help("check whether the file exists and is accessible")
)]
pub struct OpenFileError {
    /// The underlying I/O error.
    pub source: std::io::Error,
    /// The path provided.
    pub path: PathBuf,
}

impl OpenFileError {
    /// Constructs [`Self`].
    pub fn new(source: std::io::Error, path: PathBuf) -> Self {
        Self { source, path }
    }
}

/// Represents errors that can occur when reading directories.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to read directory")]
#[diagnostic(
    code(changelogging::builder::read_directory),
    help("make sure the directory is accessible")
)]
pub struct ReadDirectoryError(#[from] std::io::Error);

/// Represents errors that can occur during iterating over directories.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to iterate directory")]
#[diagnostic(
    code(changelogging::builder::iter_directory),
    help("make sure the directory is accessible")
)]
pub struct IterDirectoryError(#[from] std::io::Error);

/// Represents sources of errors that can occur during fragment collection.
#[derive(Debug, Error, Diagnostic)]
#[error(transparent)]
#[diagnostic(transparent)]
pub enum CollectErrorSource {
    /// Read directory errors.
    ReadDirectory(#[from] ReadDirectoryError),
    /// Iterate directory errors.
    IterDirectory(#[from] IterDirectoryError),
}

/// Represents errors that can occur during fragment collection.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to collect from `{path}`")]
#[diagnostic(
    code(changelogging::builder::collect),
    help("make sure the directory is accessible")
)]
pub struct CollectError {
    /// The source of this error.
    #[source]
    #[diagnostic_source]
    pub source: CollectErrorSource,
    /// The path provided.
    pub path: PathBuf,
}

impl CollectError {
    /// Constructs [`Self`].
    pub fn new(source: CollectErrorSource, path: PathBuf) -> Self {
        Self { source, path }
    }

    /// Constructs [`Self`] from [`ReadDirectoryError`].
    pub fn read_directory(error: ReadDirectoryError, path: PathBuf) -> Self {
        Self::new(error.into(), path)
    }

    /// Constructs [`Self`] from [`IterDirectoryError`].
    pub fn iter_directory(error: IterDirectoryError, path: PathBuf) -> Self {
        Self::new(error.into(), path)
    }

    /// Constructs [`ReadDirectoryError`] and constructs [`Self`] from it.
    pub fn new_read_directory(error: std::io::Error, path: PathBuf) -> Self {
        Self::read_directory(ReadDirectoryError(error), path)
    }

    /// Constructs [`IterDirectoryError`] and constructs [`Self`] from it.
    pub fn new_iter_directory(error: std::io::Error, path: PathBuf) -> Self {
        Self::iter_directory(IterDirectoryError(error), path)
    }
}

/// Represents sources of errors that can occur when building.
#[derive(Debug, Error, Diagnostic)]
#[error(transparent)]
#[diagnostic(transparent)]
pub enum BuildErrorSource {
    /// Build title errors.
    BuildTitle(#[from] BuildTitleError),
    /// Build fragment errors.
    BuildFragment(#[from] BuildFragmentError),
    /// Collect errors.
    Collect(#[from] CollectError),
}

/// Represents errors that can occur when building.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to build")]
#[diagnostic(
    code(changelogging::builder::build),
    help("see the report for more information")
)]
pub struct BuildError {
    /// The source of this error.
    #[source]
    #[diagnostic_source]
    pub source: BuildErrorSource,
}

impl BuildError {
    /// Constructs [`Self`].
    pub fn new(source: BuildErrorSource) -> Self {
        Self { source }
    }

    /// Constructs [`Self`] from [`BuildTitleError`].
    pub fn build_title(error: BuildTitleError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`Self`] from [`BuildFragmentError`].
    pub fn build_fragment(error: BuildFragmentError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`Self`] from [`CollectError`].
    pub fn collect(error: CollectError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`BuildTitleError`] and constructs [`Self`] from it.
    pub fn new_build_title(error: RenderError) -> Self {
        Self::build_title(BuildTitleError(error))
    }

    /// Constructs [`BuildFragmentError`] and constructs [`Self`] from it.
    pub fn new_build_fragment(error: RenderError) -> Self {
        Self::build_fragment(BuildFragmentError(error))
    }
}

/// Represents sources of errors that can occur when writing entries.
#[derive(Debug, Error, Diagnostic)]
#[error(transparent)]
#[diagnostic(transparent)]
pub enum WriteErrorSource {
    /// Open file errors.
    OpenFile(#[from] OpenFileError),
    /// Read file errors.
    ReadFile(#[from] ReadFileError),
    /// Build errors.
    Build(#[from] BuildError),
    /// Write file errors.
    WriteFile(#[from] WriteFileError),
}

/// Represents errors that can occur when writing entries.
#[derive(Debug, Error, Diagnostic)]
#[error("failed to write")]
#[diagnostic(
    code(changelogging::builder::write),
    help("see the report for more information")
)]
pub struct WriteError {
    /// The source of this error.
    #[source]
    #[diagnostic_source]
    pub source: WriteErrorSource,
}

impl WriteError {
    /// Constructs [`Self`].
    pub fn new(source: WriteErrorSource) -> Self {
        Self { source }
    }

    /// Constructs [`Self`] from [`OpenFileError`].
    pub fn open_file(error: OpenFileError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`Self`] from [`ReadFileError`].
    pub fn read_file(error: ReadFileError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`Self`] from [`BuildError`].
    pub fn build(error: BuildError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`Self`] from [`WriteFileError`].
    pub fn write_file(error: WriteFileError) -> Self {
        Self::new(error.into())
    }

    /// Constructs [`OpenFileError`] and constructs [`Self`] from it.
    pub fn new_open_file(error: std::io::Error, path: PathBuf) -> Self {
        Self::open_file(OpenFileError::new(error, path))
    }

    /// Constructs [`ReadFileError`] and constructs [`Self`] from it.
    pub fn new_read_file(error: std::io::Error, path: PathBuf) -> Self {
        Self::read_file(ReadFileError::new(error, path))
    }

    /// Constructs [`WriteFileError`] and constructs [`Self`] from it.
    pub fn new_write_file(error: std::io::Error, path: PathBuf) -> Self {
        Self::write_file(WriteFileError::new(error, path))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RenderTitleData<'t> {
    #[serde(flatten)]
    context: &'t Context<'t>,
    date: Cow<'t, str>,
}

impl<'t> RenderTitleData<'t> {
    fn new(context: &'t Context<'_>, date: Date) -> Self {
        Self {
            context,
            date: Cow::Owned(date.to_string()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RenderFragmentData<'f> {
    #[serde(flatten)]
    context: &'f Context<'f>,
    #[serde(flatten)]
    fragment: &'f Fragment<'f>,
}

impl<'f> RenderFragmentData<'f> {
    fn new(context: &'f Context<'_>, fragment: &'f Fragment<'_>) -> Self {
        Self { context, fragment }
    }
}

/// Represents changelog builders.
#[derive(Debug, Clone)]
pub struct Builder<'b> {
    /// The context of the project.
    pub context: Context<'b>,
    /// The configuration to use.
    pub config: Config<'b>,
    /// The date to use.
    pub date: Date,
    /// The renderer to use.
    pub renderer: Handlebars<'b>,
}

/// The `title` literal.
pub const TITLE: &str = "title";

/// The `fragment` literal.
pub const FRAGMENT: &str = "fragment";

impl<'b> Builder<'b> {
    /// Constructs [`Self`] from [`Workspace`].
    ///
    /// # Errors
    ///
    /// Returns [`InitError`] if initializing the renderer fails.
    pub fn from_workspace(workspace: Workspace<'b>, date: Date) -> Result<Self, InitError> {
        Self::new(workspace.context, workspace.config, date)
    }

    /// Constructs [`Self`].
    ///
    /// # Errors
    ///
    /// Returns [`InitError`] if initializing the renderer fails.
    pub fn new(context: Context<'b>, config: Config<'b>, date: Date) -> Result<Self, InitError> {
        let mut renderer = Handlebars::new();

        let formats = config.formats();

        renderer.set_strict_mode(true);

        renderer.register_escape_fn(no_escape);

        renderer.register_template_string(TITLE, formats.title.as_ref())?;
        renderer.register_template_string(FRAGMENT, formats.fragment.as_ref())?;

        Ok(Self {
            context,
            config,
            date,
            renderer,
        })
    }
}

const SPACE: char = ' ';
const NEW_LINE: char = '\n';
const DOUBLE_NEW_LINE: &str = "\n\n";
const NO_SIGNIFICANT_CHANGES: &str = "No significant changes.";

fn heading(character: char, level: Level) -> String {
    repeat(character)
        .take(level.into())
        .chain(once(SPACE))
        .collect()
}

fn indent(character: char) -> String {
    once(character).chain(once(SPACE)).collect()
}

impl Builder<'_> {
    /// Returns [`Context`] reference.
    pub fn context(&self) -> &Context<'_> {
        &self.context
    }

    /// Returns [`Config`] reference.
    pub fn config(&self) -> &Config<'_> {
        &self.config
    }

    // BUILDING

    /// Builds entries and writes them to the changelog.
    ///
    /// # Errors
    ///
    /// Returns [`WriteError`] when building fails, as well as when I/O operations fail.
    pub fn write(&self) -> Result<(), WriteError> {
        let entry = self.build().map_err(WriteError::build)?;

        let path = self.config.paths.output.as_ref();

        let file = File::options()
            .read(true)
            .open(path)
            .map_err(|error| WriteError::new_open_file(error, path.to_owned()))?;

        let contents = read_to_string(file)
            .map_err(|error| WriteError::new_read_file(error, path.to_owned()))?;

        let mut file = File::options()
            .create(true)
            .write(true)
            .truncate(true)
            .open(path)
            .map_err(|error| WriteError::new_open_file(error, path.to_owned()))?;

        let start = self.config.start.as_ref();

        let mut string = String::new();

        if let Some((before, after)) = contents.split_once(start) {
            string.push_str(before);

            string.push_str(start);

            string.push_str(DOUBLE_NEW_LINE);

            string.push_str(&entry);

            string.push(NEW_LINE);

            let trimmed = after.trim_start();

            if !trimmed.is_empty() {
                string.push(NEW_LINE);

                string.push_str(trimmed);
            }
        } else {
            string.push_str(&entry);

            string.push(NEW_LINE);

            let trimmed = contents.trim_start();

            if !trimmed.is_empty() {
                string.push(NEW_LINE);

                string.push_str(trimmed);
            }
        };

        write!(file, "{string}")
            .map_err(|error| WriteError::new_write_file(error, path.to_owned()))?;

        Ok(())
    }

    /// Builds and previews (prints) entries.
    ///
    /// # Errors
    ///
    /// Returns [`BuildError`] when building fails.
    pub fn preview(&self) -> Result<(), BuildError> {
        let string = self.build()?;

        println!("{string}");

        Ok(())
    }

    /// Builds and returns entries.
    ///
    /// # Errors
    ///
    /// Returns [`BuildError`] when rendering titles and fragments or collecting fragments fails.
    pub fn build(&self) -> Result<String, BuildError> {
        let mut string = self.build_title().map_err(BuildError::build_title)?;

        string.push_str(DOUBLE_NEW_LINE);

        let sections = self.collect().map_err(BuildError::collect)?;

        let built = self
            .build_sections(&sections)
            .map_err(BuildError::build_fragment)?;

        let contents = if built.is_empty() {
            NO_SIGNIFICANT_CHANGES
        } else {
            &built
        };

        string.push_str(contents);

        Ok(string)
    }

    /// Builds entry titles.
    ///
    /// # Errors
    ///
    /// Returns [`BuildTitleError`] when rendering fails.
    pub fn build_title(&self) -> Result<String, BuildTitleError> {
        let mut string = self.entry_heading();

        let title = self.render_title()?;

        string.push_str(&title);

        Ok(string)
    }

    /// Builds section titles.
    pub fn build_section_title_str(&self, title: &str) -> String {
        let mut string = self.section_heading();

        string.push_str(title);

        string
    }

    /// Similar to [`build_section_title_str`], except the input is [`AsRef<str>`].
    ///
    /// [`build_section_title_str`]: Self::build_section_title_str
    pub fn build_section_title<S: AsRef<str>>(&self, title: S) -> String {
        self.build_section_title_str(title.as_ref())
    }

    /// Builds fragments.
    ///
    /// # Errors
    ///
    /// Returns [`BuildFragmentError`] when rendering fails.
    pub fn build_fragment(&self, fragment: &Fragment<'_>) -> Result<String, BuildFragmentError> {
        let string = self.render_fragment(fragment)?;

        Ok(self.wrap(string))
    }

    /// Builds multiple fragments and joins them together.
    ///
    /// # Errors
    ///
    /// Returns [`BuildFragmentError`] when building any of the fragments fails.
    pub fn build_fragments(&self, fragments: &Fragments<'_>) -> Result<String, BuildFragmentError> {
        let string = fragments
            .iter()
            .map(|fragment| self.build_fragment(fragment))
            .process_results(|iterator| iterator.into_iter().join(DOUBLE_NEW_LINE))?;

        Ok(string)
    }

    /// Builds sections.
    ///
    /// This is essentially the same as calling [`build_section_title`] and [`build_fragments`],
    /// joining the results together.
    ///
    /// # Errors
    ///
    /// Returns [`BuildFragmentError`] when building any of the fragments fails.
    ///
    /// [`build_section_title`]: Self::build_section_title
    /// [`build_fragments`]: Self::build_fragments
    pub fn build_section_str(
        &self,
        title: &str,
        fragments: &Fragments<'_>,
    ) -> Result<String, BuildFragmentError> {
        let mut string = self.build_section_title(title);

        let built = self.build_fragments(fragments)?;

        string.push_str(DOUBLE_NEW_LINE);
        string.push_str(&built);

        Ok(string)
    }

    /// Similar to [`build_section_str`], except the input is [`AsRef<str>`].
    ///
    /// # Errors
    ///
    /// Returns [`BuildFragmentError`] when building any of the fragments fails.
    ///
    /// [`build_section_str`]: Self::build_section_str
    pub fn build_section<S: AsRef<str>>(
        &self,
        title: S,
        fragments: &Fragments<'_>,
    ) -> Result<String, BuildFragmentError> {
        self.build_section_str(title.as_ref(), fragments)
    }

    /// Builds multiple sections and joins them together.
    ///
    /// # Errors
    ///
    /// Returns [`BuildFragmentError`] when building any of the sections fails.
    pub fn build_sections(&self, sections: &Sections<'_>) -> Result<String, BuildFragmentError> {
        let types = self.config.types_with_defaults();

        let string = self
            .config
            .order
            .iter()
            .filter_map(|name| types.get(name).zip(sections.get(name)))
            .map(|(title, fragments)| self.build_section(title, fragments))
            .process_results(|iterator| iterator.into_iter().join(DOUBLE_NEW_LINE))?;

        Ok(string)
    }

    // WRAPPING

    /// Wraps the given string.
    pub fn wrap_str(&self, string: &str) -> String {
        let initial_indent = indent(self.config.indents.bullet);
        let subsequent_indent = indent(SPACE);

        let options = WrapOptions::new(self.config.wrap.get())
            .break_words(false)
            .word_separator(WordSeparator::AsciiSpace)
            .word_splitter(WordSplitter::NoHyphenation)
            .initial_indent(&initial_indent)
            .subsequent_indent(&subsequent_indent);

        fill(string, options)
    }

    /// Similar to [`wrap_str`], except the input is [`AsRef<str>`].
    ///
    /// [`wrap_str`]: Self::wrap_str
    pub fn wrap<S: AsRef<str>>(&self, string: S) -> String {
        self.wrap_str(string.as_ref())
    }

    // RENDERING

    /// Renders entry titles.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError`] if rendering the title fails.
    pub fn render_title(&self) -> Result<String, RenderError> {
        let data = RenderTitleData::new(self.context(), self.date);

        self.renderer.render(TITLE, &data)
    }

    /// Renders fragments.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError`] if rendering the given fragment fails.
    pub fn render_fragment(&self, fragment: &Fragment<'_>) -> Result<String, RenderError> {
        if fragment.partial.id.is_integer() {
            let data = RenderFragmentData::new(self.context(), fragment);

            self.renderer.render(FRAGMENT, &data)
        } else {
            Ok(fragment.content.as_ref().to_owned())
        }
    }

    // COLLECTING

    /// Collects fragments into sections.
    ///
    /// # Errors
    ///
    /// Returns [`CollectError`] when reading or iterating the fragments directory fails.
    pub fn collect(&self) -> Result<Sections<'_>, CollectError> {
        let directory = self.config.paths.directory.as_ref();

        let mut sections = Sections::new();

        read_dir(directory)
            .map_err(|error| CollectError::new_read_directory(error, directory.to_owned()))?
            .map(|result| {
                result
                    .map(|entry| entry.path())
                    .map_err(|error| CollectError::new_iter_directory(error, directory.to_owned()))
            })
            .process_results(|iterator| {
                iterator
                    .into_iter()
                    .filter_map(|path| load::<Fragment<'_>, _>(path).ok()) // ignore errors
                    .for_each(|fragment| {
                        sections
                            .entry(fragment.partial.type_name.clone())
                            .or_default()
                            .push(fragment);
                    });
            })?;

        sections.values_mut().for_each(|section| section.sort());

        Ok(sections)
    }

    /// Collects paths to fragments.
    ///
    /// # Errors
    ///
    /// Returns [`CollectError`] if reading or iterating the fragments directory fails.
    pub fn collect_paths(&self) -> Result<Vec<PathBuf>, CollectError> {
        let directory = self.config.paths.directory.as_ref();

        read_dir(directory)
            .map_err(|error| CollectError::new_read_directory(error, directory.to_owned()))?
            .map(|result| {
                result
                    .map(|entry| entry.path())
                    .map_err(|error| CollectError::new_iter_directory(error, directory.to_owned()))
            })
            .process_results(|iterator| {
                iterator
                    .into_iter()
                    .filter(|path| is_valid_path(path))
                    .collect()
            })
    }

    // HEADING

    /// Constructs headings for the given level.
    pub fn level_heading(&self, level: Level) -> String {
        heading(self.config.indents.heading, level)
    }

    /// Constructs entry headings.
    pub fn entry_heading(&self) -> String {
        self.level_heading(self.config.levels.entry)
    }

    /// Constructs section headings.
    pub fn section_heading(&self) -> String {
        self.level_heading(self.config.levels.section)
    }
}