Compare commits
No commits in common. "83a2ba0f8a4351b209387d168cb53061f8116d5d" and "5d7629487a9280a1ff8a603d5080d4d645f1d895" have entirely different histories.
83a2ba0f8a
...
5d7629487a
5 changed files with 50 additions and 167 deletions
|
@ -34,20 +34,13 @@ 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
|
||||
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
|
||||
ls: &ls "/ls"
|
||||
help:
|
||||
path: &ls "/ls"
|
||||
max_args: 0
|
||||
# Bunbun supports all standard YAML features, so things like YAML pointers
|
||||
# and references are supported.
|
||||
path: *ls
|
||||
# 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
|
||||
|
|
|
@ -2,7 +2,7 @@ use crate::BunBunError;
|
|||
use dirs::{config_dir, home_dir};
|
||||
use log::{debug, info, trace};
|
||||
use serde::{
|
||||
de::{self, Deserializer, MapAccess, Unexpected, Visitor},
|
||||
de::{self, Deserializer, MapAccess, Visitor},
|
||||
Deserialize, Serialize,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
@ -38,8 +38,6 @@ 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 {
|
||||
|
@ -50,8 +48,6 @@ impl FromStr for Route {
|
|||
path: s.to_string(),
|
||||
hidden: false,
|
||||
description: None,
|
||||
min_args: None,
|
||||
max_args: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -67,13 +63,11 @@ impl<'de> Deserialize<'de> for Route {
|
|||
D: Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
#[serde(field_identifier, rename_all = "lowercase")]
|
||||
enum Field {
|
||||
Path,
|
||||
Hidden,
|
||||
Description,
|
||||
MinArgs,
|
||||
MaxArgs,
|
||||
}
|
||||
|
||||
struct RouteVisitor;
|
||||
|
@ -89,7 +83,7 @@ impl<'de> Deserialize<'de> for Route {
|
|||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
// This is infallable
|
||||
// This is infalliable
|
||||
Ok(Self::Value::from_str(path).unwrap())
|
||||
}
|
||||
|
||||
|
@ -100,8 +94,6 @@ 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 {
|
||||
|
@ -123,32 +115,6 @@ 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",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -158,8 +124,6 @@ impl<'de> Deserialize<'de> for Route {
|
|||
path,
|
||||
hidden: hidden.unwrap_or_default(),
|
||||
description,
|
||||
min_args,
|
||||
max_args,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -373,7 +337,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: ~\nmin_args: ~\nmax_args: ~"
|
||||
"---\nroute_type: External\npath: hello world\nhidden: false\ndescription: ~"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -66,7 +66,6 @@ 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 || {
|
||||
|
|
153
src/routes.rs
153
src/routes.rs
|
@ -90,7 +90,7 @@ pub async fn hop(
|
|||
let data = data.read().unwrap();
|
||||
|
||||
match resolve_hop(&query.to, &data.routes, &data.default_route) {
|
||||
RouteResolution::Resolved { route: path, args } => {
|
||||
(Some(path), args) => {
|
||||
let resolved_template = match path {
|
||||
ConfigRoute {
|
||||
route_type: RouteType::Internal,
|
||||
|
@ -126,16 +126,10 @@ pub async fn hop(
|
|||
}
|
||||
}
|
||||
}
|
||||
RouteResolution::Unresolved => HttpResponse::NotFound().body("not found"),
|
||||
(None, _) => 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.
|
||||
|
@ -146,61 +140,48 @@ fn resolve_hop<'a>(
|
|||
query: &str,
|
||||
routes: &'a HashMap<String, Route>,
|
||||
default_route: &Option<String>,
|
||||
) -> RouteResolution<'a> {
|
||||
) -> (Option<&'a Route>, String) {
|
||||
let mut split_args = query.split_ascii_whitespace().peekable();
|
||||
let maybe_route = {
|
||||
match split_args.peek() {
|
||||
Some(command) => routes.get(*command),
|
||||
None => {
|
||||
debug!("Found empty query, returning no route.");
|
||||
return RouteResolution::Unresolved;
|
||||
}
|
||||
let command = match split_args.peek() {
|
||||
Some(command) => command,
|
||||
None => {
|
||||
debug!("Found empty query, returning no route.");
|
||||
return (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 };
|
||||
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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
// No default route and no match
|
||||
(None, None) => {
|
||||
debug!("Failed to resolve route!");
|
||||
(None, String::new())
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
@ -230,18 +211,15 @@ mod resolve_hop {
|
|||
fn generate_route_result<'a>(
|
||||
keyword: &'a Route,
|
||||
args: &str,
|
||||
) -> RouteResolution<'a> {
|
||||
RouteResolution::Resolved {
|
||||
route: keyword,
|
||||
args: String::from(args),
|
||||
}
|
||||
) -> (Option<&'a Route>, String) {
|
||||
(Some(keyword), String::from(args))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_routes_no_default_yields_failed_hop() {
|
||||
assert_eq!(
|
||||
resolve_hop("hello world", &HashMap::new(), &None),
|
||||
RouteResolution::Unresolved
|
||||
(None, String::new())
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -253,7 +231,7 @@ mod resolve_hop {
|
|||
&HashMap::new(),
|
||||
&Some(String::from("google"))
|
||||
),
|
||||
RouteResolution::Unresolved
|
||||
(None, String::new())
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -306,57 +284,6 @@ 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;
|
||||
|
|
|
@ -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 type="application/x-moz-keywordsearch" template="http://{{hostname}}/hop?to={searchTerms}" />
|
||||
<Url type="text/html" template="http://{{hostname}}/hop?to={searchTerms}"></Url>
|
||||
<Url type="application/x-moz-keywordsearch" template="http://{{hostname}}/hop?to={searchTerms}"></Url>
|
||||
</OpenSearchDescription>
|
||||
|
|
Loading…
Reference in a new issue