lewp 0.3.0

Say goodbye to the web template hell. Generate your HTML5 website technically optimized and always valid. In your Rust source.
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
//! Defines the file hierarchy of [lewp](crate).

use {
    crate::{LewpError, LewpErrorKind},
    std::{
        path::{Path, PathBuf},
        rc::Rc,
    },
};

mod builder;
mod component;
mod level;

pub use {
    builder::FileHierarchyBuilder,
    component::{Component, ComponentInformation, ComponentType},
    level::Level,
};

/// File hierarchy definition, handles file path generation.
pub struct FileHierarchy {
    mountpoint: PathBuf,
}

impl FileHierarchy {
    /// Creates a new file hierarchy instance.
    pub fn new() -> Self {
        Self {
            mountpoint: PathBuf::from("."),
        }
    }

    /// Returns the directory where the file hierarchy is mounted.
    pub fn mountpoint(&self) -> PathBuf {
        self.mountpoint.clone()
    }

    /// Generates the folder path according to the file hierarchy. The folder
    /// that contains the `file_type` always corresponds to the extension of the
    /// files contained.
    pub fn folder<COMP: Component>(&self, component: &COMP) -> PathBuf {
        let mut path = self.mountpoint.clone();
        path.push(component.level().to_string());
        path.push(component.id().to_string());
        path.push(component.kind().to_string());
        path
    }

