oxicop 0.2.0

A blazing-fast Ruby linter and formatter, reimplemented in Rust
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
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! Bundler and Gemspec cops for Gemfile and gemspec file conventions.

use regex::Regex;
use std::collections::HashMap;

use crate::cop::{Category, Cop, Severity};
use crate::offense::{Location, Offense};
use crate::source::SourceFile;

// ==================== BUNDLER COPS ====================

/// Detects duplicate gem declarations in Gemfile.
///
/// This cop ensures that each gem is only declared once in the Gemfile.
pub struct DuplicatedGem;

impl Cop for DuplicatedGem {
    fn name(&self) -> &str {
        "Bundler/DuplicatedGem"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects duplicate gem declarations in Gemfile"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let mut seen_gems: HashMap<String, usize> = HashMap::new();

        let gem_regex = Regex::new(r#"^\s*gem\s+['"]([^'"]+)['"]"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = gem_regex.captures(line) {
                if let Some(gem_name) = capture.get(1) {
                    let name = gem_name.as_str().to_string();
                    
                    if let Some(&first_line) = seen_gems.get(&name) {
                        let col = capture.get(0).unwrap().start() + 1;
                        offenses.push(Offense::new(
                            self.name(),
                            format!("Gem '{}' is declared multiple times (first seen on line {})", name, first_line),
                            self.severity(),
                            Location::new(line_number, col, line.len()),
                        ));
                    } else {
                        seen_gems.insert(name, line_number);
                    }
                }
            }
        }

        offenses
    }
}

/// Detects duplicate group declarations in Gemfile.
///
/// This cop ensures that each group is only declared once in the Gemfile.
pub struct DuplicatedGroup;

impl Cop for DuplicatedGroup {
    fn name(&self) -> &str {
        "Bundler/DuplicatedGroup"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects duplicate group declarations in Gemfile"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let mut seen_groups: HashMap<String, usize> = HashMap::new();

        let group_regex = Regex::new(r#"^\s*group\s+:([a-z_]+)"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = group_regex.captures(line) {
                if let Some(group_name) = capture.get(1) {
                    let name = group_name.as_str().to_string();
                    
                    if let Some(&first_line) = seen_groups.get(&name) {
                        let col = capture.get(0).unwrap().start() + 1;
                        offenses.push(Offense::new(
                            self.name(),
                            format!("Group '{}' is declared multiple times (first seen on line {})", name, first_line),
                            self.severity(),
                            Location::new(line_number, col, line.len()),
                        ));
                    } else {
                        seen_groups.insert(name, line_number);
                    }
                }
            }
        }

        offenses
    }
}

/// Checks that gems in Gemfile have explanatory comments.
///
/// This cop encourages documenting why each gem is included.
pub struct GemComment;

impl Cop for GemComment {
    fn name(&self) -> &str {
        "Bundler/GemComment"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks that gems have explanatory comments"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let gem_regex = Regex::new(r#"^\s*gem\s+['"]"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if gem_regex.is_match(line) {
                // Check if previous line is a comment
                let has_comment = if line_number > 1 {
                    if let Some(prev_line) = source.line(line_number - 1) {
                        prev_line.trim().starts_with('#')
                    } else {
                        false
                    }
                } else {
                    false
                };

                // Check if same line has comment
                let same_line_comment = line.contains('#');

                if !has_comment && !same_line_comment {
                    let col = gem_regex.find(line).unwrap().start() + 1;
                    offenses.push(Offense::new(
                        self.name(),
                        "Missing gem description comment",
                        self.severity(),
                        Location::new(line_number, col, 3),
                    ));
                }
            }
        }

        offenses
    }
}

/// Checks Gemfile naming convention.
///
/// This cop ensures the file is named "Gemfile" not "gemfile" or other variants.
pub struct GemFilename;

