stawege-html-plugin 0.1.2

HTML template engine plugin for Stawege.
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
extern crate alloc;

use alloc::rc::Rc;
use core::{error::Error, fmt::Debug};
use std::{
    collections::HashMap,
    fs::{self, File},
    io::{ErrorKind, Read},
    path::{Path, PathBuf},
};

use stawege_log::error;
use stawege_plugin::{Plugin, PluginContext};

use crate::{
    tag_logics::{BlockTagLogic, ExtendsTagLogic, SetTagLogic, UnsetTagLogic},
    AttributeBuilder, AttributeParseState, Attributes, HtmlError, Item, TagLogic, Template,
    TemplateContext,
};

#[derive(Default)]
pub struct HtmlPlugin {
    pub chars: Vec<char>,
    pub index: usize,
    pub last_item_end: usize,
    pub template: Template,
    pub source_root_path: Option<Rc<PathBuf>>,
    pub output_root_path: Option<Rc<PathBuf>>,
    pub default_variables: HashMap<String, String>,
    pub tag_logics: Vec<Rc<dyn TagLogic>>,
    pub dependencies: Vec<Rc<PathBuf>>,
}

impl HtmlPlugin {
    pub fn new() -> HtmlPlugin {
        HtmlPlugin {
            chars: Vec::new(),
            index: 0,
            last_item_end: 0,
            template: Template::new(),
            source_root_path: None,
            output_root_path: None,
            default_variables: HashMap::new(),
            tag_logics: vec![
                Rc::new(UnsetTagLogic::new()),
                Rc::new(SetTagLogic::new()),
                Rc::new(BlockTagLogic::new()),
                Rc::new(ExtendsTagLogic::new()),
            ],
            dependencies: Vec::new(),
        }
    }

    pub fn reset(&mut self) {
        self.chars.clear();
        self.index = 0;
        self.last_item_end = 0;
        self.template.clear();
    }

    pub fn read_file(&mut self, path: impl AsRef<Path>) -> Result<(), HtmlError> {
        match fs::read_to_string(path.as_ref()) {
            Ok(content) => {
                self.chars = content.chars().collect();
                Ok(())
            }
            Err(e) => match e.kind() {
                ErrorKind::NotFound => Err(HtmlError::FileNotFound {
                    path: PathBuf::from(path.as_ref()),
                }),
                _ => Err(HtmlError::Other {
                    message: e.to_string(),
                }),
            },
        }
    }

    pub fn parse_file(&mut self, file: &mut File) -> Result<(), HtmlError> {
        let mut content = String::new();
        if file.read_to_string(&mut content).is_err() {
            Err(HtmlError::NotValidUtf8Encoding)?
        };
        self.chars = content.chars().collect::<Vec<char>>();
        self.parse()
    }

    pub fn parse(&mut self) -> Result<(), HtmlError> {
        if self.chars.is_empty() {
            return Ok(());
        }
        while !self.is_eof() {
            if self.next_is(&['<', '!', '-', '-']) {
                self.parse_comment();
                continue;
            }
            if self.next_is(&['<', '/']) && self.parse_closing_tag()? {
                continue;
            }
            if self.next_is(&['<']) && self.parse_opening_tag()? {
                continue;
            }
            self.index += 1;
        }
        self.parse_remaining_as_text();
        if let Some(last_item) = self.template.opened_items.last() {
            Err(HtmlError::MissingClosingTag {
                tag: last_item.name(),
            })?
        }
        Ok(())
    }

    pub fn parse_remaining_as_text(&mut self) {
        let text = &self.chars[self.last_item_end..self.index];
        if !text.is_empty() {
            self.template.push_item(Item::text(text));
        }
    }

    pub fn parse_comment(&mut self) {
        self.parse_remaining_as_text();
        if let Some(end) = self.try_find(&['-', '-', '>']) {
            self.template
                .push_item(Item::comment(&self.chars[self.index + 4..end - 3]));
            self.last_item_end = end;
            self.index = end;
        } else {
            self.template
                .push_item(Item::comment(&self.chars[self.index..]));
            self.index = self.chars.len() - 1;
        }
    }