    /// Collects all filenames in the given component. The resulting
    /// vector contains the filepath including the mountpoint of the FileHierarchy.
    /// This function is not recursive.
    pub fn get_file_list<COMP: Component>(
        &self,
        component: &COMP,
    ) -> Result<Vec<PathBuf>, LewpError> {
        let subfolder = self.mountpoint.join(Path::new(&format!(
            "{}/{}/{}",
            component.level(),
            component.id(),
            component.kind()
        )));
        if !subfolder.is_dir() {
            return Err(LewpError {
                kind: LewpErrorKind::FileHierarchy,
                message: format!(
                    "Given input is not a folder: {}",
                    subfolder.display()
                ),
                source_component: component.component_information(),
            });
        }
        let mut filenames = vec![];
        for entry in walkdir::WalkDir::new(&subfolder) {
            let entry = match entry {
                Ok(v) => v.into_path(),
                Err(msg) => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: msg.to_string(),
                        source_component: component.component_information(),
                    });
                }
            };
            if entry.is_dir() {
                // skip folders because we only want to get the files in the list
                continue;
            }
            filenames.push(entry);
        }
        Ok(filenames)
    }

    fn remove_mountpoint(
        mountpoint: &Path,
        input_path: &Path,
    ) -> Result<PathBuf, String> {
        match pathdiff::diff_paths(input_path, mountpoint) {
            Some(p) => Ok(p),
            None => match input_path.to_str() {
                Some(v) => Err(format!("Could not remove base dir of {}", v)),
                None => Err("Could not remove base dir!".to_string()),
            },
        }
    }

    /// Collects all filenames in the given directory.
    ///
    /// The directory is relative to the mountpoint of the file hierarchy.
    /*
    fn collect_filenames(
        &self,
        dir: PathBuf,
    ) -> Result<Vec<PathBuf>, LewpError> {
        let mut filenames = vec![];
        for entry in walkdir::WalkDir::new(&dir) {
            let entry = match entry {
                Ok(v) => v.into_path(),
                Err(msg) => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: msg.to_string(),
                        source_component: component.component_information(),
                    });
                }
            };
            if entry.is_dir() {
                // skip folders because we only want to get the files in the list
                continue;
            }
            filenames.push(entry);
        }
        Ok(filenames)
    }
    */

    /// Gets a list of the component ids available for this [ComponentType] on the
    /// given [Level].
    pub fn collect_component_ids(
        &self,
        kind: ComponentType,
        level: Level,
    ) -> Result<Vec<String>, LewpError> {
        let mut v = vec![];
        // create a pattern to search for
        let pattern = PathBuf::from(&level.to_string())
            .join("*")
            .join(&kind.to_string());
        log::trace!("pattern: {:#?}", pattern);
        // combine it with the mountpoint
        let filepath = self.mountpoint().join(pattern);
        let filepath = match filepath.to_str() {
            Some(f) => f,
            None => {
                return Err(LewpError {
                    kind: LewpErrorKind::FileHierarchy,
                    message: String::from(
                        "Error converting filepath to string!",
                    ),
                    source_component: Rc::new(ComponentInformation::core(
                        "get_component_ids",
                    )),
                })
            }
        };
        log::trace!("filepath: {:#?}", filepath);
        // glob it!
        let glob_paths = match glob::glob(&filepath) {
            Ok(paths) => paths,
            Err(e) => {
                return Err(LewpError {
                    kind: LewpErrorKind::FileHierarchy,
                    message: format!("Error during glob call: {}", e),
                    source_component: Rc::new(ComponentInformation::core(
                        "get_component_ids",
                    )),
                })
            }
        };
        // iterate through paths
        for path in glob_paths {
            match path {
                Ok(p) => {
                    if let Some(ext) = kind.extension() {
                        // an extension is available so count the number of files
                        let count = walkdir::WalkDir::new(&p)
                            .follow_links(true)
                            .into_iter()
                            .filter_entry(|e| {
                                if e.file_type().is_dir() {
                                    return true;
                                }
                                let depth = e.depth() == 1;
                                let extension = e
                                    .file_name()
                                    .to_str()
                                    .map(|s| s.ends_with(&format!(".{}", ext)))
                                    .unwrap_or(false);
                                depth && extension
                            })
                            .count();
                        // skip path if there are no files
                        // if there is only one entry, it is the directory
                        // itself where we are iterating over
                        if count == 1 {
                            continue;
                        }
                    }
                    let p = self.extract_component_ids_from_pathbuf(&p)?;
                    v.push(p);
                }
                Err(e) => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: format!(
                            "Error during glob call: {}",
                            e.into_error()
                        ),
                        source_component: Rc::new(ComponentInformation::core(
                            "get_component_ids",
                        )),
                    })
                }
            }
        }
        log::trace!("Found component ids:\n{:#?}", v);
        Ok(v)
    }

    /// Extracts the component id from the given PathBuf.
    ///
    /// Example:
    /// `testfiles/modules/footer/css` will result in `footer`.
    fn extract_component_ids_from_pathbuf(
        &self,
        p: &PathBuf,
    ) -> Result<String, LewpError> {
        let os_str = match p.parent() {
            Some(parent) => match parent.file_name() {
                Some(f) => f,
                None => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: format!(
                            "Could not extract file name from parent of PathBuf: {:#?}",
                            p
                        ),
                        source_component: Rc::new(ComponentInformation::core(
                            "extract_component_ids_from_pathbuf",
                        )),
                    })
            }
            },
            None => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: format!(
                            "Could not extract parent from PathBuf: {:#?}",
                            p
                        ),
                        source_component: Rc::new(ComponentInformation::core(
                            "extract_component_ids_from_pathbuf",
                        )),
                    })
            }
        };
        let id = match os_str.to_str() {
            Some(s) => s.to_string(),
            None => {
                return Err(LewpError {
                    kind: LewpErrorKind::FileHierarchy,
                    message: format!(
                        "Could not create String from OsStr: {:#?}",
                        os_str
                    ),
                    source_component: Rc::new(ComponentInformation::core(
                        "extract_component_ids_from_pathbuf",
                    )),
                })
            }
        };
        Ok(id)
    }

    /// Removes `../` from the given string to isolate the filepath to a base
    /// directory.
    fn isolate_path(&self, path: &str) -> String {
        let s = String::from(path);
        let mut s = s.split('/').collect::<Vec<&str>>();
        s.retain(|&e| !e.contains(".."));
        s.join("/")
    }

    /// Collects all folders in the given subfolder. Can be used to find eg.
    /// all modules available
    ///
    /// **For internal use only.**
    fn collect_foldernames(
        &self,
        subfolder: &PathBuf,
    ) -> Result<Vec<PathBuf>, LewpError> {
        let subfolder = self.mountpoint.join(subfolder);
        if !subfolder.is_dir() {
            return Err(LewpError {
                kind: LewpErrorKind::FileHierarchy,
                message: format!(
                    "Given input is not a folder: {}",
                    subfolder.display()
                ),
                source_component: Rc::new(ComponentInformation::core(
                    "collect_foldernames",
                )),
            });
        }
        let mut foldernames = vec![];
        for entry in walkdir::WalkDir::new(&subfolder) {
            let entry = match entry {
                Ok(v) => v.into_path(),
                Err(msg) => {
                    return Err(LewpError {
                        kind: LewpErrorKind::FileHierarchy,
                        message: msg.to_string(),
                        source_component: Rc::new(ComponentInformation::core(
                            "collect_foldernames",
                        )),
                    });
                }
            };
            if !entry.is_dir() {
                // skip files because we only want to get the folders in the list
                continue;
            }
            foldernames.push(entry);
        }
        Ok(foldernames)
    }
}

