summaryrefslogtreecommitdiff
path: root/src/page.rs
blob: 485632d84318d4e4aaf98c3ff687e94ee4e687c2 (plain)
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
use crate::directive::{Processed, Toc};
use crate::html::parse;
use crate::name::Name;
use crate::parser::WikitextParser;
use crate::site::Site;
use crate::util::get_mtime;
use crate::wikitext::Snippet;
use html_page::{Document, Element, Tag};
use log::{info, trace};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

#[derive(Debug, thiserror::Error)]
pub enum PageError {
    #[error("could not read file: {0}")]
    FileRead(PathBuf, #[source] std::io::Error),

    #[error("could not convert input text from {0} to UTF-8")]
    Utf8(PathBuf, #[source] std::string::FromUtf8Error),

    #[error(transparent)]
    Util(#[from] crate::util::UtilError),

    #[error(transparent)]
    Wikitext(#[from] crate::wikitext::WikitextError),

    #[error(transparent)]
    Html(#[from] crate::html::HtmlError),

    #[error(transparent)]
    Parser(#[from] crate::parser::ParserError),
}

#[derive(Debug)]
pub struct Page {
    meta: PageMeta,
    unprocessed: UnprocessedPage,
}

impl Page {
    pub fn new(meta: PageMeta, unprocessed: UnprocessedPage) -> Self {
        Self { meta, unprocessed }
    }

    pub fn meta(&self) -> &PageMeta {
        &self.meta
    }

    pub fn markdown(&self, site: &mut Site) -> Result<MarkdownPage, PageError> {
        self.unprocessed.process(site)
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct WikitextPage {
    meta: PageMeta,
    wikitext: String,
}

impl WikitextPage {
    pub fn new(meta: PageMeta, wikitext: String) -> Self {
        Self { meta, wikitext }
    }

    pub fn read(name: &Name) -> Result<Self, PageError> {
        info!("input file: {}", name);

        let src = name.source_path();
        let data = std::fs::read(src).map_err(|e| PageError::FileRead(src.into(), e))?;
        let wikitext = String::from_utf8(data).map_err(|e| PageError::Utf8(src.into(), e))?;
        let mtime = get_mtime(src)?;

        let meta = MetaBuilder::default()
            .name(name.clone())
            .mtime(mtime)
            .build();
        Ok(Self::new(meta, wikitext))
    }

    pub fn meta(&self) -> &PageMeta {
        &self.meta
    }

    pub fn meta_mut(&mut self) -> &mut PageMeta {
        &mut self.meta
    }

    pub fn wikitext(&self) -> &str {
        &self.wikitext
    }
}

#[derive(Debug)]
pub struct UnprocessedPage {
    meta: PageMeta,
    snippets: Vec<Snippet>,
}

impl UnprocessedPage {
    pub fn new(meta: PageMeta, parser: &mut WikitextParser) -> Result<Self, PageError> {
        Ok(Self {
            meta,
            snippets: Self::snippets(parser)?,
        })
    }

    pub fn meta(&self) -> &PageMeta {
        &self.meta
    }

    fn snippets(parser: &mut WikitextParser) -> Result<Vec<Snippet>, PageError> {
        let mut snippets = vec![];
        while let Some(snippet) = parser.parse()? {
            snippets.push(snippet);
        }
        Ok(snippets)
    }

    pub fn prepare(&self, site: &mut Site) -> Result<(), PageError> {
        trace!("UnprocessedPage: preparing snippets");
        for snippet in self.snippets.iter() {
            snippet.prepare(site)?;
        }
        Ok(())
    }

    pub fn process(&self, site: &mut Site) -> Result<MarkdownPage, PageError> {
        let mut meta = self.meta.clone();
        let mut processed = vec![];
        trace!("UnprocessedPage: processing snippets");
        for snippet in self.snippets.iter() {
            processed.push(snippet.process(site, &mut meta)?);
        }
        let page_text = processed
            .iter()
            .filter_map(|p| match p {
                Processed::Markdown(s) => Some(s.as_str()),
                _ => None,
            })
            .collect::<Vec<&str>>()
            .join("");
        let body = parse(&page_text)?;
        let mut m = String::new();
        for p in processed {
            match p {
                Processed::Markdown(s) => m.push_str(&s),
                Processed::Toc(levels) => m.push_str(&Toc::post_process(&body, levels)),
            }
        }
        Ok(MarkdownPage::new(m, meta))
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MarkdownPage {
    meta: PageMeta,
    markdown: String,
}

impl MarkdownPage {
    fn new(markdown: String, meta: PageMeta) -> Self {
        Self { markdown, meta }
    }

    pub fn markdown(&self) -> &str {
        &self.markdown
    }

    pub fn meta(&self) -> &PageMeta {
        &self.meta
    }

    pub fn body_to_html(&self) -> Result<Document, PageError> {
        let mut html = Document::default();
        html.push_children(&parse(self.markdown())?);
        Ok(html)
    }

    pub fn to_html(&self) -> Result<Document, PageError> {
        let mut html = Document::default();

        let title = Element::new(Tag::Title).with_text(self.meta.title());
        html.push_to_head(&title);
        html.push_children(&parse(self.markdown())?);

        Ok(html)
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PageMeta {
    name: Name,
    title: Option<String>,
    mtime: SystemTime,
    links_to: Vec<PathBuf>,
}

impl PageMeta {
    fn new(name: Name, title: Option<String>, mtime: SystemTime) -> Self {
        trace!(
            "PageMeta: name={:?} title={:?} mtime={:?}",
            name,
            title,
            mtime,
        );
        Self {
            name,
            title,
            mtime,
            links_to: vec![],
        }
    }

    pub fn destination_filename(&self) -> PathBuf {
        self.name.destination_path().into()
    }

    pub fn set_title(&mut self, title: String) {
        trace!("PageMeta::set_title: title={:?}", title);
        self.title = Some(title);
    }

    pub fn title(&self) -> &str {
        if let Some(title) = &self.title {
            title
        } else {
            self.name.page_name()
        }
    }

    pub fn path(&self) -> &Path {
        self.name.page_path()
    }

    pub fn mtime(&self) -> SystemTime {
        self.mtime
    }

    pub fn set_mtime(&mut self, mtime: SystemTime) {
        self.mtime = mtime;
    }

    pub fn add_link(&mut self, path: &Path) {
        self.links_to.push(path.into());
    }

    pub fn links_to(&self) -> &[PathBuf] {
        &self.links_to
    }
}

#[derive(Debug, Default)]
pub struct MetaBuilder {
    name: Option<Name>,
    title: Option<String>,
    mtime: Option<SystemTime>,
}

impl MetaBuilder {
    pub fn build(self) -> PageMeta {
        PageMeta::new(
            self.name.expect("name set on MetaBuilder"),
            self.title,
            self.mtime.expect("mtime set on MetaBuilder"),
        )
    }

    pub fn name(mut self, name: Name) -> Self {
        self.name = Some(name);
        self
    }

    pub fn title(mut self, title: String) -> Self {
        self.title = Some(title);
        self
    }

    pub fn mtime(mut self, mtime: SystemTime) -> Self {
        self.mtime = Some(mtime);
        self
    }
}