    pub fn parse_opening_tag(&mut self) -> Result<bool, HtmlError> {
        let mut name_chars = Vec::new();
        for tag_logic in &self.tag_logics {
            for name in tag_logic.names() {
                name_chars.clear();
                name_chars.push('<');
                name_chars.extend(name.chars());
                if self.next_is(&name_chars) {
                    if let Ok(mut item) = Item::try_from((*name, tag_logic.clone())) {
                        self.parse_remaining_as_text();
                        self.index += name_chars.len();
                        self.last_item_end = self.index;
                        let (attributes, is_self_closing) = self.parse_attributes()?;
                        item.push_attributes(attributes);
                        if is_self_closing {
                            self.template.push_item(item);
                        } else {
                            self.template.push_opened_item(item);
                        }
                        return Ok(true);
                    }
                }
            }
        }
        Ok(false)
    }

    pub fn parse_closing_tag(&mut self) -> Result<bool, HtmlError> {
        let mut name_chars = Vec::new();
        for tag_logic in &self.tag_logics {
            for name in tag_logic.names() {
                name_chars.clear();
                name_chars.extend("</".chars());
                name_chars.extend(name.chars());
                name_chars.push('>');

                if self.next_is(&name_chars) {
                    if self.template.opened_items.is_empty() {
                        Err(HtmlError::MissingOpeningTag {
                            tag: name.to_string(),
                        })?
                    }
                    if let Ok(item) = Item::try_from((*name, tag_logic.clone())) {
                        if let Some(last_item) = self.template.opened_items.last() {
                            if !last_item.matches(&item) {
                                Err(HtmlError::MissingClosingTag { tag: item.name() })?
                            }
                        }
                    }
                    self.parse_remaining_as_text();
                    self.index += name_chars.len();
                    self.last_item_end = self.index;
                    self.template.close_opened_item();
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    pub fn parse_attributes(&mut self) -> Result<(Attributes, bool), HtmlError> {
        let mut is_self_closing = false;
        let mut attributes = Attributes::new();
        let mut attribute_builder = AttributeBuilder::new();

        while !self.is_eof() {
            let Some(c1) = self.chars.get(self.index) else {
                break;
            };

            if !attribute_builder.is_in_quote() {
                if c1 == &'>' {
                    self.index += 1;
                    attribute_builder.pop_attribute_to(&mut attributes);
                    break;
                } else if c1 == &'/' {
                    if let Some(c2) = self.chars.get(self.index + 1) {
                        if c2 == &'>' {
                            self.index += 2;
                            is_self_closing = true;
                            attribute_builder.pop_attribute_to(&mut attributes);
                            break;
                        }
                    }
                }
            }

            match attribute_builder.state {
                AttributeParseState::Key => {
                    match c1 {
                        ' ' => {
                            if !attribute_builder.key.is_empty() {
                                attribute_builder.assign_state();
                            }
                        }
                        '=' => {
                            attribute_builder.value_state();
                        }
                        _ => {
                            attribute_builder.push_char_to_key(*c1);
                        }
                    };
                }
                AttributeParseState::Assign => 'this_case: {
                    if c1 == &' ' {
                        break 'this_case;
                    }
                    if c1 == &'=' {
                        attribute_builder.value_state();
                        break 'this_case;
                    }
                    attribute_builder
                        .pop_attribute_to(&mut attributes)
                        .key_state()
                        .push_char_to_key(*c1);
                }
                AttributeParseState::Value => 'this_case: {
                    if attribute_builder.value.is_empty() {
                        for quote in &['"', '\''] {
                            if c1 == quote {
                                attribute_builder.quoted_value_state(*quote);
                                break 'this_case;
                            }
                        }
                    }
                    if c1 == &' ' {
                        attribute_builder
                            .pop_attribute_to(&mut attributes)
                            .key_state();
                        break 'this_case;
                    }
                    attribute_builder.push_char_to_value(*c1);
                }
                AttributeParseState::QuotedValue(quote) => 'this_case: {
                    if c1 == &quote {
                        attribute_builder
                            .pop_attribute_to(&mut attributes)
                            .key_state();
                        break 'this_case;
                    }
                    attribute_builder.push_char_to_value(*c1);
                }
            }
            self.index += 1;
        }
        self.last_item_end = self.index;
        Ok((attributes, is_self_closing))
    }

    pub fn process(&self, context: &mut TemplateContext) {
        for item in &self.template.items {
            if let Err(error) = item.run(context) {
                error!("Could not write to file. Reason: {error}");
            }
        }
    }

    pub fn try_find(&self, text: &[char]) -> Option<usize> {
        for i in self.index..self.chars.len() {
            for (text_i, text_char) in text.iter().enumerate() {
                if i + text_i >= self.chars.len() {
                    return None;
                } else if &self.chars[i + text_i] != text_char {
                    break;
                } else if text_i == text.len() - 1 {
                    return Some(i + text.len());
                }
            }
        }
        None
    }

    pub fn next_is(&self, text: &[char]) -> bool {
        if let Some(peek) = self.peek(text.len()) {
            if peek == text {
                return true;
            }
        }
        false
    }

    pub fn peek(&self, len: usize) -> Option<&[char]> {
        if self.chars.len() >= self.index + len {
            return Some(&self.chars[self.index..self.index + len]);
        }
        None
    }

    pub fn is_eof(&self) -> bool {
        self.index >= self.chars.len()
    }
}

// ---------------------------
// Plugin trait implementation
// ---------------------------

impl Plugin for HtmlPlugin {
    fn extensions(&self) -> &[&str] {
        &["html", "htm"]
    }

