grimoire_css 1.8.1

A magical CSS engine for all environments
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
//! This module defines the `ParserFs` struct, which extends the base Parser
//! with filesystem-specific functionality for collecting CSS classes from files and directories.

use super::Parser;
use crate::core::SourceFile;
use crate::{buffer::add_message, core::GrimoireCssError};
use std::{
    collections::HashSet,
    fs,
    path::{Path, PathBuf},
    sync::Arc,
};

type Span = (usize, usize);
type ClassWithSpan = (String, Span);
type ClassesWithSpans = Vec<ClassWithSpan>;

type SingleOutputFileClasses = (PathBuf, ClassesWithSpans);
type MultipleOutputFileClasses = (PathBuf, PathBuf, ClassesWithSpans);

/// `ParserFs` extends the base `Parser` with filesystem-specific functionality.
/// It handles file reading, directory traversal, and path resolution.
pub struct ParserFs {
    current_dir: PathBuf,
    base_parser: Parser,
}

impl ParserFs {
    /// Creates a new `ParserFs` instance.
    ///
    /// # Arguments
    ///
    /// * `current_dir` - The base directory where the parser will operate.
    pub fn new(current_dir: &Path) -> Self {
        Self {
            current_dir: current_dir.to_path_buf(),
            base_parser: Parser::new(),
        }
    }

    /// Collects all class names and templated spells from a set of input files, storing them in a vector.
    ///
    /// # Arguments
    ///
    /// * `input_paths` - A vector of file paths (as strings) relative to the `current_dir`.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing file path and found classes with spans.
    ///
    /// # Errors
    ///
    /// Returns a `GrimoireCSSError` if there is an issue reading any of the files.
    pub fn collect_classes_single_output(
        &self,
        input_paths: &Vec<String>,
    ) -> Result<Vec<SingleOutputFileClasses>, GrimoireCssError> {
        let mut results = Vec::new();
        let mut seen_class_names: HashSet<String> = HashSet::new();

        for input_path in input_paths {
            let path = self.current_dir.join(input_path);
            self.collect_spells_from_path(&path, &mut results, &mut seen_class_names)?;
        }

        Ok(results)
    }

    /// Collects class names or templated spells from multiple input paths, producing multiple outputs.
    ///
    /// # Arguments
    ///
    /// * `input_paths` - A vector of file paths to process.
    /// * `output_dir_path` - The directory where the output CSS files will be placed.
    ///
    /// # Returns
    ///
    /// A vector of tuples: (OutputCssPath, InputSourcePath, ClassesWithSpans).
    ///
    /// # Errors
    ///
    /// Returns a `GrimoireCSSError` if any file or directory cannot be processed.
    #[allow(dead_code)]
    pub fn collect_classes_multiple_output(
        &self,
        input_paths: &Vec<String>,
        output_dir_path: &Path,
    ) -> Result<Vec<MultipleOutputFileClasses>, GrimoireCssError> {
        let mut res = Vec::new();

        for input_path_string in input_paths {
            let path = self.current_dir.join(input_path_string);

            if path.is_file() {
                let mut class_names = Vec::new();
                let mut seen_class_names: HashSet<String> = HashSet::new();

                let output_file_path = path.with_extension("css");
                let bundle_output_full_path =
                    output_dir_path.join(output_file_path.file_name().ok_or_else(|| {
                        GrimoireCssError::InvalidPath(output_file_path.to_string_lossy().into())
                    })?);

                let file_content = fs::read_to_string(&path)?;
                if let Err(e) = self.base_parser.collect_candidates(
                    &file_content,
                    &mut class_names,
                    &mut seen_class_names,
                ) {
                    let src = Arc::new(SourceFile::new(
                        Some(path.clone()),
                        path.to_string_lossy().to_string(),
                        file_content.clone(),
                    ));
                    return Err(e.with_source(src));
                }

                res.push((bundle_output_full_path, path, class_names));
            } else if path.is_dir() {
                let entries = &self.get_sorted_directory_entries(&path)?;

                let dir_entry_strings = entries
                    .iter()
                    .map(|p| {
                        p.strip_prefix(&self.current_dir)
                            .unwrap_or(p)
                            .to_string_lossy()
                            .into()
                    })
                    .collect::<Vec<String>>();

                res.extend(
                    self.collect_classes_multiple_output(&dir_entry_strings, output_dir_path)?,
                );
            } else {
                add_message(format!("Invalid path: {}", path.display()));
            }
        }

        Ok(res)
    }