impl Cop for GemFilename {
    fn name(&self) -> &str {
        "Bundler/GemFilename"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks Gemfile naming convention"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        if let Some(filename) = source.path.file_name() {
            if let Some(name_str) = filename.to_str() {
                // Check if this is a Gemfile variant but with wrong casing
                if name_str.to_lowercase().starts_with("gemfile") && name_str != "Gemfile" && !name_str.starts_with("Gemfile.") {
                    offenses.push(Offense::new(
                        self.name(),
                        format!("Gemfile should be named 'Gemfile', not '{}'", name_str),
                        self.severity(),
                        Location::new(1, 1, 1),
                    ));
                }
            }
        }

        offenses
    }
}

/// Checks for gem version specifications.
///
/// This cop encourages specifying gem versions for better dependency management.
pub struct GemVersion;

impl Cop for GemVersion {
    fn name(&self) -> &str {
        "Bundler/GemVersion"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks for gem version specifications"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        // Match gem declarations: gem 'name' or gem "name" without version
        let gem_no_version_regex = Regex::new(r#"^\s*gem\s+['"]([^'"]+)['"]\s*$"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = gem_no_version_regex.captures(line) {
                if let Some(gem_name) = capture.get(1) {
                    let col = capture.get(0).unwrap().start() + 1;
                    offenses.push(Offense::new(
                        self.name(),
                        format!("Gem '{}' should have a version constraint", gem_name.as_str()),
                        self.severity(),
                        Location::new(line_number, col, line.trim().len()),
                    ));
                }
            }
        }

        offenses
    }
}

/// Detects insecure protocol sources in Gemfile.
///
/// This cop flags http:// sources and recommends using https://.
pub struct InsecureProtocolSource;

impl Cop for InsecureProtocolSource {
    fn name(&self) -> &str {
        "Bundler/InsecureProtocolSource"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects insecure protocol sources in Gemfile"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let http_regex = Regex::new(r#"['"]http://[^'"]*['"]"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            // Look for source or git declarations with http://
            if (line.contains("source") || line.contains("git")) && line.contains("http://") {
                if let Some(matched) = http_regex.find(line) {
                    let col = matched.start() + 1;
                    offenses.push(Offense::new(
                        self.name(),
                        "Use https:// instead of insecure http:// for gem sources",
                        self.severity(),
                        Location::new(line_number, col, matched.len()),
                    ));
                }
            }
        }

        offenses
    }
}

/// Checks that gems are alphabetically ordered within groups.
///
/// This cop enforces alphabetical ordering of gems for better maintainability.
pub struct OrderedGems;

impl Cop for OrderedGems {
    fn name(&self) -> &str {
        "Bundler/OrderedGems"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks that gems are alphabetically ordered"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let gem_regex = Regex::new(r#"^\s*gem\s+['"]([^'"]+)['"]"#).unwrap();

        let mut last_gem: Option<(String, usize)> = None;

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            // Reset on group boundaries
            if line.trim().starts_with("group ") || line.trim() == "end" {
                last_gem = None;
                continue;
            }

            if let Some(capture) = gem_regex.captures(line) {
                if let Some(gem_name) = capture.get(1) {
                    let name = gem_name.as_str().to_string();
                    
                    if let Some((last_name, _)) = &last_gem {
                        if name < *last_name {
                            let col = capture.get(0).unwrap().start() + 1;
                            offenses.push(Offense::new(
                                self.name(),
                                format!("Gem '{}' should be sorted before '{}'", name, last_name),
                                self.severity(),
                                Location::new(line_number, col, line.trim().len()),
                            ));
                        }
                    }
                    
                    last_gem = Some((name, line_number));
                }
            }
        }

        offenses
    }
}

// ==================== GEMSPEC COPS ====================

/// Detects use of add_runtime_dependency instead of add_dependency.
///
/// This cop prefers the shorter add_dependency method.
pub struct AddRuntimeDependency;

impl Cop for AddRuntimeDependency {
    fn name(&self) -> &str {
        "Gemspec/AddRuntimeDependency"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects use of add_runtime_dependency instead of add_dependency"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let runtime_dep_regex = Regex::new(r"\.add_runtime_dependency\b").unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(matched) = runtime_dep_regex.find(line) {
                if !source.in_string_or_comment(line_number, matched.start() + 1) {
                    offenses.push(Offense::new(
                        self.name(),
                        "Use `add_dependency` instead of `add_runtime_dependency`",
                        self.severity(),
                        Location::new(line_number, matched.start() + 1, matched.len()),
                    ));
                }
            }
        }

        offenses
    }
}

/// Detects conditional assignment of spec attributes.
///
/// This cop flags attribute assignments inside conditionals in gemspec files.
pub struct AttributeAssignment;

impl Cop for AttributeAssignment {
    fn name(&self) -> &str {
        "Gemspec/AttributeAssignment"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects conditional assignment of spec attributes"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let mut in_conditional = false;
        let mut conditional_depth = 0;

        let conditional_regex = Regex::new(r"^\s*(if|unless|case)\b").unwrap();
        let assignment_regex = Regex::new(r"^\s*\w+\.\w+\s*=").unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;
            let trimmed = line.trim();

            // Track conditional blocks
            if conditional_regex.is_match(line) {
                in_conditional = true;
                conditional_depth += 1;
            }

            if trimmed == "end" && conditional_depth > 0 {
                conditional_depth -= 1;
                if conditional_depth == 0 {
                    in_conditional = false;
                }
            }

            // Check for attribute assignments inside conditionals
            if in_conditional && assignment_regex.is_match(line) {
                if let Some(matched) = assignment_regex.find(line) {
                    offenses.push(Offense::new(
                        self.name(),
                        "Don't assign spec attributes conditionally",
                        self.severity(),
                        Location::new(line_number, matched.start() + 1, matched.len()),
                    ));
                }
            }
        }

        offenses
    }
}

/// Checks for dependency version specifications in gemspec.
///
/// This cop ensures dependencies have version constraints.
pub struct DependencyVersion;

impl Cop for DependencyVersion {
    fn name(&self) -> &str {
        "Gemspec/DependencyVersion"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks for dependency version specifications"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        // Match add_dependency or add_development_dependency with only one argument
        // Supports both add_dependency('name') and add_dependency 'name' syntax
        let dep_no_version_regex = Regex::new(r#"\.add_(development_)?dependency\s+['"]([^'"]+)['"]"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = dep_no_version_regex.captures(line) {
                // Check if there's a comma or another argument after the gem name (indicates version follows)
                let match_end = capture.get(0).unwrap().end();
                let rest_of_line = &line[match_end..];

                // If there's a comma or more content that looks like a version, skip
                if !rest_of_line.trim_start().starts_with(',') && !rest_of_line.contains("'") && !rest_of_line.contains('"') {
                    if let Some(dep_name) = capture.get(2) {
                        let col = capture.get(0).unwrap().start() + 1;
                        offenses.push(Offense::new(
                            self.name(),
                            format!("Dependency '{}' should have a version constraint", dep_name.as_str()),
                            self.severity(),
                            Location::new(line_number, col, line.trim().len()),
                        ));
                    }
                }
            }
        }

        offenses
    }
}

/// Detects use of deprecated gemspec attributes.
///
/// This cop flags deprecated attribute assignments like rubyforge_project.
pub struct DeprecatedAttributeAssignment;

impl Cop for DeprecatedAttributeAssignment {
    fn name(&self) -> &str {
        "Gemspec/DeprecatedAttributeAssignment"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects use of deprecated gemspec attributes"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let deprecated_attrs = vec!["rubyforge_project", "date", "specification_version"];
        
        for attr in deprecated_attrs {
            let attr_regex = Regex::new(&format!(r"\.{}\s*=", attr)).unwrap();

            for (line_num, line) in source.lines.iter().enumerate() {
                let line_number = line_num + 1;

                if let Some(matched) = attr_regex.find(line) {
                    if !source.in_string_or_comment(line_number, matched.start() + 1) {
                        offenses.push(Offense::new(
                            self.name(),
                            format!("Deprecated attribute '{}' should not be used", attr),
                            self.severity(),
                            Location::new(line_number, matched.start() + 1, matched.len()),
                        ));
                    }
                }
            }
        }

        offenses
    }
}

