Skip to main content

lean_ctx_ext/core/
route_extractor.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::Path;
3
4use serde::{Deserialize, Serialize};
5
6macro_rules! static_regex {
7    ($pattern:expr_2021) => {{
8        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
9        RE.get_or_init(|| {
10            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
11        })
12    }};
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct RouteEntry {
17    pub method: String,
18    pub path: String,
19    pub handler: String,
20    pub file: String,
21    pub line: usize,
22}
23
24pub(crate) fn extract_routes_from_file(file_path: &str, content: &str) -> Vec<RouteEntry> {
25    let ext = Path::new(file_path)
26        .extension()
27        .and_then(|e| e.to_str())
28        .unwrap_or("");
29
30    let mut routes = Vec::new();
31
32    routes.extend(extract_express(file_path, content, ext));
33    routes.extend(extract_flask(file_path, content, ext));
34    routes.extend(extract_actix(file_path, content, ext));
35    routes.extend(extract_axum(file_path, content, ext));
36    routes.extend(extract_match_routes(file_path, content, ext));
37    routes.extend(extract_spring(file_path, content, ext));
38    routes.extend(extract_rails(file_path, content, ext));
39    routes.extend(extract_fastapi(file_path, content, ext));
40    routes.extend(extract_nextjs(file_path, content, ext));
41
42    routes
43}
44
45pub fn extract_routes_from_project(project_root: &str, file_paths: &[String]) -> Vec<RouteEntry> {
46    let mut all_routes = Vec::new();
47
48    for rel_path in file_paths {
49        if !is_route_candidate(rel_path) {
50            continue;
51        }
52        let abs_path = Path::new(project_root).join(rel_path);
53        let Ok(content) = std::fs::read_to_string(&abs_path) else {
54            continue;
55        };
56        all_routes.extend(extract_routes_from_file(rel_path, &content));
57    }
58
59    all_routes.sort_by(|a, b| a.path.cmp(&b.path).then_with(|| a.method.cmp(&b.method)));
60    all_routes
61}
62
63fn is_route_candidate(path: &str) -> bool {
64    let ext = Path::new(path)
65        .extension()
66        .and_then(|e| e.to_str())
67        .unwrap_or("");
68    matches!(
69        ext,
70        "js" | "ts" | "jsx" | "tsx" | "py" | "rs" | "java" | "rb" | "go" | "kt"
71    )
72}
73
74fn extract_express(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
75    if !matches!(ext, "js" | "ts" | "jsx" | "tsx") {
76        return Vec::new();
77    }
78
79    let re = static_regex!(
80        r#"(?:app|router|server)\s*\.\s*(get|post|put|patch|delete|all|use|options|head)\s*\(\s*['"`]([^'"`]+)['"`]"#
81    );
82
83    content
84        .lines()
85        .enumerate()
86        .filter_map(|(i, line)| {
87            re.captures(line).map(|caps| {
88                let method = caps[1].to_uppercase();
89                let path = caps[2].to_string();
90                let handler = extract_handler_name(line);
91                RouteEntry {
92                    method,
93                    path,
94                    handler,
95                    file: file.to_string(),
96                    line: i + 1,
97                }
98            })
99        })
100        .collect()
101}
102
103fn extract_flask(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
104    if ext != "py" {
105        return Vec::new();
106    }
107
108    let route_re = static_regex!(
109        r#"@(?:app|blueprint|bp)\s*\.\s*route\s*\(\s*['"]([^'"]+)['"](?:.*methods\s*=\s*\[([^\]]+)\])?"#
110    );
111
112    let method_re = static_regex!(
113        r#"@(?:app|blueprint|bp)\s*\.\s*(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]"#
114    );
115
116    let mut routes = Vec::new();
117
118    for (i, line) in content.lines().enumerate() {
119        if let Some(caps) = route_re.captures(line) {
120            let path = caps[1].to_string();
121            let methods = caps.get(2).map_or_else(
122                || vec!["GET".to_string()],
123                |m| {
124                    m.as_str()
125                        .replace(['\'', '"'], "")
126                        .split(',')
127                        .map(|s| s.trim().to_uppercase())
128                        .collect::<Vec<_>>()
129                },
130            );
131
132            let handler = find_next_def(content, i);
133            for method in methods {
134                routes.push(RouteEntry {
135                    method,
136                    path: path.clone(),
137                    handler: handler.clone(),
138                    file: file.to_string(),
139                    line: i + 1,
140                });
141            }
142        }
143
144        if let Some(caps) = method_re.captures(line) {
145            let method = caps[1].to_uppercase();
146            let path = caps[2].to_string();
147            let handler = find_next_def(content, i);
148            routes.push(RouteEntry {
149                method,
150                path,
151                handler,
152                file: file.to_string(),
153                line: i + 1,
154            });
155        }
156    }
157
158    routes
159}
160
161fn extract_fastapi(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
162    if ext != "py" {
163        return Vec::new();
164    }
165
166    let re = static_regex!(
167        r#"@(?:app|router)\s*\.\s*(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]"#
168    );
169
170    content
171        .lines()
172        .enumerate()
173        .filter_map(|(i, line)| {
174            re.captures(line).map(|caps| {
175                let method = caps[1].to_uppercase();
176                let path = caps[2].to_string();
177                let handler = find_next_def(content, i);
178                RouteEntry {
179                    method,
180                    path,
181                    handler,
182                    file: file.to_string(),
183                    line: i + 1,
184                }
185            })
186        })
187        .collect()
188}
189
190fn extract_actix(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
191    if ext != "rs" {
192        return Vec::new();
193    }
194
195    let attr_re = static_regex!(r#"#\[(get|post|put|patch|delete)\s*\(\s*"([^"]+)""#);
196
197    let resource_re = static_regex!(
198        r#"web::resource\s*\(\s*"([^"]+)"\s*\)\s*\.route\s*\(.*Method::(GET|POST|PUT|PATCH|DELETE)"#
199    );
200
201    let mut routes = Vec::new();
202
203    for (i, line) in content.lines().enumerate() {
204        if let Some(caps) = attr_re.captures(line) {
205            let method = caps[1].to_uppercase();
206            let path = caps[2].to_string();
207            let handler = find_next_fn_rust(content, i);
208            routes.push(RouteEntry {
209                method,
210                path,
211                handler,
212                file: file.to_string(),
213                line: i + 1,
214            });
215        }
216
217        if let Some(caps) = resource_re.captures(line) {
218            let path = caps[1].to_string();
219            let method = caps[2].to_uppercase();
220            routes.push(RouteEntry {
221                method,
222                path,
223                handler: extract_handler_name(line),
224                file: file.to_string(),
225                line: i + 1,
226            });
227        }
228    }
229
230    routes
231}
232
233/// axum: `.route("/path", get(handler))`, incl. chained methods
234/// (`get(a).post(b)`) and qualified paths (`axum::routing::post(h)`).
235/// GL #454: this very codebase (http_server, lean-ctx-cloud) is axum and the
236/// Routes view showed nothing.
237fn extract_axum(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
238    if ext != "rs" {
239        return Vec::new();
240    }
241
242    let route_re = static_regex!(r#"\.route\s*\(\s*"([^"]+)"\s*,\s*(.+)$"#);
243    // Matches each `get(handler)` / `axum::routing::post(handler)` segment in
244    // the second argument, capturing method + handler name.
245    let method_re = static_regex!(
246        r"(?:axum::routing::|routing::)?\b(get|post|put|patch|delete|head|options|any)\s*\(\s*([A-Za-z0-9_:]+)"
247    );
248
249    let mut routes = Vec::new();
250    for (i, line) in content.lines().enumerate() {
251        let Some(caps) = route_re.captures(line) else {
252            continue;
253        };
254        let path = caps[1].to_string();
255        let rest = &caps[2];
256        for m in method_re.captures_iter(rest) {
257            let handler = m[2].rsplit("::").next().unwrap_or(&m[2]).to_string();
258            routes.push(RouteEntry {
259                method: m[1].to_uppercase(),
260                path: path.clone(),
261                handler,
262                file: file.to_string(),
263                line: i + 1,
264            });
265        }
266    }
267    routes
268}
269
270/// Hand-rolled `match` routers (the lean-ctx dashboard pattern):
271/// `"/api/stats" => { ... }`. Only arms whose string looks like an HTTP path
272/// (`/api/…`, `/v1/…`, `/public/…`) are reported, to avoid false positives on
273/// arbitrary string matches. Method is unknown at the match site, so it is
274/// reported as `*`.
275fn extract_match_routes(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
276    if ext != "rs" {
277        return Vec::new();
278    }
279
280    let re = static_regex!(r#"^\s*"((?:/api|/v1|/public)/[^"]*)"\s*(?:\|\s*"[^"]+"\s*)*=>"#);
281
282    content
283        .lines()
284        .enumerate()
285        .filter_map(|(i, line)| {
286            re.captures(line).map(|caps| RouteEntry {
287                method: "*".to_string(),
288                path: caps[1].to_string(),
289                handler: String::new(),
290                file: file.to_string(),
291                line: i + 1,
292            })
293        })
294        .collect()
295}
296
297fn extract_spring(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
298    if !matches!(ext, "java" | "kt") {
299        return Vec::new();
300    }
301
302    let re = static_regex!(
303        r#"@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping|RequestMapping)\s*\(\s*(?:value\s*=\s*)?["']([^"']+)["']"#
304    );
305
306    content
307        .lines()
308        .enumerate()
309        .filter_map(|(i, line)| {
310            re.captures(line).map(|caps| {
311                let annotation = &caps[1];
312                let method = match annotation {
313                    "GetMapping" => "GET",
314                    "PostMapping" => "POST",
315                    "PutMapping" => "PUT",
316                    "PatchMapping" => "PATCH",
317                    "DeleteMapping" => "DELETE",
318                    _ => "*",
319                }
320                .to_string();
321                let path = caps[2].to_string();
322                let handler = find_next_method_java(content, i);
323                RouteEntry {
324                    method,
325                    path,
326                    handler,
327                    file: file.to_string(),
328                    line: i + 1,
329                }
330            })
331        })
332        .collect()
333}
334
335fn extract_rails(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
336    if ext != "rb" {
337        return Vec::new();
338    }
339
340    let re = static_regex!(
341        r#"(get|post|put|patch|delete)\s+['"]([^'"]+)['"](?:\s*,\s*to:\s*['"]([^'"]+)['"])?"#
342    );
343
344    content
345        .lines()
346        .enumerate()
347        .filter_map(|(i, line)| {
348            re.captures(line).map(|caps| {
349                let method = caps[1].to_uppercase();
350                let path = caps[2].to_string();
351                let handler = caps
352                    .get(3)
353                    .map(|m| m.as_str().to_string())
354                    .unwrap_or_default();
355                RouteEntry {
356                    method,
357                    path,
358                    handler,
359                    file: file.to_string(),
360                    line: i + 1,
361                }
362            })
363        })
364        .collect()
365}
366
367fn extract_nextjs(file: &str, content: &str, ext: &str) -> Vec<RouteEntry> {
368    if !matches!(ext, "ts" | "js") {
369        return Vec::new();
370    }
371
372    if !file.contains("api/") && !file.contains("app/") {
373        return Vec::new();
374    }
375
376    let re = static_regex!(
377        r"export\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*\("
378    );
379
380    content
381        .lines()
382        .enumerate()
383        .filter_map(|(i, line)| {
384            re.captures(line).map(|caps| {
385                let method = caps[1].to_string();
386                let route_path = file_to_nextjs_route(file);
387                RouteEntry {
388                    method,
389                    path: route_path,
390                    handler: caps[1].to_string(),
391                    file: file.to_string(),
392                    line: i + 1,
393                }
394            })
395        })
396        .collect()
397}
398
399fn file_to_nextjs_route(file: &str) -> String {
400    let parts: Vec<&str> = file.split('/').collect();
401    if let Some(api_pos) = parts.iter().position(|p| *p == "api") {
402        let route_parts = &parts[api_pos..];
403        let mut route = format!("/{}", route_parts.join("/"));
404        if route.ends_with("/route.ts") || route.ends_with("/route.js") {
405            route = route.replace("/route.ts", "").replace("/route.js", "");
406        }
407        route = route.replace('[', ":").replace(']', "");
408        return route;
409    }
410    format!("/{file}")
411}
412
413fn extract_handler_name(line: &str) -> String {
414    let parts: Vec<&str> = line.split([',', ')']).collect();
415    if parts.len() > 1 {
416        let handler = parts
417            .last()
418            .unwrap_or(&"")
419            .trim()
420            .trim_matches(|c: char| !c.is_alphanumeric() && c != '_');
421        if !handler.is_empty() {
422            return handler.to_string();
423        }
424    }
425    String::new()
426}
427
428fn find_next_def(content: &str, after_line: usize) -> String {
429    let def_re = static_regex!(r"def\s+(\w+)");
430    for line in content.lines().skip(after_line + 1).take(5) {
431        if let Some(caps) = def_re.captures(line) {
432            return caps[1].to_string();
433        }
434    }
435    String::new()
436}
437
438fn find_next_fn_rust(content: &str, after_line: usize) -> String {
439    let fn_re = static_regex!(r"(?:pub\s+)?(?:async\s+)?fn\s+(\w+)");
440    for line in content.lines().skip(after_line + 1).take(5) {
441        if let Some(caps) = fn_re.captures(line) {
442            return caps[1].to_string();
443        }
444    }
445    String::new()
446}
447
448fn find_next_method_java(content: &str, after_line: usize) -> String {
449    let method_re = static_regex!(r"(?:public|private|protected)\s+\S+\s+(\w+)\s*\(");
450    for line in content.lines().skip(after_line + 1).take(5) {
451        if let Some(caps) = method_re.captures(line) {
452            return caps[1].to_string();
453        }
454    }
455    String::new()
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn express_get_route() {
464        let code = r"app.get('/api/users', getUsers);";
465        let routes = extract_express("routes.js", code, "js");
466        assert_eq!(routes.len(), 1);
467        assert_eq!(routes[0].method, "GET");
468        assert_eq!(routes[0].path, "/api/users");
469    }
470
471    #[test]
472    fn express_post_route() {
473        let code = r#"router.post("/api/items", createItem);"#;
474        let routes = extract_express("routes.ts", code, "ts");
475        assert_eq!(routes.len(), 1);
476        assert_eq!(routes[0].method, "POST");
477        assert_eq!(routes[0].path, "/api/items");
478    }
479
480    #[test]
481    fn flask_route_decorator() {
482        let code = "@app.route('/hello')\ndef hello():\n    return 'hi'";
483        let routes = extract_flask("app.py", code, "py");
484        assert_eq!(routes.len(), 1);
485        assert_eq!(routes[0].method, "GET");
486        assert_eq!(routes[0].path, "/hello");
487        assert_eq!(routes[0].handler, "hello");
488    }
489
490    #[test]
491    fn flask_route_with_methods() {
492        let code = "@app.route('/data', methods=['GET', 'POST'])\ndef handle_data():\n    pass";
493        let routes = extract_flask("app.py", code, "py");
494        assert_eq!(routes.len(), 2);
495    }
496
497    #[test]
498    fn fastapi_route() {
499        let code = "@app.get('/items')\nasync def list_items():\n    pass";
500        let routes = extract_fastapi("main.py", code, "py");
501        assert_eq!(routes.len(), 1);
502        assert_eq!(routes[0].method, "GET");
503        assert_eq!(routes[0].handler, "list_items");
504    }
505
506    #[test]
507    fn actix_attribute_route() {
508        let code = "#[get(\"/health\")]\nasync fn health_check() -> impl Responder {\n    HttpResponse::Ok()\n}";
509        let routes = extract_actix("main.rs", code, "rs");
510        assert_eq!(routes.len(), 1);
511        assert_eq!(routes[0].method, "GET");
512        assert_eq!(routes[0].path, "/health");
513        assert_eq!(routes[0].handler, "health_check");
514    }
515
516    #[test]
517    fn axum_simple_route() {
518        let code = r#"        .route("/health", get(health))"#;
519        let routes = extract_axum("http_server/mod.rs", code, "rs");
520        assert_eq!(routes.len(), 1);
521        assert_eq!(routes[0].method, "GET");
522        assert_eq!(routes[0].path, "/health");
523        assert_eq!(routes[0].handler, "health");
524    }
525
526    #[test]
527    fn axum_qualified_and_chained_methods() {
528        let code = concat!(
529            "        .route(\"/v1/shutdown\", axum::routing::post(v1_shutdown))\n",
530            "        .route(\"/api/items\", get(list_items).post(create_item))\n",
531        );
532        let routes = extract_axum("server.rs", code, "rs");
533        assert_eq!(routes.len(), 3);
534        assert_eq!(routes[0].method, "POST");
535        assert_eq!(routes[0].handler, "v1_shutdown");
536        assert_eq!(routes[1].method, "GET");
537        assert_eq!(routes[1].handler, "list_items");
538        assert_eq!(routes[2].method, "POST");
539        assert_eq!(routes[2].handler, "create_item");
540    }
541
542    #[test]
543    fn axum_module_path_handler_uses_last_segment() {
544        let code = r#"        .route("/api/billing/supporters", get(supporters::list_supporters))"#;
545        let routes = extract_axum("routes/mod.rs", code, "rs");
546        assert_eq!(routes.len(), 1);
547        assert_eq!(routes[0].handler, "list_supporters");
548    }
549
550    #[test]
551    fn match_router_arms_detected_with_path_prefix_only() {
552        let code = concat!(
553            "            \"/api/stats\" => {\n",
554            "            \"/api/tree\" | \"/api/symbols\" => {\n",
555            "            \"unrelated-string\" => {\n",
556            "            \"/not/an/api\" => {\n",
557        );
558        let routes = extract_match_routes("dashboard/routes/mod.rs", code, "rs");
559        assert_eq!(routes.len(), 2);
560        assert_eq!(routes[0].path, "/api/stats");
561        assert_eq!(routes[0].method, "*");
562        assert_eq!(routes[1].path, "/api/tree");
563    }
564
565    #[test]
566    fn spring_get_mapping() {
567        let code = "@GetMapping(\"/api/users\")\npublic List<User> getUsers() {";
568        let routes = extract_spring("UserController.java", code, "java");
569        assert_eq!(routes.len(), 1);
570        assert_eq!(routes[0].method, "GET");
571        assert_eq!(routes[0].path, "/api/users");
572        assert_eq!(routes[0].handler, "getUsers");
573    }
574
575    #[test]
576    fn rails_route() {
577        let code = "get '/users', to: 'users#index'";
578        let routes = extract_rails("routes.rb", code, "rb");
579        assert_eq!(routes.len(), 1);
580        assert_eq!(routes[0].method, "GET");
581        assert_eq!(routes[0].path, "/users");
582        assert_eq!(routes[0].handler, "users#index");
583    }
584
585    #[test]
586    fn nextjs_route_handler() {
587        let code = "export async function GET(request: Request) {\n  return Response.json({});\n}";
588        let routes = extract_nextjs("src/app/api/users/route.ts", code, "ts");
589        assert_eq!(routes.len(), 1);
590        assert_eq!(routes[0].method, "GET");
591        assert!(routes[0].path.contains("/api/users"));
592    }
593
594    #[test]
595    fn ignores_non_route_files() {
596        assert!(!is_route_candidate("README.md"));
597        assert!(!is_route_candidate("image.png"));
598        assert!(is_route_candidate("server.ts"));
599        assert!(is_route_candidate("routes.rb"));
600    }
601}