From 0e793243937ba09389d61f70cf306e40eb7ad15b Mon Sep 17 00:00:00 2001 From: JMARyA Date: Thu, 26 Oct 2023 13:51:08 +0200 Subject: [PATCH] add sortBy & reversed args --- Cargo.toml | 6 ++++++ src/args.rs | 2 ++ src/lib.rs | 28 +++++++++++++++++++++++++--- src/main.rs | 6 +++++- 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b8a09d6..1ec7827 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,12 @@ name = "mdq" version = "0.1.0" edition = "2021" +[profile.release] +strip = true +lto = true +codegen-units = 1 +panic = "abort" + [dependencies] clap = { version = "4.4.7", features = ["cargo"] } regex = "1.10.2" diff --git a/src/args.rs b/src/args.rs index e9b6256..22c52ef 100644 --- a/src/args.rs +++ b/src/args.rs @@ -23,5 +23,7 @@ pub fn get_args() -> ArgMatches { .required(false) .default_value("file.title:Title"), ) + .arg(arg!(-s --sortby "Sort results based on specified key").required(false)) + .arg(arg!(-r --reverse "Reverse the results").required(false)) .get_matches() } diff --git a/src/lib.rs b/src/lib.rs index 9e45287..f6edef3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -79,10 +79,32 @@ impl Index { /// Build a table with specified columns from index within specified scope #[must_use] - pub fn select_columns(&self, col: &[String], limit: usize, offset: usize) -> Table { + pub fn select_columns( + &self, + col: &[String], + limit: usize, + offset: usize, + sort: Option, + reverse: bool, + ) -> Table { let mut rows = vec![]; - let scope: Vec<_> = self.documents.clone().into_iter().skip(offset).collect(); + let mut scope = self.documents.clone(); + + if let Some(sort) = sort { + scope.sort_by(|a, b| { + let a = txd::parse(&a.get_key(&sort)); + let b = txd::parse(&b.get_key(&sort)); + + a.order_with(&b) + }); + } + + if reverse { + scope.reverse(); + } + + let scope: Vec<_> = scope.into_iter().skip(offset).collect(); let scope = if limit == 0 { scope @@ -129,7 +151,7 @@ impl Index { a = txd::DataType::String(a_str); } - if !a.compare(f.1, b) { + if !a.compare(f.1, &b) { is_included = false; } } diff --git a/src/main.rs b/src/main.rs index ee65def..27a2a4f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,6 +21,10 @@ fn main() { let offset: usize = args.get_one::("offset").unwrap().parse().unwrap(); + let sort_by = args.get_one::("sortby").map(|x| x.to_owned()); + + let reversed = args.get_flag("reverse"); + let columns: Vec<_> = args .get_many::("column") .unwrap() @@ -51,7 +55,7 @@ fn main() { i = i.filter_documents(&filters); } - let data = i.select_columns(&columns, limit, offset); + let data = i.select_columns(&columns, limit, offset, sort_by, reversed); if output_json { let mut data = serde_json::json!(