aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSven-Hendrik Haase <svenstaro@gmail.com>2024-01-13 05:11:59 +0000
committerSven-Hendrik Haase <svenstaro@gmail.com>2024-01-13 05:11:59 +0000
commit562b62a0b638d2ca0731f83476a2e5f74757962a (patch)
tree2073b8249218f86e95d57b7734310495cb7db109
parentFix formatting (diff)
downloadminiserve-562b62a0b638d2ca0731f83476a2e5f74757962a.tar.gz
miniserve-562b62a0b638d2ca0731f83476a2e5f74757962a.zip
Clean up default order function
I removed the stringly typing as we already have enums for this that we can make use of.
-rw-r--r--README.md19
-rw-r--r--src/args.rs9
-rw-r--r--src/config.rs26
-rw-r--r--src/listing.rs25
-rw-r--r--tests/navigation.rs16
-rw-r--r--tests/utils/mod.rs14
6 files changed, 45 insertions, 64 deletions
diff --git a/README.md b/README.md
index b3c832a..9494f91 100644
--- a/README.md
+++ b/README.md
@@ -210,17 +210,24 @@ Options:
[env: MINISERVE_HIDDEN=]
- -S, --default-sorting-method
- Default sort method for file list
+ -S, --default-sorting-method <DEFAULT_SORTING_METHOD>
+ Default sorting method for file list
[env: MINISERVE_DEFAULT_SORTING_METHOD=]
- [possible values: name, date, size]
- -O, --default-sorting-order
- Default sort order for file list
+ Possible values:
+ - name: Sort by name
+ - size: Sort by size
+ - date: Sort by last modification date (natural sort: follows alphanumerical order)
+
+ -O, --default-sorting-order <DEFAULT_SORTING_ORDER>
+ Default sorting order for file list
[env: MINISERVE_DEFAULT_SORTING_ORDER=]
- [possible values: asc, desc]
+
+ Possible values:
+ - ascending: Ascending order
+ - descending: Descending order
-c, --color-scheme <COLOR_SCHEME>
Default color scheme
diff --git a/src/args.rs b/src/args.rs
index e400c8a..cc8b0f1 100644
--- a/src/args.rs
+++ b/src/args.rs
@@ -6,6 +6,7 @@ use http::header::{HeaderMap, HeaderName, HeaderValue};
use crate::auth;
use crate::errors::ContextualError;
+use crate::listing::{SortingMethod, SortingOrder};
use crate::renderer::ThemeSlug;
#[derive(ValueEnum, Clone)]
@@ -117,21 +118,21 @@ pub struct CliArgs {
#[arg(
short = 'S',
long = "default-sorting-method",
- default_value = "",
+ default_value = "name",
ignore_case = true,
env = "MINISERVE_DEFAULT_SORTING_METHOD"
)]
- pub default_sorting_method: String,
+ pub default_sorting_method: SortingMethod,
/// Default sorting order for file list
#[arg(
short = 'O',
long = "default-sorting-order",
- default_value = "",
+ default_value = "desc",
ignore_case = true,
env = "MINISERVE_DEFAULT_SORTING_ORDER"
)]
- pub default_sorting_order: String,
+ pub default_sorting_order: SortingOrder,
/// Default color scheme
#[arg(
diff --git a/src/config.rs b/src/config.rs
index 491ac40..bfe916b 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -52,10 +52,10 @@ pub struct MiniserveConfig {
pub show_hidden: bool,
/// Default sorting method
- pub default_sorting_method: Option<SortingMethod>,
+ pub default_sorting_method: SortingMethod,
/// Default sorting order
- pub default_sorting_order: Option<SortingOrder>,
+ pub default_sorting_order: SortingOrder,
/// Route prefix; Either empty or prefixed with slash
pub route_prefix: String,
@@ -272,24 +272,6 @@ impl MiniserveConfig {
.transpose()?
.unwrap_or_default();
- let default_sorting_method: Option<SortingMethod> = match args
- .default_sorting_method
- .to_owned()
- .parse::<SortingMethod>()
- {
- Ok(value) => Some(value),
- Err(_) => None,
- };
-
- let default_sorting_order: Option<SortingOrder> = match args
- .default_sorting_order
- .to_owned()
- .parse::<SortingOrder>()
- {
- Ok(value) => Some(value),
- Err(_) => None,
- };
-
Ok(MiniserveConfig {
verbose: args.verbose,
path: args.path.unwrap_or_else(|| PathBuf::from(".")),
@@ -299,8 +281,8 @@ impl MiniserveConfig {
path_explicitly_chosen,
no_symlinks: args.no_symlinks,
show_hidden: args.hidden,
- default_sorting_method,
- default_sorting_order,
+ default_sorting_method: args.default_sorting_method,
+ default_sorting_order: args.default_sorting_order,
route_prefix,
favicon_route,
css_route,
diff --git a/src/listing.rs b/src/listing.rs
index 40c5a77..3cd131e 100644
--- a/src/listing.rs
+++ b/src/listing.rs
@@ -5,6 +5,7 @@ use std::time::SystemTime;
use actix_web::{dev::ServiceResponse, web::Query, HttpMessage, HttpRequest, HttpResponse};
use bytesize::ByteSize;
+use clap::ValueEnum;
use comrak::{markdown_to_html, ComrakOptions};
use percent_encoding::{percent_decode_str, utf8_percent_encode};
use regex::Regex;
@@ -39,10 +40,11 @@ pub struct ListingQueryParameters {
}
/// Available sorting methods
-#[derive(Deserialize, Clone, EnumString, Display, Copy)]
+#[derive(Deserialize, Default, Clone, EnumString, Display, Copy, ValueEnum)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum SortingMethod {
+ #[default]
/// Sort by name
Name,
@@ -54,17 +56,18 @@ pub enum SortingMethod {
}
/// Available sorting orders
-#[derive(Deserialize, Clone, EnumString, Display, Copy)]
+#[derive(Deserialize, Default, Clone, EnumString, Display, Copy, ValueEnum)]
pub enum SortingOrder {
/// Ascending order
#[serde(alias = "asc")]
#[strum(serialize = "asc")]
- Ascending,
+ Asc,
/// Descending order
+ #[default]
#[serde(alias = "desc")]
#[strum(serialize = "desc")]
- Descending,
+ Desc,
}
#[derive(PartialEq, Eq)]
@@ -223,7 +226,7 @@ pub fn directory_listing(
res
};
- let mut query_params = extract_query_parameters(req);
+ let query_params = extract_query_parameters(req);
let mut entries: Vec<Entry> = Vec::new();
let mut readme: Option<(String, String)> = None;
@@ -299,15 +302,7 @@ pub fn directory_listing(
}
}
- if query_params.sort.is_none() {
- query_params.sort = conf.default_sorting_method
- }
-
- if query_params.order.is_none() {
- query_params.order = conf.default_sorting_order
- }
-
- match query_params.sort.unwrap_or(SortingMethod::Name) {
+ match query_params.sort.unwrap_or(conf.default_sorting_method) {
SortingMethod::Name => entries.sort_by(|e1, e2| {
alphanumeric_sort::compare_str(e1.name.to_lowercase(), e2.name.to_lowercase())
}),
@@ -327,7 +322,7 @@ pub fn directory_listing(
}),
};
- if let Some(SortingOrder::Ascending) = query_params.order {
+ if let SortingOrder::Asc = query_params.order.unwrap_or(conf.default_sorting_order) {
entries.reverse()
}
diff --git a/tests/navigation.rs b/tests/navigation.rs
index b921d4c..734424a 100644
--- a/tests/navigation.rs
+++ b/tests/navigation.rs
@@ -7,7 +7,7 @@ use rstest::rstest;
use select::document::Document;
use std::process::{Command, Stdio};
use utils::get_link_from_text;
-use utils::get_link_hrefs_from_text_with_prefix;
+use utils::get_link_hrefs_with_prefix;
#[rstest(
input,
@@ -154,22 +154,18 @@ fn can_navigate_using_breadcrumbs(
#[case(server(&["--default-sorting-method", "date", "--default-sorting-order", "asc"]))]
/// We can specify the default sorting order
fn can_specify_default_sorting_order(#[case] server: TestServer) -> Result<(), Error> {
- let slash = String::from("/");
- let base_url = server.url();
- let nested_url = base_url.join(&slash)?;
-
- let resp = reqwest::blocking::get(nested_url.as_str())?;
+ let resp = reqwest::blocking::get(server.url())?;
let body = resp.error_for_status()?;
let parsed = Document::from_read(body)?;
- let links = get_link_hrefs_from_text_with_prefix(&parsed, "/");
- let first_created_file = slash + FILES.first().unwrap();
+ let links = get_link_hrefs_with_prefix(&parsed, "/");
+ let first_created_file = FILES.first().unwrap();
- if links.first().unwrap() == &first_created_file {
+ if links.first().unwrap() == first_created_file {
assert_eq!("/very/?sort=date&order=asc", links.last().unwrap());
}
- if links.last().unwrap() == &first_created_file {
+ if links.last().unwrap() == first_created_file {
assert_eq!("/very/?sort=date&order=desc", links.first().unwrap());
}
diff --git a/tests/utils/mod.rs b/tests/utils/mod.rs
index 64433fc..baffc29 100644
--- a/tests/utils/mod.rs
+++ b/tests/utils/mod.rs
@@ -13,16 +13,16 @@ pub fn get_link_from_text(document: &Document, text: &str) -> Option<String> {
Some(a_elem.attr("href")?.to_string())
}
-/// Return the href attributes of all links that start with the specified prefix `text`.
-pub fn get_link_hrefs_from_text_with_prefix(document: &Document, text: &str) -> Vec<String> {
+/// Return the href attributes of all links that start with the specified `prefix`.
+pub fn get_link_hrefs_with_prefix(document: &Document, prefix: &str) -> Vec<String> {
let mut vec: Vec<String> = Vec::new();
- let a_elem = document.find(Name("a"));
+ let a_elements = document.find(Name("a"));
- for element in a_elem {
- let str = element.attr("href").unwrap_or("");
- if str.to_string().starts_with(text) {
- vec.push(str.to_string());
+ for element in a_elements {
+ let s = element.attr("href").unwrap_or("");
+ if s.to_string().starts_with(prefix) {
+ vec.push(s.to_string());
}
}