sherwood 0.7.0

A static site generator with built-in development server
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
use super::css_processing::{apply_minification, serialize_stylesheet};
use crate::config::{CssSection, CssTargets};
use crate::core::utils::ensure_directory_exists;
use anyhow::Result;
use include_dir::{Dir, include_dir};
use lightningcss::bundler::{Bundler, FileProvider};
use lightningcss::stylesheet::{ParserOptions, StyleSheet};
use lightningcss::targets::{Browsers, Targets};
use std::fs;
use std::path::{Path, PathBuf};

// Embed styles directory at compile time
static STYLES: Dir = include_dir!("$CARGO_MANIFEST_DIR/styles");

#[derive(Debug, Clone)]
pub struct CssProcessor {
    pub minify: bool,
    pub targets: Targets,
    pub enable_css_modules: bool,
    pub source_maps: bool,
    pub remove_unused: bool,
    pub nesting: bool,
}

impl CssProcessor {
    pub fn new() -> Self {
        Self {
            minify: true,
            targets: get_default_browser_targets(),
            enable_css_modules: false,
            source_maps: false,
            remove_unused: false,
            nesting: true,
        }
    }

    pub fn from_config(css_config: &CssSection, is_development: bool) -> Self {
        let mut processor = Self {
            minify: css_config.minify.unwrap_or(!is_development),
            targets: css_config
                .targets
                .as_ref()
                .map(parse_css_targets)
                .unwrap_or_else(get_default_browser_targets),
            enable_css_modules: false, // TODO: Add CSS modules support later
            source_maps: css_config.source_maps.unwrap_or(is_development),
            remove_unused: css_config.remove_unused.unwrap_or(false),
            nesting: css_config.nesting.unwrap_or(true),
        };

        // Always disable minification and enable source maps in development
        if is_development {
            processor.minify = false;
            processor.source_maps = true;
        }

        processor
    }

    pub fn with_minify(mut self, minify: bool) -> Self {
        self.minify = minify;
        self
    }

    pub fn with_targets(mut self, targets: Targets) -> Self {
        self.targets = targets;
        self
    }

    pub fn with_css_modules(mut self, enable: bool) -> Self {
        self.enable_css_modules = enable;
        self
    }

    pub fn with_source_maps(mut self, enable: bool) -> Self {
        self.source_maps = enable;
        self
    }

    pub fn with_remove_unused(mut self, enable: bool) -> Self {
        self.remove_unused = enable;
        self
    }

    pub fn with_nesting(mut self, enable: bool) -> Self {
        self.nesting = enable;
        self
    }

    /// Process CSS content from a string and return the processed CSS string
    pub fn process_css_string(&self, content: &str, filename: &str) -> Result<String> {
        // Parse CSS with Lightning CSS
        let mut stylesheet = StyleSheet::parse(
            content,
            ParserOptions {
                filename: filename.to_string(),
                ..ParserOptions::default()
            },
        )
        .map_err(|e| anyhow::anyhow!("Failed to parse CSS content from {}: {}", filename, e))?;

        // Apply minification and other processing using shared functions
        apply_minification(&mut stylesheet, self)?;

        // Serialize to CSS
        serialize_stylesheet(&stylesheet, self, filename)
    }

    /// Write processed CSS content to a file
    pub fn write_processed_css(&self, content: &str, output_path: &Path) -> Result<()> {
        ensure_directory_exists(output_path.parent().unwrap_or_else(|| Path::new("")))?;
        fs::write(output_path, content)?;
        Ok(())
    }

    /// Process CSS from a file and write to output file (legacy method)
    pub fn process_css_file(&self, input_path: &Path, output_path: &Path) -> Result<()> {
        let css_content = fs::read_to_string(input_path)?;
        let filename = input_path.to_string_lossy().to_string();

        let processed_content = self.process_css_string(&css_content, &filename)?;
        self.write_processed_css(&processed_content, output_path)?;

        println!(
            "Processed CSS: {} -> {}",
            input_path.display(),
            output_path.display()
        );

        Ok(())
    }

