Compare commits

...

6 commits

5 changed files with 169 additions and 52 deletions

View file

@ -34,13 +34,20 @@ groups:
routes:
# /ls is the only page that comes with bunbun besides the homepage. This
# page provides a full list of routes and their groups they're in.
ls: &ls "/ls"
ls: &ls
path: "/ls"
# You can specify a maximum number of arguments, which are string
# delimited strings.
max_args: 0
# You can also specify a minimum amount of arguments.
# min_args: 1
help:
# Bunbun supports all standard YAML features, so things like YAML pointers
# and references are supported.
path: *ls
path: &ls "/ls"
max_args: 0
# Paths can be hidden from the listings page if desired.
hidden: true
# Bunbun supports all standard YAML features, so things like YAML pointers
# and references are supported.
list: *ls
-
# This is another group without a description

View file

@ -2,7 +2,7 @@ use crate::BunBunError;
use dirs::{config_dir, home_dir};
use log::{debug, info, trace};
use serde::{
de::{self, Deserializer, MapAccess, Visitor},
de::{self, Deserializer, MapAccess, Unexpected, Visitor},
Deserialize, Serialize,
};
use std::collections::HashMap;
@ -38,6 +38,8 @@ pub struct Route {
pub path: String,
pub hidden: bool,
pub description: Option<String>,
pub min_args: Option<usize>,
pub max_args: Option<usize>,
}
impl FromStr for Route {
@ -48,6 +50,8 @@ impl FromStr for Route {
path: s.to_string(),
hidden: false,
description: None,
min_args: None,
max_args: None,
})
}
}
@ -63,11 +67,13 @@ impl<'de> Deserialize<'de> for Route {
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
#[serde(field_identifier, rename_all = "snake_case")]
enum Field {
Path,
Hidden,
Description,
MinArgs,
MaxArgs,
}
struct RouteVisitor;
@ -83,7 +89,7 @@ impl<'de> Deserialize<'de> for Route {
where
E: serde::de::Error,
{
// This is infalliable
// This is infallable
Ok(Self::Value::from_str(path).unwrap())
}
@ -94,6 +100,8 @@ impl<'de> Deserialize<'de> for Route {
let mut path = None;
let mut hidden = None;
let mut description = None;
let mut min_args = None;
let mut max_args = None;
while let Some(key) = map.next_key()? {
match key {
@ -115,6 +123,32 @@ impl<'de> Deserialize<'de> for Route {
}
description = Some(map.next_value()?);
}
Field::MinArgs => {
if min_args.is_some() {
return Err(de::Error::duplicate_field("min_args"));
}
min_args = Some(map.next_value()?);
}
Field::MaxArgs => {
if max_args.is_some() {
return Err(de::Error::duplicate_field("max_args"));
}
max_args = Some(map.next_value()?);
}
}
}
if let (Some(min_args), Some(max_args)) = (min_args, max_args) {
if min_args > max_args {
{
return Err(de::Error::invalid_value(
Unexpected::Other(&format!(
"argument count range {} to {}",
min_args, max_args
)),
&"a valid argument count range",
));
}
}
}
@ -124,6 +158,8 @@ impl<'de> Deserialize<'de> for Route {
path,
hidden: hidden.unwrap_or_default(),
description,
min_args,
max_args,
})
}
}
@ -337,7 +373,7 @@ mod route {
fn serialize() {
assert_eq!(
&to_string(&Route::from_str("hello world").unwrap()).unwrap(),
"---\nroute_type: External\npath: hello world\nhidden: false\ndescription: ~"
"---\nroute_type: External\npath: hello world\nhidden: false\ndescription: ~\nmin_args: ~\nmax_args: ~"
);
}
}

View file

@ -66,6 +66,7 @@ async fn run() -> Result<(), BunBunError> {
groups: conf.groups,
}));
// Cannot be named _ or Rust will immediately drop it.
let _watch = start_watch(Arc::clone(&state), conf_data, opts.large_config)?;
HttpServer::new(move || {

View file

@ -90,7 +90,7 @@ pub async fn hop(
let data = data.read().unwrap();
match resolve_hop(&query.to, &data.routes, &data.default_route) {
(Some(path), args) => {
RouteResolution::Resolved { route: path, args } => {
let resolved_template = match path {
ConfigRoute {
route_type: RouteType::Internal,
@ -126,10 +126,16 @@ pub async fn hop(
}
}
}
(None, _) => HttpResponse::NotFound().body("not found"),
RouteResolution::Unresolved => HttpResponse::NotFound().body("not found"),
}
}
#[derive(Debug, PartialEq)]
enum RouteResolution<'a> {
Resolved { route: &'a Route, args: String },
Unresolved,
}
/// Attempts to resolve the provided string into its route and its arguments.
/// If a default route was provided, then this will consider that route before
/// failing to resolve a route.
@ -140,48 +146,61 @@ fn resolve_hop<'a>(
query: &str,
routes: &'a HashMap<String, Route>,
default_route: &Option<String>,
) -> (Option<&'a Route>, String) {
) -> RouteResolution<'a> {
let mut split_args = query.split_ascii_whitespace().peekable();
let command = match split_args.peek() {
Some(command) => command,
None => {
debug!("Found empty query, returning no route.");
return (None, String::new());
let maybe_route = {
match split_args.peek() {
Some(command) => routes.get(*command),
None => {
debug!("Found empty query, returning no route.");
return RouteResolution::Unresolved;
}
}
};
match (routes.get(*command), default_route) {
// Found a route
(Some(resolved), _) => (
Some(resolved),
match split_args.next() {
// Discard the first result, we found the route using the first arg
Some(_) => {
let args = split_args.collect::<Vec<&str>>().join(" ");
debug!("Resolved {} with args {}", resolved, args);
args
}
None => {
debug!("Resolved {} with no args", resolved);
String::new()
}
},
),
// Unable to find route, but had a default route
(None, Some(route)) => {
let args = split_args.collect::<Vec<&str>>().join(" ");
debug!("Using default route {} with args {}", route, args);
match routes.get(route) {
Some(v) => (Some(v), args),
None => (None, String::new()),
}
}
// No default route and no match
(None, None) => {
debug!("Failed to resolve route!");
(None, String::new())
let args = split_args.collect::<Vec<_>>();
let arg_count = args.len();
// Try resolving with a matched command
if let Some(route) = maybe_route {
let args = if args.is_empty() { &[] } else { &args[1..] }.join(" ");
let arg_count = arg_count - 1;
if check_route(route, arg_count) {
debug!("Resolved {} with args {}", route, args);
return RouteResolution::Resolved { route, args };
}
}
// Try resolving with the default route, if it exists
if let Some(route) = default_route {
if let Some(route) = routes.get(route) {
if check_route(route, arg_count) {
let args = args.join(" ");
debug!("Using default route {} with args {}", route, args);
return RouteResolution::Resolved { route, args };
}
}
}
RouteResolution::Unresolved
}
/// Checks if the user provided string has the correct properties required by
/// the route to be successfully matched.
fn check_route(route: &Route, arg_count: usize) -> bool {
if let Some(min_args) = route.min_args {
if arg_count < min_args {
return false;
}
}
if let Some(max_args) = route.max_args {
if arg_count > max_args {
return false;
}
}
true
}
/// Runs the executable with the user's input as a single argument. Returns Ok
@ -211,15 +230,18 @@ mod resolve_hop {
fn generate_route_result<'a>(
keyword: &'a Route,
args: &str,
) -> (Option<&'a Route>, String) {
(Some(keyword), String::from(args))
) -> RouteResolution<'a> {
RouteResolution::Resolved {
route: keyword,
args: String::from(args),
}
}
#[test]
fn empty_routes_no_default_yields_failed_hop() {
assert_eq!(
resolve_hop("hello world", &HashMap::new(), &None),
(None, String::new())
RouteResolution::Unresolved
);
}
@ -231,7 +253,7 @@ mod resolve_hop {
&HashMap::new(),
&Some(String::from("google"))
),
(None, String::new())
RouteResolution::Unresolved
);
}
@ -284,6 +306,57 @@ mod resolve_hop {
}
}
#[cfg(test)]
mod check_route {
use super::*;
fn create_route(
min_args: impl Into<Option<usize>>,
max_args: impl Into<Option<usize>>,
) -> Route {
Route {
description: None,
hidden: false,
max_args: max_args.into(),
min_args: min_args.into(),
path: String::new(),
route_type: RouteType::External,
}
}
#[test]
fn no_min_arg_no_max_arg_counts() {
assert!(check_route(&create_route(None, None), 0));
assert!(check_route(&create_route(None, None), usize::MAX));
}
#[test]
fn min_arg_no_max_arg_counts() {
assert!(!check_route(&create_route(3, None), 0));
assert!(!check_route(&create_route(3, None), 2));
assert!(check_route(&create_route(3, None), 3));
assert!(check_route(&create_route(3, None), 4));
assert!(check_route(&create_route(3, None), usize::MAX));
}
#[test]
fn no_min_arg_max_arg_counts() {
assert!(check_route(&create_route(None, 3), 0));
assert!(check_route(&create_route(None, 3), 2));
assert!(check_route(&create_route(None, 3), 3));
assert!(!check_route(&create_route(None, 3), 4));
assert!(!check_route(&create_route(None, 3), usize::MAX));
}
#[test]
fn min_arg_max_arg_counts() {
assert!(!check_route(&create_route(2, 3), 1));
assert!(check_route(&create_route(2, 3), 2));
assert!(check_route(&create_route(2, 3), 3));
assert!(!check_route(&create_route(2, 3), 4));
}
}
#[cfg(test)]
mod resolve_path {
use super::resolve_path;

View file

@ -4,6 +4,6 @@
<Description>Hop to where you need to go</Description>
<InputEncoding>UTF-8</InputEncoding>
<!--<Image width="16" height="16">data:image/x-icon;base64,</Image>-->
<Url type="text/html" template="http://{{hostname}}/hop?to={searchTerms}"></Url>
<Url type="application/x-moz-keywordsearch" template="http://{{hostname}}/hop?to={searchTerms}"></Url>
<Url type="text/html" template="http://{{hostname}}/hop?to={searchTerms}" />
<Url type="application/x-moz-keywordsearch" template="http://{{hostname}}/hop?to={searchTerms}" />
</OpenSearchDescription>