    /// Streaming variant of `collect_classes_multiple_output`.
    ///
    /// Calls `visitor` once per input file instead of building a large in-memory vector.
    pub fn for_each_classes_multiple_output<F>(
        &self,
        input_paths: &Vec<String>,
        output_dir_path: &Path,
        mut visitor: F,
    ) -> Result<(), GrimoireCssError>
    where
        F: FnMut(PathBuf, PathBuf, ClassesWithSpans) -> Result<(), GrimoireCssError>,
    {
        for input_path_string in input_paths {
            let path = self.current_dir.join(input_path_string);
            self.visit_classes_multiple_output_path(&path, output_dir_path, &mut visitor)?;
        }

        Ok(())
    }

    fn visit_classes_multiple_output_path<F>(
        &self,
        path: &Path,
        output_dir_path: &Path,
        visitor: &mut F,
    ) -> Result<(), GrimoireCssError>
    where
        F: FnMut(PathBuf, PathBuf, ClassesWithSpans) -> Result<(), GrimoireCssError>,
    {
        if path.is_file() {
            let mut class_names = Vec::new();
            let mut seen_class_names: HashSet<String> = HashSet::new();

            let output_file_path = path.with_extension("css");
            let bundle_output_full_path =
                output_dir_path.join(output_file_path.file_name().ok_or_else(|| {
                    GrimoireCssError::InvalidPath(output_file_path.to_string_lossy().into())
                })?);

            let file_content = fs::read_to_string(path)?;
            if let Err(e) = self.base_parser.collect_candidates(
                &file_content,
                &mut class_names,
                &mut seen_class_names,
            ) {
                let src = Arc::new(SourceFile::new(
                    Some(path.to_path_buf()),
                    path.to_string_lossy().to_string(),
                    file_content.clone(),
                ));
                return Err(e.with_source(src));
            }

            visitor(bundle_output_full_path, path.to_path_buf(), class_names)?;
            return Ok(());
        }

        if path.is_dir() {
            let entries = self.get_sorted_directory_entries(path)?;
            for entry in entries {
                self.visit_classes_multiple_output_path(&entry, output_dir_path, visitor)?;
            }
            return Ok(());
        }

        add_message(format!("Invalid path: {}", path.display()));
        Ok(())
    }

    /// Recursively collects CSS class names or templated spells from a given file or directory path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path of the file or directory to process.
    /// * `results` - A mutable reference to a vector that stores the collected results.
    /// * `seen_class_names` - A mutable reference to a HashSet for tracking seen class names.
    ///
    /// # Errors
    ///
    /// Returns a `GrimoireCSSError` if there is an issue reading a file.
    fn collect_spells_from_path(
        &self,
        path: &Path,
        results: &mut Vec<SingleOutputFileClasses>,
        seen_class_names: &mut HashSet<String>,
    ) -> Result<(), GrimoireCssError> {
        if path.is_file() {
            let file_content = fs::read_to_string(path)?;
            let mut class_names = Vec::new();

            if let Err(e) = self.base_parser.collect_candidates(
                &file_content,
                &mut class_names,
                seen_class_names,
            ) {
                let src = Arc::new(SourceFile::new(
                    Some(path.to_path_buf()),
                    path.to_string_lossy().to_string(),
                    file_content.clone(),
                ));
                return Err(e.with_source(src));
            }

            if !class_names.is_empty() {
                results.push((path.to_path_buf(), class_names));
            }
        } else if path.is_dir() {
            let entries = &self.get_sorted_directory_entries(path)?;

            for entry in entries {
                self.collect_spells_from_path(entry, results, seen_class_names)?;
            }
        } else {
            add_message(format!("Invalid path: {}", path.display()));
        }

        Ok(())
    }
    /// Retrieves and sorts all entries in a given directory.
    ///
    /// # Arguments
    ///
    /// * `path` - The directory path to read.
    ///
    /// # Returns
    ///
    /// A sorted vector of paths found in the directory.
    ///
    /// # Errors
    ///
    /// Returns a `GrimoireCSSError` if there is an issue reading the directory.
    fn get_sorted_directory_entries(&self, path: &Path) -> Result<Vec<PathBuf>, GrimoireCssError> {
        let mut entries = fs::read_dir(path)?
            .map(|res| res.map(|e| e.path()))
            .collect::<Result<Vec<PathBuf>, _>>()?;

        entries.sort();

        Ok(entries)
    }

