Skip to content

Commit

Permalink
refactor: Centralize sass logic
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Oct 27, 2017
1 parent 2f7058e commit bfa2307
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 112 deletions.
80 changes: 8 additions & 72 deletions src/cobalt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,12 @@ use rss;
use jsonfeed::Feed;
use jsonfeed;

#[cfg(feature = "sass")]
use sass_rs;

use config::{Config, SortOrder};
use datetime;
use document::Document;
use error::*;
use config::{Config, SortOrder};
#[cfg(feature = "sass")]
use config::SassOutputStyle;
use files::FilesBuilder;
use files;
use sass;

/// The primary build function that transforms a directory into a site
pub fn build(config: &Config) -> Result<()> {
Expand All @@ -39,7 +35,7 @@ pub fn build(config: &Config) -> Result<()> {

let mut documents = vec![];

let mut page_files = FilesBuilder::new(source)?;
let mut page_files = files::FilesBuilder::new(source)?;
page_files
.add_ignore(&format!("!{}", config.posts.dir))?
.add_ignore(&format!("!{}/**", config.posts.dir))?
Expand Down Expand Up @@ -75,7 +71,7 @@ pub fn build(config: &Config) -> Result<()> {
if let Some(ref drafts_dir) = config.posts.drafts_dir {
debug!("Draft directory: {:?}", drafts_dir);
let drafts_root = source.join(&drafts_dir);
let mut draft_files = FilesBuilder::new(drafts_root.as_path())?;
let mut draft_files = files::FilesBuilder::new(drafts_root.as_path())?;
for line in &config.ignore {
draft_files.add_ignore(line.as_str())?;
}
Expand Down Expand Up @@ -222,7 +218,7 @@ pub fn build(config: &Config) -> Result<()> {
{
info!("Copying remaining assets");

let mut asset_files = FilesBuilder::new(source)?;
let mut asset_files = files::FilesBuilder::new(source)?;
for line in &config.ignore {
asset_files.add_ignore(line.as_str())?;
}
Expand All @@ -231,12 +227,12 @@ pub fn build(config: &Config) -> Result<()> {
!template_extensions.contains(&p.extension().unwrap_or_else(|| OsStr::new("")))
}) {
if file_path.extension() == Some(OsStr::new("scss")) {
compile_sass(config, source, dest, file_path)?;
sass::compile_sass(&config.sass, source, dest, file_path)?;
} else {
let rel_src = file_path
.strip_prefix(source)
.expect("file was found under the root");
copy_file(&file_path, dest.join(rel_src).as_path())?;
files::copy_file(&file_path, dest.join(rel_src).as_path())?;
}
}
}
Expand Down Expand Up @@ -325,66 +321,6 @@ fn create_jsonfeed(path: &str, dest: &Path, config: &Config, posts: &[Document])
Ok(())
}

fn compile_sass<S: AsRef<Path>, D: AsRef<Path>, F: AsRef<Path>>(config: &Config,
source: S,
dest: D,
file_path: F)
-> Result<()> {
compile_sass_internal(config, source.as_ref(), dest.as_ref(), file_path.as_ref())
}

#[cfg(feature = "sass")]
fn compile_sass_internal(config: &Config,
source: &Path,
dest: &Path,
file_path: &Path)
-> Result<()> {
let mut sass_opts = sass_rs::Options::default();
sass_opts.include_paths = vec![source
.join(&config.sass.import_dir)
.into_os_string()
.into_string()
.unwrap()];
sass_opts.output_style = match config.sass.style {
SassOutputStyle::Nested => sass_rs::OutputStyle::Nested,
SassOutputStyle::Expanded => sass_rs::OutputStyle::Expanded,
SassOutputStyle::Compact => sass_rs::OutputStyle::Compact,
SassOutputStyle::Compressed => sass_rs::OutputStyle::Compressed,
};
let content = sass_rs::compile_file(file_path, sass_opts)?;

let rel_src = file_path
.strip_prefix(source)
.expect("file was found under the root");
let mut dest_file = dest.join(rel_src);
dest_file.set_extension("css");

create_document_file(content, dest_file)
}

#[cfg(not(feature = "sass"))]
fn compile_sass_internal(_config: &Config,
source: &Path,
dest: &Path,
file_path: &Path)
-> Result<()> {
let src_file = source.join(file_path);
copy_file(src_file.as_path(), dest.join(file_path).as_path())
}

fn copy_file(src_file: &Path, dest_file: &Path) -> Result<()> {
// create target directories if any exist
if let Some(parent) = dest_file.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("Could not create {:?}: {}", parent, e))?;
}

debug!("Copying {:?} to {:?}", src_file, dest_file);
fs::copy(src_file, dest_file)
.map_err(|e| format!("Could not copy {:?} into {:?}: {}", src_file, dest_file, e))?;
Ok(())
}

fn create_document_file<S: AsRef<str>, P: AsRef<Path>>(content: S, dest_file: P) -> Result<()> {
create_document_file_internal(content.as_ref(), dest_file.as_ref())
}
Expand Down
37 changes: 4 additions & 33 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use error::*;
use files;
use frontmatter;
use legacy::wildwest;
use sass;
use site;
use syntax_highlight::has_syntax_theme;

Expand Down Expand Up @@ -41,36 +42,6 @@ impl Default for SortOrder {
}
}

#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum SassOutputStyle {
Nested,
Expanded,
Compact,
Compressed,
}

const SASS_IMPORT_DIR: &'static str = "_sass";

#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SassOptions {
#[serde(skip)]
pub import_dir: &'static str,
pub style: SassOutputStyle,
}

impl Default for SassOptions {
fn default() -> SassOptions {
SassOptions {
import_dir: SASS_IMPORT_DIR,
style: SassOutputStyle::Nested,
}
}
}