    pub fn bundle_css_files(&self, entry_point: &Path, output_dir: &Path) -> Result<PathBuf> {
        // Use Lightning CSS bundler for proper @import resolution
        let fs_provider = FileProvider::new();
        let mut bundler = Bundler::new(
            &fs_provider,
            None,
            ParserOptions {
                filename: entry_point.to_string_lossy().to_string(),
                ..ParserOptions::default()
            },
        );

        let mut stylesheet = bundler.bundle(entry_point).map_err(|e| {
            anyhow::anyhow!("Failed to bundle CSS file {}: {}", entry_point.display(), e)
        })?;

        // Apply minification and other processing using shared functions
        apply_minification(&mut stylesheet, self)?;

        // Serialize to CSS
        let filename = entry_point.to_string_lossy();
        let result = serialize_stylesheet(&stylesheet, self, &filename)?;

        // Always output to main.css for consistent behavior
        let output_path = output_dir.join("main.css");

        ensure_directory_exists(output_dir)?;

        // Write the bundled CSS
        fs::write(&output_path, &result)?;

        println!(
            "Bundled CSS: {} -> {}",
            entry_point.display(),
            output_path.display()
        );

        Ok(output_path)
    }
}

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

fn parse_css_targets(css_targets: &CssTargets) -> Targets {
    let mut browsers = Browsers::default();

    // Parse individual browser versions
    if let Some(chrome) = &css_targets.chrome
        && let Ok(version) = parse_browser_version(chrome)
    {
        browsers.chrome = Some(version);
    }

    if let Some(firefox) = &css_targets.firefox
        && let Ok(version) = parse_browser_version(firefox)
    {
        browsers.firefox = Some(version);
    }

    if let Some(safari) = &css_targets.safari
        && let Ok(version) = parse_browser_version(safari)
    {
        browsers.safari = Some(version);
    }

    if let Some(edge) = &css_targets.edge
        && let Ok(version) = parse_browser_version(edge)
    {
        browsers.edge = Some(version);
    }

    // TODO: Parse browserslist string if provided
    // For now, fall back to defaults if browserslist is provided
    if css_targets.browserslist.is_some() {
        return get_default_browser_targets();
    }

    Targets {
        browsers: Some(browsers),
        ..Targets::default()
    }
}

fn parse_browser_version(version_str: &str) -> Result<u32, std::num::ParseIntError> {
    // Parse version like "103" or "103.0" to Lightning CSS format (version << 16)
    let parts: Vec<&str> = version_str.split('.').collect();
    let major: u32 = parts[0].parse()?;

    // Lightning CSS uses version in format: (major << 16) | (minor << 8) | patch
    let minor = if parts.len() > 1 {
        parts[1].parse().unwrap_or(0)
    } else {
        0
    };
    let patch = if parts.len() > 2 {
        parts[2].parse().unwrap_or(0)
    } else {
        0
    };

    Ok((major << 16) | (minor << 8) | patch)
}

fn get_default_browser_targets() -> Targets {
    // Target modern browsers for better CSS support
    let browsers = Browsers {
        chrome: Some(103 << 16),  // Chrome 103+
        firefox: Some(115 << 16), // Firefox 115+
        safari: Some(15 << 16),   // Safari 15+
        edge: Some(127 << 16),    // Edge 127+
        ..Browsers::default()
    };

    Targets {
        browsers: Some(browsers),
        ..Targets::default()
    }
}

#[derive(Debug)]
pub struct StyleManager {
    styles_dir: PathBuf,
    css_processor: CssProcessor,
    #[allow(dead_code)]
    is_development: bool,
}

// Entry point validation types and functions
#[derive(Debug)]
pub enum EntryPointValidationError {
    Empty,
    ContainsPathSeparators,
    MissingExtension,
    InvalidExtension,
}

impl std::fmt::Display for EntryPointValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EntryPointValidationError::Empty => write!(f, "cannot be empty"),
            EntryPointValidationError::ContainsPathSeparators => {
                write!(f, "must be a simple filename, not a path")
            }
            EntryPointValidationError::MissingExtension => write!(f, "must have a file extension"),
            EntryPointValidationError::InvalidExtension => write!(f, "must end with .css"),
        }
    }
}

fn validate_css_entry_point(entry_point: &str) -> Result<String, EntryPointValidationError> {
    if entry_point.is_empty() {
        return Err(EntryPointValidationError::Empty);
    }

    if entry_point.contains('/') || entry_point.contains('\\') {
        return Err(EntryPointValidationError::ContainsPathSeparators);
    }

    if !entry_point.contains('.') {
        return Err(EntryPointValidationError::MissingExtension);
    }

    if !entry_point.ends_with(".css") {
        return Err(EntryPointValidationError::InvalidExtension);
    }

    Ok(entry_point.to_string())
}

fn resolve_and_validate_entry_point(css_config: Option<&CssSection>) -> String {
    if let Some(css_config) = css_config
        && let Some(entry_point) = &css_config.entry_point
    {
        match validate_css_entry_point(entry_point) {
            Ok(validated) => validated,
            Err(error) => {
                eprintln!(
                    "⚠️  Warning: Invalid CSS entry point '{}': {}. Using default 'main.css'.",
                    entry_point, error
                );
                "main.css".to_string()
            }
        }
    } else {
        "main.css".to_string()
    }
}

impl StyleManager {
    pub fn new(styles_dir: &Path) -> Self {
        Self::new_with_config(styles_dir, None, false)
    }

    pub fn new_development(styles_dir: &Path) -> Self {
        Self::new_with_config(styles_dir, None, true)
    }

    pub fn new_with_config(
        styles_dir: &Path,
        css_config: Option<&CssSection>,
        is_development: bool,
    ) -> Self {
        let css_processor = if let Some(config) = css_config {
            CssProcessor::from_config(config, is_development)
        } else {
            let processor = CssProcessor::new();
            if is_development {
                processor.with_minify(false).with_source_maps(true)
            } else {
                processor
            }
        };

        Self {
            styles_dir: styles_dir.to_path_buf(),
            css_processor,
            is_development,
        }
    }

    pub fn with_processor(
        styles_dir: &Path,
        css_processor: CssProcessor,
        is_development: bool,
    ) -> Self {
        Self {
            styles_dir: styles_dir.to_path_buf(),
            css_processor,
            is_development,
        }
    }

    fn list_available_css_files(&self) -> Result<String> {
        if !self.styles_dir.exists() {
            return Ok("(no styles directory)".to_string());
        }

        let mut files = Vec::new();
        for entry in fs::read_dir(&self.styles_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file()
                && path.extension().is_some_and(|ext| ext == "css")
                && let Some(name) = path.file_name()
            {
                files.push(name.to_string_lossy().to_string());
            }
        }

        if files.is_empty() {
            Ok("(no CSS files found)".to_string())
        } else {
            Ok(files.join(", "))
        }
    }

    fn list_embedded_css_files(&self) -> String {
        let mut files = Vec::new();
        for file in STYLES.files() {
            if let Some(file_name) = file.path().file_name()
                && file.path().extension().is_some_and(|ext| ext == "css")
            {
                files.push(file_name.to_string_lossy().to_string());
            }
        }
        if files.is_empty() {
            "(no embedded CSS files found)".to_string()
        } else {
            files.join(", ")
        }
    }

