Skip to content

Instantly share code, notes, and snippets.

@timsueberkrueb
Last active February 28, 2024 16:34
Show Gist options
  • Save timsueberkrueb/e63a551b7efcede815cf5d5df2877f32 to your computer and use it in GitHub Desktop.
Save timsueberkrueb/e63a551b7efcede815cf5d5df2877f32 to your computer and use it in GitHub Desktop.
Rust build.rs file to compile SASS to CSS
use std::ffi::OsStr;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use sass_rs;
use walkdir::{DirEntry, WalkDir};
const SASS_DIR: &str = "assets/sass";
const CSS_DIR: &str = "static/css";
fn is_ignored(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s.starts_with("_"))
.unwrap_or(false)
}
fn main() {
if !Path::new(CSS_DIR).is_dir() {
std::fs::create_dir(CSS_DIR);
}
let walker = WalkDir::new(SASS_DIR).into_iter();
for entry in walker.filter_entry(|e| !is_ignored(e)) {
let entry = entry.unwrap();
let path = entry.path();
if !path.is_file() {
continue;
}
if let Some(ext) = path.extension() {
if ext != "sass" {
continue;
}
let content = sass_rs::compile_file(path, Default::default())
.unwrap_or_else(|err| panic!("Error compiling {}: {}", path.display(), err));
let stripped_path = path.strip_prefix(SASS_DIR).unwrap();
let css_filename = stripped_path
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_owned()
+ ".css";
let css_path = stripped_path.parent().unwrap().join(css_filename);
let css_path = Path::new(CSS_DIR).join(css_path);
let mut css_file = File::create(css_path).unwrap();
css_file.write_all(content.as_bytes()).unwrap();
}
}
}
[build-dependencies]
sass-rs = "0.2"
walkdir = "2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment