vespera_macro 0.1.43

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
//! Collector for routes and structs

use std::collections::HashMap;
use std::path::Path;

use syn::Item;

use crate::{
    error::{MacroResult, err_call_site},
    file_utils::{collect_files, file_to_segments},
    metadata::{CollectedMetadata, RouteMetadata},
    route::{extract_doc_comment, extract_route_info},
    route_impl::StoredRouteInfo,
};

/// Collect routes and structs from a folder.
///
/// When `route_storage` contains entries with `file_path`, files covered by
/// `ROUTE_STORAGE` skip expensive `syn::parse_file()` — route metadata is built
/// directly from the stored data. Default values for `serde(default = "fn")`
/// are already extracted by `#[derive(Schema)]` into `SCHEMA_STORAGE.field_defaults`.
///
/// Returns the metadata AND the parsed file ASTs, so downstream consumers
/// (e.g., `openapi_generator`) can reuse them without re-reading files from disk.
#[allow(clippy::option_if_let_else, clippy::too_many_lines)]
pub fn collect_metadata(
    folder_path: &Path,
    folder_name: &str,
    route_storage: &[StoredRouteInfo],
) -> MacroResult<(CollectedMetadata, HashMap<String, syn::File>)> {
    let mut metadata = CollectedMetadata::new();

    let files = collect_files(folder_path).map_err(|e| err_call_site(format!("vespera! macro: failed to scan route folder '{}': {}. Verify the folder exists and is readable.", folder_path.display(), e)))?;

    let mut file_asts = HashMap::with_capacity(files.len());

    // Index ROUTE_STORAGE entries by file path for O(1) lookup
    let storage_by_file: HashMap<&str, Vec<&StoredRouteInfo>> = {
        let mut map: HashMap<&str, Vec<&StoredRouteInfo>> = HashMap::new();
        for stored in route_storage {
            if let Some(ref fp) = stored.file_path {
                map.entry(fp.as_str()).or_default().push(stored);
            }
        }
        map
    };

    for file in files {
        if file.extension().is_none_or(|e| e != "rs") {
            continue;
        }

        let file_path = file.display().to_string();

        // Get module path (cheap — no parsing needed)
        let segments = file
            .strip_prefix(folder_path)
            .map(|file_stem| file_to_segments(file_stem, folder_path))
            .map_err(|e| {
                err_call_site(format!(
                    "Failed to strip prefix from file: {} (base: {}): {}",
                    file.display(),
                    folder_path.display(),
                    e
                ))
            })?;

        let module_path = if folder_name.is_empty() {
            segments.join("::")
        } else {
            format!("{}::{}", folder_name, segments.join("::"))
        };

        // Pre-compute base path once per file (avoids repeated segments.join per route)
        let base_path = format!("/{}", segments.join("/"));

        // Fast path: ROUTE_STORAGE has entries for this file — skip syn::parse_file()
        if let Some(stored_routes) = storage_by_file.get(file_path.as_str()) {
            for stored in stored_routes {
                let route_path = if let Some(ref custom_path) = stored.custom_path {
                    let trimmed_base = base_path.trim_end_matches('/');
                    format!("{trimmed_base}/{}", custom_path.trim_start_matches('/'))
                } else {
                    base_path.clone()
                };
                let route_path = route_path.replace('_', "-");

                // Extract doc comment from fn_item_str if no explicit description
                let description = stored.description.clone().or_else(|| {
                    syn::parse_str::<syn::ItemFn>(&stored.fn_item_str)
                        .ok()
                        .and_then(|fn_item| extract_doc_comment(&fn_item.attrs))
                });

                metadata.routes.push(RouteMetadata {
                    method: stored.method.clone().unwrap_or_default(),
                    path: route_path,
                    function_name: stored.fn_name.clone(),
                    module_path: module_path.clone(),
                    file_path: file_path.clone(),
                    signature: stored.fn_item_str.clone(),
                    error_status: stored.error_status.clone(),
                    tags: stored.tags.clone(),
                    description,
                });
            }

            // No file_asts insertion needed in fast path:
            // #[derive(Schema)] already extracts serde(default = "fn") values
            // into SCHEMA_STORAGE.field_defaults (Priority 0 in process_default_functions)
        } else {
            // Slow path: full parsing (fallback for files not in ROUTE_STORAGE)
            // Uses get_parsed_file: single syn::parse_file entry point + content cache
            let file_ast = crate::schema_macro::file_cache::get_parsed_file(&file).ok_or_else(|| err_call_site(format!("vespera! macro: cannot read or parse '{}'. Fix the Rust syntax errors in this file.", file.display())))?;

            // Store file AST for downstream reuse
            file_asts.insert(file_path.clone(), file_ast);
            let file_ast = &file_asts[&file_path];

            // Collect routes from AST
            for item in &file_ast.items {
                if let Item::Fn(fn_item) = item
                    && let Some(route_info) = extract_route_info(&fn_item.attrs)
                {
                    let route_path = if let Some(custom_path) = &route_info.path {
                        let trimmed_base = base_path.trim_end_matches('/');
                        format!("{trimmed_base}/{}", custom_path.trim_start_matches('/'))
                    } else {
                        base_path.clone()
                    };
                    let route_path = route_path.replace('_', "-");

                    // Description priority: route attribute > doc comment
                    let description = route_info
                        .description
                        .clone()
                        .or_else(|| extract_doc_comment(&fn_item.attrs));

                    metadata.routes.push(RouteMetadata {
                        method: route_info.method,
                        path: route_path,
                        function_name: fn_item.sig.ident.to_string(),
                        module_path: module_path.clone(),
                        file_path: file_path.clone(),
                        signature: quote::quote!(#fn_item).to_string(),
                        error_status: route_info.error_status.clone(),
                        tags: route_info.tags.clone(),
                        description,
                    });
                }
            }
        }
    }

    Ok((metadata, file_asts))
}

/// Collect file modification times without reading content.
/// Used for cache invalidation — much cheaper than full `collect_metadata()`.
pub fn collect_file_fingerprints(folder_path: &Path) -> MacroResult<HashMap<String, u64>> {
    let files = collect_files(folder_path).map_err(|e| {
        err_call_site(format!(
            "vespera! macro: failed to scan route folder '{}': {}",
            folder_path.display(),
            e
        ))
    })?;

    let mut fingerprints = HashMap::with_capacity(files.len());
    for file in files {
        if file.extension().is_none_or(|e| e != "rs") {
            continue;
        }
        let mtime = std::fs::metadata(&file)
            .and_then(|m| m.modified())
            .map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            })
            .unwrap_or(0);
        fingerprints.insert(file.display().to_string(), mtime);
    }
    Ok(fingerprints)
}

#[cfg(test)]
mod tests {
    use std::fs;

    use rstest::rstest;
    use tempfile::TempDir;

    use super::*;

    fn create_temp_file(dir: &TempDir, filename: &str, content: &str) -> std::path::PathBuf {
        let file_path = dir.path().join(filename);
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent).expect("Failed to create parent directory");
        }
        fs::write(&file_path, content).expect("Failed to write temp file");
        file_path
    }

    #[test]
    fn test_collect_metadata_empty_folder() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert!(metadata.routes.is_empty());
        assert!(metadata.structs.is_empty());

        drop(temp_dir);
    }

    #[rstest]
    #[case::single_get_route(
        "routes",
        vec![(
            "users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )],
        "get",
        "/users",
        "get_users",
        "routes::users",
    )]
    #[case::single_post_route(
        "routes",
        vec![(
            "create_user.rs",
            r#"
#[route(post)]
pub fn create_user() -> String {
    "created".to_string()
}
"#,
        )],
        "post",
        "/create-user",
        "create_user",
        "routes::create_user",
    )]
    #[case::route_with_custom_path(
        "routes",
        vec![(
            "users.rs",
            r#"
#[route(get, path = "/api/users")]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )],
        "get",
        "/users/api/users",
        "get_users",
        "routes::users",
    )]
    #[case::route_with_error_status(
        "routes",
        vec![(
            "users.rs",
            r#"
#[route(get, error_status = [400, 404])]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )],
        "get",
        "/users",
        "get_users",
        "routes::users",
    )]
    #[case::nested_module(
        "routes",
        vec![(
            "api/users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )],
        "get",
        "/api/users",
        "get_users",
        "routes::api::users",
    )]
    #[case::deeply_nested_module(
        "routes",
        vec![(
            "api/v1/users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )],
        "get",
        "/api/v1/users",
        "get_users",
        "routes::api::v1::users",
    )]
    fn test_collect_metadata_routes(
        #[case] folder_name: &str,
        #[case] files: Vec<(&str, &str)>,
        #[case] expected_method: &str,
        #[case] expected_path: &str,
        #[case] expected_function_name: &str,
        #[case] expected_module_path: &str,
    ) {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        for (filename, content) in &files {
            create_temp_file(&temp_dir, filename, content);
        }

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        let route = &metadata.routes[0];
        assert_eq!(route.method, expected_method);
        assert_eq!(route.path, expected_path);
        assert_eq!(route.function_name, expected_function_name);
        assert_eq!(route.module_path, expected_module_path);
        if let Some((first_filename, _)) = files.first() {
            assert!(
                route
                    .file_path
                    .contains(first_filename.split('/').next().unwrap())
            );
        }

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_single_struct() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_struct_without_schema() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "user.rs",
            r"
pub struct User {
    pub id: i32,
    pub name: String,
}
",
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 0);
        assert_eq!(metadata.structs.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_route_and_struct() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "user.rs",
            r#"
use vespera::Schema;

#[derive(Schema)]
pub struct User {
    pub id: i32,
    pub name: String,
}

#[route(get)]
pub fn get_user() -> User {
    User { id: 1, name: "Alice".to_string() }
}
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 1);

        let route = &metadata.routes[0];
        assert_eq!(route.function_name, "get_user");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_multiple_routes() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}

#[route(post)]
pub fn create_users() -> String {
    "created".to_string()
}
"#,
        );

        create_temp_file(
            &temp_dir,
            "posts.rs",
            r#"
#[route(get)]
pub fn get_posts() -> String {
    "posts".to_string()
}
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 3);
        assert_eq!(metadata.structs.len(), 0);

        // Check all routes are present
        let function_names: Vec<&str> = metadata
            .routes
            .iter()
            .map(|r| r.function_name.as_str())
            .collect();
        assert!(function_names.contains(&"get_users"));
        assert!(function_names.contains(&"create_users"));
        assert!(function_names.contains(&"get_posts"));

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_multiple_structs() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "user.rs",
            r"
use vespera::Schema;

#[derive(Schema)]
pub struct User {
    pub id: i32,
    pub name: String,
}
",
        );

        create_temp_file(
            &temp_dir,
            "post.rs",
            r"
use vespera::Schema;

#[derive(Schema)]
pub struct Post {
    pub id: i32,
    pub title: String,
}
",
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_with_mod_rs() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "mod.rs",
            r#"
#[route(get)]
pub fn index() -> String {
    "index".to_string()
}
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.function_name, "index");
        assert_eq!(route.path, "/");
        assert_eq!(route.module_path, "routes::");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_empty_folder_name() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "";

        create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.module_path, "users");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_ignores_non_rs_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        create_temp_file(&temp_dir, "config.txt", "some config content");

        create_temp_file(&temp_dir, "readme.md", "# Readme");

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        // Only .rs file should be processed
        assert_eq!(metadata.routes.len(), 1);
        assert_eq!(metadata.structs.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_ignores_invalid_syntax() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "valid.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        create_temp_file(&temp_dir, "invalid.rs", "invalid rust syntax {");

        let metadata = collect_metadata(temp_dir.path(), folder_name, &[]).map(|(m, _)| m);

        // Only valid file should be processed
        assert!(metadata.is_err());

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_error_status() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
#[route(get, error_status = [400, 404, 500])]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.method, "get");
        assert!(route.error_status.is_some());
        let error_status = route.error_status.as_ref().unwrap();
        assert_eq!(error_status.len(), 3);
        assert!(error_status.contains(&400));
        assert!(error_status.contains(&404));
        assert!(error_status.contains(&500));

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_all_http_methods() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "routes.rs",
            r#"
#[route(get)]
pub fn get_handler() -> String { "get".to_string() }

#[route(post)]
pub fn post_handler() -> String { "post".to_string() }

#[route(put)]
pub fn put_handler() -> String { "put".to_string() }

#[route(patch)]
pub fn patch_handler() -> String { "patch".to_string() }

#[route(delete)]
pub fn delete_handler() -> String { "delete".to_string() }

#[route(head)]
pub fn head_handler() -> String { "head".to_string() }

#[route(options)]
pub fn options_handler() -> String { "options".to_string() }
"#,
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        assert_eq!(metadata.routes.len(), 7);

        let methods: Vec<&str> = metadata.routes.iter().map(|r| r.method.as_str()).collect();
        assert!(methods.contains(&"get"));
        assert!(methods.contains(&"post"));
        assert!(methods.contains(&"put"));
        assert!(methods.contains(&"patch"));
        assert!(methods.contains(&"delete"));
        assert!(methods.contains(&"head"));
        assert!(methods.contains(&"options"));

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_collect_files_error() {
        // Test: collect_files returns error (non-existent directory)
        let non_existent_path = std::path::Path::new("/nonexistent/path/that/does/not/exist");
        let folder_name = "routes";

        let result = collect_metadata(non_existent_path, folder_name, &[]);

        // Should return error when collect_files fails
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("failed to scan route folder"));
    }

    #[test]
    #[cfg(unix)]
    fn test_collect_metadata_file_read_error_permissions() {
        // Test line 31-37: file read error due to permission denial
        // On Unix, we can create a file and then remove read permissions
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Create a file with valid Rust syntax
        let file_path = temp_dir.path().join("unreadable.rs");
        fs::write(
            &file_path,
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        )
        .expect("Failed to write temp file");

        // Remove read permissions
        let permissions = fs::Permissions::from_mode(0o000);
        fs::set_permissions(&file_path, permissions).expect("Failed to set permissions");

        // Verify permissions actually took effect (they don't on WSL with Windows filesystem)
        // If we can still read the file, skip this test
        if fs::read_to_string(&file_path).is_ok() {
            // Restore permissions for cleanup
            let permissions = fs::Permissions::from_mode(0o644);
            fs::set_permissions(&file_path, permissions).ok();
            eprintln!(
                "Skipping test: filesystem doesn't respect Unix permissions (likely WSL with NTFS)"
            );
            return;
        }

        // Attempt to collect metadata - should fail with "failed to read route file" error
        let result = collect_metadata(temp_dir.path(), folder_name, &[]);

        // Verify error message
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("failed to read route file"));

        // Restore permissions so tempdir cleanup doesn't fail
        let permissions = fs::Permissions::from_mode(0o644);
        fs::set_permissions(&file_path, permissions).ok();

        drop(temp_dir);
    }

    #[test]
    #[cfg(windows)]
    fn test_collect_metadata_file_read_error_documentation_windows() {
        // Test line 31-37: Documentation of file read error handling on Windows
        //
        // On Windows, file permission errors are harder to reliably trigger in tests
        // because standard read/write operations on temp files typically succeed.
        // The error path at line 31-37 is exercised by edge cases:
        //   1. Files deleted between collect_files scan and read attempt
        //   2. Network drive disconnections
        //   3. Permission changes during execution
        //
        // These are difficult to simulate reliably in automated tests.
        // The error handling code itself is straightforward:
        //   - std::fs::read_to_string() returns an io::Error
        //   - map_err() wraps it with context message
        //   - Caller receives "failed to read route file" error
        //
        // This is tested indirectly via test_collect_metadata_file_read_error_via_invalid_syntax
        // which verifies error propagation works correctly.

        // Verify the documented behavior with a comment-only test
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Successfully create a readable file to verify the happy path
        create_temp_file(
            &temp_dir,
            "readable.rs",
            r#"
#[route(get)]
pub fn get() -> String { "ok".to_string() }
"#,
        );

        let result = collect_metadata(temp_dir.path(), folder_name, &[]);
        assert!(result.is_ok());

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_file_read_error_via_invalid_syntax() {
        // Test line 31-37: verify error handling by parsing invalid files
        // While we can't easily trigger read errors on all platforms,
        // we verify the code path by ensuring errors are properly propagated
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Create a file that will fail to parse (syntax error)
        create_temp_file(&temp_dir, "invalid.rs", "{{{");

        // This should fail during syntax parsing, not file reading
        let result = collect_metadata(temp_dir.path(), folder_name, &[]);
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("syntax error"));

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_strip_prefix_succeeds_in_normal_case() {
        // Test line 49-58: strip_prefix succeeds in the normal case
        //
        // DEFENSIVE CODE ANALYSIS (line 49-58):
        // The strip_prefix error path is nearly impossible to trigger in practice because:
        // 1. collect_files() returns paths by walking folder_path
        // 2. All returned files are guaranteed to be under folder_path
        // 3. Therefore, strip_prefix(folder_path) should always succeed
        //
        // The error path is defensive programming that would only trigger if:
        // - Path normalization differences existed between collect_files and strip_prefix
        // - Or if folder_path contained symlinks with different absolute paths
        // - Or if the filesystem changed between collect_files and this loop
        //
        // This test verifies the normal case works correctly.
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Create a subdirectory
        let sub_dir = temp_dir.path().join("routes");
        std::fs::create_dir_all(&sub_dir).expect("Failed to create subdirectory");

        // Create a file in the subdirectory
        create_temp_file(
            &temp_dir,
            "routes/valid.rs",
            r#"
#[route(get)]
pub fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        // Collect metadata from the subdirectory
        let (metadata, _file_asts) = collect_metadata(&sub_dir, folder_name, &[]).unwrap();

        // Should collect the route (strip_prefix succeeds in normal cases)
        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.function_name, "get_users");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_struct_without_derive() {
        // Test line 81: attr.path().is_ident("derive") returns false
        // Struct with non-derive attributes should not be collected
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "user.rs",
            r"
pub struct User {
    pub id: i32,
    pub name: String,
}
",
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        // Struct without Schema derive should not be collected
        assert_eq!(metadata.structs.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_struct_with_other_derive() {
        // Test line 81: struct with other derive attributes (not Schema)
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        create_temp_file(
            &temp_dir,
            "user.rs",
            r"
#[derive(Debug, Clone)]
pub struct User {
    pub id: i32,
    pub name: String,
}
",
        );

        let (metadata, _file_asts) = collect_metadata(temp_dir.path(), folder_name, &[]).unwrap();

        // Struct with only Debug/Clone derive (no Schema) should not be collected
        assert_eq!(metadata.structs.len(), 0);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_with_route_storage() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Create a .rs file that the fast path will match against
        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
pub async fn get_users() -> String {
    "users".to_string()
}
"#,
        );

        let file_path_str = file_path.display().to_string();

        // Create StoredRouteInfo entries that match this file
        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_users".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            tags: Some(vec!["users".to_string()]),
            description: Some("Get all users".to_string()),
            fn_item_str: "pub async fn get_users() -> String { \"users\".to_string() }".to_string(),
            file_path: Some(file_path_str.clone()),
        }];

        let (metadata, file_asts) =
            collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        // Fast path should produce route metadata
        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.function_name, "get_users");
        assert_eq!(route.method, "get");
        assert_eq!(route.tags, Some(vec!["users".to_string()]));
        assert_eq!(route.description, Some("Get all users".to_string()));
        assert_eq!(route.module_path, "routes::users");

        // Fast path should NOT insert file ASTs (no parsing needed)
        assert!(
            file_asts.is_empty(),
            "Fast path should not populate file_asts"
        );

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_with_custom_path() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
pub async fn get_user() -> String {
    "user".to_string()
}
"#,
        );

        let file_path_str = file_path.display().to_string();

        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_user".to_string(),
            method: Some("get".to_string()),
            custom_path: Some("/{id}".to_string()),
            error_status: Some(vec![404]),
            tags: None,
            description: None,
            fn_item_str: "pub async fn get_user(id: i32) -> String { \"user\".to_string() }"
                .to_string(),
            file_path: Some(file_path_str.clone()),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.path, "/users/{id}");
        assert!(route.error_status.is_some());
        assert_eq!(route.error_status.as_ref().unwrap(), &vec![404]);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_empty_folder_name() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "";

        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