    pub fn generate_css_file(
        &self,
        output_dir: &Path,
        css_config: Option<&CssSection>,
    ) -> Result<PathBuf> {
        let css_dir = output_dir.join("css");
        ensure_directory_exists(&css_dir)?;

        let entry_point = resolve_and_validate_entry_point(css_config);

        // Check if user explicitly configured an entry_point
        let has_explicit_entry_point = css_config
            .and_then(|config| config.entry_point.as_ref())
            .is_some();

        // Try user's styles directory first, fallback to embedded styles
        if self.styles_dir.exists() {
            self.process_user_css_entry_point(&css_dir, &entry_point)?;
        } else if has_explicit_entry_point {
            // User configured entry_point but has no styles directory - error
            return Err(anyhow::anyhow!(
                "CSS entry point '{}' is configured but no styles directory exists at '{}'.\n\
                 Fix: either create the styles directory with the entry point file, or remove the 'entry_point' configuration to use embedded styles.",
                entry_point,
                self.styles_dir.display()
            ));
        } else {
            // No entry_point configured and no styles directory - use embedded styles
            self.process_embedded_css_entry_point(&css_dir, &entry_point)?;
        }

        // Always output to main.css
        Ok(css_dir.join("main.css"))
    }

    fn process_user_css_entry_point(&self, css_dir: &Path, entry_point: &str) -> Result<()> {
        let entry_path = self.styles_dir.join(entry_point);

        if entry_path.exists() {
            // Bundle the specified entry point
            self.css_processor.bundle_css_files(&entry_path, css_dir)?;
            println!("Bundled CSS: {} -> dist/css/main.css", entry_point);
        } else {
            // Entry point not found - provide helpful error message
            return Err(anyhow::anyhow!(
                "CSS entry point '{}' not found in styles directory '{}'.\n\
                 Available files: {}\n\
                 Fix: either create the file or remove the 'entry_point' configuration to use defaults.",
                entry_point,
                self.styles_dir.display(),
                self.list_available_css_files()?
            ));
        }

        Ok(())
    }

    fn process_embedded_css_entry_point(&self, css_dir: &Path, entry_point: &str) -> Result<()> {
        // Check if embedded entry point exists
        if STYLES.get_file(entry_point).is_some() {
            let main_css_path = css_dir.join("main.css");

            // Use secure temporary directory with automatic cleanup
            let temp_dir = tempfile::tempdir()?;
            let temp_path = temp_dir.path();

            // Extract embedded CSS files to temporary directory
            self.extract_embedded_css_to_temp(temp_path)?;

            // Use Lightning CSS bundler for proper @import resolution
            let fs_provider = FileProvider::new();
            let mut bundler = Bundler::new(
                &fs_provider,
                None, // No source map generation yet
                ParserOptions {
                    filename: entry_point.to_string(),
                    ..ParserOptions::default()
                },
            );

            // Change to the temp directory so bundler can resolve relative imports
            let original_dir = std::env::current_dir()?;
            std::env::set_current_dir(temp_path)?;

            let mut stylesheet = bundler
                .bundle(Path::new(entry_point))
                .map_err(|e| anyhow::anyhow!("Failed to bundle embedded CSS: {}", e))?;

            // Restore original working directory
            std::env::set_current_dir(original_dir)?;

            // Apply minification and other processing using shared functions
            apply_minification(&mut stylesheet, &self.css_processor)?;
            let result = serialize_stylesheet(&stylesheet, &self.css_processor, entry_point)?;

            fs::write(&main_css_path, &result)?;

            println!(
                "Bundled embedded CSS: {} -> {}",
                entry_point,
                main_css_path.display()
            );

            // temp_dir automatically cleaned up when it goes out of scope
        } else {
            return Err(anyhow::anyhow!(
                "Embedded CSS entry point '{}' not found.\n\
                 Available embedded files: {}\n\
                 Fix: either add the file to styles/ directory or remove 'entry_point' configuration.",
                entry_point,
                self.list_embedded_css_files()
            ));
        }

        Ok(())
    }

    fn extract_embedded_css_to_temp(&self, temp_dir: &Path) -> Result<()> {
        ensure_directory_exists(temp_dir)?;

        // Extract all embedded CSS files to temporary directory
        for file in STYLES.files() {
            let file_path = file.path();
            if let Some(file_name) = file_path.file_name()
                && let Some(extension) = Path::new(file_name).extension()
                && extension == "css"
            {
                let dest_path = temp_dir.join(file_name);
                if let Some(content) = file.contents_utf8() {
                    fs::write(&dest_path, content)?;
                }
            }
        }

        Ok(())
    }
}