/// Checks development dependencies style in gemspec.
///
/// This cop ensures consistent use of add_development_dependency.
pub struct DevelopmentDependencies;

impl Cop for DevelopmentDependencies {
    fn name(&self) -> &str {
        "Gemspec/DevelopmentDependencies"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks development dependencies style"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        // Check for Gemfile-style gem declarations in gemspec
        let gem_regex = Regex::new(r#"^\s*gem\s+['"]"#).unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if source.path.to_string_lossy().ends_with(".gemspec")
                && gem_regex.is_match(line) {
                let col = gem_regex.find(line).unwrap().start() + 1;
                offenses.push(Offense::new(
                    self.name(),
                    "Use `add_development_dependency` instead of `gem` in gemspec",
                    self.severity(),
                    Location::new(line_number, col, 3),
                ));
            }
        }

        offenses
    }
}

/// Detects duplicate assignments in gemspec.
///
/// This cop ensures each spec attribute is only assigned once.
pub struct DuplicatedAssignment;

impl Cop for DuplicatedAssignment {
    fn name(&self) -> &str {
        "Gemspec/DuplicatedAssignment"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects duplicate assignments in gemspec"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let mut seen_attrs: HashMap<String, usize> = HashMap::new();

        let assignment_regex = Regex::new(r"^\s*\w+\.([a-z_]+)\s*=").unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = assignment_regex.captures(line) {
                if let Some(attr_name) = capture.get(1) {
                    let name = attr_name.as_str().to_string();
                    
                    if let Some(&first_line) = seen_attrs.get(&name) {
                        let col = capture.get(0).unwrap().start() + 1;
                        offenses.push(Offense::new(
                            self.name(),
                            format!("Attribute '{}' is assigned multiple times (first seen on line {})", name, first_line),
                            self.severity(),
                            Location::new(line_number, col, line.trim().len()),
                        ));
                    } else {
                        seen_attrs.insert(name, line_number);
                    }
                }
            }
        }

        offenses
    }
}

/// Checks that dependencies are alphabetically ordered in gemspec.
///
/// This cop enforces alphabetical ordering of dependencies.
pub struct OrderedDependencies;

impl Cop for OrderedDependencies {
    fn name(&self) -> &str {
        "Gemspec/OrderedDependencies"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks that dependencies are alphabetically ordered"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        // Match both add_dependency('name') and add_dependency 'name' syntax
        let dep_regex = Regex::new(r#"\.add_(development_)?dependency\s*\(?\s*['"]([^'"]+)['"]"#).unwrap();

        let mut last_runtime_dep: Option<(String, usize)> = None;
        let mut last_dev_dep: Option<(String, usize)> = None;

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(capture) = dep_regex.captures(line) {
                let is_dev = capture.get(1).is_some();
                if let Some(dep_name) = capture.get(2) {
                    let name = dep_name.as_str().to_string();

                    if is_dev {
                        if let Some((last_name, _)) = &last_dev_dep {
                            if name < *last_name {
                                let col = capture.get(0).unwrap().start() + 1;
                                offenses.push(Offense::new(
                                    self.name(),
                                    format!("Development dependency '{}' should be sorted before '{}'", name, last_name),
                                    self.severity(),
                                    Location::new(line_number, col, line.trim().len()),
                                ));
                            }
                        }
                        last_dev_dep = Some((name, line_number));
                    } else {
                        if let Some((last_name, _)) = &last_runtime_dep {
                            if name < *last_name {
                                let col = capture.get(0).unwrap().start() + 1;
                                offenses.push(Offense::new(
                                    self.name(),
                                    format!("Runtime dependency '{}' should be sorted before '{}'", name, last_name),
                                    self.severity(),
                                    Location::new(line_number, col, line.trim().len()),
                                ));
                            }
                        }
                        last_runtime_dep = Some((name, line_number));
                    }
                }
            }
        }

        offenses
    }
}

/// Checks that gemspec requires MFA for gem push operations.
///
/// This cop ensures metadata includes 'allowed_push_host' or 'mfa_required'.
pub struct RequireMFA;

impl Cop for RequireMFA {
    fn name(&self) -> &str {
        "Gemspec/RequireMFA"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks that gemspec requires MFA for gem push"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let mfa_regex = Regex::new(r#"['"]mfa_required['"]"#).unwrap();
        let metadata_regex = Regex::new(r"\.metadata\b").unwrap();

        let mut has_mfa = false;
        let mut has_metadata = false;

        for (line_num, line) in source.lines.iter().enumerate() {
            let _line_number = line_num + 1;

            if mfa_regex.is_match(line) {
                has_mfa = true;
            }
            if metadata_regex.is_match(line) {
                has_metadata = true;
            }
        }

        if has_metadata && !has_mfa {
            offenses.push(Offense::new(
                self.name(),
                "Gemspec should require MFA: metadata['mfa_required'] = 'true'",
                self.severity(),
                Location::new(1, 1, 1),
            ));
        }

        offenses
    }
}

/// Checks that gemspec specifies required_ruby_version.
///
/// This cop ensures the gemspec declares a minimum Ruby version.
pub struct RequiredRubyVersion;

impl Cop for RequiredRubyVersion {
    fn name(&self) -> &str {
        "Gemspec/RequiredRubyVersion"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Checks that gemspec specifies required_ruby_version"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let required_ruby_regex = Regex::new(r"\.required_ruby_version\s*=").unwrap();

        let mut has_required_ruby = false;

        for (line_num, line) in source.lines.iter().enumerate() {
            let _line_number = line_num + 1;

            if required_ruby_regex.is_match(line) {
                has_required_ruby = true;
                break;
            }
        }

        if !has_required_ruby && source.path.to_string_lossy().ends_with(".gemspec") {
            offenses.push(Offense::new(
                self.name(),
                "Gemspec should specify required_ruby_version",
                self.severity(),
                Location::new(1, 1, 1),
            ));
        }

        offenses
    }
}

/// Detects use of RUBY_VERSION instead of Gem::Version.
///
/// This cop flags direct use of RUBY_VERSION constant in gemspec.
pub struct RubyVersionGlobalsUsage;

impl Cop for RubyVersionGlobalsUsage {
    fn name(&self) -> &str {
        "Gemspec/RubyVersionGlobalsUsage"
    }

    fn category(&self) -> Category {
        Category::Style
    }

    fn severity(&self) -> Severity {
        Severity::Convention
    }

    fn description(&self) -> &str {
        "Detects use of RUBY_VERSION instead of Gem::Version"
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        let ruby_version_regex = Regex::new(r"\bRUBY_VERSION\b").unwrap();

        for (line_num, line) in source.lines.iter().enumerate() {
            let line_number = line_num + 1;

            if let Some(matched) = ruby_version_regex.find(line) {
                if !source.in_string_or_comment(line_number, matched.start() + 1) {
                    offenses.push(Offense::new(
                        self.name(),
                        "Use Gem::Version.new(RUBY_VERSION) instead of RUBY_VERSION",
                        self.severity(),
                        Location::new(line_number, matched.start() + 1, matched.len()),
                    ));
                }
            }
        }

        offenses
    }
}

/// Returns all Bundler and Gemspec cops as trait objects.
pub fn all_bundler_gemspec_cops() -> Vec<Box<dyn Cop>> {
    vec![
        // Bundler cops
        Box::new(DuplicatedGem),
        Box::new(DuplicatedGroup),
        Box::new(GemComment),
        Box::new(GemFilename),
        Box::new(GemVersion),
        Box::new(InsecureProtocolSource),
        Box::new(OrderedGems),
        // Gemspec cops
        Box::new(AddRuntimeDependency),
        Box::new(AttributeAssignment),
        Box::new(DependencyVersion),
        Box::new(DeprecatedAttributeAssignment),
        Box::new(DevelopmentDependencies),
        Box::new(DuplicatedAssignment),
        Box::new(OrderedDependencies),
        Box::new(RequireMFA),
        Box::new(RequiredRubyVersion),
        Box::new(RubyVersionGlobalsUsage),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn test_source(content: &str) -> SourceFile {
        SourceFile::from_string(PathBuf::from("Gemfile"), content.to_string())
    }

    fn test_gemspec(content: &str) -> SourceFile {
        SourceFile::from_string(PathBuf::from("test.gemspec"), content.to_string())
    }

    // ===== DuplicatedGem Tests =====

    #[test]
    fn test_duplicated_gem_no_duplicates() {
        let source = test_source("gem 'rails'\ngem 'rspec'\n");
        let cop = DuplicatedGem;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicated_gem_with_duplicate() {
        let source = test_source("gem 'rails'\ngem 'rspec'\ngem 'rails'\n");
        let cop = DuplicatedGem;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("rails"));
    }

    // ===== DuplicatedGroup Tests =====

    #[test]
    fn test_duplicated_group_no_duplicates() {
        let source = test_source("group :development do\nend\ngroup :test do\nend\n");
        let cop = DuplicatedGroup;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicated_group_with_duplicate() {
        let source = test_source("group :development do\nend\ngroup :development do\nend\n");
        let cop = DuplicatedGroup;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("development"));
    }

    // ===== GemComment Tests =====

    #[test]
    fn test_gem_comment_with_comment() {
        let source = test_source("# Web framework\ngem 'rails'\n");
        let cop = GemComment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_gem_comment_without_comment() {
        let source = test_source("gem 'rails'\n");
        let cop = GemComment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("comment"));
    }

    #[test]
    fn test_gem_comment_inline_comment() {
        let source = test_source("gem 'rails' # Web framework\n");
        let cop = GemComment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    // ===== GemFilename Tests =====

    #[test]
    fn test_gem_filename_correct() {
        let source = SourceFile::from_string(PathBuf::from("Gemfile"), "gem 'rails'\n".to_string());
        let cop = GemFilename;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_gem_filename_incorrect() {
        let source = SourceFile::from_string(PathBuf::from("gemfile"), "gem 'rails'\n".to_string());
        let cop = GemFilename;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("Gemfile"));
    }

    // ===== GemVersion Tests =====

    #[test]
    fn test_gem_version_with_version() {
        let source = test_source("gem 'rails', '~> 7.0'\n");
        let cop = GemVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_gem_version_without_version() {
        let source = test_source("gem 'rails'\n");
        let cop = GemVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("version constraint"));
    }

    // ===== InsecureProtocolSource Tests =====

    #[test]
    fn test_insecure_protocol_https() {
        let source = test_source("source 'https://rubygems.org'\n");
        let cop = InsecureProtocolSource;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_insecure_protocol_http() {
        let source = test_source("source 'http://rubygems.org'\n");
        let cop = InsecureProtocolSource;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("https"));
    }

    // ===== OrderedGems Tests =====

    #[test]
    fn test_ordered_gems_sorted() {
        let source = test_source("gem 'rails'\ngem 'rspec'\ngem 'sqlite3'\n");
        let cop = OrderedGems;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_ordered_gems_unsorted() {
        let source = test_source("gem 'rspec'\ngem 'rails'\n");
        let cop = OrderedGems;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("sorted"));
    }

    // ===== AddRuntimeDependency Tests =====

    #[test]
    fn test_add_runtime_dependency_correct() {
        let source = test_gemspec("spec.add_dependency 'rails'\n");
        let cop = AddRuntimeDependency;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_add_runtime_dependency_incorrect() {
        let source = test_gemspec("spec.add_runtime_dependency 'rails'\n");
        let cop = AddRuntimeDependency;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("add_dependency"));
    }

    // ===== AttributeAssignment Tests =====

    #[test]
    fn test_attribute_assignment_unconditional() {
        let source = test_gemspec("spec.name = 'mygem'\n");
        let cop = AttributeAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_attribute_assignment_conditional() {
        let source = test_gemspec("if true\n  spec.name = 'mygem'\nend\n");
        let cop = AttributeAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("conditionally"));
    }

    // ===== DependencyVersion Tests =====

    #[test]
    fn test_dependency_version_with_version() {
        let source = test_gemspec("spec.add_dependency 'rails', '~> 7.0'\n");
        let cop = DependencyVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_dependency_version_without_version() {
        let source = test_gemspec("spec.add_dependency 'rails'\n");
        let cop = DependencyVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("version constraint"));
    }

    // ===== DeprecatedAttributeAssignment Tests =====

    #[test]
    fn test_deprecated_attribute_clean() {
        let source = test_gemspec("spec.name = 'mygem'\n");
        let cop = DeprecatedAttributeAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_deprecated_attribute_rubyforge() {
        let source = test_gemspec("spec.rubyforge_project = 'mygem'\n");
        let cop = DeprecatedAttributeAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("Deprecated"));
    }

    // ===== DevelopmentDependencies Tests =====

    #[test]
    fn test_development_dependencies_correct() {
        let source = test_gemspec("spec.add_development_dependency 'rspec'\n");
        let cop = DevelopmentDependencies;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_development_dependencies_gem_in_gemspec() {
        let source = test_gemspec("gem 'rspec'\n");
        let cop = DevelopmentDependencies;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("add_development_dependency"));
    }

    // ===== DuplicatedAssignment Tests =====

    #[test]
    fn test_duplicated_assignment_no_duplicates() {
        let source = test_gemspec("spec.name = 'mygem'\nspec.version = '1.0'\n");
        let cop = DuplicatedAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicated_assignment_with_duplicate() {
        let source = test_gemspec("spec.name = 'mygem'\nspec.name = 'othergem'\n");
        let cop = DuplicatedAssignment;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("name"));
    }

    // ===== OrderedDependencies Tests =====

    #[test]
    fn test_ordered_dependencies_sorted() {
        let source = test_gemspec("spec.add_dependency 'rails'\nspec.add_dependency 'rspec'\n");
        let cop = OrderedDependencies;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_ordered_dependencies_unsorted() {
        let source = test_gemspec("spec.add_dependency 'rspec'\nspec.add_dependency 'rails'\n");
        let cop = OrderedDependencies;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("sorted"));
    }

    // ===== RequireMFA Tests =====

    #[test]
    fn test_require_mfa_present() {
        let source = test_gemspec("spec.metadata['mfa_required'] = 'true'\n");
        let cop = RequireMFA;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_require_mfa_missing() {
        let source = test_gemspec("spec.metadata['homepage'] = 'http://example.com'\n");
        let cop = RequireMFA;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("MFA"));
    }

    // ===== RequiredRubyVersion Tests =====

    #[test]
    fn test_required_ruby_version_present() {
        let source = test_gemspec("spec.required_ruby_version = '>= 2.7'\n");
        let cop = RequiredRubyVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_required_ruby_version_missing() {
        let source = test_gemspec("spec.name = 'mygem'\n");
        let cop = RequiredRubyVersion;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("required_ruby_version"));
    }

    // ===== RubyVersionGlobalsUsage Tests =====

    #[test]
    fn test_ruby_version_globals_clean() {
        let source = test_gemspec("spec.required_ruby_version = '>= 2.7'\n");
        let cop = RubyVersionGlobalsUsage;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_ruby_version_globals_usage() {
        let source = test_gemspec("if RUBY_VERSION >= '2.7'\n  spec.name = 'mygem'\nend\n");
        let cop = RubyVersionGlobalsUsage;
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("Gem::Version"));
    }
}