use crate::DeclaredOp;
const ANY: &str = "ANY";
const VERBS: [&str; 7] = ["get", "post", "put", "delete", "patch", "head", "options"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouterRoute {
pub method: String,
pub path: String,
}
#[derive(Debug, Default)]
pub struct RouterDrift {
pub unspecified: Vec<RouterRoute>,
pub unserved: Vec<DeclaredOp>,
}
pub fn scan_routes(source: &str) -> Vec<RouterRoute> {
let live = &strip_test_mods(&strip_comments(source));
let bytes = live.as_bytes();
let mut out = Vec::new();
let mut at = 0;
while let Some(found) = live[at..].find(".route(") {
let open = at + found + ".route(".len();
at = open;
let Some(close) = matching_paren(bytes, open - 1) else {
continue;
};
let args = &live[open..close];
let Some((path, rest)) = leading_literal(args) else {
continue;
};
let mut methods: Vec<String> = verbs(rest).iter().map(|v| v.to_uppercase()).collect();
if methods.is_empty() {
methods.push(ANY.to_string());
}
for method in methods {
out.push(RouterRoute {
method,
path: path.to_string(),
});
}
}
out
}
pub fn compare(routes: &[RouterRoute], declared: &[DeclaredOp]) -> RouterDrift {
RouterDrift {
unspecified: routes
.iter()
.filter(|r| !declared.iter().any(|d| serves(r, d)))
.cloned()
.collect(),
unserved: declared
.iter()
.filter(|d| !routes.iter().any(|r| serves(r, d)))
.cloned()
.collect(),
}
}
fn serves(route: &RouterRoute, declared: &DeclaredOp) -> bool {
(route.method == ANY || route.method.eq_ignore_ascii_case(&declared.method))
&& suffix_of(&declared.path, &route.path)
}
fn suffix_of(spec_path: &str, route_path: &str) -> bool {
let spec = segments(spec_path);
let route = segments(route_path);
if route.is_empty() {
return spec.is_empty();
}
spec.len() >= route.len() && spec[spec.len() - route.len()..] == route[..]
}
fn segments(path: &str) -> Vec<String> {
path.split('/')
.filter(|s| !s.is_empty())
.map(|s| {
if s.starts_with(':') || s.starts_with('*') || (s.starts_with('{') && s.ends_with('}'))
{
"{}".to_string()
} else {
s.to_string()
}
})
.collect()
}
fn strip_comments(source: &str) -> String {
let bytes = source.as_bytes();
let mut out = String::with_capacity(source.len());
let mut i = 0;
while i < bytes.len() {
let end = match (bytes[i], bytes.get(i + 1)) {
(b'"', _) => string_end(bytes, i).map_or(bytes.len(), |e| e + 1),
(b'/', Some(b'/')) => source[i..].find('\n').map_or(bytes.len(), |n| i + n),
(b'/', Some(b'*')) => source[i + 2..]
.find("*/")
.map_or(bytes.len(), |n| i + 2 + n + 2),
_ => {
let ch = source[i..].chars().next().map_or(1, char::len_utf8);
out.push_str(&source[i..i + ch]);
i += ch;
continue;
}
};
if bytes[i] == b'"' {
out.push_str(&source[i..end]);
} else {
out.push(' ');
}
i = end;
}
out
}
fn strip_test_mods(source: &str) -> String {
const MARK: &str = "#[cfg(test)]";
let mut out = String::with_capacity(source.len());
let mut rest = source;
while let Some(at) = rest.find(MARK) {
out.push_str(&rest[..at]);
let after = &rest[at + MARK.len()..];
let body = after.trim_start();
let close = body
.starts_with("mod ")
.then(|| body.find('{'))
.flatten()
.and_then(|open| matching_brace(body.as_bytes(), open));
match close {
Some(close) => rest = &body[close + 1..],
None => {
out.push_str(MARK);
rest = after;
}
}
}
out.push_str(rest);
out
}
fn matching_brace(bytes: &[u8], open: usize) -> Option<usize> {
let mut depth = 0usize;
let mut i = open;
while i < bytes.len() {
match bytes[i] {
b'"' => i = string_end(bytes, i)?,
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}
fn matching_paren(bytes: &[u8], open: usize) -> Option<usize> {
let mut depth = 0usize;
let mut i = open;
while i < bytes.len() {
match bytes[i] {
b'"' => i = string_end(bytes, i)?,
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}
fn string_end(bytes: &[u8], open: usize) -> Option<usize> {
let mut i = open + 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 1,
b'"' => return Some(i),
_ => {}
}
i += 1;
}
None
}
fn leading_literal(args: &str) -> Option<(&str, &str)> {
let args = args.trim_start().strip_prefix('"')?;
let end = args.find('"')?;
let rest = args[end + 1..].trim_start().strip_prefix(',')?;
Some((&args[..end], rest))
}
fn verbs(expr: &str) -> Vec<&'static str> {
let bytes = expr.as_bytes();
let mut found = Vec::new();
let mut depth = 0usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => match string_end(bytes, i) {
Some(end) => i = end,
None => break,
},
b'(' => depth += 1,
b')' => depth = depth.saturating_sub(1),
c if depth == 0 && c.is_ascii_alphabetic() => {
let start = i;
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
i += 1;
}
let word = &expr[start..i];
let boundary =
start == 0 || !matches!(bytes[start - 1], b'a'..=b'z' | b'A'..=b'Z' | b'_');
if boundary
&& bytes.get(i) == Some(&b'(')
&& let Some(verb) = VERBS.iter().find(|v| **v == word)
{
found.push(*verb);
}
continue;
}
_ => {}
}
i += 1;
}
found
}
#[cfg(test)]
mod tests {
use super::*;
fn op(method: &str, path: &str) -> DeclaredOp {
DeclaredOp {
operation: format!("{method}{path}"),
method: method.into(),
path: path.into(),
}
}
fn route(method: &str, path: &str) -> RouterRoute {
RouterRoute {
method: method.into(),
path: path.into(),
}
}
#[test]
fn reads_one_route_per_verb() {
let src =
r#"Router::new().route("/graphql", post(run).get(playground)).route("/h", get(h))"#;
assert_eq!(
scan_routes(src),
[
route("POST", "/graphql"),
route("GET", "/graphql"),
route("GET", "/h")
]
);
}
#[test]
fn reads_multiline_registrations_and_qualified_verbs() {
let src = "r.route(\n \"/a/{id}\",\n routing::get(handlers::a).layer(L::new()),\n)";
assert_eq!(scan_routes(src), [route("GET", "/a/{id}")]);
}
#[test]
fn ignores_handler_names_that_contain_a_verb() {
let src = r#"r.route("/x", get(forget_all))"#;
assert_eq!(scan_routes(src), [route("GET", "/x")]);
}
#[test]
fn skips_test_modules_and_non_literal_paths() {
let src = "r.route(PATH, get(a)).route(\"/live\", get(b))\n#[cfg(test)]\nmod t { fn f() { r.route(\"/t\", get(c)); } }";
assert_eq!(scan_routes(src), [route("GET", "/live")]);
}
#[test]
fn ignores_commented_out_routes_but_not_slashes_in_strings() {
let src = "// r.route(\"/old\", get(h))\n/* r.route(\"/older\", get(h)) */\nr.route(\"/a//b\", get(h))";
assert_eq!(scan_routes(src), [route("GET", "/a//b")]);
}
#[test]
fn the_root_route_serves_only_the_root_path() {
let drift = compare(&[route("GET", "/")], &[op("GET", "/items"), op("GET", "/")]);
assert_eq!(drift.unserved, [op("GET", "/items")]);
assert!(drift.unspecified.is_empty());
}
#[test]
fn wildcard_segments_are_one_placeholder() {
let drift = compare(
&[route("GET", "/files/*rest")],
&[op("GET", "/files/{*path}")],
);
assert!(drift.unserved.is_empty() && drift.unspecified.is_empty());
}
#[test]
fn code_after_a_test_mod_or_a_cfg_test_use_is_still_read() {
let src = "#[cfg(test)]\nuse x::y;\nr.route(\"/a\", get(h));\n#[cfg(test)]\nmod t { fn f() { r.route(\"/t\", get(c)); } }\nr.route(\"/b\", get(h));";
assert_eq!(scan_routes(src), [route("GET", "/a"), route("GET", "/b")]);
}
#[test]
fn a_route_with_no_verb_serves_any_method() {
let routes = scan_routes(r#"r.route("/ws", any(ws))"#);
assert_eq!(routes, [route("ANY", "/ws")]);
let drift = compare(&routes, &[op("GET", "/ws")]);
assert!(drift.unserved.is_empty() && drift.unspecified.is_empty());
}
#[test]
fn finds_nothing_in_another_framework() {
assert!(scan_routes("#[get(\"/x\")] async fn x() {}").is_empty());
}
#[test]
fn matches_across_nest_prefix_and_param_spelling() {
let routes = [route("GET", "/analysis/{type}"), route("GET", "/health")];
let declared = [
op("GET", "/v2/analysis/{analysis_type}"),
op("GET", "/v2/health"),
];
let drift = compare(&routes, &declared);
assert!(drift.unspecified.is_empty() && drift.unserved.is_empty());
}
#[test]
fn reports_both_directions() {
let routes = [route("GET", "/a"), route("POST", "/b")];
let declared = [op("GET", "/v2/a"), op("GET", "/v2/c")];
let drift = compare(&routes, &declared);
assert_eq!(drift.unspecified, [route("POST", "/b")]);
assert_eq!(drift.unserved, [op("GET", "/v2/c")]);
}
#[test]
fn a_shorter_spec_path_is_not_served_by_a_longer_route() {
let drift = compare(&[route("GET", "/v2/a")], &[op("GET", "/a")]);
assert_eq!(drift.unserved.len(), 1);
assert_eq!(drift.unspecified.len(), 1);
}
}