    pub fn collect_raw_spells(
        &self,
        content: &str,
    ) -> Result<Vec<String>, crate::core::GrimoireCssError> {
        let mut raw_spells = Vec::new();
        let mut seen = std::collections::HashSet::new();
        self.base_parser
            .collect_candidates(content, &mut raw_spells, &mut seen)?;
        Ok(raw_spells.into_iter().map(|(s, _)| s).collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self};
    use tempfile::tempdir;

    #[test]
    fn test_collect_classes_single_output() {
        let temp_dir = tempdir().unwrap();
        let test_file = temp_dir.path().join("test.html");
        fs::write(
            &test_file,
            r#"<div class="test1 test2"></div><div className="test3"></div>"#,
        )
        .unwrap();

        let parser = ParserFs::new(temp_dir.path());
        let result =
            parser.collect_classes_single_output(&vec![test_file.to_str().unwrap().to_string()]);

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        let (path, classes) = &results[0];
        assert_eq!(path, &test_file);
        assert_eq!(classes.len(), 3);

        let class_names: Vec<String> = classes.iter().map(|(n, _)| n.clone()).collect();
        assert!(class_names.contains(&"test1".to_string()));
        assert!(class_names.contains(&"test2".to_string()));
        assert!(class_names.contains(&"test3".to_string()));
    }

    #[test]
    fn test_collect_classes_multiple_output() {
        let temp_dir = tempdir().unwrap();
        let test_file1 = temp_dir.path().join("test1.html");
        let test_file2 = temp_dir.path().join("test2.html");

        fs::write(&test_file1, r#"<div class="file1-class"></div>"#).unwrap();
        fs::write(&test_file2, r#"<div class="file2-class"></div>"#).unwrap();

        let parser = ParserFs::new(temp_dir.path());
        let output_dir = temp_dir.path().join("output");
        fs::create_dir(&output_dir).unwrap();

        let result = parser.collect_classes_multiple_output(
            &vec![
                test_file1.to_str().unwrap().to_string(),
                test_file2.to_str().unwrap().to_string(),
            ],
            &output_dir,
        );

        assert!(result.is_ok());
        let outputs = result.unwrap();
        assert_eq!(outputs.len(), 2);

        // Check first file output
        let (_, _, classes1) = &outputs[0];
        assert_eq!(classes1.len(), 1);
        assert_eq!(classes1[0].0, "file1-class");

        // Check second file output
        let (_, _, classes2) = &outputs[1];
        assert_eq!(classes2.len(), 1);
        assert_eq!(classes2[0].0, "file2-class");
    }

    #[test]
    fn test_collect_from_directory() {
        let temp_dir = tempdir().unwrap();
        let sub_dir = temp_dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();

        fs::write(
            sub_dir.join("test.html"),
            r#"<div class="nested-class"></div>"#,
        )
        .unwrap();

        let parser = ParserFs::new(temp_dir.path());
        let result =
            parser.collect_classes_single_output(&vec![sub_dir.to_str().unwrap().to_string()]);

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        let (_, classes) = &results[0];
        assert_eq!(classes.len(), 1);
        assert_eq!(classes[0].0, "nested-class");
    }

    #[test]
    fn test_invalid_path() {
        let temp_dir = tempdir().unwrap();
        let parser = ParserFs::new(temp_dir.path());
        let result = parser.collect_classes_single_output(&vec!["nonexistent.html".to_string()]);
        println!("{result:?}");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_empty_input() {
        let temp_dir = tempdir().unwrap();
        let parser = ParserFs::new(temp_dir.path());
        let result = parser.collect_classes_single_output(&vec!["empty.html".to_string()]);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[test]
    fn test_collect_classes_single_output_dedups_across_files() {
        let temp_dir = tempdir().unwrap();
        let a = temp_dir.path().join("a.html");
        let b = temp_dir.path().join("b.html");

        // Same token appears in both files.
        fs::write(&a, r#"<div class="h=10px"></div>"#).unwrap();
        fs::write(&b, r#"<div class="h=10px"></div>"#).unwrap();

        let parser = ParserFs::new(temp_dir.path());
        let input_paths = vec!["a.html".to_string(), "b.html".to_string()];

        let results = parser.collect_classes_single_output(&input_paths).unwrap();

        // Dedup is global across all inputs in single-output mode.
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, a);
        assert_eq!(results[0].1.len(), 1);
        assert_eq!(results[0].1[0].0, "h=10px".to_string());
    }
}