    fn prepare(&mut self, context: &PluginContext) {
        self.source_root_path = Some(context.source_root_path.clone());
        self.output_root_path = Some(context.output_root_path.clone());
        self.default_variables = context.default_variables.clone();
    }

    fn process_file_to(
        &mut self,
        mut source_file: File,
        output_file: File,
    ) -> Result<(), Box<dyn Error>> {
        self.parse_file(&mut source_file)?;

        let Some(source_root_path) = &self.source_root_path else {
            Err(HtmlError::MissingSourcePath)?
        };
        let Some(output_root_path) = &self.output_root_path else {
            Err(HtmlError::MissingOutputPath)?
        };

        let mut template_context = TemplateContext {
            input_path: source_root_path.clone(),
            output_path: output_root_path.clone(),
            file: output_file,
            other_files: HashMap::new(),
            variables: self.default_variables.clone(),
            dependencies: Vec::new(),
        };
        self.process(&mut template_context);
        self.dependencies = template_context.dependencies;
        Ok(())
    }

    fn reset(&mut self) {
        HtmlPlugin::reset(self);
    }

    fn get_dependencies(&mut self) -> Option<Vec<Rc<PathBuf>>> {
        if self.dependencies.is_empty() {
            None?
        }
        Some(self.dependencies.drain(..).collect())
    }
}

// -----------------------------
// TryFrom trait implementations
// -----------------------------

impl TryFrom<&Path> for HtmlPlugin {
    type Error = HtmlError;

    fn try_from(path: &Path) -> Result<Self, Self::Error> {
        let mut html_parser = HtmlPlugin::new();
        html_parser.read_file(path)?;
        Ok(html_parser)
    }
}

// --------------------------
// Debug trait implementation
// --------------------------

impl Debug for HtmlPlugin {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HtmlPlugin")
            .field("chars", &self.chars)
            .field("index", &self.index)
            .field("last_item_end", &self.last_item_end)
            .field("template", &self.template)
            .field("source_root_path", &self.source_root_path)
            .field("output_root_path", &self.output_root_path)
            .field("default_variables", &self.default_variables)
            .field("dependencies", &self.dependencies)
            .finish()
    }
}