pub async fn list_users() -> String {
    "list".to_string()
}
"#,
        );

        let file_path_str = file_path.display().to_string();

        let route_storage = vec![StoredRouteInfo {
            fn_name: "list_users".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            tags: None,
            description: None,
            fn_item_str: "pub async fn list_users() -> String { \"list\".to_string() }".to_string(),
            file_path: Some(file_path_str),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        // With empty folder_name, module_path should be just segments (no prefix)
        assert_eq!(route.module_path, "users");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_doc_comment_extraction() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let file_path = create_temp_file(&temp_dir, "items.rs", "// placeholder\n");

        let file_path_str = file_path.display().to_string();

        // fn_item_str includes a doc comment, description is None
        // so the fast path should extract the doc comment
        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_items".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            tags: None,
            description: None, // No explicit description -> should extract from doc comment
            fn_item_str:
                "/// List all items\npub async fn get_items() -> String { \"items\".to_string() }"
                    .to_string(),
            file_path: Some(file_path_str),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        // Description should be extracted from the doc comment in fn_item_str
        assert_eq!(route.description, Some("List all items".to_string()));

        drop(temp_dir);
    }

    #[test]
    fn test_collect_file_fingerprints_skips_non_rs_files() {
        // Exercises line 121: non-.rs files should be skipped
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create both .rs and non-.rs files
        create_temp_file(&temp_dir, "valid.rs", "pub fn hello() {}");
        create_temp_file(&temp_dir, "readme.txt", "This is a readme");
        create_temp_file(&temp_dir, "data.json", "{}");
        create_temp_file(&temp_dir, "script.py", "print('hello')");

        let fingerprints = collect_file_fingerprints(temp_dir.path()).unwrap();

        // Only .rs files should be in fingerprints
        assert_eq!(
            fingerprints.len(),
            1,
            "Only .rs files should be fingerprinted"
        );
        let keys: Vec<&String> = fingerprints.keys().collect();
        assert!(
            keys[0].ends_with("valid.rs"),
            "The only fingerprinted file should be valid.rs"
        );

        drop(temp_dir);
    }
}