summaryrefslogtreecommitdiff
path: root/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/GradleDetector.kt
blob: eda7cddf13060fc929090183d3eb8efdd6b3658a (plain)
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.lint.checks

import com.android.SdkConstants
import com.android.SdkConstants.ANDROIDX_PKG_PREFIX
import com.android.SdkConstants.ANDROID_URI
import com.android.SdkConstants.ATTR_NAME
import com.android.SdkConstants.FD_BUILD_TOOLS
import com.android.SdkConstants.GRADLE_PLUGIN_MINIMUM_VERSION
import com.android.SdkConstants.GRADLE_PLUGIN_RECOMMENDED_VERSION
import com.android.SdkConstants.PLATFORM_WINDOWS
import com.android.SdkConstants.SUPPORT_LIB_GROUP_ID
import com.android.SdkConstants.TAG_USES_FEATURE
import com.android.SdkConstants.currentPlatform
import com.android.ide.common.gradle.Version
import com.android.ide.common.repository.GoogleMavenRepository
import com.android.ide.common.repository.GoogleMavenRepository.Companion.MAVEN_GOOGLE_CACHE_DIR_KEY
import com.android.ide.common.repository.GradleCoordinate
import com.android.ide.common.repository.GradleCoordinate.COMPARE_PLUS_HIGHER
import com.android.ide.common.repository.GradleVersion
import com.android.ide.common.repository.MavenRepositories
import com.android.io.CancellableFileIo
import com.android.sdklib.AndroidTargetHash
import com.android.sdklib.SdkVersionInfo
import com.android.sdklib.SdkVersionInfo.LOWEST_ACTIVE_API
import com.android.tools.lint.checks.GooglePlaySdkIndex.Companion.GOOGLE_PLAY_SDK_INDEX_KEY
import com.android.tools.lint.checks.GooglePlaySdkIndex.Companion.GOOGLE_PLAY_SDK_INDEX_URL
import com.android.tools.lint.checks.ManifestDetector.Companion.TARGET_NEWER
import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.client.api.LintClient
import com.android.tools.lint.client.api.LintTomlDocument
import com.android.tools.lint.client.api.LintTomlMapValue
import com.android.tools.lint.client.api.LintTomlValue
import com.android.tools.lint.client.api.TomlContext
import com.android.tools.lint.client.api.TomlScanner
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Context
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.GradleContext
import com.android.tools.lint.detector.api.GradleContext.Companion.getIntLiteralValue
import com.android.tools.lint.detector.api.GradleContext.Companion.getStringLiteralValue
import com.android.tools.lint.detector.api.GradleContext.Companion.isNonNegativeInteger
import com.android.tools.lint.detector.api.GradleContext.Companion.isStringLiteral
import com.android.tools.lint.detector.api.GradleScanner
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.LintMap
import com.android.tools.lint.detector.api.Location
import com.android.tools.lint.detector.api.Project
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.getLanguageLevel
import com.android.tools.lint.detector.api.guessGradleLocation
import com.android.tools.lint.detector.api.isNumberString
import com.android.tools.lint.detector.api.readUrlData
import com.android.tools.lint.detector.api.readUrlDataAsString
import com.android.tools.lint.model.LintModelDependency
import com.android.tools.lint.model.LintModelExternalLibrary
import com.android.tools.lint.model.LintModelLibrary
import com.android.tools.lint.model.LintModelMavenName
import com.android.tools.lint.model.LintModelModuleType
import com.android.utils.appendCapitalized
import com.android.utils.iterator
import com.android.utils.usLocaleCapitalize
import com.google.common.base.Joiner
import com.google.common.base.Splitter
import com.google.common.collect.ArrayListMultimap
import com.intellij.pom.java.LanguageLevel.JDK_1_7
import com.intellij.pom.java.LanguageLevel.JDK_1_8
import java.io.File
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.file.Path
import java.util.Calendar
import java.util.Collections
import java.util.function.Predicate
import kotlin.text.Charsets.UTF_8

/** Checks Gradle files for potential errors. */
open class GradleDetector : Detector(), GradleScanner, TomlScanner {

  private var minSdkVersion: Int = 0
  private var compileSdkVersion: Int = 0
  private var compileSdkVersionCookie: Any? = null
  private var targetSdkVersion: Int = 0

  protected open val gradleUserHome: File
    get() {
      // See org.gradle.initialization.BuildLayoutParameters
      var gradleUserHome: String? = System.getProperty("gradle.user.home")
      if (gradleUserHome == null) {
        gradleUserHome = System.getenv("GRADLE_USER_HOME")
        if (gradleUserHome == null) {
          gradleUserHome = System.getProperty("user.home") + File.separator + ".gradle"
        }
      }

      return File(gradleUserHome)
    }

  private var artifactCacheHome: File? = null

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already transitively
   * checked GMS versions such that we don't flag the same error on every single dependency
   * declaration.
   */
  private var mCheckedGms: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already transitively
   * checked support library versions such that we don't flag the same error on every single
   * dependency declaration.
   */
  private var mCheckedSupportLibs: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already transitively
   * checked wearable library versions such that we don't flag the same error on every single
   * dependency declaration.
   */
  private var mCheckedWearableLibs: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already applied
   * kotlin-android plugin.
   */
  private var mAppliedKotlinAndroidPlugin: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already applied
   * kotlin-kapt plugin.
   */
  private var mAppliedKotlinKaptPlugin: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we've already applied the
   * KSP plugin.
   */
  private var mAppliedKspPlugin: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we have applied a java
   * plugin (e.g. application, java-library)
   */
  private var mAppliedJavaPlugin: Boolean = false

  data class JavaPluginInfo(val cookie: Any)

  private var mJavaPluginInfo: JavaPluginInfo? = null

  private var mDeclaredSourceCompatibility: Boolean = false
  private var mDeclaredTargetCompatibility: Boolean = false

  /**
   * If incrementally editing a single build.gradle file, tracks whether we have declared the google
   * maven repository in the buildscript block.
   */
  private var mDeclaredGoogleMavenRepository: Boolean = false

  data class AgpVersionCheckInfo(
    val newerVersion: Version,
    val newerVersionIsSafe: Boolean,
    val safeReplacement: Version?,
    val dependency: GradleCoordinate,
    val isResolved: Boolean,
    val cookie: Any
  )

  /** Stores information for a check of the Android gradle plugin dependency version. */
  private var agpVersionCheckInfo: AgpVersionCheckInfo? = null

  private val blockedDependencies = HashMap<Project, BlockedDependencies>()

  // ---- Implements GradleScanner ----

  private fun checkOctal(context: GradleContext, value: String, cookie: Any) {
    // (This will never be the case in KTS; if you try to insert "010" as an integer in Kotlin, you
    // get a compiler error, "Unsupported [literal prefixes and suffixes]".)
    if (
      value.length >= 2 &&
        value[0] == '0' &&
        (value.length > 2 || value[1] >= '8' && isNonNegativeInteger(value)) &&
        context.isEnabled(ACCIDENTAL_OCTAL)
    ) {
      var message =
        "The leading 0 turns this number into octal which is probably not what was intended"
      message +=
        try {
          val numericValue = java.lang.Long.decode(value)
          " (interpreted as $numericValue)"
        } catch (exception: NumberFormatException) {
          " (and it is not a valid octal number)"
        }

      report(context, cookie, ACCIDENTAL_OCTAL, message)
    }
  }

  /** Called with for example "android", "defaultConfig", "minSdkVersion", "7" */
  override fun checkDslPropertyAssignment(
    context: GradleContext,
    property: String,
    value: String,
    parent: String,
    parentParent: String?,
    propertyCookie: Any,
    valueCookie: Any,
    statementCookie: Any
  ) {
    if (parent == "defaultConfig") {
      if (property == "targetSdkVersion" || property == "targetSdk") {
        val version = getSdkVersion(value, valueCookie)
        if (version > 0 && version < context.client.highestKnownApiLevel) {
          var warned = false
          if (version < MINIMUM_TARGET_SDK_VERSION) {
            val now = calendar ?: Calendar.getInstance()
            val year = now.get(Calendar.YEAR)
            val month = now.get(Calendar.MONTH)

            // After November 1st 2022, the apps are required to use 31 or higher
            // https://developer.android.com/distribute/play-policies
            val required: Int
            val issue: Issue
            if (
              year > MINIMUM_TARGET_SDK_VERSION_YEAR ||
                year == MINIMUM_TARGET_SDK_VERSION_YEAR && month >= 10
            ) {
              // 10: November, the field is zero-based
              // On or after November 1st of the target requirement year, enforce with error
              // severity
              required = MINIMUM_TARGET_SDK_VERSION
              issue = EXPIRED_TARGET_SDK_VERSION
            } else if (
              version < PREVIOUS_MINIMUM_TARGET_SDK_VERSION &&
                year >= MINIMUM_TARGET_SDK_VERSION_YEAR - 1
            ) {
              // If you're not meeting the previous year's requirement, also enforce with error
              // severity
              required = PREVIOUS_MINIMUM_TARGET_SDK_VERSION
              issue = EXPIRED_TARGET_SDK_VERSION
            } else if (
              year == MINIMUM_TARGET_SDK_VERSION_YEAR && month >= 10 - 6
            ) { // 6 months before October
              // Meets last year's requirement but not yet the upcoming one.
              // Start warning 6 months in advance.
              // (Check for 2022 here: no, we don't have a time machine, but let's
              // allow developers to go back in time with their system clock.)
              required = MINIMUM_TARGET_SDK_VERSION
              issue = EXPIRING_TARGET_SDK_VERSION
            } else {
              required = -1
              issue = IssueRegistry.LINT_ERROR
            }
            if (required != -1) {
              val message =
                if (issue == EXPIRED_TARGET_SDK_VERSION)
                  "Google Play requires that apps target API level $required or higher.\n"
                else
                  "Google Play will soon require that apps target API " +
                    "level 31 or higher. This will be required for new apps " +
                    "in August $MINIMUM_TARGET_SDK_VERSION_YEAR, and for updates to existing apps in " +
                    "November $MINIMUM_TARGET_SDK_VERSION_YEAR."

              val highest = context.client.highestKnownApiLevel

              // Don't report if already suppressed with EXPIRING
              val alreadySuppressed =
                issue != EXPIRING_TARGET_SDK_VERSION &&
                  context.containsCommentSuppress() &&
                  context.isSuppressedWithComment(statementCookie, issue)

              if (!alreadySuppressed) {
                report(context, statementCookie, issue, message, null, true)
              }
              warned = true
            }
          }

          if (!warned) {
            val message =
              "Not targeting the latest versions of Android; compatibility " +
                "modes apply. Consider testing and updating this version. " +
                "Consult the android.os.Build.VERSION_CODES javadoc for " +
                "details."

            val highest = context.client.highestKnownApiLevel
            val label = "Update targetSdkVersion to $highest"
            val fix = fix().name(label).replace().text(value).with(highest.toString()).build()
            report(context, statementCookie, TARGET_NEWER, message, fix)
          }
        }
        if (version > 0) {
          targetSdkVersion = version
          if (LintClient.isStudio) {
            //noinspection FileComparisons
            if (lastTargetSdkVersion == -1 || lastTargetSdkVersionFile != context.file) {
              lastTargetSdkVersion = version
              lastTargetSdkVersionFile = context.file
            } else if (targetSdkVersion > lastTargetSdkVersion) {
              val message =
                "It looks like you just edited the `targetSdkVersion` from $lastTargetSdkVersion to $targetSdkVersion in the editor. " +
                  "Be sure to consult the documentation on the behaviors that change as result of this. " +
                  "The Android SDK Upgrade Assistant can help with safely migrating."
              report(context, statementCookie, EDITED_TARGET_SDK_VERSION, message)
            }
          }
          checkTargetCompatibility(context)
        } else {
          checkIntegerAsString(context, value, statementCookie, valueCookie)
        }
      } else if (property == "minSdkVersion" || property == "minSdk") {
        val version = getSdkVersion(value, valueCookie)
        if (version > 0) {
          minSdkVersion = version
          checkMinSdkVersion(context, version, statementCookie)
        } else {
          checkIntegerAsString(context, value, statementCookie, valueCookie)
        }
      }

      if (value.startsWith("0")) {
        checkOctal(context, value, valueCookie)
      }

      if (
        property == "versionName" ||
          property == "versionCode" && !isNonNegativeInteger(value) ||
          !isStringLiteral(value)
      ) {
        // Method call -- make sure it does not match one of the getters in the
        // configuration!
        if (value == "getVersionCode" || value == "getVersionName") {
          val message =
            "Bad method name: pick a unique method name which does not " +
              "conflict with the implicit getters for the defaultConfig " +
              "properties. For example, try using the prefix compute- " +
              "instead of get-."
          report(context, statementCookie, GRADLE_GETTER, message)
        }
      } else if (property == "packageName") {
        val message = "Deprecated: Replace 'packageName' with 'applicationId'"
        val fix =
          fix()
            .name("Replace 'packageName' with 'applicationId'", true)
            .replace()
            .text("packageName")
            .with("applicationId")
            .autoFix()
            .build()
        report(context, propertyCookie, DEPRECATED, message, fix)
      }
      if (
        property == "versionCode" &&
          context.isEnabled(HIGH_APP_VERSION_CODE) &&
          isNonNegativeInteger(value)
      ) {
        val version = getIntLiteralValue(value, -1)
        if (version >= VERSION_CODE_HIGH_THRESHOLD) {
          val message = "The 'versionCode' is very high and close to the max allowed value"
          report(context, statementCookie, HIGH_APP_VERSION_CODE, message)
        }
      }
    } else if (
      (property == "compileSdkVersion" || property == "compileSdk") && parent == "android"
    ) {
      var version = -1
      if (isStringLiteral(value)) {
        // Try to resolve values like "android-O"
        val hash = getStringLiteralValue(value, valueCookie)
        if (hash != null && !isNumberString(hash)) {
          if (property == "compileSdk") {
            val message =
              "`compileSdk` does not support strings; did you mean `compileSdkPreview` ?"
            val fix = fix().replace().text("compileSdk").with("compileSdkPreview").build()
            report(context, statementCookie, STRING_INTEGER, message, fix)
          }

          val platformVersion = AndroidTargetHash.getPlatformVersion(hash)
          if (platformVersion != null) {
            version = platformVersion.featureLevel
          }
        }
      } else {
        version = getIntLiteralValue(value, -1)
      }
      if (version > 0) {
        compileSdkVersion = version
        compileSdkVersionCookie = statementCookie
        checkTargetCompatibility(context)
      } else {
        checkIntegerAsString(context, value, statementCookie, valueCookie)
      }
    } else if (property == "buildToolsVersion" && parent == "android") {
      val versionString = getStringLiteralValue(value, valueCookie)
      if (versionString != null) {
        val version = GradleVersion.tryParse(versionString)
        if (version != null) {
          var recommended = getLatestBuildTools(context.client, version.major)

          // 23.0.0 shipped with a serious bugs which affects program correctness
          // (such as https://code.google.com/p/android/issues/detail?id=183180)
          // Make developers aware of this and suggest upgrading
          if (
            version.major == 23 &&
              version.minor == 0 &&
              version.micro == 0 &&
              context.isEnabled(COMPATIBILITY)
          ) {
            // This specific version is actually a preview version which should
            // not be used (https://code.google.com/p/android/issues/detail?id=75292)
            if (recommended == null || recommended.major < 23) {
              // First planned release to fix this
              recommended = GradleVersion(23, 0, 3)
            }
            val message =
              "Build Tools `23.0.0` should not be used; " +
                "it has some known serious bugs. Use version `$recommended` " +
                "instead."
            reportFatalCompatibilityIssue(context, statementCookie, message)
          }
        }
      }
    } else if (parent == "plugins") {
      val plugin =
        when (property) {
          "id" -> getStringLiteralValue(value, valueCookie)
          "alias" -> getPluginFromVersionCatalog(value, context)?.coordinates?.substringBefore(':')
          else -> null
        }

      when (plugin) {
        null -> {
          // Ignore, we couldn't find a plugin ID
        }
        "kotlin-android",
        "org.jetbrains.kotlin.android" -> {
          mAppliedKotlinAndroidPlugin = true
        }
        "kotlin-kapt",
        "org.jetbrains.kotlin.kapt" -> {
          mAppliedKotlinKaptPlugin = true
        }
        "com.google.devtools.ksp" -> {
          mAppliedKspPlugin = true
        }
        in JAVA_PLUGIN_IDS -> {
          mAppliedJavaPlugin = true
          mJavaPluginInfo = JavaPluginInfo(statementCookie)
        }
        OLD_APP_PLUGIN_ID,
        OLD_LIB_PLUGIN_ID -> {
          val isOldAppPlugin = OLD_APP_PLUGIN_ID == plugin
          val replaceWith = if (isOldAppPlugin) APP_PLUGIN_ID else LIB_PLUGIN_ID
          val message = "'$plugin' is deprecated; use '$replaceWith' instead"
          val fix =
            fix()
              .sharedName("Replace plugin")
              .replace()
              .text(plugin)
              .with(replaceWith)
              .autoFix()
              .build()
          report(context, valueCookie, DEPRECATED, message, fix)
        }
      }
    } else if (parent == "dependencies") {
      if (value.startsWith("files('") && value.endsWith("')")) {
        val path = value.substring("files('".length, value.length - 2)
        if (path.contains("\\\\")) {
          val fix = fix().replace().text(path).with(path.replace("\\\\", "/")).build()
          val message = "Do not use Windows file separators in .gradle files; use / instead"
          report(context, valueCookie, PATH, message, fix)
        } else if (path.startsWith("/") || File(path.replace('/', File.separatorChar)).isAbsolute) {
          val message = "Avoid using absolute paths in .gradle files"
          report(context, valueCookie, PATH, message)
        }
      } else {
        var dependency = getStringLiteralValue(value, valueCookie)
        if (dependency == null) {
          dependency = getNamedDependency(value)
        }
        // If the dependency is a GString (i.e. it uses Groovy variable substitution,
        // with a $variable_name syntax) then don't try to parse it.
        if (dependency != null) {
          dependency =
            dependency.removeSuffix(
              "!!"
            ) // Strip Gradle 'strict' version syntax (see b/257726238 and b/259279612).
          var gc = GradleCoordinate.parseCoordinateString(dependency)
          var isResolved = false
          if (gc != null && dependency.contains("$")) {
            if (
              value.startsWith("'") && value.endsWith("'") && context.isEnabled(NOT_INTERPOLATED)
            ) {
              val message =
                "It looks like you are trying to substitute a " +
                  "version variable, but using single quotes ('). For Groovy " +
                  "string interpolation you must use double quotes (\")."
              val fix =
                fix()
                  .name("Replace single quotes with double quotes")
                  .replace()
                  .text(value)
                  .with("\"" + value.substring(1, value.length - 1) + "\"")
                  .build()
              report(context, statementCookie, NOT_INTERPOLATED, message, fix)
            }

            gc = resolveCoordinate(context, property, gc)
            isResolved = true
          } else if (gc != null && !value.contains(gc.revision)) {
            isResolved = true
          }
          if (gc != null) {
            if (gc.acceptsGreaterRevisions()) {
              val message =
                "Avoid using + in version numbers; can lead " +
                  "to unpredictable and unrepeatable builds (" +
                  dependency +
                  ")"
              val fix = fix().data(KEY_COORDINATE, gc.toString())
              report(context, valueCookie, PLUS, message, fix)
            }

            val tomlLibraries = context.getTomlValue(VC_LIBRARIES)
            if (
              tomlLibraries != null &&
                !dependency.contains("+") &&
                (!dependency.contains("$") || isResolved)
            ) {
              val versionVar = getVersionVariable(value)
              val result = createMoveToTomlFix(context, tomlLibraries, gc, valueCookie, versionVar)
              val message = result?.first ?: "Use version catalog instead"
              val fix = result?.second
              report(context, valueCookie, SWITCH_TO_TOML, message, fix)
            }

            // Check dependencies without the PSI read lock, because we
            // may need to make network requests to retrieve version info.
            context.driver.runLaterOutsideReadAction {
              checkDependency(context, gc, isResolved, valueCookie, statementCookie)
            }
          }
          if (hasLifecycleAnnotationProcessor(dependency) && targetJava8Plus(context.project)) {
            report(
              context,
              valueCookie,
              LIFECYCLE_ANNOTATION_PROCESSOR_WITH_JAVA8,
              "Use the Lifecycle Java 8 API provided by the " +
                "`lifecycle-common` library instead of Lifecycle annotations " +
                "for faster incremental build.",
              null
            )
          }
          checkAnnotationProcessorOnCompilePath(property, dependency, context, propertyCookie)
        }
        checkDeprecatedConfigurations(property, context, propertyCookie)

        // If we haven't managed to parse the dependency yet, try getting it from version catalog
        var libTomlValue: LintTomlValue? = null
        if (dependency == null) {
          val dependencyFromVc = getDependencyFromVersionCatalog(value, context)
          if (dependencyFromVc != null) {
            dependency = dependencyFromVc.coordinates
            libTomlValue = dependencyFromVc.tomlValue
          }
        }

        if (dependency != null) {
          if (property == "kapt") {
            checkKaptUsage(dependency, libTomlValue, context, statementCookie)
          }
          checkForBomUsageWithoutPlatform(property, dependency, value, context, valueCookie)
        }
      }
    } else if (property == "packageNameSuffix") {
      val message = "Deprecated: Replace 'packageNameSuffix' with 'applicationIdSuffix'"
      val fix =
        fix()
          .name("Replace 'packageNameSuffix' with 'applicationIdSuffix'", true)
          .replace()
          .text("packageNameSuffix")
          .with("applicationIdSuffix")
          .autoFix()
          .build()
      report(context, propertyCookie, DEPRECATED, message, fix)
    } else if (property == "applicationIdSuffix") {
      val suffix = getStringLiteralValue(value, valueCookie)
      if (suffix != null && !suffix.startsWith(".")) {
        val message = "Application ID suffix should probably start with a \".\""
        report(context, statementCookie, PATH, message)
      }
    } else if (
      (property == "minSdkVersion" || property == "minSdk") &&
        parent == "dev" &&
        "21" == value &&
        // Don't flag this error from Gradle; users invoking lint from Gradle may
        // still want dev mode for command line usage
        LintClient.CLIENT_GRADLE != LintClient.clientName
    ) {
      report(
        context,
        statementCookie,
        DEV_MODE_OBSOLETE,
        "You no longer need a `dev` mode to enable multi-dexing during development, and this can break API version checks"
      )
    } else if (
      parent == "dataBinding" && ((property == "enabled" || property == "isEnabled")) ||
        (parent == "buildFeatures" && property == "dataBinding")
    ) {
      // Note: "enabled" is used by build.gradle and "isEnabled" is used by build.gradle.kts
      if (value == SdkConstants.VALUE_TRUE) {
        if (mAppliedKotlinAndroidPlugin && !mAppliedKotlinKaptPlugin) {
          val message =
            "If you plan to use data binding in a Kotlin project, you should apply the kotlin-kapt plugin."
          report(context, statementCookie, DATA_BINDING_WITHOUT_KAPT, message, null)
        }
      }
    } else if ((parent == "" || parent == "java") && property == "sourceCompatibility") {
      mDeclaredSourceCompatibility = true
    } else if ((parent == "" || parent == "java") && property == "targetCompatibility") {
      mDeclaredTargetCompatibility = true
    } else if (
      property == "include" && parent == "abi" || property == "abiFilters" && parent == "ndk"
    ) {
      checkForChromeOSAbiSplits(context, valueCookie, value)
    }
  }

  /**
   * Given a dependency string, returns the name of the version variable, if any, assuming it's a
   * single variable which represents the whole revision. For example, for `foo:bar:$version` and
   * `foo:bar:${version}` and `foo:bar:${version}@jar` it would return "version". For `foo:bar:1.0`
   * or `foo:bar:${version}-alpha` it would return null.
   */
  private fun getVersionVariable(dependency: String): String? {
    if (!dependency.contains("\$")) {
      return null
    }
    var value = dependency.removeSurrounding("'").removeSurrounding("\"").substringAfterLast(':')
    if (value.startsWith("\$")) {
      if (value.startsWith("\${")) {
        val end = value.indexOf('}')
        if (end == -1 || end < value.length - 1 && value[end + 1] != '@') {
          return null
        }
        value = value.removePrefix("\${").removeSuffix("}")
      } else {
        value = value.removePrefix("\$")
      }
    } else {
      return null
    }
    if (value.all { it.isLetter() }) {
      return value
    } else {
      return null
    }
  }

  /**
   * For ChromeOS performance, we want to check if a developer has turned on abiSplits or abiFilters
   * as they target specific ABIs. If the developer has included both `x86` and `x86_64` no warning
   * will show. However, if either of those are missing the warning will pop up.
   *
   * If the user has not included `abiSplits` or `abiFilters` this logic will not be called.
   */
  private fun checkForChromeOSAbiSplits(context: GradleContext, valueCookie: Any, value: String) {
    val abis = value.split(',')
    var hasX86 = false
    var hasX8664 = false
    for (i in abis.indices) {
      if (abis[i].contains("\"x86_64\"") || abis[i].contains("\'x86_64\'")) {
        hasX8664 = true
      } else if (abis[i].contains("\"x86\"") || abis[i].contains("\'x86\'")) {
        hasX86 = true
      }
    }

    val message: String? =
      if (!hasX86 && !hasX8664) {
        "Missing x86 and x86_64 ABI support for ChromeOS"
      } else if (!hasX86) {
        "Missing x86 ABI support for ChromeOS"
      } else if (!hasX8664) {
        "Missing x86_64 ABI support for ChromeOS"
      } else {
        null
      }

    message?.let { m -> report(context, valueCookie, CHROMEOS_ABI_SUPPORT, m) }
  }

  private enum class DeprecatedConfiguration(
    private val deprecatedName: String,
    private val replacementName: String
  ) {
    COMPILE("compile", "implementation"),
    PROVIDED("provided", "compileOnly"),
    APK("apk", "runtimeOnly"),
    ;

    private val deprecatedSuffix: String = deprecatedName.usLocaleCapitalize()
    private val replacementSuffix: String = replacementName.usLocaleCapitalize()

    fun matches(configurationName: String): Boolean {
      return configurationName == deprecatedName || configurationName.endsWith(deprecatedSuffix)
    }

    fun replacement(configurationName: String): String {
      return if (configurationName == deprecatedName) {
        replacementName
      } else {
        configurationName.removeSuffix(deprecatedSuffix) + replacementSuffix
      }
    }
  }

  private fun checkDeprecatedConfigurations(
    configuration: String,
    context: GradleContext,
    propertyCookie: Any
  ) {
    if (context.project.gradleModelVersion?.isAtLeastIncludingPreviews(3, 0, 0) == false) {
      // All of these deprecations were made in AGP 3.0.0
      return
    }

    for (deprecatedConfiguration in DeprecatedConfiguration.values()) {
      if (deprecatedConfiguration.matches(configuration)) {
        // Compile was replaced by API and Implementation, but only suggest API if it was used
        if (
          deprecatedConfiguration == DeprecatedConfiguration.COMPILE &&
            suggestApiConfigurationUse(context.project, configuration)
        ) {
          val implementation: String
          val api: String
          if (configuration == "compile") {
            implementation = "implementation"
            api = "api"
          } else {
            val prefix = configuration.removeSuffix("Compile")
            implementation = "${prefix}Implementation"
            api = "${prefix}Api"
          }

          val message =
            "`$configuration` is deprecated; " +
              "replace with either `$api` to maintain current behavior, " +
              "or `$implementation` to improve build performance " +
              "by not sharing this dependency transitively."
          val apiFix =
            fix()
              .name("Replace '$configuration' with '$api'")
              .family("Replace compile with api")
              .replace()
              .text(configuration)
              .with(api)
              .autoFix()
              .build()
          val implementationFix =
            fix()
              .name("Replace '$configuration' with '$implementation'")
              .family("Replace compile with implementation")
              .replace()
              .text(configuration)
              .with(implementation)
              .autoFix()
              .build()

          val fixes =
            fix()
              .alternatives()
              .name("Replace '$configuration' with '$api' or '$implementation'")
              .add(apiFix)
              .add(implementationFix)
              .build()

          report(context, propertyCookie, DEPRECATED_CONFIGURATION, message, fixes)
        } else {
          // Unambiguous replacement case
          val replacement = deprecatedConfiguration.replacement(configuration)
          val message = "`$configuration` is deprecated; replace with `$replacement`"
          val fix =
            fix()
              .name("Replace '$configuration' with '$replacement'")
              .family("Replace deprecated configurations")
              .replace()
              .text(configuration)
              .with(replacement)
              .autoFix()
              .build()
          report(context, propertyCookie, DEPRECATED_CONFIGURATION, message, fix)
        }
      }
    }
  }

  private fun checkAnnotationProcessorOnCompilePath(
    configuration: String,
    dependency: String,
    context: GradleContext,
    propertyCookie: Any
  ) {
    for (compileConfiguration in CompileConfiguration.values()) {
      if (compileConfiguration.matches(configuration) && isCommonAnnotationProcessor(dependency)) {
        val replacement: String = compileConfiguration.replacement(configuration)
        val fix =
          fix()
            .name("Replace $configuration with $replacement")
            .family("Replace compile classpath with annotationProcessor")
            .replace()
            .text(configuration)
            .with(replacement)
            .autoFix()
            .build()
        val message =
          "Add annotation processor to processor path using `$replacement`" +
            " instead of `$configuration`"
        report(context, propertyCookie, ANNOTATION_PROCESSOR_ON_COMPILE_PATH, message, fix)
      }
    }
  }

  private fun checkMinSdkVersion(context: GradleContext, version: Int, valueCookie: Any) {
    if (version in 1 until LOWEST_ACTIVE_API) {
      val message =
        "The value of minSdkVersion is too low. It can be incremented " +
          "without noticeably reducing the number of supported devices."

      val label = "Update minSdkVersion to $LOWEST_ACTIVE_API"
      val fix =
        fix()
          .name(label)
          .replace()
          .text(version.toString())
          .with(LOWEST_ACTIVE_API.toString())
          .build()
      report(context, valueCookie, MIN_SDK_TOO_LOW, message, fix)
    }
  }

  private fun checkIntegerAsString(
    context: GradleContext,
    value: String,
    cookie: Any,
    valueCookie: Any
  ) {
    // When done developing with a preview platform you might be tempted to switch from
    //     compileSdkVersion 'android-G'
    // to
    //     compileSdkVersion '19'
    // but that won't work; it needs to be
    //     compileSdkVersion 19
    val string = getStringLiteralValue(value, valueCookie)
    if (isNumberString(string)) {
      val message = "Use an integer rather than a string here (replace $value with just $string)"
      val fix = fix().name("Replace with integer", true).replace().text(value).with(string).build()
      report(context, cookie, STRING_INTEGER, message, fix)
    }
  }

  override fun checkMethodCall(
    context: GradleContext,
    statement: String,
    parent: String?,
    parentParent: String?,
    namedArguments: Map<String, String>,
    unnamedArguments: List<String>,
    cookie: Any
  ) {
    val plugin = namedArguments["plugin"]
    if (statement == "apply" && parent == null) {
      val isOldAppPlugin = OLD_APP_PLUGIN_ID == plugin
      if (isOldAppPlugin || OLD_LIB_PLUGIN_ID == plugin) {
        val replaceWith = if (isOldAppPlugin) APP_PLUGIN_ID else LIB_PLUGIN_ID
        val message = "'$plugin' is deprecated; use '$replaceWith' instead"
        val fix =
          fix()
            .sharedName("Replace plugin")
            .replace()
            .text(plugin)
            .with(replaceWith)
            .autoFix()
            .build()
        report(context, cookie, DEPRECATED, message, fix)
      }

      if (plugin == "kotlin-android") {
        mAppliedKotlinAndroidPlugin = true
      }
      if (plugin == "kotlin-kapt") {
        mAppliedKotlinKaptPlugin = true
      }
      if (plugin == "com.google.devtools.ksp") {
        mAppliedKspPlugin = true
      }
      if (JAVA_PLUGIN_IDS.contains(plugin)) {
        mAppliedJavaPlugin = true
        mJavaPluginInfo = JavaPluginInfo(cookie)
      }
    }
    if (statement == "google" && parent == "repositories" && parentParent == "buildscript") {
      mDeclaredGoogleMavenRepository = true
      maybeReportAgpVersionIssue(context)
    }
    if (statement == "jcenter" && parent == "repositories") {
      val message =
        "JCenter Maven repository is no longer receiving updates: newer library versions may be available elsewhere"
      val replaceFix =
        fix()
          .name("Replace with mavenCentral")
          .replace()
          .text("jcenter")
          .with("mavenCentral")
          .build()
      val deleteFix =
        fix().name("Delete this repository declaration").replace().all().with("").build()
      report(
        context,
        cookie,
        JCENTER_REPOSITORY_OBSOLETE,
        message,
        fix().alternatives(replaceFix, deleteFix)
      )
    }
  }

  private fun checkTargetCompatibility(context: GradleContext) {
    if (compileSdkVersion > 0 && targetSdkVersion > 0 && targetSdkVersion > compileSdkVersion) {
      val message =
        "The compileSdkVersion (" +
          compileSdkVersion +
          ") should not be lower than the targetSdkVersion (" +
          targetSdkVersion +
          ")"
      val fix =
        fix()
          .name("Set compileSdkVersion to $targetSdkVersion")
          .replace()
          .text(compileSdkVersion.toString())
          .with(targetSdkVersion.toString())
          .build()
      reportNonFatalCompatibilityIssue(context, compileSdkVersionCookie!!, message, fix)
    }
  }

  // Important: This is called without the PSI read lock, since it may make network requests.
  // Any interaction with PSI or issue reporting should be wrapped in a read action.
  private fun checkDependency(
    context: Context,
    dependency: GradleCoordinate,
    isResolved: Boolean,
    cookie: Any,
    statementCookie: Any
  ) {
    val version = dependency.lowerBoundVersion
    val groupId = dependency.groupId
    val artifactId = dependency.artifactId
    val revision = dependency.revision
    var safeReplacement: Version? = null
    var newerVersion: Version? = null

    val filter = getUpgradeVersionFilter(context, groupId, artifactId, revision)

    when (groupId) {
      GMS_GROUP_ID,
      FIREBASE_GROUP_ID,
      GOOGLE_SUPPORT_GROUP_ID,
      ANDROID_WEAR_GROUP_ID -> {
        // Play services

        checkPlayServices(context, dependency, version, revision, cookie, statementCookie)
      }
      "com.android.tools.build" -> {
        if ("gradle" == artifactId) {
          if (checkGradlePluginDependency(context, dependency, statementCookie)) {
            return
          }

          // If it's available in maven.google.com, fetch latest available version
          newerVersion =
            newerVersion maxOrNull getGoogleMavenRepoVersion(context, dependency, filter)

          // Compare with what's in the Gradle cache, except when lint is invoked from
          // Gradle (because checking the Gradle cache is incompatible with Gradle task
          // cacheability).
          if (!LintClient.isGradle) {
            newerVersion = newerVersion maxOrNull findCachedNewerVersion(dependency, filter)
          }

          // Compare with IDE's repository cache, if available.
          newerVersion =
            newerVersion maxOrNull context.client.getHighestKnownVersion(dependency, filter)

          // Don't just offer the latest available version, but if that is more than
          // a micro-level different, and there is a newer micro version of the
          // version that the user is currently using, offer that one as well as it
          // may be easier to upgrade to.
          if (
            newerVersion != null &&
              !version.isPreview &&
              newerVersion != version &&
              (version.major != newerVersion.major || version.minor != newerVersion.minor)
          ) {
            safeReplacement =
              getGoogleMavenRepoVersion(context, dependency) { filterVersion ->
                filterVersion.major != null &&
                  filterVersion.major == version.major &&
                  filterVersion.minor != null &&
                  filterVersion.minor == version.minor &&
                  filterVersion.micro?.let { m -> version.micro?.let { m > it } } == true &&
                  !filterVersion.isPreview &&
                  filterVersion < newerVersion!! &&
                  !filterVersion.isSnapshot
              }
          }
          if (newerVersion != null && newerVersion.isNewerThan(dependency)) {
            agpVersionCheckInfo =
              AgpVersionCheckInfo(
                newerVersion,
                newerVersion.major == version.major && newerVersion.minor == version.minor,
                safeReplacement,
                dependency,
                isResolved,
                statementCookie
              )
            maybeReportAgpVersionIssue(context)
          }
          return
        }
      }
      "com.google.guava" -> {
        // TODO: 24.0-android
        if ("guava" == artifactId) {
          newerVersion = getNewerVersion(version, 21, 0)
        }
      }
      "com.google.code.gson" -> {
        if ("gson" == artifactId) {
          newerVersion = getNewerVersion(version, 2, 8, 2)
        }
      }
      "org.apache.httpcomponents" -> {
        if ("httpclient" == artifactId) {
          newerVersion = getNewerVersion(version, 4, 5, 5)
        }
      }
      "com.squareup.okhttp3" -> {
        if ("okhttp" == artifactId) {
          newerVersion = getNewerVersion(version, 3, 10, 0)
        }
      }
      "com.github.bumptech.glide" -> {
        if ("glide" == artifactId) {
          newerVersion = getNewerVersion(version, 3, 7, 0)
        }
      }
      "io.fabric.tools" -> {
        if ("gradle" == artifactId) {
          val parsed = GradleVersion.tryParse(revision)
          if (parsed != null && parsed < "1.21.6") {
            val fix = getUpdateDependencyFix(revision, "1.22.1")
            report(
              context,
              statementCookie,
              DEPENDENCY,
              "Use Fabric Gradle plugin version 1.21.6 or later to " +
                "improve Instant Run performance (was $revision)",
              fix
            )
          } else {
            // From
            // https://s3.amazonaws.com/fabric-artifacts/public/io/fabric/tools/gradle/maven-metadata.xml
            newerVersion = getNewerVersion(version, 1, 25, 1)
          }
        }
      }
      "com.bugsnag" -> {
        if ("bugsnag-android-gradle-plugin" == artifactId) {
          if (version < Version.parse("2.1.2")) {
            val fix = getUpdateDependencyFix(revision, "2.4.1")
            report(
              context,
              statementCookie,
              DEPENDENCY,
              "Use BugSnag Gradle plugin version 2.1.2 or later to " +
                "improve Instant Run performance (was $revision)",
              fix
            )
          } else {
            // From http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.bugsnag%22%20AND
            // %20a%3A%22bugsnag-android-gradle-plugin%22
            newerVersion = getNewerVersion(version, 3, 2, 5)
          }
        }
      }

      // https://issuetracker.google.com/120098460
      "org.robolectric" -> {
        if ("robolectric" == artifactId && currentPlatform() == PLATFORM_WINDOWS) {
          if (version < Version.parse("4.2.1")) {
            val fix = getUpdateDependencyFix(revision, "4.2.1")
            report(
              context,
              cookie,
              DEPENDENCY,
              "Use robolectric version 4.2.1 or later to " +
                "fix issues with parsing of Windows paths",
              fix
            )
          }
        }
      }

      // TODO: This is a hotfix to suppress Kotlin version warnings in Compose projects
      // (b/194313332)
      //  and it should be removed eventually.
      "org.jetbrains.kotlin" -> {
        if (artifactId == "kotlin-gradle-plugin") {
          return
        }
      }
    }

    checkForKtxExtension(context, groupId, artifactId, version, cookie)

    val blockedDependencies = blockedDependencies[context.project]
    if (blockedDependencies != null) {
      val path = blockedDependencies.checkDependency(groupId, artifactId, true)
      if (path != null) {
        val message = getBlockedDependencyMessage(path)
        val fix = fix().name("Delete dependency").replace().all().build()
        // Provisional: have to check consuming app's targetSdkVersion
        report(context, statementCookie, DUPLICATE_CLASSES, message, fix, partial = true)
      }
    }

    val sdkIndex = getGooglePlaySdkIndex(context.client)
    if (sdkIndex.isReady()) {
      val versionString = version.toString()
      var reportCreated = false
      val buildFile = context.file
      if (sdkIndex.isLibraryNonCompliant(groupId, artifactId, versionString, buildFile)) {
        val message = sdkIndex.generatePolicyMessage(groupId, artifactId, versionString)
        val fix = sdkIndex.generateSdkLinkLintFix(groupId, artifactId, versionString, buildFile)
        reportCreated = report(context, cookie, PLAY_SDK_INDEX_NON_COMPLIANT, message, fix)
      }
      if (!reportCreated) {
        val isBlocking = sdkIndex.hasLibraryBlockingIssues(groupId, artifactId, versionString)
        if (isBlocking) {
          if (sdkIndex.hasLibraryCriticalIssues(groupId, artifactId, versionString, buildFile)) {
            val message =
              sdkIndex.generateBlockingCriticalMessage(groupId, artifactId, versionString)
            val fix = sdkIndex.generateSdkLinkLintFix(groupId, artifactId, versionString, buildFile)
            reportCreated =
              report(
                context,
                cookie,
                RISKY_LIBRARY,
                message,
                fix,
                overrideSeverity = Severity.ERROR
              )
          }
          if (
            (!reportCreated) &&
              sdkIndex.isLibraryOutdated(groupId, artifactId, versionString, buildFile)
          ) {
            val message =
              sdkIndex.generateBlockingOutdatedMessage(groupId, artifactId, versionString)
            val fix = sdkIndex.generateSdkLinkLintFix(groupId, artifactId, versionString, buildFile)
            report(
              context,
              cookie,
              DEPRECATED_LIBRARY,
              message,
              fix,
              overrideSeverity = Severity.ERROR
            )
          }
        } else {
          if (sdkIndex.isLibraryOutdated(groupId, artifactId, versionString, buildFile)) {
            val message = sdkIndex.generateOutdatedMessage(groupId, artifactId, versionString)
            val fix = sdkIndex.generateSdkLinkLintFix(groupId, artifactId, versionString, buildFile)
            report(context, cookie, DEPRECATED_LIBRARY, message, fix)
          }
        }
      }
    }

    // Network check for really up to date libraries? Only done in batch mode.
    var issue = DEPENDENCY
    if (
      context.scope.size > 1 &&
        context.isEnabled(REMOTE_VERSION) &&
        // Common but served from maven.google.com so no point to
        // ping other maven repositories about these
        !groupId.startsWith("androidx.")
    ) {
      val latest =
        getLatestVersionFromRemoteRepo(context.client, dependency, filter, dependency.isPreview)
      if (latest != null && version < latest) {
        newerVersion = latest
        issue = REMOTE_VERSION
      }
    }

    // Compare with what's in the Gradle cache.
    newerVersion = newerVersion maxOrNull findCachedNewerVersion(dependency, filter)

    // Compare with IDE's repository cache, if available.
    newerVersion = newerVersion maxOrNull context.client.getHighestKnownVersion(dependency, filter)

    // If it's available in maven.google.com, fetch latest available version.
    newerVersion = newerVersion maxOrNull getGoogleMavenRepoVersion(context, dependency, filter)

    if (groupId == SUPPORT_LIB_GROUP_ID || groupId == "com.android.support.test") {
      checkSupportLibraries(context, dependency, version, newerVersion, cookie)
    }

    if (
      newerVersion != null &&
        version > Version.prefixInfimum("0") &&
        newerVersion.isNewerThan(dependency)
    ) {
      val versionString = newerVersion.toString()
      val message =
        if (
          dependency.groupId == "androidx.slidingpanelayout" &&
            dependency.artifactId == "slidingpanelayout"
        ) {
          "Upgrade `androidx.slidingpanelayout` for keyboard and mouse support"
        } else if (
          dependency.groupId == "androidx.compose.foundation" &&
            dependency.artifactId == "foundation"
        ) {
          "Upgrade `androidx.compose.foundation` for keyboard and mouse support"
        } else {
          getNewerVersionAvailableMessage(dependency, versionString, null)
        }
      val fix = if (!isResolved) getUpdateDependencyFix(revision, versionString) else null
      report(context, cookie, issue, message, fix)
    }
  }

  /**
   * Returns a predicate that encapsulates version constraints for the given library, or null if
   * there are no constraints.
   */
  private fun getUpgradeVersionFilter(
    context: Context,
    groupId: String,
    artifactId: String,
    revision: String
  ): Predicate<Version>? {
    // Logic here has to match checkSupportLibraries method to avoid creating contradictory
    // warnings.
    if (isSupportLibraryDependentOnCompileSdk(groupId, artifactId)) {
      if (compileSdkVersion >= 18) {
        return Predicate { version ->
          version > Version.prefixInfimum("$compileSdkVersion") &&
            version < Version.prefixInfimum("${compileSdkVersion + 1}")
        }
      } else if (targetSdkVersion > 0) {
        return Predicate { version -> version > Version.prefixInfimum("$targetSdkVersion") }
      }
    }

    if (groupId == "com.android.tools.build" && LintClient.isStudio) {
      val clientRevision = context.client.getClientRevision() ?: return null
      val ideVersion = Version.parse(clientRevision)
      val version = Version.parse(revision)
      // TODO(b/145606749): this assumes that the IDE version and the AGP version are directly
      // comparable
      return Predicate { v ->
        // Any higher IDE version that matches major and minor
        // (e.g. from 3.3.0 offer 3.3.2 but not 3.4.0)
        (v.major == ideVersion.major && v.minor == ideVersion.minor) ||
          // Also allow matching latest current existing major/minor version
          (v.major == version.major && v.minor == version.minor)
      }
    }
    return null
  }

  /** Home in the Gradle cache for artifact caches. */
  @Suppress("MemberVisibilityCanBePrivate") // overridden in the IDE
  protected fun getArtifactCacheHome(): File {
    return artifactCacheHome
      ?: run {
        val home =
          File(
            gradleUserHome,
            "caches" + File.separator + "modules-2" + File.separator + "files-2.1"
          )
        artifactCacheHome = home
        home
      }
  }

  private fun findCachedNewerVersion(
    dependency: GradleCoordinate,
    filter: Predicate<Version>?
  ): Version? {
    val versionDir =
      getArtifactCacheHome()
        .toPath()
        .resolve(dependency.groupId + File.separator + dependency.artifactId)
    return if (CancellableFileIo.exists(versionDir)) {
      MavenRepositories.getHighestVersion(
        versionDir,
        filter,
        MavenRepositories.isPreview(dependency)
      )
    } else null
  }

  private fun ensureTargetCompatibleWithO(
    context: Context,
    version: Version,
    cookie: Any,
    major: Int,
    minor: Int,
    micro: Int
  ) {
    if (version < Version.prefixInfimum("$major.$minor.$micro")) {
      val message = "Version must be at least $major.$minor.$micro when targeting O"
      reportFatalCompatibilityIssue(context, cookie, message)
    }
  }

  // Important: This is called without the PSI read lock, since it may make network requests.
  // Any interaction with PSI or issue reporting should be wrapped in a read action.
  private fun checkGradlePluginDependency(
    context: Context,
    dependency: GradleCoordinate,
    cookie: Any
  ): Boolean {
    val minimum =
      GradleCoordinate.parseCoordinateString(
        SdkConstants.GRADLE_PLUGIN_NAME + GRADLE_PLUGIN_MINIMUM_VERSION
      )
    if (minimum != null && COMPARE_PLUS_HIGHER.compare(dependency, minimum) < 0) {
      val recommended =
        Version.parse(GRADLE_PLUGIN_RECOMMENDED_VERSION).let { recommended ->
          getGoogleMavenRepoVersion(context, minimum, null)?.takeIf { it > recommended }
            ?: recommended
        }
      val message =
        "You must use a newer version of the Android Gradle plugin. The " +
          "minimum supported version is " +
          GRADLE_PLUGIN_MINIMUM_VERSION +
          " and the recommended version is " +
          recommended
      report(context, cookie, GRADLE_PLUGIN_COMPATIBILITY, message)
      return true
    }
    return false
  }

  private fun checkSupportLibraries(
    context: Context,
    dependency: GradleCoordinate,
    version: Version,
    newerVersion: Version?,
    cookie: Any
  ) {
    val groupId = dependency.groupId
    val artifactId = dependency.artifactId

    // For artifacts that follow the platform numbering scheme, check that it matches the SDK
    // versions used.
    if (isSupportLibraryDependentOnCompileSdk(groupId, artifactId)) {
      if (
        compileSdkVersion >= 18 &&
          dependency.majorVersion != compileSdkVersion &&
          dependency.majorVersion != GradleCoordinate.PLUS_REV_VALUE &&
          context.isEnabled(COMPATIBILITY)
      ) {
        if (compileSdkVersion >= 29 && dependency.majorVersion < 29) {
          reportNonFatalCompatibilityIssue(
            context,
            cookie,
            "Version 28 (intended for Android Pie and below) is the last " +
              "version of the legacy support library, so we recommend that " +
              "you migrate to AndroidX libraries when using Android Q and " +
              "moving forward. The IDE can help with this: " +
              "Refactor > Migrate to AndroidX..."
          )
          return
        }

        var fix: LintFix? = null
        if (newerVersion != null) {
          fix =
            fix()
              .name("Replace with $newerVersion")
              .replace()
              .text(version.toString())
              .with(newerVersion.toString())
              .build()
        }
        val message =
          "This support library should not use a different version (" +
            dependency.majorVersion +
            ") than the `compileSdkVersion` (" +
            compileSdkVersion +
            ")"
        reportNonFatalCompatibilityIssue(context, cookie, message, fix)
      }
    }

    if (
      !mCheckedSupportLibs &&
        !artifactId.startsWith("multidex") &&
        !artifactId.startsWith("renderscript") &&
        artifactId != "support-annotations"
    ) {
      mCheckedSupportLibs = true
      if (!context.scope.contains(Scope.ALL_RESOURCE_FILES) && context.isGlobalAnalysis()) {
        // Incremental editing: try flagging them in this file!
        checkConsistentSupportLibraries(context, cookie)
      }
    }

    if ("appcompat-v7" == artifactId) {
      val supportLib26Beta = version >= Version.parse("26.0.0.beta.1")
      var compile26Beta = compileSdkVersion >= 26
      // It's not actually compileSdkVersion 26, it's using O revision 2 or higher
      if (compileSdkVersion == 26) {
        val buildTarget = context.project.buildTarget
        if (buildTarget != null && buildTarget.version.isPreview) {
          compile26Beta = buildTarget.revision != 1
        }
      }

      if (
        supportLib26Beta &&
          !compile26Beta &&
          // We already flag problems when these aren't matching.
          compileSdkVersion == version.major
      ) {
        reportNonFatalCompatibilityIssue(
          context,
          cookie,
          "When using a `compileSdkVersion` older than android-O revision 2, " +
            "the support library version must be 26.0.0-alpha1 or lower " +
            "(was $version)"
        )
      } else if (!supportLib26Beta && compile26Beta) {
        reportNonFatalCompatibilityIssue(
          context,
          cookie,
          "When using a `compileSdkVersion` android-O revision 2 " +
            "or higher, the support library version should be 26.0.0-beta1 " +
            "or higher (was $version)"
        )
      }
    }
  }

  private fun checkPlayServices(
    context: Context,
    dependency: GradleCoordinate,
    version: Version,
    revision: String,
    cookie: Any,
    statementCookie: Any
  ) {
    val groupId = dependency.groupId
    val artifactId = dependency.artifactId

    // 5.2.08 is not supported; special case and warn about this
    if ("5.2.08" == revision && context.isEnabled(COMPATIBILITY)) {
      // This specific version is actually a preview version which should
      // not be used (https://code.google.com/p/android/issues/detail?id=75292)
      val maxVersion =
        Version.parse("10.2.1").let { v ->
          getGoogleMavenRepoVersion(context, dependency, null)?.takeIf { it > v } ?: v
        }
      val fix = getUpdateDependencyFix(revision, maxVersion.toString())
      val message =
        "Version `5.2.08` should not be used; the app " +
          "can not be published with this version. Use version `$maxVersion` " +
          "instead."
      reportFatalCompatibilityIssue(context, cookie, message, fix)
    }

    if (
      context.isEnabled(BUNDLED_GMS) &&
        PLAY_SERVICES_V650.isSameArtifact(dependency) &&
        COMPARE_PLUS_HIGHER.compare(dependency, PLAY_SERVICES_V650) >= 0
    ) {
      // Play services 6.5.0 is the first version to allow un-bundling, so if the user is
      // at or above 6.5.0, recommend un-bundling
      val message = "Avoid using bundled version of Google Play services SDK."
      report(context, cookie, BUNDLED_GMS, message)
    }

    if (GMS_GROUP_ID == groupId && "play-services-appindexing" == artifactId) {
      val message =
        "Deprecated: Replace '" +
          GMS_GROUP_ID +
          ":play-services-appindexing:" +
          revision +
          "' with 'com.google.firebase:firebase-appindexing:10.0.0' or above. " +
          "More info: http://firebase.google.com/docs/app-indexing/android/migrate"
      val fix =
        fix()
          .name("Replace with Firebase")
          .replace()
          .text("$GMS_GROUP_ID:play-services-appindexing:$revision")
          .with("com.google.firebase:firebase-appindexing:10.2.1")
          .build()
      report(context, cookie, DEPRECATED, message, fix)
    }

    if (targetSdkVersion >= 26) {
      // When targeting O the following libraries must be using at least version 10.2.1
      // (or 0.6.0 of the jobdispatcher API)
      // com.google.android.gms:play-services-gcm:V
      // com.google.firebase:firebase-messaging:V
      if (GMS_GROUP_ID == groupId && "play-services-gcm" == artifactId) {
        ensureTargetCompatibleWithO(context, version, cookie, 10, 2, 1)
      } else if (FIREBASE_GROUP_ID == groupId && "firebase-messaging" == artifactId) {
        ensureTargetCompatibleWithO(context, version, cookie, 10, 2, 1)
      } else if (
        "firebase-jobdispatcher" == artifactId ||
          "firebase-jobdispatcher-with-gcm-dep" == artifactId
      ) {
        ensureTargetCompatibleWithO(context, version, cookie, 0, 6, 0)
      }
    }

    if (GMS_GROUP_ID == groupId || FIREBASE_GROUP_ID == groupId) {
      if (!mCheckedGms) {
        mCheckedGms = true
        // Incremental analysis only? If so, tie the check to
        // a specific GMS play dependency if only, such that it's highlighted
        // in the editor
        if (!context.scope.contains(Scope.ALL_RESOURCE_FILES) && context.isGlobalAnalysis()) {
          // Incremental editing: try flagging them in this file!
          checkConsistentPlayServices(context, cookie)
        }
      }
    } else {
      if (!mCheckedWearableLibs) {
        mCheckedWearableLibs = true
        // Incremental analysis only? If so, tie the check to
        // a specific GMS play dependency if only, such that it's highlighted
        // in the editor
        if (!context.scope.contains(Scope.ALL_RESOURCE_FILES) && context.isGlobalAnalysis()) {
          // Incremental editing: try flagging them in this file!
          checkConsistentWearableLibraries(context, cookie, statementCookie)
        }
      }
    }
  }

  private fun LintModelMavenName.isSupportLibArtifact() =
    isSupportLibraryDependentOnCompileSdk(groupId, artifactId)

  /**
   * Returns if the given group id belongs to an AndroidX artifact. This usually means that it
   * starts with "androidx." but there is an special case for the navigation artifact which does
   * start with "androidx." but links to non-androidx classes.
   */
  private fun LintModelMavenName.isAndroidxArtifact() =
    groupId.startsWith(ANDROIDX_PKG_PREFIX) && groupId != "androidx.navigation"

  private fun checkConsistentSupportLibraries(context: Context, cookie: Any?) {
    checkConsistentLibraries(context, cookie, SUPPORT_LIB_GROUP_ID, null)

    val androidLibraries =
      getAllLibraries(context.project).filterIsInstance<LintModelExternalLibrary>()
    var usesOldSupportLib: LintModelMavenName? = null
    var usesAndroidX: LintModelMavenName? = null
    for (library in androidLibraries) {
      val coordinates = library.resolvedCoordinates
      if (usesOldSupportLib == null && coordinates.isSupportLibArtifact()) {
        usesOldSupportLib = coordinates
      }
      if (usesAndroidX == null && coordinates.isAndroidxArtifact()) {
        usesAndroidX = coordinates
      }

      if (usesOldSupportLib != null && usesAndroidX != null) {
        break
      }
    }

    if (usesOldSupportLib != null && usesAndroidX != null) {
      val message =
        "Dependencies using groupId " +
          "`$SUPPORT_LIB_GROUP_ID` and `$ANDROIDX_PKG_PREFIX*` " +
          "can not be combined but " +
          "found `$usesOldSupportLib` and `$usesAndroidX` incompatible dependencies"
      if (cookie != null) {
        reportNonFatalCompatibilityIssue(context, cookie, message)
      } else {
        val location = getDependencyLocation(context, usesOldSupportLib, usesAndroidX)
        reportNonFatalCompatibilityIssue(context, location, message)
      }
    }
  }

  private fun checkConsistentPlayServices(context: Context, cookie: Any?) {
    checkConsistentLibraries(context, cookie, GMS_GROUP_ID, FIREBASE_GROUP_ID)
  }

  private fun checkConsistentWearableLibraries(
    context: Context,
    cookie: Any?,
    statementCookie: Any?
  ) {
    // Make sure we have both
    //   compile 'com.google.android.support:wearable:2.0.0-alpha3'
    //   provided 'com.google.android.wearable:wearable:2.0.0-alpha3'
    val project = context.mainProject
    if (!project.isGradleProject) {
      return
    }
    val supportVersions = HashSet<String>()
    val wearableVersions = HashSet<String>()
    for (library in getAllLibraries(project).filterIsInstance<LintModelExternalLibrary>()) {
      val coordinates = library.resolvedCoordinates
      if (
        WEARABLE_ARTIFACT_ID == coordinates.artifactId &&
          GOOGLE_SUPPORT_GROUP_ID == coordinates.groupId
      ) {
        supportVersions.add(coordinates.version)
      }

      // Claims to be non-null but may not be after a failed gradle sync
      if (
        WEARABLE_ARTIFACT_ID == coordinates.artifactId &&
          ANDROID_WEAR_GROUP_ID == coordinates.groupId
      ) {
        if (!library.provided) {
          var message = "This dependency should be marked as `compileOnly`, not `compile`"
          if (statementCookie != null) {
            reportFatalCompatibilityIssue(context, statementCookie, message)
          } else {
            val location = getDependencyLocation(context, coordinates)
            if (location.start == null) {
              message =
                "The $ANDROID_WEAR_GROUP_ID:$WEARABLE_ARTIFACT_ID dependency should be marked as `compileOnly`, not `compile`"
            }
            reportFatalCompatibilityIssue(context, location, message)
          }
        }
        wearableVersions.add(coordinates.version)
      }
    }

    if (supportVersions.isNotEmpty()) {
      if (wearableVersions.isEmpty()) {
        val list = ArrayList(supportVersions)
        val first = Collections.min(list)
        val message =
          "Project depends on $GOOGLE_SUPPORT_GROUP_ID:$WEARABLE_ARTIFACT_ID:$first, " +
            "so it must also depend (as a provided dependency) on " +
            "$ANDROID_WEAR_GROUP_ID:$WEARABLE_ARTIFACT_ID:$first"
        if (cookie != null) {
          reportFatalCompatibilityIssue(context, cookie, message)
        } else {
          val location =
            getDependencyLocation(context, GOOGLE_SUPPORT_GROUP_ID, WEARABLE_ARTIFACT_ID, first)
          reportFatalCompatibilityIssue(context, location, message)
        }
      } else {
        // Check that they have the same versions
        if (supportVersions != wearableVersions) {
          val sortedSupportVersions = ArrayList(supportVersions)
          sortedSupportVersions.sort()
          val supportedWearableVersions = ArrayList(wearableVersions)
          supportedWearableVersions.sort()
          val message =
            String.format(
              "The wearable libraries for %1\$s and %2\$s " +
                "must use **exactly** the same versions; found %3\$s " +
                "and %4\$s",
              GOOGLE_SUPPORT_GROUP_ID,
              ANDROID_WEAR_GROUP_ID,
              if (sortedSupportVersions.size == 1) sortedSupportVersions[0]
              else sortedSupportVersions.toString(),
              if (supportedWearableVersions.size == 1) supportedWearableVersions[0]
              else supportedWearableVersions.toString()
            )
          if (cookie != null) {
            reportFatalCompatibilityIssue(context, cookie, message)
          } else {
            val location =
              getDependencyLocation(
                context,
                GOOGLE_SUPPORT_GROUP_ID,
                WEARABLE_ARTIFACT_ID,
                sortedSupportVersions[0],
                ANDROID_WEAR_GROUP_ID,
                WEARABLE_ARTIFACT_ID,
                supportedWearableVersions[0]
              )
            reportFatalCompatibilityIssue(context, location, message)
          }
        }
      }
    }
  }

  private fun getAllLibraries(project: Project): List<LintModelLibrary> {
    return project.buildVariant?.mainArtifact?.dependencies?.getAll() ?: emptyList()
  }

  private fun checkConsistentLibraries(
    context: Context,
    cookie: Any?,
    groupId: String,
    groupId2: String?
  ) {
    // Make sure we're using a consistent version across all play services libraries
    // (b/22709708)

    val project = context.mainProject
    val versionToCoordinate = ArrayListMultimap.create<String, LintModelMavenName>()
    val allLibraries = getAllLibraries(project).filterIsInstance<LintModelExternalLibrary>()
    for (library in allLibraries) {
      val coordinates = library.resolvedCoordinates
      if (
        (coordinates.groupId == groupId || coordinates.groupId == groupId2) &&
          // Historically the multidex library ended up in the support package but
          // decided to do its own numbering (and isn't tied to the rest in terms
          // of implementation dependencies)
          !coordinates.artifactId.startsWith("multidex") &&
          // Renderscript has stated in b/37630182 that they are built and
          // distributed separate from the rest and do not have any version
          // dependencies
          !coordinates.artifactId.startsWith("renderscript") &&
          // Similarly firebase job dispatcher doesn't follow normal firebase version
          // numbering
          !coordinates.artifactId.startsWith("firebase-jobdispatcher") &&
          // The Android annotations library is decoupled from the rest and doesn't
          // need to be matched to the other exact support library versions
          coordinates.artifactId != "support-annotations"
      ) {
        versionToCoordinate.put(coordinates.version, coordinates)
      }
    }

    val versions = versionToCoordinate.keySet()
    if (versions.size > 1) {
      val sortedVersions = ArrayList(versions)
      sortedVersions.sortWith(Collections.reverseOrder())
      val c1 = findFirst(versionToCoordinate.get(sortedVersions[0]))
      val c2 = findFirst(versionToCoordinate.get(sortedVersions[1]))

      // For GMS, the synced version requirement ends at version 14
      if (groupId == GMS_GROUP_ID || groupId == FIREBASE_GROUP_ID) {
        // c2 is the smallest of all the versions; if it is at least 14,
        // they all are
        val version = GradleVersion.tryParse(c2.version)
        if (version != null && (version.major >= 14 || version.major == 0)) {
          return
        }
      }

      // Not using toString because in the IDE, these are model proxies which display garbage output
      val example1 = c1.groupId + ":" + c1.artifactId + ":" + c1.version
      val example2 = c2.groupId + ":" + c2.artifactId + ":" + c2.version
      val groupDesc = if (GMS_GROUP_ID == groupId) "gms/firebase" else groupId
      var message =
        "All " +
          groupDesc +
          " libraries must use the exact same " +
          "version specification (mixing versions can lead to runtime crashes). " +
          "Found versions " +
          Joiner.on(", ").join(sortedVersions) +
          ". " +
          "Examples include `" +
          example1 +
          "` and `" +
          example2 +
          "`"

      // Create an improved error message for a confusing scenario where you use
      // data binding and end up with conflicting versions:
      // https://code.google.com/p/android/issues/detail?id=229664
      val allItems =
        project.buildVariant?.mainArtifact?.dependencies?.compileDependencies?.getAllGraphItems()
          ?: emptyList()
      for (library in allItems) {
        if (library.artifactName == "com.android.databinding:library") {
          for (dep in library.dependencies) {
            if (
              dep.artifactName == "com.android.support:support-v4" &&
                sortedVersions[0] !=
                  (dep.findLibrary() as? LintModelExternalLibrary)?.resolvedCoordinates?.version
            ) {
              message +=
                ". Note that this project is using data binding " +
                  "(com.android.databinding:library:" +
                  (library.findLibrary() as? LintModelExternalLibrary)
                    ?.resolvedCoordinates
                    ?.version +
                  ") which pulls in com.android.support:support-v4:" +
                  (dep.findLibrary() as? LintModelExternalLibrary)?.resolvedCoordinates?.version +
                  ". You can try to work around this " +
                  "by adding an explicit dependency on " +
                  "com.android.support:support-v4:" +
                  sortedVersions[0]
              break
            }
          }
          break
        }
      }

      if (cookie != null) {
        reportNonFatalCompatibilityIssue(context, cookie, message)
      } else {
        val location = getDependencyLocation(context, c1, c2)
        reportNonFatalCompatibilityIssue(context, location, message)
      }
    }
  }

  override fun beforeCheckRootProject(context: Context) {
    val project = context.project
    blockedDependencies[project] = BlockedDependencies(project)
  }

  override fun afterCheckRootProject(context: Context) {
    val project = context.project
    // Check for disallowed dependencies
    checkBlockedDependencies(context, project)
    if (!LintClient.isGradle) {
      // In the IDE, in tests, etc, we can run the detectors repeatedly,
      // and we don't want the reserved names to accumulate. In Gradle however
      // we do want to make sure that we assign unique names, even across
      // modules.
      reservedQuickfixNames = null
    }
  }

  private fun checkLibraryConsistency(context: Context) {
    checkConsistentPlayServices(context, null)
    checkConsistentSupportLibraries(context, null)
    checkConsistentWearableLibraries(context, null, null)
  }

  override fun visitTomlDocument(context: TomlContext, document: LintTomlDocument) {
    // Look for version catalogs
    val libraries = document.getValue(VC_LIBRARIES) as? LintTomlMapValue
    if (libraries != null) {
      val versions = document.getValue(VC_VERSIONS) as? LintTomlMapValue
      for ((_, library) in libraries.getMappedValues()) {
        val (coordinate, versionNode) = getLibraryFromTomlEntry(versions, library) ?: continue
        val gc = GradleCoordinate.parseCoordinateString(coordinate) ?: return
        // Check dependencies without the PSI read lock, because we
        // may need to make network requests to retrieve version info.
        context.driver.runLaterOutsideReadAction {
          checkDependency(context, gc, false, versionNode, versionNode)
        }
      }
    }
  }

  override fun afterCheckFile(context: Context) {
    if (mAppliedJavaPlugin && !(mDeclaredSourceCompatibility && mDeclaredTargetCompatibility)) {
      val file = context.file
      val contents = context.client.readFile(file).toString()
      val message =
        when {
          mDeclaredTargetCompatibility -> "no Java sourceCompatibility directive"
          mDeclaredSourceCompatibility -> "no Java targetCompatibility directive"
          else -> "no Java language level directives"
        }
      val fixDisplayName =
        when {
          mDeclaredTargetCompatibility -> "Insert sourceCompatibility directive for JDK8"
          mDeclaredSourceCompatibility -> "Insert targetCompatibility directive for JDK8"
          else -> "Insert JDK8 language level directives"
        }
      val insertion =
        when {
          // Note that these replacement texts must be valid in both Groovy and KotlinScript Gradle
          // files
          mDeclaredTargetCompatibility -> "\njava.sourceCompatibility = JavaVersion.VERSION_1_8"
          mDeclaredSourceCompatibility -> "\njava.targetCompatibility = JavaVersion.VERSION_1_8"
          else ->
            """

                    java {
                        sourceCompatibility = JavaVersion.VERSION_1_8
                        targetCompatibility = JavaVersion.VERSION_1_8
                    }
                """
              .trimIndent()
        }
      val fix =
        fix()
          .replace()
          .name(fixDisplayName)
          .range(Location.create(context.file, contents, 0, contents.length))
          .end()
          .with(insertion)
          .build()
      report(context, mJavaPluginInfo!!.cookie, JAVA_PLUGIN_LANGUAGE_LEVEL, message, fix)
    }
  }

  private fun maybeReportAgpVersionIssue(context: Context) {
    // b/144442233: surface check for outdated AGP only if google() is in buildscript repositories
    if (mDeclaredGoogleMavenRepository || context is TomlContext) {
      agpVersionCheckInfo?.let {
        val versionString = it.newerVersion.toString()
        val message =
          getNewerVersionAvailableMessage(it.dependency, versionString, it.safeReplacement)
        val fix =
          when {
            it.isResolved -> null
            else ->
              getUpdateDependencyFix(
                it.dependency.revision,
                versionString,
                it.newerVersionIsSafe,
                it.safeReplacement
              )
          }
        report(context, it.cookie, AGP_DEPENDENCY, message, fix)
      }
    }
  }

  private fun checkKaptUsage(
    dependency: String,
    libTomlValue: LintTomlValue?,
    context: GradleContext,
    statementCookie: Any
  ) {
    // Drop version, leaving "group:module"
    val module = dependency.substringBeforeLast(':')
    // See if we have a KSP replacement
    val replacement =
      annotationProcessorsWithKspReplacements[module] ?: return // No replacement to offer

    val fix =
      if (!mAppliedKspPlugin) {
        // KSP plugin not applied yet in this module, point to docs on how to enable it
        fix()
          .name(
            "Learn about how to enable KSP and use the KSP processor for this dependency instead"
          )
          .url("https://developer.android.com/studio/build/migrate-to-ksp")
          .build()
      } else {
        if (libTomlValue != null) { // Dependency is from version catalog
          val declaredWithGroupAndName = (libTomlValue as? LintTomlMapValue)?.get("group") != null
          val catalogFix =
            if (declaredWithGroupAndName) {
              val (oldGroup, oldName) = module.split(":")
              val (newGroup, newName) = replacement.split(":")
              fix()
                .replace()
                .range(libTomlValue.getLocation())
                .pattern("((.*)$oldGroup(.*)$oldName(.*))")
                .with("\\k<2>$newGroup\\k<3>$newName\\k<4>")
                .build()
            } else {
              fix()
                .replace()
                .range(libTomlValue.getLocation())
                .text(module)
                .with(replacement)
                .build()
            }
          val usageFix = fix().replace().text("kapt").with("ksp").build()

          fix().name("Replace usage of kapt with KSP").composite(catalogFix, usageFix)
        } else { // Dependency is declared locally in the build.gradle file
          // Fix within just build.gradle file for locally declared dependency
          fix()
            .name("Replace usage of kapt with KSP")
            .replace()
            .pattern("((.*)kapt(.*)$module(.*))")
            .with("\\k<2>ksp\\k<3>$replacement\\k<4>")
            .build()
        }
      }

    report(
      context = context,
      cookie = statementCookie,
      issue = KAPT_USAGE_INSTEAD_OF_KSP,
      message =
        "This library supports using KSP instead of kapt," +
          " which greatly improves performance. Learn more: " +
          "https://developer.android.com/studio/build/migrate-to-ksp",
      fix = fix
    )
  }

  /**
   * Checks to see if a KTX extension is available for the given library. If so, we offer a
   * suggestion to switch the dependency to the KTX version. See
   * https://developer.android.com/kotlin/ktx for details.
   *
   * This should be called outside of a read action, since it may trigger network requests.
   */
  private fun checkForKtxExtension(
    context: Context,
    groupId: String,
    artifactId: String,
    version: Version,
    cookie: Any
  ) {
    if (!mAppliedKotlinAndroidPlugin) return
    if (artifactId.endsWith("-ktx")) return
    if (cookie is LintTomlValue) return

    val mavenName = "$groupId:$artifactId"
    if (!libraryHasKtxExtension(mavenName)) {
      return
    }

    // Make sure the Kotlin stdlib is used by the main artifact (not just by tests).
    val variant = context.project.buildVariant ?: return
    variant.mainArtifact.findCompileDependency("org.jetbrains.kotlin:kotlin-stdlib") ?: return

    // Make sure the KTX extension exists for this version of the library.
    val repository = getGoogleMavenRepository(context.client)
    repository.findVersion(
      groupId,
      "$artifactId-ktx",
      filter = { it == version },
      allowPreview = true
    )
      ?: return

    // Note: once b/155974293 is fixed, we can check whether the KTX extension is
    // already a direct dependency. If it is, then we could offer a slightly better
    // warning message along the lines of: "There is no need to declare this dependency
    // because the corresponding KTX extension pulls it in automatically."

    val msg = "Add suffix `-ktx` to enable the Kotlin extensions for this library"
    val fix =
      fix()
        .name("Replace with KTX dependency")
        .replace()
        .text(mavenName)
        .with("$mavenName-ktx")
        .build()
    report(context, cookie, KTX_EXTENSION_AVAILABLE, msg, fix)
  }

  private fun checkForBomUsageWithoutPlatform(
    property: String,
    dependency: String,
    value: String,
    context: GradleContext,
    valueCookie: Any
  ) {
    if (
      dependency.substringBeforeLast(':') in commonBoms &&
        (CompileConfiguration.IMPLEMENTATION.matches(property) ||
          CompileConfiguration.API.matches(property))
    ) {
      val message = "BOM should be added with a call to platform()"
      val fix =
        fix()
          .name("Add platform() to BOM declaration", true)
          .replace()
          .text(value)
          .with("platform($value)")
          .build()
      report(context, valueCookie, BOM_WITHOUT_PLATFORM, message, fix)
    }
  }

  /**
   * Report any blocked dependencies that weren't found in the build.gradle source file during
   * processing (we don't have accurate position info at this point)
   */
  private fun checkBlockedDependencies(context: Context, project: Project) {
    val blockedDependencies = blockedDependencies[project] ?: return
    val dependencies = blockedDependencies.getForbiddenDependencies()
    if (dependencies.isNotEmpty()) {
      for (path in dependencies) {
        val message = getBlockedDependencyMessage(path)
        val projectDir = context.project.dir
        val gc =
          path[0].findLibrary()?.let {
            if (it is LintModelExternalLibrary) {
              it.resolvedCoordinates
            } else null
          }
        val location =
          if (gc != null) {
            getDependencyLocation(context, gc.groupId, gc.artifactId, gc.version)
          } else {
            val mavenName = path[0].artifactName
            guessGradleLocation(context.client, projectDir, mavenName)
          }
        context.report(Incident(DUPLICATE_CLASSES, location, message), map())
      }
    }
    this.blockedDependencies.remove(project)
  }

  private fun report(
    context: Context,
    cookie: Any,
    issue: Issue,
    message: String,
    fix: LintFix? = null,
    partial: Boolean = false,
    overrideSeverity: Severity? = null
  ): Boolean {
    // Some methods in GradleDetector are run without the PSI read lock in order
    // to accommodate network requests, so we grab the read lock here.
    var reportCreated = false
    context.client.runReadAction(
      Runnable {
        val enabled = context.isEnabled(issue)
        if (enabled && context is GradleContext) {
          // Suppressed?
          // Temporarily unconditionally checking for suppress comments in Gradle files
          // since Studio insists on an AndroidLint id prefix
          val checkComments = /*context.getClient().checkForSuppressComments() &&*/
            context.containsCommentSuppress()
          if (checkComments && context.isSuppressedWithComment(cookie, issue)) {
            return@Runnable
          }

          val location = context.getLocation(cookie)
          val incident = Incident(issue, location, message, fix)
          overrideSeverity?.let { incident.overrideSeverity(it) }
          if (partial) {
            context.report(incident, map())
          } else {
            context.report(incident)
          }
          reportCreated = true
        } else if (enabled && context is TomlContext) {
          val location = context.getLocation(cookie)
          val start = location.start?.offset ?: 0
          val checkComments = context.containsCommentSuppress()
          if (checkComments && context.isSuppressedWithComment(start, issue)) {
            return@Runnable
          }
          val incident = Incident(issue, location, message, fix)
          overrideSeverity?.let { incident.overrideSeverity(it) }
          if (partial) {
            context.report(incident, map())
          } else {
            context.report(incident)
          }
          reportCreated = true
        }
      }
    )
    return reportCreated
  }

  /**
   * Normally, all warnings reported for a given issue will have the same severity, so it isn't
   * possible to have some of them reported as errors and others as warnings. And this is
   * intentional, since users should get to designate whether an issue is an error or a warning (or
   * ignored for that matter).
   *
   * However, for [COMPATIBILITY] we want to treat some issues as fatal (breaking the build) but not
   * others. To achieve this we tweak things a little bit. All compatibility issues are now marked
   * as fatal, and if we're *not* in the "fatal only" mode, all issues are reported as before (with
   * severity fatal, which has the same visual appearance in the IDE as the previous severity,
   * "error".) However, if we're in a "fatal-only" build, then we'll stop reporting the issues that
   * aren't meant to be treated as fatal. That's what this method does; issues reported to it should
   * always be reported as fatal. There is a corresponding method,
   * [reportNonFatalCompatibilityIssue] which can be used to report errors that shouldn't break the
   * build; those are ignored in fatal-only mode.
   */
  private fun reportFatalCompatibilityIssue(context: Context, cookie: Any, message: String) {
    report(context, cookie, COMPATIBILITY, message)
  }

  private fun reportFatalCompatibilityIssue(
    context: Context,
    cookie: Any,
    message: String,
    fix: LintFix?
  ) {
    report(context, cookie, COMPATIBILITY, message, fix)
  }

  /** See [reportFatalCompatibilityIssue] for an explanation. */
  private fun reportNonFatalCompatibilityIssue(
    context: Context,
    cookie: Any,
    message: String,
    lintFix: LintFix? = null
  ) {
    if (context.driver.fatalOnlyMode) {
      return
    }

    report(context, cookie, COMPATIBILITY, message, lintFix)
  }

  private fun reportFatalCompatibilityIssue(context: Context, location: Location, message: String) {
    // Some methods in GradleDetector are run without the PSI read lock in order
    // to accommodate network requests, so we grab the read lock here.
    context.client.runReadAction { context.report(COMPATIBILITY, location, message) }
  }

  /** See [reportFatalCompatibilityIssue] for an explanation. */
  private fun reportNonFatalCompatibilityIssue(
    context: Context,
    location: Location,
    message: String
  ) {
    if (context.driver.fatalOnlyMode) {
      return
    }

    // Some methods in GradleDetector are run without the PSI read lock in order
    // to accommodate network requests, so we grab the read lock here.
    context.client.runReadAction { context.report(COMPATIBILITY, location, message) }
  }

  private fun getSdkVersion(value: String, valueCookie: Any): Int {
    var version = 0
    if (isStringLiteral(value)) {
      val codeName = getStringLiteralValue(value, valueCookie)
      if (codeName != null) {
        if (isNumberString(codeName)) {
          // Don't access numbered strings; should be literal numbers (lint will warn)
          return -1
        }
        val androidVersion = SdkVersionInfo.getVersion(codeName, null)
        if (androidVersion != null) {
          version = androidVersion.featureLevel
        }
      }
    } else {
      version = getIntLiteralValue(value, -1)
    }
    return version
  }

  @SuppressWarnings("ExpensiveAssertion")
  private fun resolveCoordinate(
    context: GradleContext,
    property: String,
    gc: GradleCoordinate
  ): GradleCoordinate? {
    assert(gc.revision.contains("$")) { gc.revision }
    val project = context.project
    val variant = project.buildVariant
    if (variant != null) {
      val artifact =
        when {
          property.startsWith("androidTest") -> variant.androidTestArtifact
          property.startsWith("testFixtures") -> variant.testFixturesArtifact
          property.startsWith("test") -> variant.testArtifact
          else -> variant.mainArtifact
        }
          ?: return null
      for (library in artifact.dependencies.getAll()) {
        if (library is LintModelExternalLibrary) {
          val mc = library.resolvedCoordinates
          if (mc.groupId == gc.groupId && mc.artifactId == gc.artifactId) {
            val revisions = GradleCoordinate.parseRevisionNumber(mc.version)
            if (revisions.isNotEmpty()) {
              return GradleCoordinate(mc.groupId, mc.artifactId, revisions, null)
            }
            break
          }
        }
      }
    }
    return null
  }

  /** True if the given project uses the legacy http library. */
  private fun usesLegacyHttpLibrary(project: Project): Boolean {
    val model = project.buildModule ?: return false
    for (file in model.bootClassPath) {
      if (file.endsWith("org.apache.http.legacy.jar")) {
        return true
      }
    }

    return false
  }

  private fun getUpdateDependencyFix(
    currentVersion: String,
    suggestedVersion: String,
    suggestedVersionIsSafe: Boolean = false,
    safeReplacement: Version? = null
  ): LintFix {
    val fix =
      fix()
        .name("Change to $suggestedVersion")
        .sharedName("Update versions")
        .replace()
        .text(currentVersion)
        .with(suggestedVersion)
        .autoFix(suggestedVersionIsSafe, suggestedVersionIsSafe)
        .build()
    return if (safeReplacement != null) {
      val stableVersion = safeReplacement.toString()
      val stableFix =
        fix()
          .name("Change to $stableVersion")
          .sharedName("Update versions")
          .replace()
          .text(currentVersion)
          .with(stableVersion)
          .autoFix()
          .build()
      fix().alternatives(fix, stableFix)
    } else {
      fix
    }
  }

  private fun getNewerVersionAvailableMessage(
    dependency: GradleCoordinate,
    version: String,
    stable: Version?
  ): String {
    val message = StringBuilder()
    with(message) {
      append("A newer version of ")
      append(dependency.groupId)
      append(":")
      append(dependency.artifactId)
      append(" than ")
      append(dependency.revision)
      append(" is available: ")
      append(version)
      if (stable != null) {
        append(". (There is also a newer version of ")
        append(stable.major.toString())
        append(".")
        append(stable.minor.toString())
        // \uD835\uDC65 is 𝑥, unicode for Mathematical Italic Small X
        append(".\uD835\uDC65 available, if upgrading to ")
        append(version)
        append(" is difficult: ")
        append(stable.toString())
        append(")")
      }
    }
    return message.toString()
  }

  /**
   * Checks if the library with the given `groupId` and `artifactId` has to match compileSdkVersion.
   */
  private fun isSupportLibraryDependentOnCompileSdk(groupId: String, artifactId: String): Boolean {
    return (SUPPORT_LIB_GROUP_ID == groupId &&
      !artifactId.startsWith("multidex") &&
      !artifactId.startsWith("renderscript") &&
      // Support annotation libraries work with any compileSdkVersion
      artifactId != "support-annotations")
  }

  private fun findFirst(coordinates: Collection<LintModelMavenName>): LintModelMavenName {
    return Collections.min(coordinates) { o1, o2 -> o1.toString().compareTo(o2.toString()) }
  }

  override fun filterIncident(context: Context, incident: Incident, map: LintMap): Boolean {
    val issue = incident.issue
    if (issue === DUPLICATE_CLASSES) {
      return context.mainProject.minSdk < 23 || usesLegacyHttpLibrary(context.mainProject)
    } else if (issue == EXPIRING_TARGET_SDK_VERSION || issue == EXPIRED_TARGET_SDK_VERSION) {
      // These checks only apply if the merged manifest does not mark this app as a wear app
      // (which may not appear in the manifest of the app module)
      return !isWearApp(context)
    } else {
      error(issue.id)
    }
  }

  private fun isWearApp(context: Context): Boolean {
    val manifest = context.mainProject.mergedManifest?.documentElement ?: return false
    for (element in manifest) {
      if (
        element.tagName == TAG_USES_FEATURE &&
          element.getAttributeNS(ANDROID_URI, ATTR_NAME) == "android.hardware.type.watch"
      ) {
        return true
      }
    }
    return false
  }

  override fun checkMergedProject(context: Context) {
    if (context.isGlobalAnalysis() && context.driver.isIsolated()) {
      // Already performed on occurrences in the file being edited
      return
    }
    checkLibraryConsistency(context)
  }

  private fun getBlockedDependencyMessage(path: List<LintModelDependency>): String {
    val direct = path.size == 1
    val message: String
    val resolution =
      "Solutions include " +
        "finding newer versions or alternative libraries that don't have the " +
        "same problem (for example, for `httpclient` use `HttpUrlConnection` or " +
        "`okhttp` instead), or repackaging the library using something like " +
        "`jarjar`."
    if (direct) {
      message =
        "`${path[0].getArtifactId()}` defines classes that conflict with classes now provided by Android. $resolution"
    } else {
      val sb = StringBuilder()
      var first = true
      for (library in path) {
        if (first) {
          first = false
        } else {
          sb.append(" \u2192 ") // right arrow
        }
        val coordinates = library.artifactName
        sb.append(coordinates)
      }
      sb.append(") ")
      val chain = sb.toString()
      message =
        "`${path[0].getArtifactId()}` depends on a library " +
          "(${path[path.size - 1].artifactName}) which defines " +
          "classes that conflict with classes now provided by Android. $resolution " +
          "Dependency chain: $chain"
    }
    return message
  }

  private fun getNewerVersion(version1: Version, major: Int, minor: Int, micro: Int): Version? =
    Version.parse("$major.$minor.$micro").takeIf {
      version1 > Version.prefixInfimum("0") && version1 < it
    }

  private fun getNewerVersion(version1: Version, major: Int, minor: Int): Version? =
    Version.parse("$major.$minor").takeIf { version1 > Version.prefixInfimum("0") && version1 < it }

  private var googleMavenRepository: GoogleMavenRepository? = null
  private var googlePlaySdkIndex: GooglePlaySdkIndex? = null

  private fun getGoogleMavenRepoVersion(
    context: Context,
    dependency: GradleCoordinate,
    filter: Predicate<Version>?
  ): Version? {
    val repository = getGoogleMavenRepository(context.client)
    return repository.findVersion(dependency, filter, dependency.isPreview)
  }

  fun getGoogleMavenRepository(client: LintClient): GoogleMavenRepository {
    return googleMavenRepository
      ?: run {
        val cacheDir = client.getCacheDir(MAVEN_GOOGLE_CACHE_DIR_KEY, true)
        val repository =
          object : GoogleMavenRepository(cacheDir?.toPath()) {

            public override fun readUrlData(url: String, timeout: Int): ByteArray? =
              readUrlData(client, url, timeout)

            public override fun error(throwable: Throwable, message: String?) =
              client.log(throwable, message)
          }

        googleMavenRepository = repository
        repository
      }
  }

  private fun getGooglePlaySdkIndex(client: LintClient): GooglePlaySdkIndex {
    return googlePlaySdkIndex
      ?: run {
        val cacheDir = client.getCacheDir(GOOGLE_PLAY_SDK_INDEX_KEY, true)
        val repository = playSdkIndexFactory(cacheDir?.toPath(), client)
        googlePlaySdkIndex = repository
        repository
      }
  }

  companion object {
    private var lastTargetSdkVersion: Int = -1
    private var lastTargetSdkVersionFile: File? = null

    /** If you invoke the target SDK versin migration assistant, stop flagging edits. */
    fun stopFlaggingTargetSdkEdits() {
      lastTargetSdkVersion = Integer.MAX_VALUE
      lastTargetSdkVersionFile = null
    }

    /** Calendar to use to look up the current time (used by tests to set specific time. */
    var calendar: Calendar? = null

    const val KEY_COORDINATE = "coordinate"

    private const val VC_LIBRARY_PREFIX = "libs."
    private const val VC_PLUGIN_PREFIX = "libs.plugins."

    private val IMPLEMENTATION = Implementation(GradleDetector::class.java, Scope.GRADLE_SCOPE)
    private val IMPLEMENTATION_WITH_TOML =
      Implementation(
        GradleDetector::class.java,
        Scope.GRADLE_AND_TOML_SCOPE,
        Scope.GRADLE_SCOPE,
        Scope.TOML_SCOPE
      )

    /** Obsolete dependencies. */
    @JvmField
    val DEPENDENCY =
      Issue.create(
        id = "GradleDependency",
        briefDescription = "Obsolete Gradle Dependency",
        explanation =
          """
                This detector looks for usages of libraries where the version you are using \
                is not the current stable release. Using older versions is fine, and there \
                are cases where you deliberately want to stick with an older version. \
                However, you may simply not be aware that a more recent version is \
                available, and that is what this lint check helps find.""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION_WITH_TOML
      )

    /**
     * Using a gradle group:artifact:id directly instead of placing it in the version catalog TOML
     * file
     */
    @JvmField
    val SWITCH_TO_TOML =
      Issue.create(
        id = "UseTomlInstead",
        briefDescription = "Use TOML Version Catalog Instead",
        explanation =
          """
                If your project is using a `libs.versions.toml` file, you should place \
                all Gradle dependencies in the TOML file. This lint check looks for \
                version declarations outside of the TOML file and suggests moving them \
                (and in the IDE, provides a quickfix to performing the operation automatically).
                """,
        category = Category.PRODUCTIVITY,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION_WITH_TOML
      )

    /** A dependency on an obsolete version of the Android Gradle Plugin. */
    @JvmField
    val AGP_DEPENDENCY =
      Issue.create(
        id = "AndroidGradlePluginVersion",
        briefDescription = "Obsolete Android Gradle Plugin Version",
        explanation =
          """
                This detector looks for usage of the Android Gradle Plugin where the version \
                you are using is not the current stable release. Using older versions is fine, \
                and there are cases where you deliberately want to stick with an older version. \
                However, you may simply not be aware that a more recent version is available, \
                and that is what this lint check helps find.""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION_WITH_TOML
      )

    /** Deprecated Gradle constructs. */
    @JvmField
    val DEPRECATED =
      Issue.create(
        id = "GradleDeprecated",
        briefDescription = "Deprecated Gradle Construct",
        explanation =
          """
                This detector looks for deprecated Gradle constructs which currently work \
                but will likely stop working in a future update.""",
        category = Category.CORRECTNESS,
        priority = 6,
        androidSpecific = true,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION
      )

    /** Deprecated Gradle configurations. */
    @JvmField
    val DEPRECATED_CONFIGURATION =
      Issue.create(
        id = "GradleDeprecatedConfiguration",
        briefDescription = "Deprecated Gradle Configuration",
        explanation =
          """
                Some Gradle configurations have been deprecated since Android Gradle Plugin 3.0.0 \
                and will be removed in a future version of the Android Gradle Plugin.
             """,
        category = Category.CORRECTNESS,
        moreInfo = "https://d.android.com/r/tools/update-dependency-configurations",
        priority = 6,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION
      )

    /** Incompatible Android Gradle plugin. */
    @JvmField
    val GRADLE_PLUGIN_COMPATIBILITY =
      Issue.create(
        id = "GradlePluginVersion",
        briefDescription = "Incompatible Android Gradle Plugin",
        explanation =
          """
                Not all versions of the Android Gradle plugin are compatible with all \
                versions of the SDK. If you update your tools, or if you are trying to \
                open a project that was built with an old version of the tools, you may \
                need to update your plugin version number.""",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.ERROR,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Invalid or dangerous paths. */
    @JvmField
    val PATH =
      Issue.create(
        id = "GradlePath",
        briefDescription = "Gradle Path Issues",
        explanation =
          """
                Gradle build scripts are meant to be cross platform, so file paths use \
                Unix-style path separators (a forward slash) rather than Windows path \
                separators (a backslash). Similarly, to keep projects portable and \
                repeatable, avoid using absolute paths on the system; keep files within \
                the project instead. To share code between projects, consider creating \
                an android-library and an AAR dependency""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION
      )

    /** Constructs the IDE support struggles with. */
    @JvmField
    val IDE_SUPPORT =
      Issue.create(
        id = "GradleIdeError",
        briefDescription = "Gradle IDE Support Issues",
        explanation =
          """
                Gradle is highly flexible, and there are things you can do in Gradle \
                files which can make it hard or impossible for IDEs to properly handle \
                the project. This lint check looks for constructs that potentially \
                break IDE support.""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.ERROR,
        implementation = IMPLEMENTATION
      )

    /** Using + in versions. */
    @JvmField
    val PLUS =
      Issue.create(
        id = "GradleDynamicVersion",
        briefDescription = "Gradle Dynamic Version",
        explanation =
          """
                Using `+` in dependencies lets you automatically pick up the latest \
                available version rather than a specific, named version. However, \
                this is not recommended; your builds are not repeatable; you may have \
                tested with a slightly different version than what the build server \
                used. (Using a dynamic version as the major version number is more \
                problematic than using it in the minor version position.)""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION
      )

    /** Accidentally calling a getter instead of your own methods. */
    @JvmField
    val GRADLE_GETTER =
      Issue.create(
        id = "GradleGetter",
        briefDescription = "Gradle Implicit Getter Call",
        explanation =
          """
                Gradle will let you replace specific constants in your build scripts \
                with method calls, so you can for example dynamically compute a version \
                string based on your current version control revision number, rather \
                than hardcoding a number.

                When computing a version name, it's tempting to for example call the \
                method to do that `getVersionName`. However, when you put that method \
                call inside the `defaultConfig` block, you will actually be calling the \
                Groovy getter for the `versionName` property instead. Therefore, you \
                need to name your method something which does not conflict with the \
                existing implicit getters. Consider using `compute` as a prefix instead \
                of `get`.""",
        category = Category.CORRECTNESS,
        priority = 6,
        severity = Severity.ERROR,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using incompatible versions. */
    @JvmField
    val COMPATIBILITY =
      Issue.create(
        id = "GradleCompatible",
        briefDescription = "Incompatible Gradle Versions",
        explanation =
          """
                There are some combinations of libraries, or tools and libraries, that \
                are incompatible, or can lead to bugs. One such incompatibility is \
                compiling with a version of the Android support libraries that is not \
                the latest version (or in particular, a version lower than your \
                `targetSdkVersion`).""",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.FATAL,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using a string where an integer is expected. */
    @JvmField
    val STRING_INTEGER =
      Issue.create(
        id = "StringShouldBeInt",
        briefDescription = "String should be int",
        explanation =
          """
                The properties `compileSdkVersion`, `minSdkVersion` and `targetSdkVersion` \
                are usually numbers, but can be strings when you are using an add-on (in \
                the case of `compileSdkVersion`) or a preview platform (for the other two \
                properties).

                However, you can not use a number as a string (e.g. "19" instead of 19); \
                that will result in a platform not found error message at build/sync \
                time.""",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.ERROR,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Attempting to use substitution with single quotes. */
    @JvmField
    val NOT_INTERPOLATED =
      Issue.create(
        id = "NotInterpolated",
        briefDescription = "Incorrect Interpolation",
        explanation =
          """
                To insert the value of a variable, you can use `${"$"}{variable}` inside a \
                string literal, but **only** if you are using double quotes!""",
        moreInfo = "https://www.groovy-lang.org/syntax.html#_string_interpolation",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.ERROR,
        implementation = IMPLEMENTATION
      )

    /** A newer version is available on a remote server. */
    @JvmField
    val REMOTE_VERSION =
      Issue.create(
        id = "NewerVersionAvailable",
        briefDescription = "Newer Library Versions Available",
        explanation =
          """
                This detector checks with a central repository to see if there are newer \
                versions available for the dependencies used by this project. This is \
                similar to the `GradleDependency` check, which checks for newer versions \
                available in the Android SDK tools and libraries, but this works with any \
                MavenCentral dependency, and connects to the library every time, which \
                makes it more flexible but also **much** slower.""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION_WITH_TOML,
        enabledByDefault = false
      )

    /** The API version is set too low. */
    @JvmField
    val MIN_SDK_TOO_LOW =
      Issue.create(
        id = "MinSdkTooLow",
        briefDescription = "API Version Too Low",
        explanation =
          """
                The value of the `minSdkVersion` property is too low and can be \
                incremented without noticeably reducing the number of supported \
                devices.""",
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION,
        androidSpecific = true,
        enabledByDefault = false
      )

    /** Accidentally using octal numbers. */
    @JvmField
    val ACCIDENTAL_OCTAL =
      Issue.create(
        id = "AccidentalOctal",
        briefDescription = "Accidental Octal",
        explanation =
          """
                In Groovy, an integer literal that starts with a leading 0 will be \
                interpreted as an octal number. That is usually (always?) an accident \
                and can lead to subtle bugs, for example when used in the `versionCode` \
                of an app.""",
        category = Category.CORRECTNESS,
        priority = 2,
        severity = Severity.ERROR,
        implementation = IMPLEMENTATION
      )

    @JvmField
    val BUNDLED_GMS =
      Issue.create(
        id = "UseOfBundledGooglePlayServices",
        briefDescription = "Use of bundled version of Google Play services",
        explanation =
          """
                Google Play services SDK's can be selectively included, which enables a \
                smaller APK size. Consider declaring dependencies on individual Google \
                Play services SDK's. If you are using Firebase API's \
                (https://firebase.google.com/docs/android/setup), Android Studio's \
                Tools → Firebase assistant window can automatically add just the \
                dependencies needed for each feature.""",
        moreInfo = "https://developers.google.com/android/guides/setup#split",
        category = Category.PERFORMANCE,
        priority = 4,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using a versionCode that is very high. */
    @JvmField
    val HIGH_APP_VERSION_CODE =
      Issue.create(
        id = "HighAppVersionCode",
        briefDescription = "VersionCode too high",
        explanation =
          """
                The declared `versionCode` is an Integer. Ensure that the version number is \
                not close to the limit. It is recommended to monotonically increase this \
                number each minor or major release of the app. Note that updating an app \
                with a versionCode over `Integer.MAX_VALUE` is not possible.""",
        moreInfo = "https://developer.android.com/studio/publish/versioning.html",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.ERROR,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Dev mode is no longer relevant. */
    @JvmField
    val DEV_MODE_OBSOLETE =
      Issue.create(
        id = "DevModeObsolete",
        briefDescription = "Dev Mode Obsolete",
        explanation =
          """
                In the past, our documentation recommended creating a `dev` product flavor \
                with has a minSdkVersion of 21, in order to enable multidexing to speed up \
                builds significantly during development.

                That workaround is no longer necessary, and it has some serious downsides, \
                such as breaking API access checking (since the true `minSdkVersion` is no \
                longer known).

                In recent versions of the IDE and the Gradle plugin, the IDE automatically \
                passes the API level of the connected device used for deployment, and if \
                that device is at least API 21, then multidexing is automatically turned \
                on, meaning that you get the same speed benefits as the `dev` product \
                flavor but without the downsides.""",
        category = Category.PERFORMANCE,
        priority = 2,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Duplicate HTTP classes. */
    @JvmField
    val DUPLICATE_CLASSES =
      Issue.create(
        id = "DuplicatePlatformClasses",
        briefDescription = "Duplicate Platform Classes",
        explanation =
          """
                There are a number of libraries that duplicate not just functionality \
                of the Android platform but using the exact same class names as the ones \
                provided in Android -- for example the apache http classes. This can \
                lead to unexpected crashes.

                To solve this, you need to either find a newer version of the library \
                which no longer has this problem, or to repackage the library (and all \
                of its dependencies) using something like the `jarjar` tool, or finally, \
                rewriting the code to use different APIs (for example, for http code, \
                consider using `HttpUrlConnection` or a library like `okhttp`).""",
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.FATAL,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /**
     * The minimum API required as of August (new apps) and November (updated apps) of the year
     * [MINIMUM_TARGET_SDK_VERSION_YEAR]. See
     * https://developer.android.com/google/play/requirements/target-sdk.
     */
    val MINIMUM_TARGET_SDK_VERSION = 31

    /**
     * The API requirement the previous year. This is normally -1, but we have a separate constant
     * in case we rev the API level more than one level in a year (such that we don't have to find
     * all the "- 1" logic throughout the code.)
     */
    val PREVIOUS_MINIMUM_TARGET_SDK_VERSION = MINIMUM_TARGET_SDK_VERSION - 1

    /** The year that the API requirement of [MINIMUM_TARGET_SDK_VERSION] is enforced. */
    val MINIMUM_TARGET_SDK_VERSION_YEAR = 2022

    /**
     * Reserved variable names used by [pickLibraryVariableName] and [pickVersionVariableName]
     * suggesting library and version variable names; we need to make sure we keep track of previous
     * suggestions made such that we don't have multiple quickfixes making the same suggestion and
     * creating a clash if all fixes are applied.
     */
    var reservedQuickfixNames: MutableMap<String, MutableSet<String>>? = null

    /** targetSdkVersion about to expire */
    @JvmField
    val EXPIRING_TARGET_SDK_VERSION =
      Issue.create(
          id = "ExpiringTargetSdkVersion",
          briefDescription = "TargetSdkVersion Soon Expiring",
          explanation =
            """
                In the second half of 2018, Google Play will require that new apps and app \
                updates target API level 26 or higher. This will be required for new apps in \
                August 2018, and for updates to existing apps in November 2018.

                Configuring your app to target a recent API level ensures that users benefit \
                from significant security and performance improvements, while still allowing \
                your app to run on older Android versions (down to the `minSdkVersion`).

                This lint check starts warning you some months **before** these changes go \
                into effect if your `targetSdkVersion` is 25 or lower. This is intended to \
                give you a heads up to update your app, since depending on your current \
                `targetSdkVersion` the work can be nontrivial.

                To update your `targetSdkVersion`, follow the steps from \
                "Meeting Google Play requirements for target API level", \
                https://developer.android.com/distribute/best-practices/develop/target-sdk.html
                """,
          category = Category.COMPLIANCE,
          priority = 8,
          severity = Severity.ERROR,
          androidSpecific = true,
          implementation = IMPLEMENTATION
        )
        .addMoreInfo(
          "https://support.google.com/googleplay/android-developer/answer/113469#targetsdk"
        )
        .addMoreInfo(
          "https://developer.android.com/distribute/best-practices/develop/target-sdk.html"
        )

    /** targetSdkVersion no longer supported */
    @JvmField
    val EXPIRED_TARGET_SDK_VERSION =
      Issue.create(
          id = "ExpiredTargetSdkVersion",
          briefDescription = "TargetSdkVersion No Longer Supported",
          moreInfo =
            "https://support.google.com/googleplay/android-developer/answer/113469#targetsdk",
          explanation =
            """
                As of the second half of 2018, Google Play requires that new apps and app \
                updates target API level 26 or higher.

                Configuring your app to target a recent API level ensures that users benefit \
                from significant security and performance improvements, while still allowing \
                your app to run on older Android versions (down to the `minSdkVersion`).

                To update your `targetSdkVersion`, follow the steps from \
                "Meeting Google Play requirements for target API level", \
                https://developer.android.com/distribute/best-practices/develop/target-sdk.html
                """,
          category = Category.COMPLIANCE,
          priority = 8,
          severity = Severity.FATAL,
          androidSpecific = true,
          implementation = IMPLEMENTATION
        )
        .addMoreInfo(
          "https://developer.android.com/distribute/best-practices/develop/target-sdk.html"
        )

    /** targetSdkVersion was manually edited */
    @JvmField
    val EDITED_TARGET_SDK_VERSION =
      Issue.create(
        id = "EditedTargetSdkVersion",
        briefDescription = "Manually Edited TargetSdkVersion",
        explanation =
          """
        Updating the `targetSdkVersion` of an app is seemingly easy: just increment the \
        `targetSdkVersion` number in the manifest file!

        But that's not actually safe. The `targetSdkVersion` controls a wide range of \
        behaviors that change from release to release, and to update, you should carefully \
        consult the documentation to see what has changed, how your app may need to adjust, \
        and then of course, carefully test everything.

        In new versions of Android Studio, there is a special migration assistant, available \
        from the tools menu (and as a quickfix from this lint warning) which analyzes your \
        specific app and filters the set of applicable migration steps to those needed for \
        your app.

        This lint check does something very simple: it just detects whether it looks like \
        you've manually edited the targetSdkVersion field in a build.gradle file. Obviously, \
        as part of doing the above careful steps, you may end up editing the value, which \
        would trigger the check -- and it's safe to ignore it; this lint check *only* runs \
        in the IDE, not from the command line; it's sole purpose to bring *awareness* to the \
        (many) developers who haven't been aware of this issue and have just bumped the \
        targetSdkVersion, recompiled, and uploaded their updated app to the Google Play Store, \
        sometimes leading to crashes or other problems on newer devices.
        """,
        category = Category.CORRECTNESS,
        priority = 2,
        severity = Severity.ERROR,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using a deprecated library. */
    @JvmField
    val DEPRECATED_LIBRARY =
      Issue.create(
        id = "OutdatedLibrary",
        briefDescription = "Outdated Library",
        explanation =
          """
                Your app is using an outdated version of a library. This may cause violations \
                of Google Play policies (see https://play.google.com/about/monetization-ads/ads/) \
                and/or may affect your app’s visibility on the Play Store.

                Please try updating your app with an updated version of this library, or remove \
                it from your app.
                """,
        category = Category.COMPLIANCE,
        priority = 5,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION_WITH_TOML,
        moreInfo = GOOGLE_PLAY_SDK_INDEX_URL
      )

    /** Using data binding with Kotlin but not Kotlin annotation processing. */
    @JvmField
    val DATA_BINDING_WITHOUT_KAPT =
      Issue.create(
        id = "DataBindingWithoutKapt",
        briefDescription = "Data Binding without Annotation Processing",
        moreInfo = "https://kotlinlang.org/docs/reference/kapt.html",
        explanation =
          """
                Apps that use Kotlin and data binding should also apply the kotlin-kapt plugin.
                """,
        category = Category.CORRECTNESS,
        priority = 1,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using Lifecycle annotation processor with java8. */
    @JvmField
    val LIFECYCLE_ANNOTATION_PROCESSOR_WITH_JAVA8 =
      Issue.create(
        id = "LifecycleAnnotationProcessorWithJava8",
        briefDescription = "Lifecycle Annotation Processor with Java 8 Compile Option",
        moreInfo = "https://d.android.com/r/studio-ui/lifecycle-release-notes",
        explanation =
          """
                For faster incremental build, switch to the Lifecycle Java 8 API with these steps:

                First replace
                ```gradle
                annotationProcessor "androidx.lifecycle:lifecycle-compiler:*version*"
                kapt "androidx.lifecycle:lifecycle-compiler:*version*"
                ```
                with
                ```gradle
                implementation "androidx.lifecycle:lifecycle-common-java8:*version*"
                ```
                Then remove any `OnLifecycleEvent` annotations from `Observer` classes \
                and make them implement the `DefaultLifecycleObserver` interface.
                """,
        category = Category.PERFORMANCE,
        priority = 6,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    /** Using a vulnerable library. */
    @JvmField
    val RISKY_LIBRARY =
      Issue.create(
          id = "RiskyLibrary",
          briefDescription = "Libraries with Privacy or Security Risks",
          explanation =
            """
                Your app is using a version of a library that has been identified by \
                the library developer as a potential source of privacy and/or security risks. \
                This may be a violation of Google Play policies (see \
                https://play.google.com/about/monetization-ads/ads/) and/or affect your app’s \
                visibility on the Play Store.

                When available, the individual error messages from lint will include details \
                about the reasons for this advisory.

                Please try updating your app with an updated version of this library, or remove \
                it from your app.
            """,
          category = Category.SECURITY,
          priority = 4,
          severity = Severity.WARNING,
          androidSpecific = true,
          implementation = IMPLEMENTATION_WITH_TOML,
          moreInfo = GOOGLE_PLAY_SDK_INDEX_URL
        )
        .addMoreInfo("https://goo.gle/RiskyLibrary")

    @JvmField
    val ANNOTATION_PROCESSOR_ON_COMPILE_PATH =
      Issue.create(
        id = "AnnotationProcessorOnCompilePath",
        briefDescription = "Annotation Processor on Compile Classpath",
        explanation =
          """
               This dependency is identified as an annotation processor. Consider adding it to the \
               processor path using `annotationProcessor` instead of including it to the \
               compile path.
            """,
        category = Category.PERFORMANCE,
        priority = 8,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION
      )

    @JvmField
    val KTX_EXTENSION_AVAILABLE =
      Issue.create(
        id = "KtxExtensionAvailable",
        briefDescription = "KTX Extension Available",
        explanation =
          """
                Android KTX extensions augment some libraries with support for modern Kotlin \
                language features like extension functions, extension properties, lambdas, named \
                parameters, coroutines, and more.

                In Kotlin projects, use the KTX version of a library by replacing the \
                dependency in your `build.gradle` file. For example, you can replace \
                `androidx.fragment:fragment` with `androidx.fragment:fragment-ktx`.
            """,
        category = Category.PRODUCTIVITY,
        priority = 4,
        severity = Severity.INFORMATIONAL,
        androidSpecific = true,
        implementation = IMPLEMENTATION,
        moreInfo = "https://developer.android.com/kotlin/ktx"
      )

    @JvmField
    val KAPT_USAGE_INSTEAD_OF_KSP =
      Issue.create(
        id = "KaptUsageInsteadOfKsp",
        briefDescription = "Kapt usage should be replaced with KSP",
        explanation =
          """
                KSP is a more efficient replacement for kapt. For libraries that support both, \
                KSP should be used to improve build times.
            """,
        category = Category.PERFORMANCE,
        priority = 4,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION,
        moreInfo = "https://developer.android.com/studio/build/migrate-to-ksp"
      )

    @JvmField
    val BOM_WITHOUT_PLATFORM =
      Issue.create(
        id = "BomWithoutPlatform",
        briefDescription = "Using a BOM without platform call",
        explanation =
          """
          When including a BOM, the dependency's coordinates must be wrapped \
          in a call to `platform()` for Gradle to interpret it correctly.
          """,
        category = Category.CORRECTNESS,
        priority = 4,
        severity = Severity.WARNING,
        androidSpecific = true,
        implementation = IMPLEMENTATION_WITH_TOML,
        moreInfo = "https://developer.android.com/r/tools/gradle-bom-docs"
      )

    @JvmField
    val JAVA_PLUGIN_LANGUAGE_LEVEL =
      Issue.create(
        id = "JavaPluginLanguageLevel",
        briefDescription = "No Explicit Java Language Level Given",
        explanation =
          """
                In modules using plugins deriving from the Gradle `java` plugin (e.g. \
                `java-library` or `application`), the java source and target compatibility \
                default to the version of the JDK being used to run Gradle, which may cause \
                compatibility problems with Android (or other) modules.

                You can specify an explicit sourceCompatibility and targetCompatibility in this \
                module to maintain compatibility no matter which JDK is used to run Gradle.
            """,
        category = Category.INTEROPERABILITY,
        priority = 6,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION
      )

    @JvmField
    val JCENTER_REPOSITORY_OBSOLETE =
      Issue.create(
        id = "JcenterRepositoryObsolete",
        briefDescription = "JCenter Maven repository is read-only",
        explanation =
          """
                The JCenter Maven repository is no longer accepting submissions of Maven \
                artifacts since 31st March 2021.  Ensure that the project is configured \
                to search in repositories with the latest versions of its dependencies.
            """,
        category = Category.CORRECTNESS,
        priority = 8,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION,
        moreInfo = "https://developer.android.com/r/tools/jcenter-end-of-service"
      )

    @JvmField
    val PLAY_SDK_INDEX_NON_COMPLIANT =
      Issue.create(
        id = "PlaySdkIndexNonCompliant",
        briefDescription = "Library has policy issues in SDK Index",
        explanation =
          """
                This library version has policy issues that will block publishing in the Google Play Store.
            """,
        category = Category.COMPLIANCE,
        priority = 8,
        severity = Severity.ERROR,
        implementation = IMPLEMENTATION_WITH_TOML,
        moreInfo = GOOGLE_PLAY_SDK_INDEX_URL,
        androidSpecific = true
      )

    @JvmField
    val CHROMEOS_ABI_SUPPORT =
      Issue.create(
        id = "ChromeOsAbiSupport",
        briefDescription = "Missing ABI Support for ChromeOS",
        explanation =
          """
                To properly support ChromeOS, your Android application should have an x86 and/or x86_64 binary \
                as part of the build configuration. To fix the issue, ensure your files are properly optimized \
                for ARM; the binary translator will then ensure compatibility with x86. Alternatively, add an \
                `abiSplit` for x86 within your `build.gradle` file and create the required x86 dependencies.
            """,
        category = Category.CHROME_OS,
        priority = 4,
        severity = Severity.WARNING,
        implementation = IMPLEMENTATION,
        moreInfo = "https://developer.android.com/ndk/guides/abis",
        androidSpecific = true
      )

    /** Gradle plugin IDs based on the Java plugin. */
    val JAVA_PLUGIN_IDS =
      listOf("java", "java-library", "application").flatMap { listOf(it, "org.gradle.$it") }

    /** The Gradle plugin ID for Android applications. */
    const val APP_PLUGIN_ID = "com.android.application"

    /** The Gradle plugin ID for Android libraries. */
    const val LIB_PLUGIN_ID = "com.android.library"

    /** Previous plugin id for applications. */
    const val OLD_APP_PLUGIN_ID = "android"

    /** Previous plugin id for libraries. */
    const val OLD_LIB_PLUGIN_ID = "android-library"

    /** Group ID for GMS. */
    const val GMS_GROUP_ID = "com.google.android.gms"

    const val FIREBASE_GROUP_ID = "com.google.firebase"
    const val GOOGLE_SUPPORT_GROUP_ID = "com.google.android.support"
    const val ANDROID_WEAR_GROUP_ID = "com.google.android.wearable"
    private const val WEARABLE_ARTIFACT_ID = "wearable"

    private val PLAY_SERVICES_V650 =
      GradleCoordinate.parseCoordinateString("$GMS_GROUP_ID:play-services:6.5.0")!!

    /**
     * Threshold to consider a versionCode very high and issue a warning.
     * https://developer.android.com/studio/publish/versioning.html indicates that the highest value
     * accepted by Google Play is 2100000000.
     */
    private const val VERSION_CODE_HIGH_THRESHOLD = 2000000000

    /** Returns the best guess for where a dependency is declared in the given project. */
    fun getDependencyLocation(context: Context, c: LintModelMavenName): Location {
      return getDependencyLocation(context, c.groupId, c.artifactId, c.version)
    }

    /** Returns the best guess for where a dependency is declared in the given project. */
    fun getDependencyLocation(
      context: Context,
      groupId: String,
      artifactId: String,
      version: String
    ): Location {
      val client = context.client
      val projectDir = context.project.dir
      val withoutQuotes = "$groupId:$artifactId:$version"
      var location = guessGradleLocation(client, projectDir, withoutQuotes)
      if (location.start != null) return location
      // Try with just the group+artifact (relevant for example when using
      // version variables)
      location = guessGradleLocation(client, projectDir, "$groupId:$artifactId:")
      if (location.start != null) return location
      // Just the artifact -- important when using the other dependency syntax,
      // e.g. variations of
      //   group: 'comh.android.support', name: 'support-v4', version: '21.0.+'
      location = guessGradleLocation(client, projectDir, artifactId)
      if (location.start != null) return location
      // just the group: less precise but better than just the gradle file
      location = guessGradleLocation(client, projectDir, groupId)
      return location
    }

    /** Returns the best guess for where two dependencies are declared in a project. */
    fun getDependencyLocation(
      context: Context,
      address1: LintModelMavenName,
      address2: LintModelMavenName
    ): Location {
      return getDependencyLocation(
        context,
        address1.groupId,
        address1.artifactId,
        address1.version,
        address2.groupId,
        address2.artifactId,
        address2.version
      )
    }

    /** Returns the best guess for where two dependencies are declared in a project. */
    fun getDependencyLocation(
      context: Context,
      groupId1: String,
      artifactId1: String,
      version1: String,
      groupId2: String,
      artifactId2: String,
      version2: String,
      message: String? = null
    ): Location {
      val location1 = getDependencyLocation(context, groupId1, artifactId1, version1)
      val location2 = getDependencyLocation(context, groupId2, artifactId2, version2)
      //noinspection FileComparisons
      if (location2.start != null || location1.file != location2.file) {
        location1.secondary = location2
        message?.let { location2.message = it }
      }
      return location1
    }

    /** TODO: Cache these results somewhere! */
    @JvmStatic
    fun getLatestVersionFromRemoteRepo(
      client: LintClient,
      dependency: GradleCoordinate,
      filter: Predicate<Version>?,
      allowPreview: Boolean
    ): Version? {
      val groupId = dependency.groupId
      val artifactId = dependency.artifactId
      val query = StringBuilder()
      val encoding = UTF_8.name()
      try {
        query.append("http://search.maven.org/solrsearch/select?q=g:%22")
        query.append(URLEncoder.encode(groupId, encoding))
        query.append("%22+AND+a:%22")
        query.append(URLEncoder.encode(artifactId, encoding))
      } catch (e: UnsupportedEncodingException) {
        return null
      }

      query.append("%22&core=gav")
      if (groupId == "com.google.guava" || artifactId == "kotlinx-coroutines-core") {
        // These libraries aren't releasing previews in their version strings;
        // instead, the suffix is used to indicate different variants (JRE vs Android,
        // JVM vs Kotlin Native)
      } else if (filter == null && allowPreview) {
        query.append("&rows=1")
      }
      query.append("&wt=json")

      val response: String?
      try {
        response = readUrlDataAsString(client, query.toString(), 20000)
        if (response == null) {
          return null
        }
      } catch (e: IOException) {
        client.log(
          null,
          "Could not connect to maven central to look up the latest " +
            "available version for %1\$s",
          dependency
        )
        return null
      }

      // Sample response:
      //    {
      //        "responseHeader": {
      //            "status": 0,
      //            "QTime": 0,
      //            "params": {
      //                "fl": "id,g,a,v,p,ec,timestamp,tags",
      //                "sort": "score desc,timestamp desc,g asc,a asc,v desc",
      //                "indent": "off",
      //                "q": "g:\"com.google.guava\" AND a:\"guava\"",
      //                "core": "gav",
      //                "wt": "json",
      //                "rows": "1",
      //                "version": "2.2"
      //            }
      //        },
      //        "response": {
      //            "numFound": 37,
      //            "start": 0,
      //            "docs": [{
      //                "id": "com.google.guava:guava:17.0",
      //                "g": "com.google.guava",
      //                "a": "guava",
      //                "v": "17.0",
      //                "p": "bundle",
      //                "timestamp": 1398199666000,
      //                "tags": ["spec", "libraries", "classes", "google", "code"],
      //                "ec": ["-javadoc.jar", "-sources.jar", ".jar", "-site.jar", ".pom"]
      //            }]
      //        }
      //    }

      // Look for version info:  This is just a cheap skim of the above JSON results.
      var index = response.indexOf("\"response\"")
      val versions = mutableListOf<Version>()
      while (index != -1) {
        index = response.indexOf("\"v\":", index)
        if (index != -1) {
          index += 4
          val start = response.indexOf('"', index) + 1
          val end = response.indexOf('"', start + 1)
          if (start in 0 until end) {
            val substring = response.substring(start, end)
            val revision = Version.parse(substring)
            if (revision != null) {
              versions.add(revision)
            }
          }
        }
      }

      // Some special cases for specific artifacts that were versioned
      // incorrectly (using a string suffix to delineate separate branches
      // whereas Gradle will just use an alphabetical sort on these). See
      // 171369798 for an example.

      if (groupId == "com.google.guava") {
        val version = dependency.lowerBoundVersion
        val suffix = version.toString()
        val jre: (Version) -> Boolean = { v -> v.toString().endsWith("-jre") }
        val android: (Version) -> Boolean = { v -> !v.toString().endsWith("-jre") }
        return versions.filter(if (suffix.endsWith("-jre")) jre else android).maxOrNull()
      } else if (artifactId == "kotlinx-coroutines-core") {
        val version = dependency.lowerBoundVersion
        if (version != null) {
          val suffix = version.toString()
          return versions
            .filter(
              when {
                suffix.indexOf('-') == -1 -> {
                  { (allowPreview || !it.isPreview) && !it.toString().contains("-native-mt") }
                }
                suffix.contains("-native-mt-2") -> {
                  { it.toString().contains("-native-mt-2") }
                }
                suffix.contains("-native-mt") -> {
                  {
                    it.toString().contains("-native-mt") && !it.toString().contains("-native-mt-2")
                  }
                }
                else -> {
                  { (allowPreview || !it.isPreview) && !it.toString().contains("-native-mt") }
                }
              }
            )
            .maxOrNull()
        }
      }

      return versions
        .filter { filter == null || filter.test(it) }
        .filter { allowPreview || !it.isPreview }
        .maxOrNull()
    }

    private data class VersionCatalogDependency(
      val coordinates: String,
      val tomlValue: LintTomlValue
    )

    /**
     * For the given library reference [expression] in the "libs.some.library.name" format, returns
     * the fully resolved coordinates of the library (including the version) and the corresponding
     * library declaration value in the version catalog.
     */
    private fun getDependencyFromVersionCatalog(
      expression: String,
      context: GradleContext
    ): VersionCatalogDependency? {
      if (!expression.startsWith(VC_LIBRARY_PREFIX)) return null

      // Remove the "libs." prefix
      val libName = expression.substring(VC_LIBRARY_PREFIX.length)

      // Find current library declaration in catalog, accounting for the declaration
      // possibly using - and _ characters in the name
      val library =
        (context.getTomlValue(VC_LIBRARIES) as? LintTomlMapValue)
          ?.getMappedValues()
          ?.asIterable()
          ?.find { it.key.replace('-', '.').replace('_', '.') == libName }
          ?.value
          ?: return null

      // Find full coordinates of lib, including version
      val versions = context.getTomlValue(VC_VERSIONS) as? LintTomlMapValue
      val (coordinate, _) = getLibraryFromTomlEntry(versions, library) ?: return null

      return VersionCatalogDependency(coordinate, library)
    }

    /**
     * For the given plugin reference [expression] in the "libs.plugins.some.plugin.name" format,
     * returns the fully resolved coordinates of the plugin (including the version) and the
     * corresponding plugin declaration value in the version catalog.
     */
    private fun getPluginFromVersionCatalog(
      expression: String,
      context: GradleContext
    ): VersionCatalogDependency? {
      if (!expression.startsWith(VC_PLUGIN_PREFIX)) return null

      // Remove the "libs.plugins." prefix
      val pluginName = expression.substring(VC_PLUGIN_PREFIX.length)

      // Find current plugin declaration in catalog, accounting for the declaration
      // possibly using - and _ characters in the name
      val plugin =
        (context.getTomlValue(VC_PLUGINS) as? LintTomlMapValue)
          ?.getMappedValues()
          ?.asIterable()
          ?.find { it.key.replace('-', '.').replace('_', '.') == pluginName }
          ?.value
          ?: return null

      // Find full coordinates of plugin, including version
      val versions = context.getTomlValue(VC_VERSIONS) as? LintTomlMapValue
      val (coordinate, _) = getPluginFromTomlEntry(versions, plugin) ?: return null

      return VersionCatalogDependency(coordinate, plugin)
    }

    // Convert a long-hand dependency, like
    //    group: 'com.android.support', name: 'support-v4', version: '21.0.+'
    // into an equivalent short-hand dependency, like
    //   com.android.support:support-v4:21.0.+
    @JvmStatic
    fun getNamedDependency(expression: String): String? {
      // if (value.startsWith("group: 'com.android.support', name: 'support-v4', version:
      // '21.0.+'"))
      if (expression.indexOf(',') != -1 && expression.contains("version:")) {
        var artifact: String? = null
        var group: String? = null
        var version: String? = null
        val splitter = Splitter.on(',').omitEmptyStrings().trimResults()
        for (property in splitter.split(expression)) {
          val colon = property.indexOf(':')
          if (colon == -1) {
            return null
          }
          var quote = '\''
          var valueStart = property.indexOf(quote, colon + 1)
          if (valueStart == -1) {
            quote = '"'
            valueStart = property.indexOf(quote, colon + 1)
          }
          if (valueStart == -1) {
            // For example, "transitive: false"
            continue
          }
          valueStart++
          val valueEnd = property.indexOf(quote, valueStart)
          if (valueEnd == -1) {
            return null
          }
          val value = property.substring(valueStart, valueEnd)
          when {
            property.startsWith("group:") -> group = value
            property.startsWith("name:") -> artifact = value
            property.startsWith("version:") -> version = value
          }
        }

        if (artifact != null && group != null && version != null) {
          return "$group:$artifact:$version"
        }
      }

      return null
    }

    private var majorBuildTools: Int = 0
    private var latestBuildTools: GradleVersion? = null

    /**
     * Returns the latest build tools installed for the given major version. We just cache this
     * once; we don't need to be accurate in the sense that if the user opens the SDK manager and
     * installs a more recent version, we capture this in the same IDE session.
     *
     * @param client the associated client
     * @param major the major version of build tools to look up (e.g. typically 18, 19, ...)
     * @return the corresponding highest known revision
     */
    private fun getLatestBuildTools(client: LintClient, major: Int): GradleVersion? {
      if (major != majorBuildTools) {
        majorBuildTools = major

        val revisions = ArrayList<GradleVersion>()
        when (major) {
          27 -> revisions.add(GradleVersion(27, 0, 3))
          26 -> revisions.add(GradleVersion(26, 0, 3))
          25 -> revisions.add(GradleVersion(25, 0, 3))
          24 -> revisions.add(GradleVersion(24, 0, 3))
          23 -> revisions.add(GradleVersion(23, 0, 3))
          22 -> revisions.add(GradleVersion(22, 0, 1))
          21 -> revisions.add(GradleVersion(21, 1, 2))
          20 -> revisions.add(GradleVersion(20, 0))
          19 -> revisions.add(GradleVersion(19, 1))
          18 -> revisions.add(GradleVersion(18, 1, 1))
        }

        // The above versions can go stale.
        // Check if a more recent one is installed. (The above are still useful for
        // people who haven't updated with the SDK manager recently.)
        val sdkHome = client.getSdkHome()
        if (sdkHome != null) {
          val dirs = File(sdkHome, FD_BUILD_TOOLS).listFiles()
          if (dirs != null) {
            for (dir in dirs) {
              val name = dir.name
              if (!dir.isDirectory || !Character.isDigit(name[0])) {
                continue
              }
              val v = GradleVersion.tryParse(name)
              if (v != null && v.major == major) {
                revisions.add(v)
              }
            }
          }
        }

        if (revisions.isNotEmpty()) {
          latestBuildTools = Collections.max(revisions)
        }
      }

      return latestBuildTools
    }

    private fun suggestApiConfigurationUse(project: Project, configuration: String): Boolean {
      return when {
        configuration.startsWith("test") || configuration.startsWith("androidTest") -> false
        else ->
          when (project.type) {
            LintModelModuleType.APP ->
              // Applications can only generally be consumed if there are dynamic features
              // (Ignoring the test-only project for this purpose)
              project.hasDynamicFeatures()
            LintModelModuleType.LIBRARY -> true
            LintModelModuleType.JAVA_LIBRARY -> true
            LintModelModuleType.FEATURE,
            LintModelModuleType.DYNAMIC_FEATURE -> true
            LintModelModuleType.TEST -> false
            LintModelModuleType.INSTANT_APP -> false
          }
      }
    }

    private fun targetJava8Plus(project: Project): Boolean {
      return getLanguageLevel(project, JDK_1_7).isAtLeast(JDK_1_8)
    }

    private fun hasLifecycleAnnotationProcessor(dependency: String) =
      dependency.contains("android.arch.lifecycle:compiler") ||
        dependency.contains("androidx.lifecycle:lifecycle-compiler")

    private fun isCommonAnnotationProcessor(dependency: String): Boolean =
      when (val index = dependency.lastIndexOf(":")) {
        -1 -> false
        else -> dependency.substring(0, index) in commonAnnotationProcessors
      }

    private enum class CompileConfiguration(private val compileConfigName: String) {
      API("api"),
      COMPILE("compile"),
      IMPLEMENTATION("implementation"),
      COMPILE_ONLY("compileOnly");

      private val annotationProcessor = "annotationProcessor"
      private val compileConfigSuffix = compileConfigName.usLocaleCapitalize()

      fun matches(configurationName: String): Boolean {
        return configurationName == compileConfigName ||
          configurationName.endsWith(compileConfigSuffix)
      }

      fun replacement(configurationName: String): String {
        return if (configurationName == compileConfigName) {
          annotationProcessor
        } else {
          configurationName.removeSuffix(compileConfigSuffix).appendCapitalized(annotationProcessor)
        }
      }
    }

    private val commonAnnotationProcessors: Set<String> =
      setOf(
        "com.jakewharton:butterknife-compiler",
        "com.github.bumptech.glide:compiler",
        "androidx.databinding:databinding-compiler",
        "com.google.dagger:dagger-compiler",
        "com.google.auto.service:auto-service",
        "android.arch.persistence.room:compiler",
        "android.arch.lifecycle:compiler",
        "io.realm:realm-annotations-processor",
        "com.google.dagger:dagger-android-processor",
        "androidx.room:room-compiler",
        "com.android.databinding:compiler",
        "androidx.lifecycle:lifecycle-compiler",
        "org.projectlombok:lombok",
        "com.google.auto.value:auto-value",
        "org.parceler:parceler",
        "com.github.hotchemi:permissionsdispatcher-processor",
        "com.alibaba:arouter-compiler",
        "org.androidannotations:androidannotations",
        "com.github.Raizlabs.DBFlow:dbflow-processor",
        "frankiesardo:icepick-processor",
        "org.greenrobot:eventbus-annotation-processor",
        "com.ryanharter.auto.value:auto-value-gson",
        "io.objectbox:objectbox-processor",
        "com.arello-mobile:moxy-compiler",
        "com.squareup.dagger:dagger-compiler",
        "io.realm:realm-android",
        "com.bluelinelabs:logansquare-compiler",
        "com.tencent.tinker:tinker-android-anno",
        "com.raizlabs.android:DBFlow-Compiler",
        "com.google.auto.factory:auto-factory",
        "com.airbnb:deeplinkdispatch-processor",
        "com.alipay.android.tools:androidannotations",
        "org.permissionsdispatcher:permissionsdispatcher-processor",
        "com.airbnb.android:epoxy-processor",
        "org.immutables:value",
        "com.github.stephanenicolas.toothpick:toothpick-compiler",
        "com.mindorks.android:placeholderview-compiler",
        "com.github.frankiesardo:auto-parcel-processor",
        "com.hannesdorfmann.fragmentargs:processor",
        "com.evernote:android-state-processor",
        "org.mapstruct:mapstruct-processor",
        "com.iqiyi.component.router:qyrouter-compiler",
        "com.iqiyi.component.mm:mm-compiler",
        "dk.ilios:realmfieldnameshelper",
        "com.lianjia.common.android.router2:compiler",
        "com.smile.gifshow.annotation:invoker_processor",
        "com.f2prateek.dart:dart-processor",
        "com.sankuai.waimai.router:compiler",
        "org.qiyi.card:card-action-compiler",
        "com.iqiyi.video:eventbus-annotation-processor",
        "ly.img.android.pesdk:build-processor",
        "org.apache.logging.log4j:log4j-core",
        "com.github.jokermonn:permissions4m",
        "com.arialyy.aria:aria-compiler",
        "com.smile.gifshow.annotation:provide_processor",
        "com.smile.gifshow.annotation:preference_processor",
        "com.smile.gifshow.annotation:plugin_processor",
        "org.inferred:freebuilder",
        "com.smile.gifshow.annotation:router_processor"
      )

    // From https://kotlinlang.org/docs/ksp-overview.html#supported-libraries
    private val annotationProcessorsWithKspReplacements: Map<String, String> =
      mapOf(
        // Note: this is the only dependency where coordinates actually have to be updated
        "com.github.bumptech.glide:compiler" to "com.github.bumptech.glide:ksp",
        "androidx.room:room-compiler" to "androidx.room:room-compiler",
        "com.squareup.moshi:moshi-kotlin-codegen" to "com.squareup.moshi:moshi-kotlin-codegen",
        "com.github.liujingxing.rxhttp:rxhttp-compiler" to
          "com.github.liujingxing.rxhttp:rxhttp-compiler",
        "se.ansman.kotshi:compiler" to "se.ansman.kotshi:compiler",
        "com.linecorp.lich:savedstate-compiler" to "com.linecorp.lich:savedstate-compiler",
        "io.github.amrdeveloper:easyadapter-compiler" to
          "io.github.amrdeveloper:easyadapter-compiler",
        "com.airbnb:deeplinkdispatch-processor" to "com.airbnb:deeplinkdispatch-processor",
        "com.airbnb.android:epoxy-processor" to "com.airbnb.android:epoxy-processor",
        "com.airbnb.android:paris-processor" to "com.airbnb.android:paris-processor",
      )

    private val commonBoms: Set<String> =
      setOf(
        // Google
        "androidx.compose:compose-bom",
        "com.google.firebase:firebase-bom",
        // JetBrains
        "org.jetbrains.kotlin:kotlin-bom",
        "org.jetbrains.kotlinx:kotlinx-coroutines-bom",
        "io.ktor:ktor-bom",
        // Network and serialization
        "com.squareup.okio:okio-bom",
        "com.squareup.okhttp3:okhttp-bom",
        "com.squareup.wire:wire-bom",
        "com.fasterxml.jackson:jackson-bom",
        "io.grpc:grpc-bom",
        "org.http4k:http4k-bom",
        "org.http4k:http4k-connect-bom",
        // Testing
        "org.junit:junit-bom",
        "io.kotest:kotest-bom",
        "io.cucumber:cucumber-bom",
        // Others
        "io.arrow-kt:arrow-stack",
        "io.sentry:sentry-bom",
        "dev.chrisbanes.compose:compose-bom",
        "org.ow2.asm:asm-bom",
        "software.amazon.awssdk:bom",
        "com.walletconnect:android-bom",
      )

    private fun libraryHasKtxExtension(mavenName: String): Boolean {
      // From https://developer.android.com/kotlin/ktx/extensions-list.
      return when (mavenName) {
        "androidx.activity:activity",
        "androidx.collection:collection",
        "androidx.core:core",
        "androidx.dynamicanimation:dynamicanimation",
        "androidx.fragment:fragment",
        "androidx.lifecycle:lifecycle-livedata-core",
        "androidx.lifecycle:lifecycle-livedata",
        "androidx.lifecycle:lifecycle-reactivestreams",
        "androidx.lifecycle:lifecycle-runtime",
        "androidx.lifecycle:lifecycle-viewmodel",
        "androidx.navigation:navigation-runtime",
        "androidx.navigation:navigation-fragment",
        "androidx.navigation:navigation-ui",
        "androidx.paging:paging-common",
        "androidx.paging:paging-runtime",
        "androidx.paging:paging-rxjava2",
        "androidx.palette:palette",
        "androidx.preference:preference",
        "androidx.slice:slice-builders",
        "androidx.sqlite:sqlite",
        "com.google.android.play:core" -> true
        else -> false
      }
    }

    @JvmStatic
    var playSdkIndexFactory: (Path?, LintClient) -> GooglePlaySdkIndex =
      { path: Path?, client: LintClient ->
        val index =
          object : GooglePlaySdkIndex(path) {
            public override fun readUrlData(url: String, timeout: Int) =
              readUrlData(client, url, timeout)

            override fun error(throwable: Throwable, message: String?) {
              client.log(throwable, message)
            }
          }
        index.initialize()
        index
      }
  }
}

private infix fun Version?.maxOrNull(other: Version?): Version? =
  when {
    this == null -> other
    other == null -> this
    else -> if (this > other) this else other
  }

/**
 * This exists to smooth over the fact that we represent the Version of a prefix matcher as the
 * least possible version that would match, but we want here to find newer versions that would not
 * match (e.g. if [dependency] has a version specification of 1.0.+ we should return false for a
 * [Version] of 1.0.2, but true for a [Version] of 1.1.0.
 *
 * A clearer implementation fix for this is to have two Version getters for GradleCoordinate:
 * getLowerBoundVersion and getUpperBoundVersion (both of which are computable) and to use the
 * appropriate one in the right context (in most of this file, the upper bound).
 */
private fun Version?.isNewerThan(dependency: GradleCoordinate) =
  dependency.lowerBoundVersion.let { version ->
    if (this == null) return false
    GradleCoordinate(dependency.groupId, dependency.artifactId, this.toString()).let {
      newerCoordinate ->
      when {
        dependency.acceptsGreaterRevisions() ->
          this > version && COMPARE_PLUS_HIGHER.compare(newerCoordinate, dependency) > 0
        else -> this > version
      }
    }
  }