impl Default for FileHierarchy {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use {
        super::{
            Component,
            ComponentInformation,
            ComponentType,
            FileHierarchy,
            FileHierarchyBuilder,
            Level,
        },
        crate::LewpError,
        std::rc::Rc,
    };
    struct Css {
        id: String,
        fh: Rc<FileHierarchy>,
    }
    impl Component for Css {
        type Content = ();
        type ContentParameter = ();
        fn component_information(&self) -> Rc<ComponentInformation> {
            Rc::new(ComponentInformation {
                id: self.id.clone(),
                level: Level::Module,
                kind: ComponentType::Css,
            })
        }
        fn content(
            &self,
            _: Self::ContentParameter,
        ) -> Result<Self::Content, LewpError> {
            Ok(())
        }
        fn file_hierarchy(&self) -> Rc<FileHierarchy> {
            self.fh.clone()
        }
    }
    struct Js {
        fh: Rc<FileHierarchy>,
    }
    impl Component for Js {
        type Content = ();
        type ContentParameter = ();
        fn component_information(&self) -> Rc<ComponentInformation> {
            Rc::new(ComponentInformation {
                id: "hello-world".to_string(),
                level: Level::Page,
                kind: ComponentType::JavaScript,
            })
        }
        fn content(
            &self,
            _: Self::ContentParameter,
        ) -> Result<Self::Content, LewpError> {
            Ok(())
        }
        fn file_hierarchy(&self) -> Rc<FileHierarchy> {
            self.fh.clone()
        }
    }

    #[test]
    fn folder_name_generation() {
        let fh = Rc::new(FileHierarchy::new());
        let css = Css {
            id: String::from("module-id"),
            fh: fh.clone(),
        };
        let js = Js { fh: fh.clone() };
        assert_eq!(
            "./modules/module-id/css",
            fh.folder(&css).to_str().unwrap()
        );
        assert_eq!("./pages/hello-world/js", fh.folder(&js).to_str().unwrap());
    }

    #[test]
    fn isolate_file_paths() {
        let fh = FileHierarchyBuilder::new().build();
        let breakout = "../something";
        let isolated = fh.isolate_path(breakout);
        assert_eq!(isolated, "something");
        let non_breakout = "something/subfolder";
        let isolated = fh.isolate_path(non_breakout);
        assert_eq!(isolated, "something/subfolder");
    }

    #[test]
    fn collect_filenames() {
        use std::path::PathBuf;
        let fh = Rc::new(
            FileHierarchyBuilder::new()
                .mountpoint(PathBuf::from("testfiles"))
                .build(),
        );
        let css = Css {
            id: String::from("hello-world"),
            fh: fh.clone(),
        };
        let mut filenames = match fh.get_file_list(&css) {
            Ok(f) => f,
            Err(e) => {
                panic!("{}", e)
            }
        };
        let mut reference = vec![
            PathBuf::from("modules/hello-world/css/primary.css"),
            PathBuf::from("modules/hello-world/css/secondary.css"),
        ];
        assert_eq!(filenames.sort(), reference.sort());
    }

    #[test]
    fn collect_foldernames() {
        use std::path::PathBuf;
        let fh = Rc::new(
            FileHierarchyBuilder::new()
                .mountpoint(PathBuf::from("testfiles"))
                .build(),
        );
        let css = Css {
            id: String::from("hello-world"),
            fh: fh.clone(),
        };
        let mut filenames =
            match fh.collect_foldernames(&PathBuf::from("modules")) {
                Ok(f) => f,
                Err(e) => {
                    panic!("{}", e)
                }
            };
        let mut reference = vec![PathBuf::from("modules/hello-world")];
        assert_eq!(filenames.sort(), reference.sort());
    }

    #[test]
    fn collect_component_ids() {
        use std::path::PathBuf;
        let fh = Rc::new(
            FileHierarchyBuilder::new()
                .mountpoint(PathBuf::from("testfiles"))
                .build(),
        );
        let mut component_ids =
            match fh.collect_component_ids(ComponentType::Css, Level::Module) {
                Ok(ids) => ids,
                Err(e) => {
                    panic!("{}", e)
                }
            };
        let mut reference = vec!["footer", "hello-world", "navigation"];
        assert_eq!(component_ids.sort(), reference.sort());
    }
}