Skip to content

Commit

Permalink
Implement sorting using custom sorter from output css file
Browse files Browse the repository at this point in the history
  • Loading branch information
praveenperera committed Jul 9, 2023
1 parent 9fe632c commit 0927653
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 32 deletions.
16 changes: 10 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pub mod consts;
pub mod defaults;
pub mod options;
pub mod parser;
pub mod utils;
pub mod sorter;

use clap::Parser;
use eyre::Result;
Expand Down Expand Up @@ -62,8 +62,12 @@ pub struct Cli {
/// When set, RustyWind will use the config file to derive configurations. The config file
/// current only supports json with one property sortOrder, e.g.
/// { "sortOrder": ["class1", ...] }.
#[arg(long)]
#[arg(long, conflicts_with_all = &["output_css_file"])]
config_file: Option<String>,
/// When set RustyWind will determine the sort order
/// by the order the class appears in the the given css file.
#[arg(long, conflicts_with_all = &["config_file"])]
output_css_file: Option<String>,
/// When set, RustyWind will ignore this list of files.
#[arg(long)]
ignored_files: Option<Vec<String>>,
Expand Down Expand Up @@ -99,8 +103,8 @@ fn main() -> Result<()> {
if let WriteMode::ToStdOut = &options.write_mode {
let contents = options.stdin.clone().unwrap_or_default();

if utils::has_classes(&contents, &options) {
let sorted_content = utils::sort_file_contents(&contents, &options);
if sorter::has_classes(&contents, &options) {
let sorted_content = sorter::sort_file_contents(&contents, &options);
print!("{sorted_content}");
} else {
print!("{contents}");
Expand Down Expand Up @@ -129,8 +133,8 @@ fn run_on_file_paths(file_path: &Path, options: &Options) {

match fs::read_to_string(file_path) {
Ok(contents) => {
if utils::has_classes(&contents, options) {
let sorted_content = utils::sort_file_contents(&contents, options);
if sorter::has_classes(&contents, options) {
let sorted_content = sorter::sort_file_contents(&contents, options);

match &options.write_mode {
WriteMode::ToStdOut => (),
Expand Down
22 changes: 16 additions & 6 deletions src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::io::Read;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::parser;
use crate::Cli;

#[derive(Debug)]
Expand Down Expand Up @@ -80,8 +81,17 @@ impl Options {
}

fn get_sorter_from_cli(cli: &Cli) -> Result<Sorter> {
match &cli.config_file {
Some(config_file) => {
match (&cli.config_file, &cli.output_css_file) {
(_, Some(css_file)) => {
let css_file = std::fs::File::open(css_file)
.wrap_err_with(|| format!("Error opening the css file {css_file}"))
.with_suggestion(|| format!("Make sure the file {css_file} exists"))?;

let sorter = parser::parse_classes(css_file).wrap_err("Error parsing the css file")?;
Ok(Sorter::CustomSorter(sorter))
}

(Some(config_file), _) => {
let file_contents = fs::read_to_string(config_file)
.wrap_err_with(|| format!("Error reading the config file {config_file}"))
.with_suggestion(|| format!("Make sure the file {config_file} exists"));
Expand All @@ -92,11 +102,11 @@ fn get_sorter_from_cli(cli: &Cli) -> Result<Sorter> {
format!("Make sure the {config_file} is valid json, with the expected format")
})?;

Ok(Sorter::CustomSorter(parse_custom_sorter(
config_file.sort_order,
)))
let sorter = parse_custom_sorter(config_file.sort_order);
Ok(Sorter::CustomSorter(sorter))
}
None => Ok(Sorter::DefaultSorter),

(None, None) => Ok(Sorter::DefaultSorter),
}
}

Expand Down
27 changes: 16 additions & 11 deletions src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
use std::collections::HashMap;
use std::{
collections::{hash_map::Entry, HashMap},
fs::File,
io::{BufRead, BufReader},
};

use once_cell::sync::Lazy;
use regex::Regex;

pub static PARSER_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"^(\.[^\s]+)[ ]"#).unwrap());
static PARSER_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"^(\.[^\s]+)[ ]"#).unwrap());

pub fn parse_classes(css: &str) -> HashMap<String, usize> {
pub fn parse_classes(css_file: File) -> eyre::Result<HashMap<String, usize>> {
let css_reader = BufReader::new(css_file);
let mut classes: HashMap<String, usize> = HashMap::new();

let mut index = 0_usize;
for line in css.lines() {
if let Some(captures) = PARSER_RE.captures(line) {
let class = captures[1].trim_start_matches('.').replace("\\", "");
for line in css_reader.lines() {
if let Some(captures) = PARSER_RE.captures(&line?) {
let class = captures[1].trim_start_matches('.').replace('\\', "");

if !classes.contains_key(&class) {
classes.insert(class, index);
if let Entry::Vacant(entry) = classes.entry(class) {
entry.insert(index);
index += 1;
}
}
}

classes
Ok(classes)
}

#[cfg(test)]
Expand All @@ -30,8 +35,8 @@ mod tests {

#[test]
fn extracts_all_classes() {
let css = std::fs::read_to_string("tests/fixtures/tailwind.css").unwrap();
let classes = parse_classes(&css);
let css_file = std::fs::File::open("tests/fixtures/tailwind.css").unwrap();
let classes = parse_classes(css_file).unwrap();

assert_eq!(classes.get("container"), Some(&0));
assert_eq!(classes.len(), 221);
Expand Down
File renamed without changes.
18 changes: 9 additions & 9 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ mod tests {
"#.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand All @@ -64,7 +64,7 @@ mod tests {
"#.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand All @@ -88,7 +88,7 @@ mod tests {
"#.to_string();

assert_eq!(
utils::sort_file_contents(
sort::sort_file_contents(
file_contents,
&Options {
allow_duplicates: true,
Expand All @@ -111,7 +111,7 @@ mod tests {
.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand Down Expand Up @@ -154,7 +154,7 @@ fn test_multi_line_class_list() {
.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand Down Expand Up @@ -192,7 +192,7 @@ fn test_sort_file_contents_with_space_and_newline_separated_class_lists() {
.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand All @@ -217,7 +217,7 @@ fn test_sort_file_contents_with_spaces_newlines_and_custom_classes() {
.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand All @@ -242,7 +242,7 @@ fn test_sort_file_contents_with_responsive_classes() {
"#.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}
Expand All @@ -267,7 +267,7 @@ fn test_sort_file_contents_with_variant_classes() {
"#.to_string();

assert_eq!(
utils::sort_file_contents(file_contents, &default_options_for_test()),
sort::sort_file_contents(file_contents, &default_options_for_test()),
expected_outcome
)
}

0 comments on commit 0927653

Please sign in to comment.