#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
Expand Down Expand Up @@ -142,7 +113,7 @@ pub struct ConfigBuilder {
pub ignore: Vec<String>,
pub syntax_highlight: SyntaxHighlight,
pub layouts_dir: &'static str,
pub sass: SassOptions,
pub sass: sass::SassOptions,
// This is a debug-only field and should be transient rather than persistently set.
#[serde(skip)]
pub dump: Vec<Dump>,
Expand All @@ -167,7 +138,7 @@ impl Default for ConfigBuilder {
ignore: vec![],
syntax_highlight: SyntaxHighlight::default(),
layouts_dir: LAYOUTS_DIR,
sass: SassOptions::default(),
sass: sass::SassOptions::default(),
dump: vec![],
}
}
Expand Down Expand Up @@ -303,7 +274,7 @@ pub struct Config {
pub ignore: Vec<String>,
pub syntax_highlight: SyntaxHighlight,
pub layouts_dir: &'static str,
pub sass: SassOptions,
pub sass: sass::SassOptions,
pub dump: Vec<Dump>,
}

Expand Down
17 changes: 15 additions & 2 deletions src/files.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fs::File;
use std::fs;
use std::io::Read;
use std::path;

Expand Down Expand Up @@ -172,12 +172,25 @@ pub fn cleanup_path(path: String) -> String {
}

pub fn read_file<P: AsRef<path::Path>>(path: P) -> Result<String> {
let mut file = File::open(path.as_ref())?;
let mut file = fs::File::open(path.as_ref())?;
let mut text = String::new();
file.read_to_string(&mut text)?;
Ok(text)
}

pub fn copy_file(src_file: &path::Path, dest_file: &path::Path) -> Result<()> {
// create target directories if any exist
if let Some(parent) = dest_file.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("Could not create {:?}: {}", parent, e))?;
}

debug!("Copying {:?} to {:?}", src_file, dest_file);
fs::copy(src_file, dest_file)
.map_err(|e| format!("Could not copy {:?} into {:?}: {}", src_file, dest_file, e))?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
11 changes: 6 additions & 5 deletions src/legacy/wildwest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use liquid;
use super::super::config;
use super::super::datetime;
use super::super::frontmatter;
use super::super::sass;
use super::super::site;

#[derive(Debug, Eq, PartialEq, Default, Clone)]
Expand Down Expand Up @@ -251,12 +252,12 @@ impl From<GlobalConfig> for config::ConfigBuilder {
};

let syntax_highlight = config::SyntaxHighlight { theme: syntax_highlight.theme };
let sass = config::SassOptions {
let sass = sass::SassOptions {
style: match sass.style {
SassOutputStyle::Nested => config::SassOutputStyle::Nested,
SassOutputStyle::Expanded => config::SassOutputStyle::Expanded,
SassOutputStyle::Compact => config::SassOutputStyle::Compact,
SassOutputStyle::Compressed => config::SassOutputStyle::Compressed,
SassOutputStyle::Nested => sass::SassOutputStyle::Nested,
SassOutputStyle::Expanded => sass::SassOutputStyle::Expanded,
SassOutputStyle::Compact => sass::SassOutputStyle::Compact,
SassOutputStyle::Compressed => sass::SassOutputStyle::Compressed,
},
..Default::default()
};
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ mod cobalt;
mod config;
mod document;
mod new;
mod sass;
mod site;
mod slug;
mod datetime;
Expand Down
85 changes: 85 additions & 0 deletions src/sass.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use std::path;

#[cfg(feature = "sass")]
use sass_rs;

use error::*;
use files;

#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum SassOutputStyle {
Nested,
Expanded,
Compact,
Compressed,
}

const SASS_IMPORT_DIR: &'static str = "_sass";

#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SassOptions {
#[serde(skip)]
pub import_dir: &'static str,
pub style: SassOutputStyle,
}

impl Default for SassOptions {
fn default() -> SassOptions {
SassOptions {
import_dir: SASS_IMPORT_DIR,
style: SassOutputStyle::Nested,
}
}
}

pub fn compile_sass<S: AsRef<path::Path>, D: AsRef<path::Path>, F: AsRef<path::Path>>
(config: &SassOptions,
source: S,
dest: D,
file_path: F)
-> Result<()> {
compile_sass_internal(config, source.as_ref(), dest.as_ref(), file_path.as_ref())
}

#[cfg(feature = "sass")]
fn compile_sass_internal(config: &SassOptions,
source: &path::Path,
dest: &path::Path,
file_path: &path::Path)
-> Result<()> {
let mut sass_opts = sass_rs::Options::default();
sass_opts.include_paths = vec![source
.join(&config.sass.import_dir)
.into_os_string()
.into_string()
.unwrap()];
sass_opts.output_style = match config.sass.style {
SassOutputStyle::Nested => sass_rs::OutputStyle::Nested,
SassOutputStyle::Expanded => sass_rs::OutputStyle::Expanded,
SassOutputStyle::Compact => sass_rs::OutputStyle::Compact,
SassOutputStyle::Compressed => sass_rs::OutputStyle::Compressed,
};
let content = sass_rs::compile_file(file_path, sass_opts)?;

let rel_src = file_path
.strip_prefix(source)
.expect("file was found under the root");
let mut dest_file = dest.join(rel_src);
dest_file.set_extension("css");

create_document_file(content, dest_file)
}

#[cfg(not(feature = "sass"))]
fn compile_sass_internal(_config: &SassOptions,
source: &path::Path,
dest: &path::Path,
file_path: &path::Path)
-> Result<()> {
let src_file = source.join(file_path);
files::copy_file(src_file.as_path(), dest.join(file_path).as_path())
}

0 comments on commit bfa2307

Please sign in to comment.