File: git_cl.py

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (7373 lines) | stat: -rwxr-xr-x 292,821 bytes parent folder | download | duplicates (3)
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
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
#!/usr/bin/env vpython3
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Copyright (C) 2008 Evan Martin <martine@danga.com>
"""A git-command for integrating reviews on Gerrit."""

from __future__ import annotations

import base64
import collections
import datetime
import enum
import fnmatch
import functools
import httplib2
import itertools
import json
import logging
import multiprocessing
import optparse
import os
import re
import shutil
import stat
import sys
import tempfile
import textwrap
import time
import typing
import urllib.error
import urllib.parse
import urllib.request
import uuid
import webbrowser
import zlib

from typing import Any
from typing import AnyStr
from typing import Callable
from typing import List
from typing import Mapping
from typing import NoReturn
from typing import Optional
from typing import Sequence
from typing import Tuple

import auth
import clang_format
import gclient_paths
import gclient_utils
import gerrit_util
import git_auth
import git_common
import git_footers
import git_new_branch
import git_squash_branch
import google_java_format
import metrics
import metrics_utils
import metrics_xml_format
import newauth
import owners_client
import owners_finder
import presubmit_canned_checks
import presubmit_support
import rustfmt
import scm
import setup_color
import split_cl
import subcommand
import subprocess2
import swift_format
import watchlists

from third_party import colorama


__version__ = '2.0'

# TODO: Should fix these warnings.
# pylint: disable=line-too-long

# Traces for git push will be stored in a traces directory inside the
# depot_tools checkout.
DEPOT_TOOLS = os.path.dirname(os.path.abspath(__file__))
TRACES_DIR = os.path.join(DEPOT_TOOLS, 'traces')
PRESUBMIT_SUPPORT = os.path.join(DEPOT_TOOLS, 'presubmit_support.py')

# When collecting traces, Git hashes will be reduced to 6 characters to reduce
# the size after compression.
GIT_HASH_RE = re.compile(r'\b([a-f0-9]{6})[a-f0-9]{34}\b', flags=re.I)
# Used to redact the cookies from the gitcookies file.
GITCOOKIES_REDACT_RE = re.compile(r'1/.*')

MAX_ATTEMPTS = 3

# The maximum number of traces we will keep. Multiplied by 3 since we store
# 3 files per trace.
MAX_TRACES = 3 * 10
# Message to be displayed to the user to inform where to find the traces for a
# git-cl upload execution.
TRACES_MESSAGE = (
    '\n'
    'The traces of this git-cl execution have been recorded at:\n'
    '  %(trace_name)s-traces.zip\n'
    'Copies of your gitcookies file and git config have been recorded at:\n'
    '  %(trace_name)s-git-info.zip\n')
# Format of the message to be stored as part of the traces to give developers a
# better context when they go through traces.
TRACES_README_FORMAT = ('Date: %(now)s\n'
                        '\n'
                        'Change: https://%(gerrit_host)s/q/%(change_id)s\n'
                        'Title: %(title)s\n'
                        '\n'
                        '%(description)s\n'
                        '\n'
                        'Execution time: %(execution_time)s\n'
                        'Exit code: %(exit_code)s\n') + TRACES_MESSAGE

POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land'
DESCRIPTION_BACKUP_FILE = '.git_cl_description_backup'
REFS_THAT_ALIAS_TO_OTHER_REFS = {
    'refs/remotes/origin/lkgr': 'refs/remotes/origin/main',
    'refs/remotes/origin/lkcr': 'refs/remotes/origin/main',
}

DEFAULT_OLD_BRANCH = 'refs/remotes/origin/master'
DEFAULT_NEW_BRANCH = 'refs/remotes/origin/main'

DEFAULT_BUILDBUCKET_HOST = 'cr-buildbucket.appspot.com'

# Valid extensions for files we want to lint.
DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
DEFAULT_LINT_IGNORE_REGEX = r"$^"

# File name for yapf style config files.
YAPF_CONFIG_FILENAME = '.style.yapf'

# The issue, patchset and codereview server are stored on git config for each
# branch under branch.<branch-name>.<config-key>.
ISSUE_CONFIG_KEY = 'gerritissue'
PATCHSET_CONFIG_KEY = 'gerritpatchset'
CODEREVIEW_SERVER_CONFIG_KEY = 'gerritserver'
# When using squash workflow, _CMDUploadChange doesn't simply push the commit(s)
# you make to Gerrit. Instead, it creates a new commit object that contains all
# changes you've made, diffed against a parent/merge base.
# This is the hash of the new squashed commit and you can find this on Gerrit.
GERRIT_SQUASH_HASH_CONFIG_KEY = 'gerritsquashhash'
# This is the latest uploaded local commit hash.
LAST_UPLOAD_HASH_CONFIG_KEY = 'last-upload-hash'

# Shortcut since it quickly becomes repetitive.
Fore = colorama.Fore

# Used by tests/git_cl_test.py to add extra logging.
# Inside the weirdly failing test, add this:
# >>> self.mock(git_cl, '_IS_BEING_TESTED', True)
# And scroll up to see the stack trace printed.
_IS_BEING_TESTED = False

_GOOGLESOURCE = 'googlesource.com'

_KNOWN_GERRIT_TO_SHORT_URLS = {
    'https://chrome-internal-review.googlesource.com': 'https://crrev.com/i',
    'https://chromium-review.googlesource.com': 'https://crrev.com/c',
}
assert len(_KNOWN_GERRIT_TO_SHORT_URLS) == len(
    set(_KNOWN_GERRIT_TO_SHORT_URLS.values())), 'must have unique values'

# Maximum number of branches in a stack that can be traversed and uploaded
# at once. Picked arbitrarily.
_MAX_STACKED_BRANCHES_UPLOAD = 20

_NO_BRANCH_ERROR = (
    'Unable to determine base commit in detached HEAD state. '
    'Get on a branch or run `git cl upload --no-squash <base>` to '
    'upload all commits since base!')


class GitPushError(Exception):
    pass


def DieWithError(message, change_desc=None) -> NoReturn:
    if change_desc:
        SaveDescriptionBackup(change_desc)
        print('\n ** Content of CL description **\n' + '=' * 72 + '\n' +
              change_desc.description + '\n' + '=' * 72 + '\n')

    print(message, file=sys.stderr)
    sys.exit(1)


def SaveDescriptionBackup(change_desc):
    backup_path = os.path.join(DEPOT_TOOLS, DESCRIPTION_BACKUP_FILE)
    print('\nsaving CL description to %s\n' % backup_path)
    with open(backup_path, 'wb') as backup_file:
        backup_file.write(change_desc.description.encode('utf-8'))


def GetNoGitPagerEnv():
    env = os.environ.copy()
    # 'cat' is a magical git string that disables pagers on all platforms.
    env['GIT_PAGER'] = 'cat'
    return env


def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs):
    try:
        stdout = subprocess2.check_output(args, shell=shell, **kwargs)
        return stdout.decode('utf-8', 'replace')
    except subprocess2.CalledProcessError as e:
        logging.debug('Failed running %s', args)
        if not error_ok:
            message = error_message or e.stdout.decode('utf-8', 'replace') or ''
            DieWithError('Command "%s" failed.\n%s' % (' '.join(args), message))
        out = e.stdout.decode('utf-8', 'replace')
        if e.stderr:
            out += e.stderr.decode('utf-8', 'replace')
        return out


def RunGit(args, **kwargs) -> str:
    """Returns stdout."""
    return RunCommand(['git'] + args, **kwargs)


def RunGitWithCode(args, suppress_stderr=False, cwd=None):
    """Returns return code and stdout."""
    if suppress_stderr:
        stderr = subprocess2.DEVNULL
    else:
        stderr = sys.stderr
    try:
        (out, _), code = subprocess2.communicate(['git'] + args,
                                                 env=GetNoGitPagerEnv(),
                                                 stdout=subprocess2.PIPE,
                                                 stderr=stderr,
                                                 cwd=cwd)
        return code, out.decode('utf-8', 'replace')
    except subprocess2.CalledProcessError as e:
        logging.debug('Failed running %s', ['git'] + args)
        return e.returncode, e.stdout.decode('utf-8', 'replace')


def RunGitSilent(args, cwd=None):
    """Returns stdout, suppresses stderr and ignores the return code."""
    return RunGitWithCode(args, suppress_stderr=True, cwd=cwd)[1]


def time_sleep(seconds):
    # Use this so that it can be mocked in tests without interfering with python
    # system machinery.
    return time.sleep(seconds)


def time_time():
    # Use this so that it can be mocked in tests without interfering with python
    # system machinery.
    return time.time()


def datetime_now():
    # Use this so that it can be mocked in tests without interfering with python
    # system machinery.
    return datetime.datetime.now()


def confirm_or_exit(prefix='', action='confirm'):
    """Asks user to press enter to continue or press Ctrl+C to abort."""
    if not prefix or prefix.endswith('\n'):
        mid = 'Press'
    elif prefix.endswith('.') or prefix.endswith('?'):
        mid = ' Press'
    elif prefix.endswith(' '):
        mid = 'press'
    else:
        mid = ' press'
    gclient_utils.AskForData('%s%s Enter to %s, or Ctrl+C to abort' %
                             (prefix, mid, action))


def ask_for_explicit_yes(prompt):
    """Returns whether user typed 'y' or 'yes' to confirm the given prompt."""
    result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower()
    while True:
        if 'yes'.startswith(result):
            return True
        if 'no'.startswith(result):
            return False
        result = gclient_utils.AskForData('Please, type yes or no: ').lower()


def _get_properties_from_options(options):
    prop_list = getattr(options, 'properties', [])
    properties = dict(x.split('=', 1) for x in prop_list)
    for key, val in properties.items():
        try:
            properties[key] = json.loads(val)
        except ValueError:
            pass  # If a value couldn't be evaluated, treat it as a string.
    return properties


def _call_buildbucket(http, buildbucket_host, method, request):
    """Calls a buildbucket v2 method and returns the parsed json response."""
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
    request = json.dumps(request)
    url = 'https://%s/prpc/buildbucket.v2.Builds/%s' % (buildbucket_host,
                                                        method)

    logging.info('POST %s with %s' % (url, request))

    attempts = 1
    time_to_sleep = 1
    while True:
        response, content = http.request(url,
                                         'POST',
                                         body=request,
                                         headers=headers)
        if response.status == 200:
            return json.loads(content[4:])
        if attempts >= MAX_ATTEMPTS or 400 <= response.status < 500:
            msg = '%s error when calling POST %s with %s: %s' % (
                response.status, url, request, content)
            raise BuildbucketResponseException(msg)
        logging.debug('%s error when calling POST %s with %s. '
                      'Sleeping for %d seconds and retrying...' %
                      (response.status, url, request, time_to_sleep))
        time.sleep(time_to_sleep)
        time_to_sleep *= 2
        attempts += 1

    assert False, 'unreachable'


def _parse_bucket(raw_bucket):
    legacy = True
    project = bucket = None
    if '/' in raw_bucket:
        legacy = False
        project, bucket = raw_bucket.split('/', 1)
    # Assume luci.<project>.<bucket>.
    elif raw_bucket.startswith('luci.'):
        project, bucket = raw_bucket[len('luci.'):].split('.', 1)
    # Otherwise, assume prefix is also the project name.
    elif '.' in raw_bucket:
        project = raw_bucket.split('.')[0]
        bucket = raw_bucket
    # Legacy buckets.
    if legacy and project and bucket:
        print('WARNING Please use %s/%s to specify the bucket.' %
              (project, bucket))
    return project, bucket


def _canonical_git_googlesource_host(host):
    """Normalizes Gerrit hosts (with '-review') to Git host."""
    assert host.endswith(_GOOGLESOURCE)
    # Prefix doesn't include '.' at the end.
    prefix = host[:-(1 + len(_GOOGLESOURCE))]
    if prefix.endswith('-review'):
        prefix = prefix[:-len('-review')]
    return prefix + '.' + _GOOGLESOURCE


def _canonical_gerrit_googlesource_host(host):
    git_host = _canonical_git_googlesource_host(host)
    prefix = git_host.split('.', 1)[0]
    return prefix + '-review.' + _GOOGLESOURCE


def _get_counterpart_host(host):
    assert host.endswith(_GOOGLESOURCE)
    git = _canonical_git_googlesource_host(host)
    gerrit = _canonical_gerrit_googlesource_host(git)
    return git if gerrit == host else gerrit


def _trigger_tryjobs(changelist, jobs, options, patchset):
    """Sends a request to Buildbucket to trigger tryjobs for a changelist.

    Args:
        changelist: Changelist that the tryjobs are associated with.
        jobs: A list of (project, bucket, builder).
        options: Command-line options.
    """
    print('Scheduling jobs on:')
    for project, bucket, builder in jobs:
        print('  %s/%s: %s' % (project, bucket, builder))
    print('To see results here, run:        git cl try-results')
    print('To see results in browser, run:  git cl web')

    requests = _make_tryjob_schedule_requests(changelist, jobs, options,
                                              patchset)
    if not requests:
        return

    http = auth.Authenticator().authorize(httplib2.Http())
    http.force_exception_to_status_code = True

    batch_request = {'requests': requests}
    batch_response = _call_buildbucket(http, DEFAULT_BUILDBUCKET_HOST, 'Batch',
                                       batch_request)

    errors = [
        '  ' + response['error']['message']
        for response in batch_response.get('responses', [])
        if 'error' in response
    ]
    if errors:
        raise BuildbucketResponseException(
            'Failed to schedule builds for some bots:\n%s' % '\n'.join(errors))


def _make_tryjob_schedule_requests(changelist, jobs, options, patchset):
    """Constructs requests for Buildbucket to trigger tryjobs."""
    gerrit_changes = [changelist.GetGerritChange(patchset)]
    shared_properties = {
        'category': options.ensure_value('category', 'git_cl_try')
    }
    shared_properties.update(_get_properties_from_options(options) or {})

    shared_tags = [{'key': 'user_agent', 'value': 'git_cl_try'}]
    if options.ensure_value('retry_failed', False):
        shared_tags.append({'key': 'retry_failed', 'value': '1'})

    requests = []
    for (project, bucket, builder) in jobs:
        properties = shared_properties.copy()
        if 'presubmit' in builder.lower():
            properties['dry_run'] = 'true'

        requests.append({
            'scheduleBuild': {
                'requestId': str(uuid.uuid4()),
                'builder': {
                    'project': getattr(options, 'project', None) or project,
                    'bucket': bucket,
                    'builder': builder,
                },
                'gerritChanges': gerrit_changes,
                'properties': properties,
                'tags': [
                    {
                        'key': 'builder',
                        'value': builder
                    },
                ] + shared_tags,
            }
        })

        if options.ensure_value('revision', None):
            remote, remote_branch = changelist.GetRemoteBranch()
            requests[-1]['scheduleBuild']['gitilesCommit'] = {
                'host':
                _canonical_git_googlesource_host(gerrit_changes[0]['host']),
                'project': gerrit_changes[0]['project'],
                'id': options.revision,
                'ref': GetTargetRef(remote, remote_branch, None)
            }

    return requests


def _fetch_tryjobs(changelist, buildbucket_host, patchset=None):
    """Fetches tryjobs from buildbucket.

    Returns list of buildbucket.v2.Build with the try jobs for the changelist.
    """
    fields = ['id', 'builder', 'status', 'createTime', 'tags']
    request = {
        'predicate': {
            'gerritChanges': [changelist.GetGerritChange(patchset)],
        },
        'fields': ','.join('builds.*.' + field for field in fields),
    }

    authenticator = auth.Authenticator()
    if authenticator.has_cached_credentials():
        http = authenticator.authorize(httplib2.Http())
    else:
        print('Warning: Some results might be missing because %s' %
              # Get the message on how to login.
              (
                  str(auth.LoginRequiredError()), ))
        http = httplib2.Http()
    http.force_exception_to_status_code = True

    response = _call_buildbucket(http, buildbucket_host, 'SearchBuilds',
                                 request)
    return response.get('builds', [])


def _fetch_latest_builds(changelist, buildbucket_host, latest_patchset=None):
    """Fetches builds from the latest patchset that has builds (within
    the last few patchsets).

    Args:
        changelist (Changelist): The CL to fetch builds for
        buildbucket_host (str): Buildbucket host, e.g. "cr-buildbucket.appspot.com"
        lastest_patchset(int|NoneType): the patchset to start fetching builds from.
            If None (default), starts with the latest available patchset.
    Returns:
        A tuple (builds, patchset) where builds is a list of buildbucket.v2.Build,
        and patchset is the patchset number where those builds came from.
    """
    assert buildbucket_host
    assert changelist.GetIssue(), 'CL must be uploaded first'
    assert changelist.GetCodereviewServer(), 'CL must be uploaded first'
    if latest_patchset is None:
        assert changelist.GetMostRecentPatchset()
        ps = changelist.GetMostRecentPatchset()
    else:
        assert latest_patchset > 0, latest_patchset
        ps = latest_patchset

    min_ps = max(1, ps - 5)
    while ps >= min_ps:
        builds = _fetch_tryjobs(changelist, buildbucket_host, patchset=ps)
        if len(builds):
            return builds, ps
        ps -= 1
    return [], 0


def _filter_failed_for_retry(all_builds):
    """Returns a list of buckets/builders that are worth retrying.

    Args:
        all_builds (list): Builds, in the format returned by _fetch_tryjobs,
            i.e. a list of buildbucket.v2.Builds which includes status and builder
            info.

    Returns:
        A dict {(proj, bucket): [builders]}. This is the same format accepted by
        _trigger_tryjobs.
    """
    grouped = {}
    for build in all_builds:
        builder = build['builder']
        key = (builder['project'], builder['bucket'], builder['builder'])
        grouped.setdefault(key, []).append(build)

    jobs = []
    for (project, bucket, builder), builds in grouped.items():
        if 'triggered' in builder:
            print(
                'WARNING: Not scheduling %s. Triggered bots require an initial job '
                'from a parent. Please schedule a manual job for the parent '
                'instead.')
            continue
        if any(b['status'] in ('STARTED', 'SCHEDULED') for b in builds):
            # Don't retry if any are running.
            continue
        # If builder had several builds, retry only if the last one failed.
        # This is a bit different from CQ, which would re-use *any* SUCCESS-full
        # build, but in case of retrying failed jobs retrying a flaky one makes
        # sense.
        builds = sorted(builds, key=lambda b: b['createTime'])
        if builds[-1]['status'] not in ('FAILURE', 'INFRA_FAILURE'):
            continue
        # Don't retry experimental build previously triggered by CQ.
        if any(t['key'] == 'cq_experimental' and t['value'] == 'true'
               for t in builds[-1]['tags']):
            continue
        jobs.append((project, bucket, builder))

    # Sort the jobs to make testing easier.
    return sorted(jobs)


def _print_tryjobs(options, builds):
    """Prints nicely result of _fetch_tryjobs."""
    if not builds:
        print('No tryjobs scheduled.')
        return

    longest_builder = max(len(b['builder']['builder']) for b in builds)
    name_fmt = '{builder:<%d}' % longest_builder
    if options.print_master:
        longest_bucket = max(len(b['builder']['bucket']) for b in builds)
        name_fmt = ('{bucket:>%d} ' % longest_bucket) + name_fmt

    builds_by_status = {}
    for b in builds:
        builds_by_status.setdefault(b['status'], []).append({
            'id':
            b['id'],
            'name':
            name_fmt.format(builder=b['builder']['builder'],
                            bucket=b['builder']['bucket']),
        })

    sort_key = lambda b: (b['name'], b['id'])

    def print_builds(title, builds, fmt=None, color=None):
        """Pop matching builds from `builds` dict and print them."""
        if not builds:
            return

        fmt = fmt or '{name} https://ci.chromium.org/b/{id}'
        if not options.color or color is None:
            colorize = lambda x: x
        else:
            colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET)

        print(colorize(title))
        for b in sorted(builds, key=sort_key):
            print(' ', colorize(fmt.format(**b)))

    total = len(builds)
    print_builds('Successes:',
                 builds_by_status.pop('SUCCESS', []),
                 color=Fore.GREEN)
    print_builds('Infra Failures:',
                 builds_by_status.pop('INFRA_FAILURE', []),
                 color=Fore.MAGENTA)
    print_builds('Failures:',
                 builds_by_status.pop('FAILURE', []),
                 color=Fore.RED)
    print_builds('Canceled:',
                 builds_by_status.pop('CANCELED', []),
                 fmt='{name}',
                 color=Fore.MAGENTA)
    print_builds('Started:',
                 builds_by_status.pop('STARTED', []),
                 color=Fore.YELLOW)
    print_builds('Scheduled:',
                 builds_by_status.pop('SCHEDULED', []),
                 fmt='{name} id={id}')
    # The last section is just in case buildbucket API changes OR there is a
    # bug.
    print_builds('Other:',
                 sum(builds_by_status.values(), []),
                 fmt='{name} id={id}')
    print('Total: %d tryjobs' % total)


def _ComputeFormatDiffLineRanges(files, upstream_commit, expand=0):
    """Gets the changed line ranges for each file since upstream_commit.

    Parses a git diff on provided files and returns a dict that maps a file name
    to an ordered list of range tuples in the form (start_line, count).
    Ranges are in the same format as a git diff.

    Args:
        files: List of paths to diff.
        upstream_commit: Commit to diff against to find changed lines.
        expand: Expand diff ranges by this many lines before & after.

    Returns:
        A dict of path->[(start_line, end_line), ...]
    """
    # If files is empty then diff_output will be a full diff.
    if len(files) == 0:
        return {}

    # Take the git diff and find the line ranges where there are changes.
    diff_output = RunGitDiffCmd(['-U0'],
                                upstream_commit,
                                files,
                                allow_prefix=True)

    pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)'
    # 2 capture groups
    # 0 == fname of diff file
    # 1 == 'diff_start,diff_count' or 'diff_start'
    # will match each of
    # diff --git a/foo.foo b/foo.py
    # @@ -12,2 +14,3 @@
    # @@ -12,2 +17 @@
    # running re.findall on the above string with pattern will give
    # [('foo.py', ''), ('', '14,3'), ('', '17')]

    curr_file = None
    line_diffs = {}
    for match in re.findall(pattern, diff_output, flags=re.MULTILINE):
        if match[0] != '':
            # Will match the second filename in diff --git a/a.py b/b.py.
            curr_file = match[0]
            line_diffs[curr_file] = []
            prev_end = 1
        else:
            # Matches +14,3
            if ',' in match[1]:
                diff_start, diff_count = match[1].split(',')
            else:
                # Single line changes are of the form +12 instead of +12,1.
                diff_start = match[1]
                diff_count = 1

            # if the original lines were removed without replacements,
            # the diff count is 0. Then, no formatting is necessary.
            if diff_count == 0:
                continue

            diff_start = int(diff_start)
            diff_count = int(diff_count)
            # diff_count contains the diff_start line, and the line numbers
            # given to formatter args are inclusive. For example, in
            # google-java-format "--lines 5:10" includes 5th-10th lines.
            diff_end = diff_start + diff_count - 1 + expand
            diff_start = max(prev_end + 1, diff_start - expand)
            if diff_start <= diff_end:
                prev_end = diff_end
                line_diffs[curr_file].append((diff_start, diff_end))

    return line_diffs


def _FindYapfConfigFile(fpath, yapf_config_cache, top_dir=None):
    """Checks if a yapf file is in any parent directory of fpath until top_dir.

    Recursively checks parent directories to find yapf file and if no yapf file
    is found returns None. Uses yapf_config_cache as a cache for previously found
    configs.
    """
    fpath = os.path.abspath(fpath)
    # Return result if we've already computed it.
    if fpath in yapf_config_cache:
        return yapf_config_cache[fpath]

    parent_dir = os.path.dirname(fpath)
    if os.path.isfile(fpath):
        ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
    else:
        # Otherwise fpath is a directory
        yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME)
        if os.path.isfile(yapf_file):
            ret = yapf_file
        elif fpath in (top_dir, parent_dir):
            # If we're at the top level directory, or if we're at root
            # there is no provided style.
            ret = None
        else:
            # Otherwise recurse on the current directory.
            ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
    yapf_config_cache[fpath] = ret
    return ret


def _GetYapfIgnorePatterns(top_dir):
    """Returns all patterns in the .yapfignore file.

    yapf is supposed to handle the ignoring of files listed in .yapfignore itself,
    but this functionality appears to break when explicitly passing files to
    yapf for formatting. According to
    https://github.com/google/yapf/blob/HEAD/README.rst#excluding-files-from-formatting-yapfignore,
    the .yapfignore file should be in the directory that yapf is invoked from,
    which we assume to be the top level directory in this case.

    Args:
        top_dir: The top level directory for the repository being formatted.

    Returns:
        A set of all fnmatch patterns to be ignored.
    """
    yapfignore_file = os.path.join(top_dir, '.yapfignore')
    ignore_patterns = set()
    if not os.path.exists(yapfignore_file):
        return ignore_patterns

    for line in gclient_utils.FileRead(yapfignore_file).split('\n'):
        stripped_line = line.strip()
        # Comments and blank lines should be ignored.
        if stripped_line.startswith('#') or stripped_line == '':
            continue
        ignore_patterns.add(stripped_line)
    return ignore_patterns


def _FilterYapfIgnoredFiles(filepaths, patterns):
    """Filters out any filepaths that match any of the given patterns.

    Args:
        filepaths: An iterable of strings containing filepaths to filter.
        patterns: An iterable of strings containing fnmatch patterns to filter on.

    Returns:
        A list of strings containing all the elements of |filepaths| that did not
        match any of the patterns in |patterns|.
    """
    # Not inlined so that tests can use the same implementation.
    return [
        f for f in filepaths
        if not any(fnmatch.fnmatch(f, p) for p in patterns)
    ]


def _GetCommitCountSummary(begin_commit: str,
                           end_commit: str = "HEAD") -> Optional[str]:
    """Generate a summary of the number of commits in (begin_commit, end_commit).

    Returns a string containing the summary, or None if the range is empty.
    """
    count = int(
        RunGitSilent(['rev-list', '--count', f'{begin_commit}..{end_commit}']))

    if not count:
        return None

    return f'{count} commit{"s"[:count!=1]}'


def _prepare_superproject_push_option() -> str | None:
    """Returns the push option specifying the root repo of a gclient checkout.

    The push option will be formatted:
        'custom-keyed-value=rootRepo:{host}/{project}@{ref}'

    For chromium/src the entire push option would be:
        'custom-keyed-value=rootRepo:chromium/chromium/src@d3adb33f'.
    """
    gclient_root = gclient_paths.FindGclientRoot(os.getcwd())
    if not gclient_root:
        return None

    superproject_url = gclient_paths.GetGClientPrimarySolutionURL(gclient_root)
    if not superproject_url:
        return None

    parsed_url = urllib.parse.urlparse(superproject_url)
    host = parsed_url.netloc.removesuffix('.googlesource.com')
    project = parsed_url.path.strip('/').removesuffix('.git')
    soln_root = gclient_paths.GetPrimarySolutionPath()
    rev = RunGitSilent(['rev-parse', 'refs/heads/main'], cwd=soln_root).strip()
    return f'custom-keyed-value=rootRepo:{host}/{project}@{rev}'


def print_stats(args):
    """Prints statistics about the change to the user."""
    # --no-ext-diff is broken in some versions of Git, so try to work around
    # this by overriding the environment (but there is still a problem if the
    # git config key "diff.external" is used).
    env = GetNoGitPagerEnv()
    if 'GIT_EXTERNAL_DIFF' in env:
        del env['GIT_EXTERNAL_DIFF']

    return subprocess2.call(
        ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args,
        env=env)


class BuildbucketResponseException(Exception):
    pass


class Settings(object):
    def __init__(self):
        self.cc = None
        self.root = None
        self.tree_status_url = None
        self.viewvc_url = None
        self.updated = False
        self.is_gerrit = None
        self.squash_gerrit_uploads = None
        self.gerrit_skip_ensure_authenticated = None
        self.git_editor = None
        self.format_full_by_default = None
        self.is_status_commit_order_by_date = None

    def _LazyUpdateIfNeeded(self):
        """Updates the settings from a codereview.settings file, if available."""
        if self.updated:
            return

        # The only value that actually changes the behavior is
        # autoupdate = "false". Everything else means "true".
        autoupdate = (scm.GIT.GetConfig(self.GetRoot(), 'rietveld.autoupdate',
                                        '').lower())

        cr_settings_file = FindCodereviewSettingsFile()
        if autoupdate != 'false' and cr_settings_file:
            LoadCodereviewSettingsFromFile(cr_settings_file)
            cr_settings_file.close()

        self.updated = True

    @staticmethod
    def GetRelativeRoot():
        return scm.GIT.GetCheckoutRoot('.')

    def GetRoot(self):
        if self.root is None:
            self.root = os.path.realpath(os.path.abspath(
                self.GetRelativeRoot()))
        return self.root

    def GetTreeStatusUrl(self, error_ok=False):
        if not self.tree_status_url:
            self.tree_status_url = self._GetConfig('rietveld.tree-status-url')
            if self.tree_status_url is None and not error_ok:
                DieWithError(
                    'You must configure your tree status URL by running '
                    '"git cl config".')
        return self.tree_status_url

    def GetViewVCUrl(self) -> str:
        if not self.viewvc_url:
            self.viewvc_url = self._GetConfig('rietveld.viewvc-url')
        return self.viewvc_url

    def GetBugPrefix(self):
        return self._GetConfig('rietveld.bug-prefix')

    def GetRunPostUploadHook(self):
        run_post_upload_hook = self._GetConfig('rietveld.run-post-upload-hook')
        return run_post_upload_hook == "True"

    def GetDefaultCCList(self):
        return self._GetConfig('rietveld.cc')

    def GetSquashGerritUploads(self):
        """Returns True if uploads to Gerrit should be squashed by default."""
        if self.squash_gerrit_uploads is None:
            self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
        if self.squash_gerrit_uploads is None:
            # Default is squash now (http://crbug.com/611892#c23).
            self.squash_gerrit_uploads = self._GetConfig(
                'gerrit.squash-uploads').lower() != 'false'
        return self.squash_gerrit_uploads

    def GetSquashGerritUploadsOverride(self):
        """Return True or False if codereview.settings should be overridden.

        Returns None if no override has been defined.
        """
        # See also http://crbug.com/611892#c23
        result = self._GetConfig('gerrit.override-squash-uploads').lower()
        if result == 'true':
            return True
        if result == 'false':
            return False
        return None

    def GetIsGerrit(self):
        """Return True if gerrit.host is set."""
        if self.is_gerrit is None:
            self.is_gerrit = bool(self._GetConfig('gerrit.host', False))
        return self.is_gerrit

    def GetGerritSkipEnsureAuthenticated(self):
        """Return True if EnsureAuthenticated should not be done for Gerrit
        uploads."""
        if self.gerrit_skip_ensure_authenticated is None:
            self.gerrit_skip_ensure_authenticated = self._GetConfig(
                'gerrit.skip-ensure-authenticated').lower() == 'true'
        return self.gerrit_skip_ensure_authenticated

    def GetGitEditor(self):
        """Returns the editor specified in the git config, or None if none is."""
        if self.git_editor is None:
            # Git requires single quotes for paths with spaces. We need to
            # replace them with double quotes for Windows to treat such paths as
            # a single path.
            self.git_editor = self._GetConfig('core.editor').replace('\'', '"')
        return self.git_editor or None

    def GetLintRegex(self):
        return self._GetConfig('rietveld.cpplint-regex', DEFAULT_LINT_REGEX)

    def GetLintIgnoreRegex(self):
        return self._GetConfig('rietveld.cpplint-ignore-regex',
                               DEFAULT_LINT_IGNORE_REGEX)

    def GetFormatFullByDefault(self):
        if self.format_full_by_default is None:
            self.format_full_by_default = self._GetConfigBool(
                'rietveld.format-full-by-default')
        return self.format_full_by_default

    def IsStatusCommitOrderByDate(self):
        if self.is_status_commit_order_by_date is None:
            self.is_status_commit_order_by_date = self._GetConfigBool(
                'cl.date-order')
        return self.is_status_commit_order_by_date

    def _GetConfig(self, key, default=''):
        self._LazyUpdateIfNeeded()
        return scm.GIT.GetConfig(self.GetRoot(), key, default)

    def _GetConfigBool(self, key) -> bool:
        self._LazyUpdateIfNeeded()
        return scm.GIT.GetConfigBool(self.GetRoot(), key)


settings = Settings()


class _CQState(object):
    """Enum for states of CL with respect to CQ."""
    NONE = 'none'
    DRY_RUN = 'dry_run'
    COMMIT = 'commit'

    ALL_STATES = [NONE, DRY_RUN, COMMIT]


class _ParsedIssueNumberArgument(object):
    def __init__(self, issue=None, patchset=None, hostname=None):
        self.issue = issue
        self.patchset = patchset
        self.hostname = hostname

    @property
    def valid(self):
        return self.issue is not None


def ParseIssueNumberArgument(arg):
    """Parses the issue argument and returns _ParsedIssueNumberArgument."""
    fail_result = _ParsedIssueNumberArgument()

    if isinstance(arg, int):
        return _ParsedIssueNumberArgument(issue=arg)
    if not isinstance(arg, str):
        return fail_result

    if arg.isdigit():
        return _ParsedIssueNumberArgument(issue=int(arg))

    url = gclient_utils.UpgradeToHttps(arg)
    if not url.startswith('http'):
        return fail_result
    for gerrit_url, short_url in _KNOWN_GERRIT_TO_SHORT_URLS.items():
        if url.startswith(short_url):
            url = gerrit_url + url[len(short_url):]
            break

    try:
        parsed_url = urllib.parse.urlparse(url)
    except ValueError:
        return fail_result

    # If "https://" was automatically added, fail if `arg` looks unlikely to be
    # a URL.
    if not arg.startswith('http') and '.' not in parsed_url.netloc:
        return fail_result

    # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]]
    # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]]
    # Short urls like https://domain/<issue_number> can be used, but don't allow
    # specifying the patchset (you'd 404), but we allow that here.
    if parsed_url.path == '/':
        part = parsed_url.fragment
    else:
        part = parsed_url.path

    match = re.match(r'(/c(/.*/\+)?)?/(?P<issue>\d+)(/(?P<patchset>\d+)?/?)?$',
                     part)
    if not match:
        return fail_result

    issue = int(match.group('issue'))
    patchset = match.group('patchset')
    return _ParsedIssueNumberArgument(
        issue=issue,
        patchset=int(patchset) if patchset else None,
        hostname=parsed_url.netloc)


def _create_description_from_log(args):
    """Pulls out the commit log to use as a base for the CL description."""
    log_args = []
    if len(args) == 1 and args[0] == None:
        # Handle the case where None is passed as the branch.
        return ''
    if len(args) == 1 and not args[0].endswith('.'):
        log_args = [args[0] + '..']
    elif len(args) == 1 and args[0].endswith('...'):
        log_args = [args[0][:-1]]
    elif len(args) == 2:
        log_args = [args[0] + '..' + args[1]]
    else:
        log_args = args[:]  # Hope for the best!
    return RunGit(['log', '--pretty=format:%B%n'] + log_args)


class GerritChangeNotExists(Exception):
    def __init__(self, issue, url):
        self.issue = issue
        self.url = url
        super(GerritChangeNotExists, self).__init__()

    def __str__(self):
        return 'change %s at %s does not exist or you have no access to it' % (
            self.issue, self.url)


_CommentSummary = collections.namedtuple(
    '_CommentSummary',
    [
        'date',
        'message',
        'sender',
        'autogenerated',
        # TODO(tandrii): these two aren't known in Gerrit.
        'approval',
        'disapproval'
    ])

# TODO(b/265929888): Change `parent` to `pushed_commit_base`.
_NewUpload = collections.namedtuple('NewUpload', [
    'reviewers', 'ccs', 'commit_to_push', 'new_last_uploaded_commit', 'parent',
    'change_desc', 'prev_patchset'
])


class ChangeDescription(object):
    """Contains a parsed form of the change description."""
    R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
    CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$'
    BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$'
    FIXED_LINE = r'^[ \t]*Fixed[ \t]*:[ \t]*(.*?)[ \t]*$'
    CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$'
    STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*'
    BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]'
    COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):($|[^:])'
    BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+'

    def __init__(self, description, bug=None, fixed=None):
        self._description_lines = (description or '').strip().splitlines()
        if bug:
            regexp = re.compile(self.BUG_LINE)
            prefix = settings.GetBugPrefix()
            if not any(
                (regexp.match(line) for line in self._description_lines)):
                values = list(_get_bug_line_values(prefix, bug))
                self.append_footer('Bug: %s' % ', '.join(values))
        if fixed:
            regexp = re.compile(self.FIXED_LINE)
            prefix = settings.GetBugPrefix()
            if not any(
                (regexp.match(line) for line in self._description_lines)):
                values = list(_get_bug_line_values(prefix, fixed))
                self.append_footer('Fixed: %s' % ', '.join(values))

    @property  # www.logilab.org/ticket/89786
    def description(self):  # pylint: disable=method-hidden
        return '\n'.join(self._description_lines)

    def set_description(self, desc):
        if isinstance(desc, str):
            lines = desc.splitlines()
        else:
            lines = [line.rstrip() for line in desc]
        while lines and not lines[0]:
            lines.pop(0)
        while lines and not lines[-1]:
            lines.pop(-1)
        self._description_lines = lines

    def ensure_change_id(self, change_id):
        description = self.description
        footer_change_ids = git_footers.get_footer_change_id(description)
        # Make sure that the Change-Id in the description matches the given one.
        if footer_change_ids != [change_id]:
            if footer_change_ids:
                # Remove any existing Change-Id footers since they don't match
                # the expected change_id footer.
                description = git_footers.remove_footer(description,
                                                        'Change-Id')
                print(
                    'WARNING: Change-Id has been set to %s. Use `git cl issue 0` '
                    'if you want to set a new one.')
            # Add the expected Change-Id footer.
            description = git_footers.add_footer_change_id(
                description, change_id)
            self.set_description(description)

    def update_reviewers(self, reviewers):
        """Rewrites the R= line(s) as a single line each.

        Args:
            reviewers (list(str)) - list of additional emails to use for reviewers.
        """
        if not reviewers:
            return

        reviewers = set(reviewers)

        # Get the set of R= lines and remove them from the description.
        regexp = re.compile(self.R_LINE)
        matches = [regexp.match(line) for line in self._description_lines]
        new_desc = [
            l for i, l in enumerate(self._description_lines) if not matches[i]
        ]
        self.set_description(new_desc)

        # Construct new unified R= lines.

        # First, update reviewers with names from the R= lines (if any).
        for match in matches:
            if not match:
                continue
            reviewers.update(cleanup_list([match.group(2).strip()]))

        new_r_line = 'R=' + ', '.join(sorted(reviewers))

        # Put the new lines in the description where the old first R= line was.
        line_loc = next((i for i, match in enumerate(matches) if match), -1)
        if 0 <= line_loc < len(self._description_lines):
            self._description_lines.insert(line_loc, new_r_line)
        else:
            self.append_footer(new_r_line)

    def set_preserve_tryjobs(self):
        """Ensures description footer contains 'Cq-Do-Not-Cancel-Tryjobs: true'."""
        footers = git_footers.parse_footers(self.description)
        for v in footers.get('Cq-Do-Not-Cancel-Tryjobs', []):
            if v.lower() == 'true':
                return
        self.append_footer('Cq-Do-Not-Cancel-Tryjobs: true')

    def prompt(self):
        """Asks the user to update the description."""
        self.set_description([
            '# Enter a description of the change.',
            '# This will be displayed on the codereview site.',
            '# The first line will also be used as the subject of the review.',
            '#--------------------This line is 72 characters long'
            '--------------------',
        ] + self._description_lines)
        bug_regexp = re.compile(self.BUG_LINE)
        fixed_regexp = re.compile(self.FIXED_LINE)
        prefix = settings.GetBugPrefix()
        has_issue = lambda l: bug_regexp.match(l) or fixed_regexp.match(l)

        if not any((has_issue(line) for line in self._description_lines)):
            self.append_footer('Bug: %s' % prefix)

        print('Waiting for editor...')
        content = gclient_utils.RunEditor(self.description,
                                          True,
                                          git_editor=settings.GetGitEditor())
        if not content:
            DieWithError('Running editor failed')
        lines = content.splitlines()

        # Strip off comments and default inserted "Bug:" line.
        clean_lines = [
            line.rstrip() for line in lines
            if not (line.startswith('#') or line.rstrip() == "Bug:"
                    or line.rstrip() == "Bug: " + prefix)
        ]
        if not clean_lines:
            DieWithError('No CL description, aborting')
        self.set_description(clean_lines)

    def append_footer(self, line):
        """Adds a footer line to the description.

        Differentiates legacy "KEY=xxx" footers (used to be called tags) and
        Gerrit's footers in the form of "Footer-Key: footer any value" and ensures
        that Gerrit footers are always at the end.
        """
        parsed_footer_line = git_footers.parse_footer(line)
        if parsed_footer_line:
            # Line is a gerrit footer in the form: Footer-Key: any value.
            # Thus, must be appended observing Gerrit footer rules.
            self.set_description(
                git_footers.add_footer(self.description,
                                       key=parsed_footer_line[0],
                                       value=parsed_footer_line[1]))
            return

        if not self._description_lines:
            self._description_lines.append(line)
            return

        top_lines, gerrit_footers, _ = git_footers.split_footers(
            self.description)
        if gerrit_footers:
            # git_footers.split_footers ensures that there is an empty line
            # before actual (gerrit) footers, if any. We have to keep it that
            # way.
            assert top_lines and top_lines[-1] == ''
            top_lines, separator = top_lines[:-1], top_lines[-1:]
        else:
            separator = [
            ]  # No need for separator if there are no gerrit_footers.

        prev_line = top_lines[-1] if top_lines else ''
        if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line)
                or not presubmit_support.Change.TAG_LINE_RE.match(line)):
            top_lines.append('')
        top_lines.append(line)
        self._description_lines = top_lines + separator + gerrit_footers

    def get_reviewers(self, tbr_only=False):
        """Retrieves the list of reviewers."""
        matches = [
            re.match(self.R_LINE, line) for line in self._description_lines
        ]
        reviewers = [
            match.group(2).strip() for match in matches
            if match and (not tbr_only or match.group(1).upper() == 'TBR')
        ]
        return cleanup_list(reviewers)

    def get_cced(self):
        """Retrieves the list of reviewers."""
        matches = [
            re.match(self.CC_LINE, line) for line in self._description_lines
        ]
        cced = [match.group(2).strip() for match in matches if match]
        return cleanup_list(cced)

    def get_hash_tags(self):
        """Extracts and sanitizes a list of Gerrit hashtags."""
        subject = (self._description_lines or ('', ))[0]
        subject = re.sub(self.STRIP_HASH_TAG_PREFIX,
                         '',
                         subject,
                         flags=re.IGNORECASE)

        tags = []
        start = 0
        bracket_exp = re.compile(self.BRACKET_HASH_TAG)
        while True:
            m = bracket_exp.match(subject, start)
            if not m:
                break
            tags.append(self.sanitize_hash_tag(m.group(1)))
            start = m.end()

        if not tags:
            # Try "Tag: " prefix.
            m = re.match(self.COLON_SEPARATED_HASH_TAG, subject)
            if m:
                tags.append(self.sanitize_hash_tag(m.group(1)))
        return tags

    @classmethod
    def sanitize_hash_tag(cls, tag):
        """Returns a sanitized Gerrit hash tag.

        A sanitized hashtag can be used as a git push refspec parameter value.
        """
        return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower()


class Changelist(object):
    """Changelist works with one changelist in local branch.

    Notes:
        * Not safe for concurrent multi-{thread,process} use.
        * Caches values from current branch. Therefore, re-use after branch change
        with great care.
    """
    def __init__(self,
                 branchref=None,
                 issue=None,
                 codereview_host=None,
                 commit_date=None):
        """Create a new ChangeList instance.

        **kwargs will be passed directly to Gerrit implementation.
        """
        self.branchref = branchref
        if self.branchref:
            assert (branchref.startswith(('refs/heads/', 'refs/branch-heads/'))
                    or branchref == 'refs/meta/config')
            self.branch = scm.GIT.ShortBranchName(self.branchref)
        else:
            self.branch = None
        self.commit_date = commit_date
        self.upstream_branch = None
        self.lookedup_issue = False
        self.issue = issue or None
        self.description = None
        self.lookedup_patchset = False
        self.patchset = None
        self.cc = None
        self.more_cc = []
        self._remote = None
        self._cached_remote_url = (False, None)  # (is_cached, value)

        # Lazily cached values.
        self._gerrit_host = None  # e.g. chromium-review.googlesource.com
        self._gerrit_server = None  # e.g. https://chromium-review.googlesource.com
        self._owners_client = None
        # Map from change number (issue) to its detail cache.
        self._detail_cache = {}

        if codereview_host is not None:
            assert not codereview_host.startswith('https://'), codereview_host
            self._gerrit_host = codereview_host
            self._gerrit_server = 'https://%s' % codereview_host

    @property
    def owners_client(self):
        if self._owners_client is None:
            remote, remote_branch = self.GetRemoteBranch()
            branch = GetTargetRef(remote, remote_branch, None)
            self._owners_client = owners_client.GetCodeOwnersClient(
                host=self.GetGerritHost(),
                project=self.GetGerritProject(),
                branch=branch)
        return self._owners_client

    def GetCCList(self):
        """Returns the users cc'd on this CL.

        The return value is a string suitable for passing to git cl with the --cc
        flag.
        """
        if self.cc is None:
            base_cc = settings.GetDefaultCCList()
            more_cc = ','.join(self.more_cc)
            self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
        return self.cc

    def ExtendCC(self, more_cc):
        """Extends the list of users to cc on this CL based on the changed files."""
        self.more_cc.extend(more_cc)

    def GetCommitDate(self):
        """Returns the commit date as provided in the constructor"""
        return self.commit_date

    def GetBranch(self):
        """Returns the short branch name, e.g. 'main'."""
        if not self.branch:
            branchref = scm.GIT.GetBranchRef(settings.GetRoot())
            if not branchref:
                return None
            self.branchref = branchref
            self.branch = scm.GIT.ShortBranchName(self.branchref)
        return self.branch

    def GetBranchRef(self):
        """Returns the full branch name, e.g. 'refs/heads/main'."""
        self.GetBranch()  # Poke the lazy loader.
        return self.branchref

    def _GitGetBranchConfigValue(self, key, default=None):
        return scm.GIT.GetBranchConfig(settings.GetRoot(), self.GetBranch(),
                                       key, default)

    def _GitSetBranchConfigValue(self, key, value):
        action = 'set %s to %r' % (key, value)
        if not value:
            action = 'unset %s' % key
        assert self.GetBranch(), 'a branch is needed to ' + action
        return scm.GIT.SetBranchConfig(settings.GetRoot(), self.GetBranch(),
                                       key, value)

    @staticmethod
    def FetchUpstreamTuple(branch):
        """Returns a tuple containing remote and remote ref,
        e.g. 'origin', 'refs/heads/main'
        """
        remote, upstream_branch = scm.GIT.FetchUpstreamTuple(
            settings.GetRoot(), branch)
        if not remote or not upstream_branch:
            DieWithError(
                'Unable to determine default branch to diff against.\n'
                'Verify this branch is set up to track another \n'
                '(via the --track argument to "git checkout -b ..."). \n'
                'or pass complete "git diff"-style arguments if supported, like\n'
                '  git cl upload origin/main\n')

        return remote, upstream_branch

    def GetCommonAncestorWithUpstream(self):
        upstream_branch = self.GetUpstreamBranch()
        if not scm.GIT.IsValidRevision(settings.GetRoot(), upstream_branch):
            DieWithError(
                'The current branch (%s) has an upstream (%s) that does not exist '
                'anymore.\nPlease fix it and try again.' %
                (self.GetBranch(), upstream_branch))
        return git_common.get_or_create_merge_base(self.GetBranch(),
                                                   upstream_branch)

    def GetUpstreamBranch(self):
        if self.upstream_branch is None:
            remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
            if remote != '.':
                upstream_branch = upstream_branch.replace(
                    'refs/heads/', 'refs/remotes/%s/' % remote)
                upstream_branch = upstream_branch.replace(
                    'refs/branch-heads/', 'refs/remotes/branch-heads/')
            self.upstream_branch = upstream_branch
        return self.upstream_branch

    def GetRemoteBranch(self):
        if not self._remote:
            remote, branch = None, self.GetBranch()
            seen_branches = set()
            while branch not in seen_branches:
                seen_branches.add(branch)
                remote, branch = self.FetchUpstreamTuple(branch)
                branch = scm.GIT.ShortBranchName(branch)
                if remote != '.' or branch.startswith('refs/remotes'):
                    break
            else:
                remotes = RunGit(['remote'], error_ok=True).split()
                if len(remotes) == 1:
                    remote, = remotes
                elif 'origin' in remotes:
                    remote = 'origin'
                    logging.warning(
                        'Could not determine which remote this change is '
                        'associated with, so defaulting to "%s".' %
                        self._remote)
                else:
                    logging.warning(
                        'Could not determine which remote this change is '
                        'associated with.')
                branch = 'HEAD'
            if branch.startswith('refs/remotes'):
                self._remote = (remote, branch)
            elif branch.startswith('refs/branch-heads/'):
                self._remote = (remote, branch.replace('refs/',
                                                       'refs/remotes/'))
            else:
                self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
        return self._remote

    def GetRemoteUrl(self) -> Optional[str]:
        """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.

        Returns None if there is no remote.
        """
        is_cached, value = self._cached_remote_url
        if is_cached:
            return value

        remote, _ = self.GetRemoteBranch()
        url = scm.GIT.GetConfig(settings.GetRoot(), 'remote.%s.url' % remote,
                                '')

        # Check if the remote url can be parsed as an URL.
        host = urllib.parse.urlparse(url).netloc
        if host:
            self._cached_remote_url = (True, url)
            return url

        # If it cannot be parsed as an url, assume it is a local directory,
        # probably a git cache.
        logging.warning(
            '"%s" doesn\'t appear to point to a git host. '
            'Interpreting it as a local directory.', url)
        if not os.path.isdir(url):
            logging.error(
                'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
                'but it doesn\'t exist.', {
                    'remote': remote,
                    'branch': self.GetBranch(),
                    'url': url
                })
            return None

        cache_path = url
        url = scm.GIT.GetConfig(url, 'remote.%s.url' % remote, '')

        host = urllib.parse.urlparse(url).netloc
        if not host:
            logging.error(
                'Remote "%(remote)s" for branch "%(branch)s" points to '
                '"%(cache_path)s", but it is misconfigured.\n'
                '"%(cache_path)s" must be a git repo and must have a remote named '
                '"%(remote)s" pointing to the git host.', {
                    'remote': remote,
                    'cache_path': cache_path,
                    'branch': self.GetBranch()
                })
            return None

        self._cached_remote_url = (True, url)
        return url

    def _GetIssueFromTripletId(self):
        project = self.GetGerritProject()
        remote, branch = self.GetRemoteBranch()
        remote_ref = GetTargetRef(remote, branch,
                                  None).replace("refs/heads/", "")
        # _create_description_from_log calls into `git log
        # HEAD^..`. This will exclude everything reachable from `HEAD^`,
        # leaving just `HEAD`.
        change_ids = git_footers.get_footer_change_id(
            _create_description_from_log(["HEAD^"]))
        if len(change_ids) != 1:
            return None
        change_id = change_ids[0]
        triplet_id = urllib.parse.quote("%s~%s~%s" %
                                        (project, remote_ref, change_id),
                                        safe='')

        # GetGerritHost() would attempt to lookup the host from the
        # issue first, leading to infinite recursion. Instead, use the
        # fallback of getting the host from the remote URL.
        gerrit_host = self._GetGerritHostFromRemoteUrl()
        change = gerrit_util.GetChange(gerrit_host,
                                       triplet_id,
                                       accept_statuses=[200, 404])
        return change.get('_number')

    def GetIssue(self):
        """Returns the issue number as a int or None if not set."""
        if self.issue is None and not self.lookedup_issue:
            if self.GetBranch():
                self.issue = self._GitGetBranchConfigValue(ISSUE_CONFIG_KEY)

            if not settings.GetSquashGerritUploads() and self.issue is None:
                self.issue = self._GetIssueFromTripletId()

            if self.issue is not None:
                self.issue = int(self.issue)
            self.lookedup_issue = True
        return self.issue

    def GetIssueURL(self, short=False):
        """Get the URL for a particular issue."""
        issue = self.GetIssue()
        if not issue:
            return None
        server = self.GetCodereviewServer()
        if short:
            server = _KNOWN_GERRIT_TO_SHORT_URLS.get(server, server)
        return '%s/%s' % (server, issue)

    def FetchDescription(self, pretty=False):
        assert self.GetIssue(), 'issue is required to query Gerrit'

        if self.description is None:
            data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
            current_rev = data['current_revision']
            self.description = data['revisions'][current_rev]['commit'][
                'message']

        if not pretty:
            return self.description

        # Set width to 72 columns + 2 space indent.
        wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True)
        wrapper.initial_indent = wrapper.subsequent_indent = '  '
        lines = self.description.splitlines()
        return '\n'.join([wrapper.fill(line) for line in lines])

    def GetPatchset(self):
        """Returns the patchset number as a int or None if not set."""
        if self.patchset is None and not self.lookedup_patchset:
            if self.GetBranch():
                self.patchset = self._GitGetBranchConfigValue(
                    PATCHSET_CONFIG_KEY)
            if self.patchset is not None:
                self.patchset = int(self.patchset)
            self.lookedup_patchset = True
        return self.patchset

    def GetAuthor(self):
        return scm.GIT.GetConfig(settings.GetRoot(), 'user.email')

    def SetPatchset(self, patchset):
        """Set this branch's patchset. If patchset=0, clears the patchset."""
        assert self.GetBranch()
        if not patchset:
            self.patchset = None
        else:
            self.patchset = int(patchset)
        self._GitSetBranchConfigValue(PATCHSET_CONFIG_KEY, str(self.patchset))

    def SetIssue(self, issue=None):
        """Set this branch's issue. If issue isn't given, clears the issue."""
        assert self.GetBranch()
        if issue:
            issue = int(issue)
            self._GitSetBranchConfigValue(ISSUE_CONFIG_KEY, str(issue))
            self.issue = issue
            codereview_server = self.GetCodereviewServer()
            if codereview_server:
                self._GitSetBranchConfigValue(CODEREVIEW_SERVER_CONFIG_KEY,
                                              codereview_server)
        else:
            # Reset all of these just to be clean.
            reset_suffixes = [
                LAST_UPLOAD_HASH_CONFIG_KEY,
                ISSUE_CONFIG_KEY,
                PATCHSET_CONFIG_KEY,
                CODEREVIEW_SERVER_CONFIG_KEY,
                GERRIT_SQUASH_HASH_CONFIG_KEY,
            ]
            for prop in reset_suffixes:
                try:
                    self._GitSetBranchConfigValue(prop, None)
                except subprocess2.CalledProcessError:
                    pass
            msg = RunGit(['log', '-1', '--format=%B']).strip()
            if msg and git_footers.get_footer_change_id(msg):
                print(
                    'WARNING: The change patched into this branch has a Change-Id. '
                    'Removing it.')
                RunGit([
                    'commit', '--amend', '-m',
                    git_footers.remove_footer(msg, 'Change-Id')
                ])
            self.lookedup_issue = True
            self.issue = None
            self.patchset = None

    def GetAffectedFiles(self,
                         upstream: str,
                         end_commit: Optional[str] = None) -> Sequence[str]:
        """Returns the list of affected files for the given commit range."""
        try:
            return [
                f for _, f in scm.GIT.CaptureStatus(
                    settings.GetRoot(), upstream, end_commit=end_commit)
            ]
        except subprocess2.CalledProcessError:
            DieWithError(
                ('\nFailed to diff against upstream branch %s\n\n'
                 'This branch probably doesn\'t exist anymore. To reset the\n'
                 'tracking branch, please run\n'
                 '    git branch --set-upstream-to origin/main %s\n'
                 'or replace origin/main with the relevant branch') %
                (upstream, self.GetBranch()))

    def UpdateDescription(self, description, force=False):
        assert self.GetIssue(), 'issue is required to update description'

        if gerrit_util.HasPendingChangeEdit(self.GetGerritHost(),
                                            self._GerritChangeIdentifier()):
            if not force:
                confirm_or_exit(
                    'The description cannot be modified while the issue has a pending '
                    'unpublished edit. Either publish the edit in the Gerrit web UI '
                    'or delete it.\n\n',
                    action='delete the unpublished edit')

            gerrit_util.DeletePendingChangeEdit(self.GetGerritHost(),
                                                self._GerritChangeIdentifier())
        gerrit_util.SetCommitMessage(self.GetGerritHost(),
                                     self._GerritChangeIdentifier(),
                                     description,
                                     notify='NONE')

        self.description = description

    def _GetCommonPresubmitArgs(self, verbose, upstream):
        args = [
            '--root',
            settings.GetRoot(),
            '--upstream',
            upstream,
        ]

        args.extend(['--verbose'] * verbose)

        remote, remote_branch = self.GetRemoteBranch()
        target_ref = GetTargetRef(remote, remote_branch, None)
        if settings.GetIsGerrit():
            args.extend(['--gerrit_url', self.GetCodereviewServer()])
            args.extend(['--gerrit_project', self.GetGerritProject()])
            args.extend(['--gerrit_branch', target_ref])

        author = self.GetAuthor()
        issue = self.GetIssue()
        patchset = self.GetPatchset()
        if author:
            args.extend(['--author', author])
        if issue:
            args.extend(['--issue', str(issue)])
        if patchset:
            args.extend(['--patchset', str(patchset)])

        return args

    def RunHook(self,
                committing: bool,
                may_prompt: bool,
                verbose: bool,
                parallel: bool,
                upstream: str,
                description: str,
                all_files: bool,
                files: Optional[Sequence[str]] = None,
                resultdb: Optional[bool] = None,
                realm: Optional[str] = None,
                end_commit: Optional[str] = None) -> Mapping[str, Any]:
        """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
        args = self._GetCommonPresubmitArgs(verbose, upstream)
        args.append('--commit' if committing else '--upload')
        if end_commit:
            args.extend(['--end_commit', end_commit])
        if may_prompt:
            args.append('--may_prompt')
        if parallel:
            args.append('--parallel')
        if all_files:
            args.append('--all_files')
        if files:
            args.extend(files.split(';'))
            args.append('--source_controlled_only')
        if files or all_files:
            args.append('--no_diffs')

        if resultdb and not realm:
            # TODO (crbug.com/1113463): store realm somewhere and look it up so
            # it is not required to pass the realm flag
            print(
                'Note: ResultDB reporting will NOT be performed because --realm'
                ' was not specified. To enable ResultDB, please run the command'
                ' again with the --realm argument to specify the LUCI realm.')

        return self._RunPresubmit(args,
                                  description,
                                  resultdb=resultdb,
                                  realm=realm)

    def _RunPresubmit(self,
                      args: Sequence[str],
                      description: str,
                      resultdb: bool = False,
                      realm: Optional[str] = None) -> Mapping[str, Any]:
        args = list(args)

        with gclient_utils.temporary_file() as description_file:
            with gclient_utils.temporary_file() as json_output:
                gclient_utils.FileWrite(description_file, description)
                args.extend(['--json_output', json_output])
                args.extend(['--description_file', description_file])
                start = time_time()
                cmd = ['vpython3', PRESUBMIT_SUPPORT] + args
                if resultdb and realm:
                    cmd = ['rdb', 'stream', '-new', '-realm', realm, '--'] + cmd

                p = subprocess2.Popen(cmd)
                exit_code = p.wait()

                metrics.collector.add_repeated(
                    'sub_commands', {
                        'command': 'presubmit',
                        'execution_time': time_time() - start,
                        'exit_code': exit_code,
                    })

                if exit_code:
                    sys.exit(exit_code)

                json_results = gclient_utils.FileRead(json_output)
                return json.loads(json_results)

    def RunPostUploadHook(self, verbose, upstream, description):
        args = self._GetCommonPresubmitArgs(verbose, upstream)
        args.append('--post_upload')

        with gclient_utils.temporary_file() as description_file:
            gclient_utils.FileWrite(description_file, description)
            args.extend(['--description_file', description_file])
            subprocess2.Popen(['vpython3', PRESUBMIT_SUPPORT] + args).wait()

    def _GetDescriptionForUpload(self, options: optparse.Values,
                                 git_diff_args: Sequence[str],
                                 files: Sequence[str]) -> ChangeDescription:
        """Get description message for upload."""
        if options.commit_description:
            description = options.commit_description
            if description == '-':
                description = '\n'.join(l.rstrip() for l in sys.stdin)
            elif description == '+':
                description = _create_description_from_log(git_diff_args)
        elif self.GetIssue() and options.squash:
            description = self.FetchDescription()
        elif options.message:
            description = options.message
        else:
            description = _create_description_from_log(git_diff_args)
            if options.title and options.squash:
                description = options.title + '\n\n' + description

        bug = options.bug
        fixed = options.fixed
        if not self.GetIssue():
            # Extract bug number from branch name, but only if issue is being
            # created. It must start with bug or fix, followed by _ or - and
            # number. Optionally, it may contain _ or - after number with
            # arbitrary text. Examples: bug-123 bug_123 fix-123
            # fix-123-some-description
            branch = self.GetBranch()
            if branch is not None:
                match = re.match(
                    r'^(?P<type>bug|fix(?:e[sd])?)[_-]?(?P<bugnum>\d+)([-_]|$)',
                    branch)
                if not bug and not fixed and match:
                    if match.group('type') == 'bug':
                        bug = match.group('bugnum')
                    else:
                        fixed = match.group('bugnum')

        change_description = ChangeDescription(description, bug, fixed)

        # Fill gaps in OWNERS coverage to reviewers if requested.
        if options.add_owners_to:
            assert options.add_owners_to in ('R'), options.add_owners_to
            status = self.owners_client.GetFilesApprovalStatus(
                files, [], options.reviewers)
            missing_files = [
                f for f in files
                if status[f] == self._owners_client.INSUFFICIENT_REVIEWERS
            ]
            owners = self.owners_client.SuggestOwners(
                missing_files, exclude=[self.GetAuthor()])
            assert isinstance(options.reviewers, list), options.reviewers
            options.reviewers.extend(owners)

        # Set the reviewer list now so that presubmit checks can access it.
        if options.reviewers:
            change_description.update_reviewers(options.reviewers)

        return change_description

    def _GetTitleForUpload(self, options, multi_change_upload=False):
        # type: (optparse.Values, Optional[bool]) -> str

        # Getting titles for multipl commits is not supported so we return the
        # default.
        if not options.squash or multi_change_upload or options.title:
            return options.title

        # On first upload, patchset title is always this string, while
        # options.title gets converted to first line of message.
        if not self.GetIssue():
            return 'Initial upload'

        # When uploading subsequent patchsets, options.message is taken as the
        # title if options.title is not provided.
        if options.message:
            return options.message.strip()

        # Use the subject of the last commit as title by default.
        title = RunGit(['show', '-s', '--format=%s', 'HEAD', '--']).strip()
        if options.force or options.skip_title:
            return title
        user_title = gclient_utils.AskForData(
            'Title for patchset (\'y\' for default) [%s]: ' % title)

        # Use the default title if the user confirms the default with a 'y'.
        if user_title.lower() == 'y':
            return title
        return user_title or title

    def _GetRefSpecOptions(self,
                           options: optparse.Values,
                           change_desc: ChangeDescription,
                           multi_change_upload: bool = False,
                           dogfood_path: bool = False) -> List[str]:
        # Extra options that can be specified at push time. Doc:
        # https://gerrit-review.googlesource.com/Documentation/user-upload.html
        refspec_opts = []

        # By default, new changes are started in WIP mode, and subsequent
        # patchsets don't send email. At any time, passing --send-mail or
        # --send-email will mark the change ready and send email for that
        # particular patch.
        if options.send_mail:
            refspec_opts.append('ready')
            refspec_opts.append('notify=ALL')
        elif (not self.GetIssue() and options.squash and not dogfood_path):
            refspec_opts.append('wip')

        # TODO(tandrii): options.message should be posted as a comment if
        # --send-mail or --send-email is set on non-initial upload as Rietveld
        # used to do it.

        # Set options.title in case user was prompted in _GetTitleForUpload and
        # _CMDUploadChange needs to be called again.
        options.title = self._GetTitleForUpload(
            options, multi_change_upload=multi_change_upload)

        if options.title:
            # Punctuation and whitespace in |title| must be percent-encoded.
            refspec_opts.append(
                'm=' + gerrit_util.PercentEncodeForGitRef(options.title))

        if options.private:
            refspec_opts.append('private')

        if options.topic:
            # Documentation on Gerrit topics is here:
            # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic
            refspec_opts.append('topic=%s' % options.topic)

        if options.enable_auto_submit:
            refspec_opts.append('l=Auto-Submit+1')
        if options.enable_owners_override:
            refspec_opts.append('l=Owners-Override+1')
        if options.set_bot_commit:
            refspec_opts.append('l=Bot-Commit+1')
        if options.use_commit_queue:
            refspec_opts.append('l=Commit-Queue+2')
        elif options.cq_dry_run:
            refspec_opts.append('l=Commit-Queue+1')

        if change_desc.get_reviewers(tbr_only=True):
            score = gerrit_util.GetCodeReviewTbrScore(self.GetGerritHost(),
                                                      self.GetGerritProject())
            refspec_opts.append('l=Code-Review+%s' % score)

        # Gerrit sorts hashtags, so order is not important.
        hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags}
        # We check GetIssue because we only add hashtags from the
        # description on the first upload.
        # TODO(b/265929888): When we fully launch the new path:
        # 1) remove fetching hashtags from description alltogether
        # 2) Or use descrtiption hashtags for:
        #    `not (self.GetIssue() and multi_change_upload)`
        # 3) Or enabled change description tags for multi and single changes
        #    by adding them post `git push`.
        if not (self.GetIssue() and dogfood_path):
            hashtags.update(change_desc.get_hash_tags())
        refspec_opts.extend(['hashtag=%s' % t for t in hashtags])

        # Note: Reviewers, and ccs are handled individually for each
        # branch/change.
        return refspec_opts

    def PrepareSquashedCommit(self,
                              options: optparse.Values,
                              parent: str,
                              orig_parent: str,
                              end_commit: Optional[str] = None) -> _NewUpload:
        """Create a squashed commit to upload.

        Args:
            parent: The commit to use as the parent for the new squashed.
            orig_parent: The commit that is an actual ancestor of `end_commit`. It
                is part of the same original tree as end_commit, which does not
                contain squashed commits. This is used to create the change
                description for the new squashed commit with:
                `git log orig_parent..end_commit`.
            end_commit: The commit to use as the end of the new squashed commit.
        """

        if end_commit is None:
            end_commit = RunGit(['rev-parse', self.branchref]).strip()

        reviewers, ccs, change_desc = self._PrepareChange(
            options, orig_parent, end_commit)
        latest_tree = RunGit(['rev-parse', end_commit + ':']).strip()
        with gclient_utils.temporary_file() as desc_tempfile:
            gclient_utils.FileWrite(desc_tempfile, change_desc.description)
            commit_to_push = RunGit(
                ['commit-tree', latest_tree, '-p', parent, '-F',
                 desc_tempfile]).strip()

        # Gerrit may or may not update fast enough to return the correct
        # patchset number after we push. Get the pre-upload patchset and
        # increment later.
        prev_patchset = self.GetMostRecentPatchset(update=False) or 0
        return _NewUpload(reviewers, ccs, commit_to_push, end_commit, parent,
                          change_desc, prev_patchset)

    def PrepareCherryPickSquashedCommit(self, options: optparse.Values,
                                        parent: str) -> _NewUpload:
        """Create a commit cherry-picked on parent to push."""

        # The `parent` is what we will cherry-pick on top of.
        # The `cherry_pick_base` is the beginning range of what
        # we are cherry-picking.
        cherry_pick_base = self.GetCommonAncestorWithUpstream()
        reviewers, ccs, change_desc = self._PrepareChange(
            options, cherry_pick_base, self.branchref)

        new_upload_hash = RunGit(['rev-parse', self.branchref]).strip()
        latest_tree = RunGit(['rev-parse', self.branchref + ':']).strip()
        with gclient_utils.temporary_file() as desc_tempfile:
            gclient_utils.FileWrite(desc_tempfile, change_desc.description)
            commit_to_cp = RunGit([
                'commit-tree', latest_tree, '-p', cherry_pick_base, '-F',
                desc_tempfile
            ]).strip()

        RunGit(['checkout', '-q', parent])
        ret, _out = RunGitWithCode(['cherry-pick', commit_to_cp])
        if ret:
            RunGit(['cherry-pick', '--abort'])
            RunGit(['checkout', '-q', self.branch])
            DieWithError('Could not cleanly cherry-pick')

        commit_to_push = RunGit(['rev-parse', 'HEAD']).strip()
        RunGit(['checkout', '-q', self.branch])

        # Gerrit may or may not update fast enough to return the correct
        # patchset number after we push. Get the pre-upload patchset and
        # increment later.
        prev_patchset = self.GetMostRecentPatchset(update=False) or 0
        return _NewUpload(reviewers, ccs, commit_to_push, new_upload_hash,
                          cherry_pick_base, change_desc, prev_patchset)

    def _PrepareChange(
        self, options: optparse.Values, parent: str, end_commit: str
    ) -> Tuple[Sequence[str], Sequence[str], ChangeDescription]:
        """Prepares the change to be uploaded."""
        self.EnsureCanUploadPatchset(options.force)

        files = self.GetAffectedFiles(parent, end_commit=end_commit)
        change_desc = self._GetDescriptionForUpload(options,
                                                    [parent, end_commit], files)

        watchlist = watchlists.Watchlists(settings.GetRoot())
        self.ExtendCC(watchlist.GetWatchersForPaths(files))
        if not options.bypass_hooks:
            hook_results = self.RunHook(committing=False,
                                        may_prompt=not options.force,
                                        verbose=options.verbose,
                                        parallel=options.parallel,
                                        upstream=parent,
                                        description=change_desc.description,
                                        all_files=False,
                                        end_commit=end_commit)
            self.ExtendCC(hook_results['more_cc'])

        # Update the change description and ensure we have a Change Id.
        if self.GetIssue():
            if options.edit_description:
                change_desc.prompt()
            change_detail = self._GetChangeDetail(['CURRENT_REVISION'])
            change_id = change_detail['change_id']
            change_desc.ensure_change_id(change_id)

        else:  # No change issue. First time uploading
            if not options.force and not (options.message_file
                                          or options.commit_description):
                change_desc.prompt()

            # Check if user added a change_id in the descripiton.
            change_ids = git_footers.get_footer_change_id(
                change_desc.description)
            if len(change_ids) == 1:
                change_id = change_ids[0]
            else:
                change_id = GenerateGerritChangeId(change_desc.description)
                change_desc.ensure_change_id(change_id)

        if options.preserve_tryjobs:
            change_desc.set_preserve_tryjobs()

        SaveDescriptionBackup(change_desc)

        # Add ccs
        ccs = []
        # Add default, watchlist, presubmit ccs if this is the initial upload
        # and CL is not private and auto-ccing has not been disabled.
        if not options.private and not options.no_autocc and not self.GetIssue(
        ):
            ccs = self.GetCCList().split(',')

        # Add ccs from the --cc flag.
        if options.cc:
            ccs.extend(options.cc)

        ccs = [email.strip() for email in ccs if email.strip()]
        if change_desc.get_cced():
            ccs.extend(change_desc.get_cced())

        return change_desc.get_reviewers(), ccs, change_desc

    def PostUploadUpdates(self, options: optparse.Values,
                          new_upload: _NewUpload, change_number: str) -> None:
        """Makes necessary post upload changes to the local and remote cl."""
        if not self.GetIssue():
            self.SetIssue(change_number)

        self.SetPatchset(new_upload.prev_patchset + 1)

        self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
                                      new_upload.commit_to_push)
        self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY,
                                      new_upload.new_last_uploaded_commit)

        if settings.GetRunPostUploadHook():
            self.RunPostUploadHook(options.verbose, new_upload.parent,
                                   new_upload.change_desc.description)

        if new_upload.reviewers or new_upload.ccs:
            gerrit_util.AddReviewers(self.GetGerritHost(),
                                     self._GerritChangeIdentifier(),
                                     reviewers=new_upload.reviewers,
                                     ccs=new_upload.ccs,
                                     notify=bool(options.send_mail))

    def CMDUpload(self, options, git_diff_args, orig_args):
        """Uploads a change to codereview."""
        custom_cl_base = None
        if git_diff_args:
            custom_cl_base = base_branch = git_diff_args[0]
        else:
            if self.GetBranch() is None:
                DieWithError(_NO_BRANCH_ERROR)

            # Default to diffing against common ancestor of upstream branch
            base_branch = self.GetCommonAncestorWithUpstream()
            git_diff_args = [base_branch, 'HEAD']

        # Fast best-effort checks to abort before running potentially expensive
        # hooks if uploading is likely to fail anyway. Passing these checks does
        # not guarantee that uploading will not fail.
        self.EnsureAuthenticated(force=options.force)
        self.EnsureCanUploadPatchset(force=options.force)

        print(f'Processing {_GetCommitCountSummary(*git_diff_args)}...')

        # Apply watchlists on upload.
        watchlist = watchlists.Watchlists(settings.GetRoot())
        files = self.GetAffectedFiles(base_branch)
        if not options.bypass_watchlists:
            self.ExtendCC(watchlist.GetWatchersForPaths(files))

        change_desc = self._GetDescriptionForUpload(options, git_diff_args,
                                                    files)

        # For options.squash, RunHook is called once for each branch in
        # PrepareChange().
        if not options.bypass_hooks and not options.squash:
            hook_results = self.RunHook(committing=False,
                                        may_prompt=not options.force,
                                        verbose=options.verbose,
                                        parallel=options.parallel,
                                        upstream=base_branch,
                                        description=change_desc.description,
                                        all_files=False)
            self.ExtendCC(hook_results['more_cc'])

        print_stats(git_diff_args)
        ret = self.CMDUploadChange(options, git_diff_args, custom_cl_base,
                                   change_desc)
        if not ret:
            if self.GetBranch() is not None:
                self._GitSetBranchConfigValue(
                    LAST_UPLOAD_HASH_CONFIG_KEY,
                    scm.GIT.ResolveCommit(settings.GetRoot(), 'HEAD'))
            # Run post upload hooks, if specified.
            if settings.GetRunPostUploadHook():
                self.RunPostUploadHook(options.verbose, base_branch,
                                       change_desc.description)

            # Upload all dependencies if specified.
            if options.dependencies:
                print()
                print('--dependencies has been specified.')
                print('All dependent local branches will be re-uploaded.')
                print()
                # Remove the dependencies flag from args so that we do not end
                # up in a loop.
                orig_args.remove('--dependencies')
                ret = upload_branch_deps(self, orig_args, options.force)
        return ret

    def SetCQState(self, new_state):
        """Updates the CQ state for the latest patchset.

        Issue must have been already uploaded and known.
        """
        assert new_state in _CQState.ALL_STATES
        assert self.GetIssue()
        try:
            vote_map = {
                _CQState.NONE: 0,
                _CQState.DRY_RUN: 1,
                _CQState.COMMIT: 2,
            }
            labels = {'Commit-Queue': vote_map[new_state]}
            notify = False if new_state == _CQState.DRY_RUN else None
            gerrit_util.SetReview(self.GetGerritHost(),
                                  self._GerritChangeIdentifier(),
                                  labels=labels,
                                  notify=notify)
            return 0
        except KeyboardInterrupt:
            raise
        except:
            print(
                'WARNING: Failed to %s.\n'
                'Either:\n'
                ' * Your project has no CQ,\n'
                ' * You don\'t have permission to change the CQ state,\n'
                ' * There\'s a bug in this code (see stack trace below).\n'
                'Consider specifying which bots to trigger manually or asking your '
                'project owners for permissions or contacting Chrome Infra at:\n'
                'https://www.chromium.org/infra\n\n' %
                ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ'))
            # Still raise exception so that stack trace is printed.
            raise

    def GetGerritHost(self) -> Optional[str]:
        # Populate self._gerrit_host
        self.GetCodereviewServer()

        if self._gerrit_host and '.' not in self._gerrit_host:
            # Abbreviated domain like "chromium" instead of
            # chromium.googlesource.com.
            parsed = urllib.parse.urlparse(self.GetRemoteUrl())
            if parsed.scheme == 'sso':
                self._gerrit_host = '%s.googlesource.com' % self._gerrit_host
                self._gerrit_server = 'https://%s' % self._gerrit_host

        return self._gerrit_host

    def _GetGitHost(self):
        """Returns git host to be used when uploading change to Gerrit."""
        remote_url = self.GetRemoteUrl()
        if not remote_url:
            return None
        return urllib.parse.urlparse(remote_url).netloc

    def _GetGerritHostFromRemoteUrl(self) -> str:
        url = urllib.parse.urlparse(self.GetRemoteUrl())
        parts = url.netloc.split('.')

        # We assume repo to be hosted on Gerrit, and hence Gerrit server
        # has "-review" suffix for lowest level subdomain.
        parts[0] = parts[0] + '-review'

        if url.scheme == 'sso' and len(parts) == 1:
            # sso:// uses abbreivated hosts, eg. sso://chromium instead
            # of chromium.googlesource.com. Hence, for code review
            # server, they need to be expanded.
            parts[0] += '.googlesource.com'

        return '.'.join(parts)

    def GetCodereviewServer(self) -> str:
        if not self._gerrit_server:
            # If we're on a branch then get the server potentially associated
            # with that branch.
            if self.GetIssue() and self.GetBranch():
                self._gerrit_server = self._GitGetBranchConfigValue(
                    CODEREVIEW_SERVER_CONFIG_KEY)
                if self._gerrit_server:
                    self._gerrit_host = urllib.parse.urlparse(
                        self._gerrit_server).netloc
            if not self._gerrit_server:
                self._gerrit_host = self._GetGerritHostFromRemoteUrl()
                self._gerrit_server = 'https://%s' % self._gerrit_host
        return self._gerrit_server

    def GetGerritProject(self):
        """Returns Gerrit project name based on remote git URL."""
        remote_url = self.GetRemoteUrl()
        if remote_url is None:
            logging.warning('can\'t detect Gerrit project.')
            return None
        project = urllib.parse.urlparse(remote_url).path.strip('/')
        if project.endswith('.git'):
            project = project[:-len('.git')]
        # *.googlesource.com hosts ensure that Git/Gerrit projects don't start
        # with 'a/' prefix, because 'a/' prefix is used to force authentication
        # in gitiles/git-over-https protocol. E.g.,
        # https://chromium.googlesource.com/a/v8/v8 refers to the same
        # repo/project as https://chromium.googlesource.com/v8/v8
        if project.startswith('a/'):
            project = project[len('a/'):]
        return project

    def _GerritChangeIdentifier(self):
        """Handy method for gerrit_util.ChangeIdentifier for a given CL.

        Not to be confused by value of "Change-Id:" footer.
        If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC.
        """
        project = self.GetGerritProject()
        if project:
            return gerrit_util.ChangeIdentifier(project, self.GetIssue())
        # Fall back on still unique, but less efficient change number.
        return str(self.GetIssue())

    def EnsureAuthenticated(self, force: bool) -> None:
        """Best effort check that user is authenticated with Gerrit server."""
        if settings.GetGerritSkipEnsureAuthenticated():
            # For projects with unusual authentication schemes.
            # See http://crbug.com/603378.
            return

        remote_url = self.GetRemoteUrl()
        if remote_url is None:
            logging.warning('invalid remote')
            return

        parsed_url = urllib.parse.urlparse(remote_url)
        if parsed_url.scheme == 'sso':
            # Skip checking authentication for projects with sso:// scheme.
            return
        if parsed_url.scheme != 'https':
            logging.warning(
                'Ignoring branch %(branch)s with non-https remote '
                '%(remote)s', {
                    'branch': self.branch,
                    'remote': self.GetRemoteUrl()
                })
            return

        if newauth.Enabled():
            git_auth.AutoConfigure(os.getcwd(), Changelist())
            return

        # Lazy-loader to identify Gerrit and Git hosts.
        self.GetCodereviewServer()
        git_host = self._GetGitHost()
        assert self._gerrit_server and self._gerrit_host and git_host

        bypassable, msg = gerrit_util.ensure_authenticated(
            git_host, self._gerrit_host)
        if not msg:
            return  # OK
        if bypassable:
            if not force:
                confirm_or_exit(msg, action='continue')
        else:
            DieWithError(msg)

    def EnsureCanUploadPatchset(self, force):
        issue = self.GetIssue()
        if not issue:
            return

        status = self._GetChangeDetail()['status']
        if status == 'ABANDONED':
            DieWithError(
                'Change %s has been abandoned, new uploads are not allowed' %
                (self.GetIssueURL()))
        if status == 'MERGED':
            answer = gclient_utils.AskForData(
                'Change %s has been submitted, new uploads are not allowed. '
                'Would you like to start a new change (Y/n)?' %
                self.GetIssueURL()).lower()
            if answer not in ('y', ''):
                DieWithError('New uploads are not allowed.')
            self.SetIssue()
            return

        # Check to see if the currently authenticated account is the issue
        # owner.

        # first, grab the issue owner email
        owner = self.GetIssueOwner()

        # do a quick check to see if this matches the local git config's
        # configured email.
        git_config_email = scm.GIT.GetConfig(settings.GetRoot(), 'user.email')
        if git_config_email == owner:
            # Good enough - Gerrit will reject this if the user is doing funny things
            # with user.email.
            return

        # However, the user may have linked accounts in Gerrit, so pull up the
        # list of all known emails for the currently authenticated account.
        emails = gerrit_util.GetAccountEmails(self.GetGerritHost(), 'self')
        if not emails:
            print('WARNING: Gerrit does not have a record for your account.')
            print('Please browse to https://{self.GetGerritHost()} and log in.')
            return

        # If the issue owner is one of the emails for the currently
        # authenticated account, Gerrit will accept the upload.
        if any(owner == e['email'] for e in emails):
            return

        if not force:
            print(
                f'WARNING: Change {issue} is owned by {owner}, but Gerrit knows you as:'
            )
            for email in emails:
                tag = ' (preferred)' if email.get('preferred') else ''
                print(f'  * {email["email"]}{tag}')
            print('Uploading may fail due to lack of permissions.')
            confirm_or_exit(action='upload')

    def GetStatus(self):
        """Applies a rough heuristic to give a simple summary of an issue's review
        or CQ status, assuming adherence to a common workflow.

        Returns None if no issue for this branch, or one of the following keywords:
            * 'error'   - error from review tool (including deleted issues)
            * 'unsent'  - no reviewers added
            * 'waiting' - waiting for review
            * 'reply'   - waiting for uploader to reply to review
            * 'lgtm'    - Code-Review label has been set
            * 'dry-run' - dry-running in the CQ
            * 'commit'  - in the CQ
            * 'closed'  - successfully submitted or abandoned
        """
        if not self.GetIssue():
            return None

        try:
            data = self._GetChangeDetail(
                ['DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE'])
        except GerritChangeNotExists:
            return 'error'

        if data['status'] in ('ABANDONED', 'MERGED'):
            return 'closed'

        cq_label = data['labels'].get('Commit-Queue', {})
        max_cq_vote = 0
        for vote in cq_label.get('all', []):
            max_cq_vote = max(max_cq_vote, vote.get('value', 0))
        if max_cq_vote == 2:
            return 'commit'
        if max_cq_vote == 1:
            return 'dry-run'

        if data['labels'].get('Code-Review', {}).get('approved'):
            return 'lgtm'

        if not data.get('reviewers', {}).get('REVIEWER', []):
            return 'unsent'

        owner = data['owner'].get('_account_id')
        messages = sorted(data.get('messages', []), key=lambda m: m.get('date'))
        while messages:
            m = messages.pop()
            if (m.get('tag', '').startswith('autogenerated:cq')
                    or m.get('tag', '').startswith('autogenerated:cv')):
                # Ignore replies from LUCI CV/CQ.
                continue
            if m.get('author', {}).get('_account_id') == owner:
                # Most recent message was by owner.
                return 'waiting'

            # Some reply from non-owner.
            return 'reply'

        # Somehow there are no messages even though there are reviewers.
        return 'unsent'

    def GetMostRecentPatchset(self, update=True):
        if not self.GetIssue():
            return None

        data = self._GetChangeDetail(['CURRENT_REVISION'])
        patchset = data['revisions'][data['current_revision']]['_number']
        if update:
            self.SetPatchset(patchset)
        return patchset

    def _IsPatchsetRangeSignificant(self, lower, upper):
        """Returns True if the inclusive range of patchsets contains any reworks or
        rebases."""
        if not self.GetIssue():
            return False

        data = self._GetChangeDetail(['ALL_REVISIONS'])
        ps_kind = {}
        for rev_info in data.get('revisions', {}).values():
            ps_kind[rev_info['_number']] = rev_info.get('kind', '')

        for ps in range(lower, upper + 1):
            assert ps in ps_kind, 'expected patchset %d in change detail' % ps
            if ps_kind[ps] not in ('NO_CHANGE', 'NO_CODE_CHANGE'):
                return True
        return False

    def GetMostRecentDryRunPatchset(self):
        """Get patchsets equivalent to the most recent patchset and return
        the patchset with the latest dry run. If none have been dry run, return
        the latest patchset."""
        if not self.GetIssue():
            return None

        data = self._GetChangeDetail(['ALL_REVISIONS'])
        patchset = data['revisions'][data['current_revision']]['_number']
        dry_run = {
            int(m['_revision_number'])
            for m in data.get('messages', [])
            if m.get('tag', '').endswith('dry-run')
        }

        for revision_info in sorted(data.get('revisions', {}).values(),
                                    key=lambda c: c['_number'],
                                    reverse=True):
            if revision_info['_number'] in dry_run:
                patchset = revision_info['_number']
                break
            if revision_info.get('kind', '') not in \
                ('NO_CHANGE', 'NO_CODE_CHANGE', 'TRIVIAL_REBASE'):
                break
        self.SetPatchset(patchset)
        return patchset

    def AddComment(self, message, publish=None):
        gerrit_util.SetReview(self.GetGerritHost(),
                              self._GerritChangeIdentifier(),
                              msg=message,
                              ready=publish)

    def GetCommentsSummary(self, readable=True):
        # DETAILED_ACCOUNTS is to get emails in accounts.
        # CURRENT_REVISION is included to get the latest patchset so that
        # only the robot comments from the latest patchset can be shown.
        messages = self._GetChangeDetail(
            options=['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION']).get(
                'messages', [])
        file_comments = gerrit_util.GetChangeComments(
            self.GetGerritHost(), self._GerritChangeIdentifier())
        robot_file_comments = gerrit_util.GetChangeRobotComments(
            self.GetGerritHost(), self._GerritChangeIdentifier())

        # Add the robot comments onto the list of comments, but only
        # keep those that are from the latest patchset.
        latest_patch_set = self.GetMostRecentPatchset()
        for path, robot_comments in robot_file_comments.items():
            line_comments = file_comments.setdefault(path, [])
            line_comments.extend([
                c for c in robot_comments if c['patch_set'] == latest_patch_set
            ])

        # Build dictionary of file comments for easy access and sorting later.
        # {author+date: {path: {patchset: {line: url+message}}}}
        comments = collections.defaultdict(lambda: collections.defaultdict(
            lambda: collections.defaultdict(dict)))

        server = self.GetCodereviewServer()
        if server in _KNOWN_GERRIT_TO_SHORT_URLS:
            # /c/ is automatically added by short URL server.
            url_prefix = '%s/%s' % (_KNOWN_GERRIT_TO_SHORT_URLS[server],
                                    self.GetIssue())
        else:
            url_prefix = '%s/c/%s' % (server, self.GetIssue())

        for path, line_comments in file_comments.items():
            for comment in line_comments:
                tag = comment.get('tag', '')
                if tag.startswith(
                        'autogenerated') and 'robot_id' not in comment:
                    continue
                key = (comment['author']['email'], comment['updated'])
                if comment.get('side', 'REVISION') == 'PARENT':
                    patchset = 'Base'
                else:
                    patchset = 'PS%d' % comment['patch_set']
                line = comment.get('line', 0)
                url = ('%s/%s/%s#%s%s' %
                       (url_prefix, comment['patch_set'],
                        path, 'b' if comment.get('side') == 'PARENT' else '',
                        str(line) if line else ''))
                comments[key][path][patchset][line] = (url, comment['message'])

        summaries = []
        for msg in messages:
            summary = self._BuildCommentSummary(msg, comments, readable)
            if summary:
                summaries.append(summary)
        return summaries

    @staticmethod
    def _BuildCommentSummary(msg, comments, readable):
        if 'email' not in msg['author']:
            # Some bot accounts may not have an email associated.
            return None

        key = (msg['author']['email'], msg['date'])
        # Don't bother showing autogenerated messages that don't have associated
        # file or line comments. this will filter out most autogenerated
        # messages, but will keep robot comments like those from Tricium.
        is_autogenerated = msg.get('tag', '').startswith('autogenerated')
        if is_autogenerated and not comments.get(key):
            return None
        message = msg['message']
        # Gerrit spits out nanoseconds.
        assert len(msg['date'].split('.')[-1]) == 9
        date = datetime.datetime.strptime(msg['date'][:-3],
                                          '%Y-%m-%d %H:%M:%S.%f')
        if key in comments:
            message += '\n'
        for path, patchsets in sorted(comments.get(key, {}).items()):
            if readable:
                message += '\n%s' % path
            for patchset, lines in sorted(patchsets.items()):
                for line, (url, content) in sorted(lines.items()):
                    if line:
                        line_str = 'Line %d' % line
                        path_str = '%s:%d:' % (path, line)
                    else:
                        line_str = 'File comment'
                        path_str = '%s:0:' % path
                    if readable:
                        message += '\n  %s, %s: %s' % (patchset, line_str, url)
                        message += '\n  %s\n' % content
                    else:
                        message += '\n%s ' % path_str
                        message += '\n%s\n' % content

        return _CommentSummary(
            date=date,
            message=message,
            sender=msg['author']['email'],
            autogenerated=is_autogenerated,
            # These could be inferred from the text messages and correlated with
            # Code-Review label maximum, however this is not reliable.
            # Leaving as is until the need arises.
            approval=False,
            disapproval=False,
        )

    def CloseIssue(self):
        gerrit_util.AbandonChange(self.GetGerritHost(),
                                  self._GerritChangeIdentifier(),
                                  msg='')

    def SubmitIssue(self):
        gerrit_util.SubmitChange(self.GetGerritHost(),
                                 self._GerritChangeIdentifier())

    def _GetChangeDetail(self, options=None):
        """Returns details of associated Gerrit change and caching results."""
        options = options or []
        assert self.GetIssue(), 'issue is required to query Gerrit'

        # Optimization to avoid multiple RPCs:
        if 'CURRENT_REVISION' in options or 'ALL_REVISIONS' in options:
            options.append('CURRENT_COMMIT')

        # Normalize issue and options for consistent keys in cache.
        cache_key = str(self.GetIssue())
        options_set = frozenset(o.upper() for o in options)

        for cached_options_set, data in self._detail_cache.get(cache_key, []):
            # Assumption: data fetched before with extra options is suitable
            # for return for a smaller set of options.
            # For example, if we cached data for
            #     options=[CURRENT_REVISION, DETAILED_FOOTERS]
            #   and request is for options=[CURRENT_REVISION],
            # THEN we can return prior cached data.
            if options_set.issubset(cached_options_set):
                return data

        try:
            data = gerrit_util.GetChangeDetail(self.GetGerritHost(),
                                               self._GerritChangeIdentifier(),
                                               options_set)
        except gerrit_util.GerritError as e:
            if e.http_status == 404:
                raise GerritChangeNotExists(self.GetIssue(),
                                            self.GetCodereviewServer())
            raise

        self._detail_cache.setdefault(cache_key, []).append((options_set, data))
        return data

    def _GetChangeCommit(self, revision: str = 'current') -> dict:
        assert self.GetIssue(), 'issue must be set to query Gerrit'
        try:
            data: dict = gerrit_util.GetChangeCommit(
                self.GetGerritHost(), self._GerritChangeIdentifier(), revision)
        except gerrit_util.GerritError as e:
            if e.http_status == 404:
                raise GerritChangeNotExists(self.GetIssue(),
                                            self.GetCodereviewServer())
            raise
        return data

    def _IsCqConfigured(self):
        detail = self._GetChangeDetail(['LABELS'])
        return u'Commit-Queue' in detail.get('labels', {})

    def CMDLand(self, force, bypass_hooks, verbose, parallel, resultdb, realm):
        if git_common.is_dirty_git_tree('land'):
            return 1

        detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS'])
        if not force and self._IsCqConfigured():
            confirm_or_exit(
                '\nIt seems this repository has a CQ, '
                'which can test and land changes for you. '
                'Are you sure you wish to bypass it?\n',
                action='bypass CQ')
        differs = True
        last_upload = self._GitGetBranchConfigValue(
            GERRIT_SQUASH_HASH_CONFIG_KEY)
        # Note: git diff outputs nothing if there is no diff.
        if not last_upload or RunGit(['diff', last_upload]).strip():
            print(
                'WARNING: Some changes from local branch haven\'t been uploaded.'
            )
        else:
            if detail['current_revision'] == last_upload:
                differs = False
            else:
                print(
                    'WARNING: Local branch contents differ from latest uploaded '
                    'patchset.')
        if differs:
            if not force:
                confirm_or_exit(
                    'Do you want to submit latest Gerrit patchset and bypass hooks?\n',
                    action='submit')
            print(
                'WARNING: Bypassing hooks and submitting latest uploaded patchset.'
            )
        elif not bypass_hooks:
            upstream = self.GetCommonAncestorWithUpstream()
            if self.GetIssue():
                description = self.FetchDescription()
            else:
                description = _create_description_from_log([upstream])
            self.RunHook(committing=True,
                         may_prompt=not force,
                         verbose=verbose,
                         parallel=parallel,
                         upstream=upstream,
                         description=description,
                         all_files=False,
                         resultdb=resultdb,
                         realm=realm)

        self.SubmitIssue()
        print('Issue %s has been submitted.' % self.GetIssueURL())
        links = self._GetChangeCommit().get('web_links', [])
        for link in links:
            if link.get('name') in ['gitiles', 'browse'] and link.get('url'):
                print('Landed as: %s' % link.get('url'))
                break
        return 0

    def CMDPatchWithParsedIssue(self, parsed_issue_arg, nocommit, force):
        assert parsed_issue_arg.valid

        self.issue = parsed_issue_arg.issue

        if parsed_issue_arg.hostname:
            self._gerrit_host = parsed_issue_arg.hostname
            self._gerrit_server = 'https://%s' % self._gerrit_host

        try:
            detail = self._GetChangeDetail(['ALL_REVISIONS'])
        except GerritChangeNotExists as e:
            DieWithError(str(e))

        if not parsed_issue_arg.patchset:
            # Use current revision by default.
            revision_info = detail['revisions'][detail['current_revision']]
            patchset = int(revision_info['_number'])
        else:
            patchset = parsed_issue_arg.patchset
            for revision_info in detail['revisions'].values():
                if int(revision_info['_number']) == parsed_issue_arg.patchset:
                    break
            else:
                DieWithError('Couldn\'t find patchset %i in change %i' %
                             (parsed_issue_arg.patchset, self.GetIssue()))

        remote_url = self.GetRemoteUrl()
        if remote_url.endswith('.git'):
            remote_url = remote_url[:-len('.git')]
        remote_url = remote_url.rstrip('/')

        fetch_info = revision_info['fetch']['http']
        fetch_info['url'] = fetch_info['url'].rstrip('/')

        if remote_url != fetch_info['url']:
            DieWithError(
                'Trying to patch a change from %s but this repo appears '
                'to be %s.' % (fetch_info['url'], remote_url))

        RunGit(['fetch', fetch_info['url'], fetch_info['ref']])

        # Set issue immediately in case the cherry-pick fails, which happens
        # when resolving conflicts.
        if self.GetBranch():
            self.SetIssue(parsed_issue_arg.issue)

        if force:
            RunGit(['reset', '--hard', 'FETCH_HEAD'])
            print('Checked out commit for change %i patchset %i locally' %
                  (parsed_issue_arg.issue, patchset))
        elif nocommit:
            RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD'])
            print('Patch applied to index.')
        else:
            RunGit(['cherry-pick', 'FETCH_HEAD'])
            print('Committed patch for change %i patchset %i locally.' %
                  (parsed_issue_arg.issue, patchset))
            print(
                'Note: this created a local commit on top of parent commit '
                'that is different from the one in Gerrit. If the patched CL '
                'is not yours and you cannot upload new patches to it, you '
                'will not be able to upload stacked changes created on top of '
                'this branch.\n'
                'If you want to do that, use "git cl patch --force" instead.')

        if self.GetBranch():
            self.SetPatchset(patchset)
            fetched_hash = scm.GIT.ResolveCommit(settings.GetRoot(),
                                                 'FETCH_HEAD')
            self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY,
                                          fetched_hash)
            self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
                                          fetched_hash)
        else:
            print(
                'WARNING: You are in detached HEAD state.\n'
                'The patch has been applied to your checkout, but you will not be '
                'able to upload a new patch set to the gerrit issue.\n'
                'Try using the \'-b\' option if you would like to work on a '
                'branch and/or upload a new patch set.')

        return 0

    @staticmethod
    def _GerritCommitMsgHookCheck(offer_removal):
        # type: (bool) -> None
        """Checks for the gerrit's commit-msg hook and removes it if necessary."""
        hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
        if not os.path.exists(hook):
            return
        # Crude attempt to distinguish Gerrit Codereview hook from a potentially
        # custom developer-made one.
        data = gclient_utils.FileRead(hook)
        if not ('From Gerrit Code Review' in data and 'add_ChangeId()' in data):
            return
        print('WARNING: You have Gerrit commit-msg hook installed.\n'
              'It is not necessary for uploading with git cl in squash mode, '
              'and may interfere with it in subtle ways.\n'
              'We recommend you remove the commit-msg hook.')
        if offer_removal:
            if ask_for_explicit_yes('Do you want to remove it now?'):
                gclient_utils.rm_file_or_tree(hook)
                print('Gerrit commit-msg hook removed.')
            else:
                print('OK, will keep Gerrit commit-msg hook in place.')

    def _CleanUpOldTraces(self):
        """Keep only the last |MAX_TRACES| traces."""
        try:
            traces = sorted([
                os.path.join(TRACES_DIR, f) for f in os.listdir(TRACES_DIR)
                if (os.path.isfile(os.path.join(TRACES_DIR, f))
                    and not f.startswith('tmp'))
            ])
            traces_to_delete = traces[:-MAX_TRACES]
            for trace in traces_to_delete:
                os.remove(trace)
        except OSError:
            print('WARNING: Failed to remove old git traces from\n'
                  '  %s'
                  'Consider removing them manually.' % TRACES_DIR)

    def _WriteGitPushTraces(self, trace_name, traces_dir, git_push_metadata):
        """Zip and write the git push traces stored in traces_dir."""
        gclient_utils.safe_makedirs(TRACES_DIR)
        traces_zip = trace_name + '-traces'
        traces_readme = trace_name + '-README'
        # Create a temporary dir to store git config and gitcookies in. It will
        # be compressed and stored next to the traces.
        git_info_dir = tempfile.mkdtemp()
        git_info_zip = trace_name + '-git-info'

        git_push_metadata['now'] = datetime_now().strftime(
            '%Y-%m-%dT%H:%M:%S.%f')

        git_push_metadata['trace_name'] = trace_name
        gclient_utils.FileWrite(traces_readme,
                                TRACES_README_FORMAT % git_push_metadata)

        # Keep only the first 6 characters of the git hashes on the packet
        # trace. This greatly decreases size after compression.
        packet_traces = os.path.join(traces_dir, 'trace-packet')
        if os.path.isfile(packet_traces):
            contents = gclient_utils.FileRead(packet_traces)
            gclient_utils.FileWrite(packet_traces,
                                    GIT_HASH_RE.sub(r'\1', contents))
        shutil.make_archive(traces_zip, 'zip', traces_dir)

        # Collect and compress the git config and gitcookies.
        git_config = '\n'.join(
            f'{k}={v}' for k, v in scm.GIT.YieldConfigRegexp(settings.GetRoot()))
        gclient_utils.FileWrite(os.path.join(git_info_dir, 'git-config'),
                                git_config)

        auth_name, debug_state = gerrit_util.debug_auth()
        # Writes a file like CookiesAuthenticator.debug_summary_state
        gclient_utils.FileWrite(
            os.path.join(git_info_dir, f'{auth_name}.debug_summary_state'),
            debug_state)
        shutil.make_archive(git_info_zip, 'zip', git_info_dir)

        gclient_utils.rmtree(git_info_dir)

    def _RunGitPushWithTraces(self,
                              refspec,
                              refspec_opts,
                              git_push_metadata,
                              git_push_options=None):
        """Run git push and collect the traces resulting from the execution."""
        # Create a temporary directory to store traces in. Traces will be
        # compressed and stored in a 'traces' dir inside depot_tools.
        traces_dir = tempfile.mkdtemp()
        trace_name = os.path.join(TRACES_DIR,
                                  datetime_now().strftime('%Y%m%dT%H%M%S.%f'))

        env = os.environ.copy()
        env['GIT_REDACT_COOKIES'] = 'o,SSO,GSSO_Uberproxy'
        env['GIT_TR2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
        env['GIT_TRACE2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
        env['GIT_TRACE_CURL'] = os.path.join(traces_dir, 'trace-curl')
        env['GIT_TRACE_CURL_NO_DATA'] = '1'
        env['GIT_TRACE_PACKET'] = os.path.join(traces_dir, 'trace-packet')

        push_returncode = 0
        before_push = time_time()
        try:
            # Combine user-provided push options with the potential
            # superproject push option.
            all_push_options = []
            if git_push_options:
                all_push_options.extend(git_push_options)
            if superproject_option := _prepare_superproject_push_option():
                all_push_options.append(superproject_option)

            remote_url = self.GetRemoteUrl()
            push_cmd = ['git', 'push', remote_url, refspec]
            if all_push_options:
                for opt in all_push_options:
                    push_cmd.extend(['-o', opt])

            push_stdout = gclient_utils.CheckCallAndFilter(
                push_cmd,
                env=env,
                print_stdout=True,
                # Flush after every line: useful for seeing progress when
                # running as recipe.
                filter_fn=lambda _: sys.stdout.flush())
            push_stdout = push_stdout.decode('utf-8', 'replace')
        except subprocess2.CalledProcessError as e:
            push_returncode = e.returncode
            if 'blocked keyword' in str(e.stdout) or 'banned word' in str(
                    e.stdout):
                raise GitPushError(
                    'Failed to create a change, very likely due to blocked keyword. '
                    'Please examine output above for the reason of the failure.\n'
                    'If this is a false positive, you can try to bypass blocked '
                    'keyword by using push option '
                    '-o banned-words~skip, e.g.:\n'
                    'git cl upload -o banned-words~skip\n\n'
                    'If git-cl is not working correctly, file a bug under the '
                    'Infra>SDK component.')
            if 'git push -o nokeycheck' in str(e.stdout):
                raise GitPushError(
                    'Failed to create a change, very likely due to a private key being '
                    'detected. Please examine output above for the reason of the '
                    'failure.\n'
                    'If this is a false positive, you can try to bypass private key '
                    'detection by using push option '
                    '-o nokeycheck, e.g.:\n'
                    'git cl upload -o nokeycheck\n\n'
                    'If git-cl is not working correctly, file a bug under the '
                    'Infra>SDK component.')

            raise GitPushError(
                'Failed to create a change. Please examine output above for the '
                'reason of the failure.\n'
                'For emergencies, Googlers can escalate to '
                'go/gob-support or go/notify#gob\n'
                'Hint: run command below to diagnose common Git/Gerrit '
                'credential problems:\n'
                '  git cl creds-check\n'
                '\n'
                'If git-cl is not working correctly, file a bug under the Infra>SDK '
                'component including the files below.\n'
                'Review the files before upload, since they might contain sensitive '
                'information.\n'
                'Set the Restrict-View-Google label so that they are not publicly '
                'accessible.\n' + TRACES_MESSAGE % {'trace_name': trace_name})
        finally:
            execution_time = time_time() - before_push
            metrics.collector.add_repeated(
                'sub_commands', {
                    'command':
                    'git push',
                    'execution_time':
                    execution_time,
                    'exit_code':
                    push_returncode,
                    'arguments':
                    metrics_utils.extract_known_subcommand_args(refspec_opts),
                })

            git_push_metadata['execution_time'] = execution_time
            git_push_metadata['exit_code'] = push_returncode
            self._WriteGitPushTraces(trace_name, traces_dir, git_push_metadata)

            self._CleanUpOldTraces()
            gclient_utils.rmtree(traces_dir)

        return push_stdout

    def CMDUploadChange(self, options, git_diff_args, custom_cl_base,
                        change_desc):
        """Upload the current branch to Gerrit, retry if new remote HEAD is
        found. options and change_desc may be mutated."""
        remote, remote_branch = self.GetRemoteBranch()
        branch = GetTargetRef(remote, remote_branch, options.target_branch)

        try:
            return self._CMDUploadChange(options, git_diff_args, custom_cl_base,
                                         change_desc, branch)
        except GitPushError as e:
            # Repository might be in the middle of transition to main branch as
            # default, and uploads to old default might be blocked.
            if remote_branch not in [DEFAULT_OLD_BRANCH, DEFAULT_NEW_BRANCH]:
                DieWithError(str(e), change_desc)

            project_head = gerrit_util.GetProjectHead(self._gerrit_host,
                                                      self.GetGerritProject())
            if project_head == branch:
                DieWithError(str(e), change_desc)
            branch = project_head

        print("WARNING: Fetching remote state and retrying upload to default "
              "branch...")
        RunGit(['fetch', '--prune', remote])
        options.edit_description = False
        options.force = True
        try:
            self._CMDUploadChange(options, git_diff_args, custom_cl_base,
                                  change_desc, branch)
        except GitPushError as e:
            DieWithError(str(e), change_desc)

    def _CMDUploadChange(self, options, git_diff_args, custom_cl_base,
                         change_desc, branch):
        """Upload the current branch to Gerrit."""
        if options.squash:
            Changelist._GerritCommitMsgHookCheck(
                offer_removal=not options.force)
            external_parent = None
            if self.GetIssue():
                # User requested to change description
                if options.edit_description:
                    change_desc.prompt()
                change_detail = self._GetChangeDetail(['CURRENT_REVISION'])
                change_id = change_detail['change_id']
                change_desc.ensure_change_id(change_id)

                # Check if changes outside of this workspace have been uploaded.
                current_rev = change_detail['current_revision']
                last_uploaded_rev = self._GitGetBranchConfigValue(
                    GERRIT_SQUASH_HASH_CONFIG_KEY)
                if last_uploaded_rev and current_rev != last_uploaded_rev:
                    external_parent = self._UpdateWithExternalChanges()
            else:  # if not self.GetIssue()
                if not options.force and not (options.message_file
                                              or options.commit_description):
                    change_desc.prompt()
                change_ids = git_footers.get_footer_change_id(
                    change_desc.description)
                if len(change_ids) == 1:
                    change_id = change_ids[0]
                else:
                    change_id = GenerateGerritChangeId(change_desc.description)
                    change_desc.ensure_change_id(change_id)

            if options.preserve_tryjobs:
                change_desc.set_preserve_tryjobs()

            remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
            parent = external_parent or self._ComputeParent(
                remote, upstream_branch, custom_cl_base, options.force,
                change_desc)
            tree = RunGit(['rev-parse', 'HEAD:']).strip()
            with gclient_utils.temporary_file() as desc_tempfile:
                gclient_utils.FileWrite(desc_tempfile, change_desc.description)
                ref_to_push = RunGit(
                    ['commit-tree', tree, '-p', parent, '-F',
                     desc_tempfile]).strip()
        else:  # if not options.squash
            if options.no_add_changeid:
                pass
            else:  # adding Change-Ids is okay.
                if not git_footers.get_footer_change_id(
                        change_desc.description):
                    DownloadGerritHook(False)
                    change_desc.set_description(
                        self._AddChangeIdToCommitMessage(
                            change_desc.description, git_diff_args))
            ref_to_push = 'HEAD'
            # For no-squash mode, we assume the remote called "origin" is the
            # one we want. It is not worthwhile to support different workflows
            # for no-squash mode.
            parent = 'origin/%s' % branch
            # attempt to extract the changeid from the current description
            # fail informatively if not possible.
            change_id_candidates = git_footers.get_footer_change_id(
                change_desc.description)
            if not change_id_candidates:
                DieWithError("Unable to extract change-id from message.")
            change_id = change_id_candidates[0]

        SaveDescriptionBackup(change_desc)
        commits = RunGitSilent(['rev-list',
                                '%s..%s' % (parent, ref_to_push)]).splitlines()
        if len(commits) > 1:
            print(
                'WARNING: This will upload %d commits. Run the following command '
                'to see which commits will be uploaded: ' % len(commits))
            print('git log %s..%s' % (parent, ref_to_push))
            print('You can also use `git squash-branch` to squash these into a '
                  'single commit.')
            confirm_or_exit(action='upload')

        reviewers = sorted(change_desc.get_reviewers())
        cc = []
        # Add default, watchlist, presubmit ccs if this is the initial upload
        # and CL is not private and auto-ccing has not been disabled.
        if not options.private and not options.no_autocc and not self.GetIssue(
        ):
            cc = self.GetCCList().split(',')
        # Add cc's from the --cc flag.
        if options.cc:
            cc.extend(options.cc)
        cc = [email.strip() for email in cc if email.strip()]
        if change_desc.get_cced():
            cc.extend(change_desc.get_cced())
        if self.GetGerritHost() == 'chromium-review.googlesource.com':
            valid_accounts = set(reviewers + cc)
            # TODO(crbug/877717): relax this for all hosts.
        else:
            valid_accounts = gerrit_util.ValidAccounts(self.GetGerritHost(),
                                                       reviewers + cc)
        logging.info('accounts %s are recognized, %s invalid',
                     sorted(valid_accounts),
                     set(reviewers + cc).difference(set(valid_accounts)))

        # Extra options that can be specified at push time. Doc:
        # https://gerrit-review.googlesource.com/Documentation/user-upload.html
        refspec_opts = self._GetRefSpecOptions(options, change_desc)

        for r in sorted(reviewers):
            if r in valid_accounts:
                refspec_opts.append('r=%s' % r)
                reviewers.remove(r)
            else:
                # TODO(tandrii): this should probably be a hard failure.
                print(
                    'WARNING: reviewer %s doesn\'t have a Gerrit account, skipping'
                    % r)
        for c in sorted(cc):
            # refspec option will be rejected if cc doesn't correspond to an
            # account, even though REST call to add such arbitrary cc may
            # succeed.
            if c in valid_accounts:
                refspec_opts.append('cc=%s' % c)
                cc.remove(c)

        refspec_suffix = ''
        if refspec_opts:
            refspec_suffix = '%' + ','.join(refspec_opts)
            assert ' ' not in refspec_suffix, (
                'spaces not allowed in refspec: "%s"' % refspec_suffix)
        refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix)

        git_push_metadata = {
            'gerrit_host': self.GetGerritHost(),
            'title': options.title or '<untitled>',
            'change_id': change_id,
            'description': change_desc.description,
        }

        # Gerrit may or may not update fast enough to return the correct
        # patchset number after we push. Get the pre-upload patchset and
        # increment later.
        latest_ps = self.GetMostRecentPatchset(update=False) or 0

        push_stdout = self._RunGitPushWithTraces(refspec, refspec_opts,
                                                 git_push_metadata,
                                                 options.push_options)

        if options.squash:
            regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
            change_numbers = [
                m.group(1) for m in map(regex.match, push_stdout.splitlines())
                if m
            ]
            if len(change_numbers) != 1:
                DieWithError((
                    'Created|Updated %d issues on Gerrit, but only 1 expected.\n'
                    'Change-Id: %s') % (len(change_numbers), change_id),
                             change_desc)
            self.SetIssue(change_numbers[0])
            self.SetPatchset(latest_ps + 1)
            self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
                                          ref_to_push)

        if self.GetIssue() and (reviewers or cc):
            # GetIssue() is not set in case of non-squash uploads according to
            # tests. TODO(crbug.com/751901): non-squash uploads in git cl should
            # be removed.
            gerrit_util.AddReviewers(self.GetGerritHost(),
                                     self._GerritChangeIdentifier(),
                                     reviewers,
                                     cc,
                                     notify=bool(options.send_mail))

        return 0

    def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force,
                       change_desc):
        """Computes parent of the generated commit to be uploaded to Gerrit.

        Returns revision or a ref name.
        """
        if custom_cl_base:
            # Try to avoid creating additional unintended CLs when uploading,
            # unless user wants to take this risk.
            local_ref_of_target_remote = self.GetRemoteBranch()[1]
            code, _ = RunGitWithCode([
                'merge-base', '--is-ancestor', custom_cl_base,
                local_ref_of_target_remote
            ])
            if code == 1:
                print(
                    '\nWARNING: Manually specified base of this CL `%s` '
                    'doesn\'t seem to belong to target remote branch `%s`.\n\n'
                    'If you proceed with upload, more than 1 CL may be created by '
                    'Gerrit as a result, in turn confusing or crashing git cl.\n\n'
                    'If you are certain that specified base `%s` has already been '
                    'uploaded to Gerrit as another CL, you may proceed.\n' %
                    (custom_cl_base, local_ref_of_target_remote,
                     custom_cl_base))
                if not force:
                    confirm_or_exit(
                        'Do you take responsibility for cleaning up potential mess '
                        'resulting from proceeding with upload?',
                        action='upload')
            return custom_cl_base

        if remote != '.':
            return self.GetCommonAncestorWithUpstream()

        # If our upstream branch is local, we base our squashed commit on its
        # squashed version.
        upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)

        if upstream_branch_name == 'master':
            return self.GetCommonAncestorWithUpstream()
        if upstream_branch_name == 'main':
            return self.GetCommonAncestorWithUpstream()

        # Check the squashed hash of the parent.
        # TODO(tandrii): consider checking parent change in Gerrit and using its
        # hash if tree hash of latest parent revision (patchset) in Gerrit
        # matches the tree hash of the parent branch. The upside is less likely
        # bogus requests to reupload parent change just because it's uploadhash
        # is missing, yet the downside likely exists, too (albeit unknown to me
        # yet).
        parent = scm.GIT.GetBranchConfig(settings.GetRoot(),
                                         upstream_branch_name,
                                         GERRIT_SQUASH_HASH_CONFIG_KEY)
        # Verify that the upstream branch has been uploaded too, otherwise
        # Gerrit will create additional CLs when uploading.
        if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
                          RunGitSilent(['rev-parse', parent + ':'])):
            DieWithError(
                '\nUpload upstream branch %s first.\n'
                'It is likely that this branch has been rebased since its last '
                'upload, so you just need to upload it again.\n'
                '(If you uploaded it with --no-squash, then branch dependencies '
                'are not supported, and you should reupload with --squash.)' %
                upstream_branch_name, change_desc)
        return parent

    def _UpdateWithExternalChanges(self) -> Optional[str]:
        """Updates workspace with external changes.

        Returns the commit hash that should be used as the merge base on upload.
        """
        local_ps = self.GetPatchset()
        if local_ps is None:
            return

        external_ps = self.GetMostRecentPatchset(update=False)
        if external_ps is None or local_ps == external_ps or \
            not self._IsPatchsetRangeSignificant(local_ps + 1, external_ps):
            return

        num_changes = external_ps - local_ps
        if num_changes > 1:
            change_words = 'changes were'
        else:
            change_words = 'change was'
        print('\n%d external %s published to %s:\n' %
              (num_changes, change_words, self.GetIssueURL(short=True)))

        # Print an overview of external changes.
        ps_to_commit = {}
        ps_to_info = {}
        revisions = self._GetChangeDetail(['ALL_REVISIONS'])
        for commit_id, revision_info in revisions.get('revisions', {}).items():
            ps_num = revision_info['_number']
            ps_to_commit[ps_num] = commit_id
            ps_to_info[ps_num] = revision_info

        for ps in range(external_ps, local_ps, -1):
            commit = ps_to_commit[ps][:8]
            desc = ps_to_info[ps].get('description', '')
            print('Patchset %d [%s] %s' % (ps, commit, desc))

        print('\nSee diff at: %s/%d..%d' %
              (self.GetIssueURL(short=True), local_ps, external_ps))
        print('\nUploading without applying patches will override them.')

        if not ask_for_explicit_yes('Get the latest changes and apply on top?'):
            return

        # Get latest Gerrit merge base. Use the first parent even if multiple
        # exist.
        external_parent: dict = self._GetChangeCommit(
            revision=external_ps)['parents'][0]
        external_base: str = external_parent['commit']

        branch = git_common.current_branch()
        local_base = self.GetCommonAncestorWithUpstream()
        if local_base != external_base:
            print('\nLocal merge base %s is different from Gerrit %s.\n' %
                  (local_base, external_base))
            if git_common.upstream(branch):
                confirm_or_exit(
                    'Can\'t apply the latest changes from Gerrit.\n'
                    'Continue with upload and override the latest changes?')
                return
            print(
                'No upstream branch set. Continuing upload with Gerrit merge base.'
            )

        external_parent_last_uploaded = self._GetChangeCommit(
            revision=local_ps)['parents'][0]
        external_base_last_uploaded = external_parent_last_uploaded['commit']

        if external_base != external_base_last_uploaded:
            print('\nPatch set merge bases are different (%s, %s).\n' %
                  (external_base_last_uploaded, external_base))
            confirm_or_exit(
                'Can\'t apply the latest changes from Gerrit.\n'
                'Continue with upload and override the latest changes?')
            return

        # Fetch Gerrit's CL base if it doesn't exist locally.
        remote, _ = self.GetRemoteBranch()
        if not scm.GIT.IsValidRevision(settings.GetRoot(), external_base):
            RunGitSilent(['fetch', remote, external_base])

        # Get the diff between local_ps and external_ps.
        print('Fetching changes...')
        issue = self.GetIssue()
        changes_ref = 'refs/changes/%02d/%d/' % (issue % 100, issue)
        RunGitSilent(['fetch', remote, changes_ref + str(local_ps)])
        last_uploaded = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip()
        RunGitSilent(['fetch', remote, changes_ref + str(external_ps)])
        latest_external = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip()

        # If the commit parents are different, don't apply the diff as it very
        # likely contains many more changes not relevant to this CL.
        parents = RunGitSilent(
            ['rev-parse',
             '%s~1' % (last_uploaded),
             '%s~1' % (latest_external)]).strip().split()
        assert len(parents) == 2, 'Expected two parents.'
        if parents[0] != parents[1]:
            confirm_or_exit(
                'Can\'t apply the latest changes from Gerrit (parent mismatch '
                'between PS).\n'
                'Continue with upload and override the latest changes?')
            return

        diff = RunGitSilent([
            'diff', '--no-ext-diff',
            '%s..%s' % (last_uploaded, latest_external)
        ])

        # Diff can be empty in the case of trivial rebases.
        if not diff:
            return external_base

        # Apply the diff.
        with gclient_utils.temporary_file() as diff_tempfile:
            gclient_utils.FileWrite(diff_tempfile, diff)
            clean_patch = RunGitWithCode(['apply', '--check',
                                          diff_tempfile])[0] == 0
            RunGitSilent(['apply', '-3', '--intent-to-add', diff_tempfile])
            if not clean_patch:
                # Normally patchset is set after upload. But because we exit,
                # that never happens. Updating here makes sure that subsequent
                # uploads don't need to fetch/apply the same diff again.
                self.SetPatchset(external_ps)
                DieWithError(
                    '\nPatch did not apply cleanly. Please resolve any '
                    'conflicts and reupload.')

            message = 'Incorporate external changes from '
            if num_changes == 1:
                message += 'patchset %d' % external_ps
            else:
                message += 'patchsets %d to %d' % (local_ps + 1, external_ps)
            RunGitSilent(['commit', '-am', message])
            # TODO(crbug.com/1382528): Use the previous commit's message as a
            # default patchset title instead of this 'Incorporate' message.
        return external_base

    def _AddChangeIdToCommitMessage(self, log_desc, args):
        """Re-commits using the current message, assumes the commit hook is in
        place.
        """
        RunGit(['commit', '--amend', '-m', log_desc])
        new_log_desc = _create_description_from_log(args)
        if git_footers.get_footer_change_id(new_log_desc):
            print('git-cl: Added Change-Id to commit message.')
            return new_log_desc

        DieWithError('ERROR: Gerrit commit-msg hook not installed.')

    def CannotTriggerTryJobReason(self):
        try:
            data = self._GetChangeDetail()
        except GerritChangeNotExists:
            return 'Gerrit doesn\'t know about your change %s' % self.GetIssue()

        if data['status'] in ('ABANDONED', 'MERGED'):
            return 'CL %s is closed' % self.GetIssue()

    def GetGerritChange(self, patchset=None):
        """Returns a buildbucket.v2.GerritChange message for the current issue."""
        host = urllib.parse.urlparse(self.GetCodereviewServer()).hostname
        issue = self.GetIssue()
        patchset = int(patchset or self.GetPatchset())
        data = self._GetChangeDetail(['ALL_REVISIONS'])

        assert host and issue and patchset, 'CL must be uploaded first'

        has_patchset = any(
            int(revision_data['_number']) == patchset
            for revision_data in data['revisions'].values())
        if not has_patchset:
            raise Exception('Patchset %d is not known in Gerrit change %d' %
                            (patchset, self.GetIssue()))

        return {
            'host': host,
            'change': issue,
            'project': data['project'],
            'patchset': patchset,
        }

    def GetIssueOwner(self):
        return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email']

    def GetReviewers(self):
        details = self._GetChangeDetail(['DETAILED_ACCOUNTS'])
        return [r['email'] for r in details['reviewers'].get('REVIEWER', [])]


def _get_bug_line_values(default_project_prefix, bugs):
    """Given default_project_prefix and comma separated list of bugs, yields bug
    line values.

    Each bug can be either:
        * a number, which is combined with default_project_prefix
        * string, which is left as is.

    This function may produce more than one line, because bugdroid expects one
    project per line.

    >>> list(_get_bug_line_values('v8:', '123,chromium:789'))
        ['v8:123', 'chromium:789']
    """
    default_bugs = []
    others = []
    for bug in bugs.split(','):
        bug = bug.strip()
        if bug:
            try:
                default_bugs.append(int(bug))
            except ValueError:
                others.append(bug)

    if default_bugs:
        default_bugs = ','.join(map(str, default_bugs))
        if default_project_prefix:
            if not default_project_prefix.endswith(':'):
                default_project_prefix += ':'
            yield '%s%s' % (default_project_prefix, default_bugs)
        else:
            yield default_bugs
    for other in sorted(others):
        # Don't bother finding common prefixes, CLs with >2 bugs are very very
        # rare.
        yield other


def FindCodereviewSettingsFile(filename='codereview.settings'):
    """Finds the given file starting in the cwd and going up.

    Only looks up to the top of the repository unless an
    'inherit-review-settings-ok' file exists in the root of the repository.
    """
    inherit_ok_file = 'inherit-review-settings-ok'
    cwd = os.getcwd()
    root = settings.GetRoot()
    if os.path.isfile(os.path.join(root, inherit_ok_file)):
        root = None
    while True:
        if os.path.isfile(os.path.join(cwd, filename)):
            return open(os.path.join(cwd, filename))
        if cwd == root:
            break
        parent_dir = os.path.dirname(cwd)
        if parent_dir == cwd:
            # We hit the system root directory.
            break
        cwd = parent_dir
    return None


def LoadCodereviewSettingsFromFile(fileobj):
    """Parses a codereview.settings file and updates hooks."""
    keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
    root = settings.GetRoot()

    def SetProperty(name, setting):
        fullname = 'rietveld.' + name
        if setting in keyvals:
            scm.GIT.SetConfig(root, fullname, keyvals[setting])
        else:
            scm.GIT.SetConfig(root, fullname, None, modify_all=True)

    if not keyvals.get('GERRIT_HOST', False):
        SetProperty('server', 'CODE_REVIEW_SERVER')
    # Only server setting is required. Other settings can be absent.
    # In that case, we ignore errors raised during option deletion attempt.
    SetProperty('cc', 'CC_LIST')
    SetProperty('tree-status-url', 'STATUS')
    SetProperty('viewvc-url', 'VIEW_VC')
    SetProperty('bug-prefix', 'BUG_PREFIX')
    SetProperty('cpplint-regex', 'LINT_REGEX')
    SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX')
    SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK')
    SetProperty('format-full-by-default', 'FORMAT_FULL_BY_DEFAULT')

    if 'GERRIT_HOST' in keyvals:
        scm.GIT.SetConfig(root, 'gerrit.host', keyvals['GERRIT_HOST'])

    if 'GERRIT_SQUASH_UPLOADS' in keyvals:
        scm.GIT.SetConfig(root, 'gerrit.squash-uploads',
                          keyvals['GERRIT_SQUASH_UPLOADS'])

    if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals:
        scm.GIT.SetConfig('gerrit.skip-ensure-authenticated',
                          keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED'])

    if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
        # should be of the form
        # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
        # ORIGIN_URL_CONFIG: http://src.chromium.org/git
        scm.GIT.SetConfig(keyvals['PUSH_URL_CONFIG'],
                          keyvals['ORIGIN_URL_CONFIG'])


def urlretrieve(source, destination):
    """Downloads a network object to a local file, like urllib.urlretrieve.

    This is necessary because urllib is broken for SSL connections via a proxy.
    """
    with open(destination, 'wb') as f:
        f.write(urllib.request.urlopen(source).read())


def hasSheBang(fname):
    """Checks fname is a #! script."""
    with open(fname) as f:
        return f.read(2).startswith('#!')


def DownloadGerritHook(force):
    """Downloads and installs a Gerrit commit-msg hook.

    Args:
        force: True to update hooks. False to install hooks if not present.
    """
    src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
    dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
    if not os.access(dst, os.X_OK):
        if os.path.exists(dst):
            if not force:
                return
        try:
            urlretrieve(src, dst)
            if not hasSheBang(dst):
                DieWithError('Not a script: %s\n'
                             'You need to download from\n%s\n'
                             'into .git/hooks/commit-msg and '
                             'chmod +x .git/hooks/commit-msg' % (dst, src))
            os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        except Exception:
            if os.path.exists(dst):
                os.remove(dst)
            DieWithError('\nFailed to download hooks.\n'
                         'You need to download from\n%s\n'
                         'into .git/hooks/commit-msg and '
                         'chmod +x .git/hooks/commit-msg' % src)


class _GitCookiesChecker(object):
    """Provides facilities for validating and suggesting fixes to .gitcookies."""
    def __init__(self):
        # Cached list of [host, identity, source], where source is
        # .gitcookies
        self._all_hosts = None

    def ensure_configured_gitcookies(self):
        """Runs checks and suggests fixes to make git use .gitcookies from default
        path."""
        default = gerrit_util.CookiesAuthenticator.get_gitcookies_path()
        configured_path = scm.GIT.GetConfig(settings.GetRoot(),
                                            'http.cookiefile', '')
        configured_path = os.path.expanduser(configured_path)
        if configured_path:
            self._ensure_default_gitcookies_path(configured_path, default)
        else:
            self._configure_gitcookies_path(default)

    @staticmethod
    def _ensure_default_gitcookies_path(configured_path, default_path):
        assert configured_path
        if configured_path == default_path:
            print('git is already configured to use your .gitcookies from %s' %
                  configured_path)
            return

        print('WARNING: You have configured custom path to .gitcookies: %s\n'
              'Gerrit and other depot_tools expect .gitcookies at %s\n' %
              (configured_path, default_path))

        if not os.path.exists(configured_path):
            print('However, your configured .gitcookies file is missing.')
            confirm_or_exit('Reconfigure git to use default .gitcookies?',
                            action='reconfigure')
            scm.GIT.SetConfig(settings.GetRoot(),
                              'http.cookiefile',
                              default_path,
                              scope='global')
            return

        if os.path.exists(default_path):
            print('WARNING: default .gitcookies file already exists %s' %
                  default_path)
            DieWithError(
                'Please delete %s manually and re-run git cl creds-check' %
                default_path)

        confirm_or_exit('Move existing .gitcookies to default location?',
                        action='move')
        shutil.move(configured_path, default_path)
        scm.GIT.SetConfig(settings.GetRoot(),
                          'http.cookiefile',
                          default_path,
                          scope='global')
        print('Moved and reconfigured git to use .gitcookies from %s' %
              default_path)

    @staticmethod
    def _configure_gitcookies_path(default_path):
        print(
            'This tool will guide you through setting up recommended '
            '.gitcookies store for git credentials.\n'
            '\n'
            'IMPORTANT: If something goes wrong and you decide to go back, do:\n'
            '  git config --global --unset http.cookiefile\n'
            '  mv %s %s.backup\n\n' % (default_path, default_path))
        confirm_or_exit(action='setup .gitcookies')
        scm.GIT.SetConfig(settings.GetRoot(),
                          'http.cookiefile',
                          default_path,
                          scope='global')
        print('Configured git to use .gitcookies from %s' % default_path)

    def get_hosts_with_creds(self):
        if self._all_hosts is None:
            a = gerrit_util.CookiesAuthenticator()
            self._all_hosts = [(h, u, '.gitcookies')
                               for h, (u, _) in a.gitcookies.items()
                               if h.endswith(_GOOGLESOURCE)]

        return self._all_hosts

    def print_current_creds(self):
        hosts = sorted(self.get_hosts_with_creds())
        if not hosts:
            print('No Git/Gerrit credentials found.')
            return
        lengths = [max(map(len, (row[i] for row in hosts))) for i in range(3)]
        header = [('Host', 'User', 'Which file'), ['=' * l for l in lengths]]
        print('Your .gitcookies have credentials for these hosts:')
        for row in (header + hosts):
            print('\t'.join((('%%+%ds' % l) % s) for l, s in zip(lengths, row)))

    @staticmethod
    def _parse_identity(identity):
        """Parses identity "git-<username>.domain" into <username> and domain."""
        # Special case: usernames that contain ".", which are generally not
        # distinguishable from sub-domains. But we do know typical domains:
        if identity.endswith('.chromium.org'):
            domain = 'chromium.org'
            username = identity[:-len('.chromium.org')]
        else:
            username, domain = identity.split('.', 1)
        if username.startswith('git-'):
            username = username[len('git-'):]
        return username, domain

    def has_generic_host(self):
        """Returns whether generic .googlesource.com has been configured.

        Chrome Infra recommends to use explicit ${host}.googlesource.com instead.
        """
        for host, _, _ in self.get_hosts_with_creds():
            if host == '.' + _GOOGLESOURCE:
                return True
        return False

    def _get_git_gerrit_identity_pairs(self):
        """Returns map from canonic host to pair of identities (Git, Gerrit).

        One of identities might be None, meaning not configured.
        """
        host_to_identity_pairs = {}
        for host, identity, _ in self.get_hosts_with_creds():
            canonical = _canonical_git_googlesource_host(host)
            pair = host_to_identity_pairs.setdefault(canonical, [None, None])
            idx = 0 if canonical == host else 1
            pair[idx] = identity
        return host_to_identity_pairs

    def get_partially_configured_hosts(self):
        return set(
            (host if i1 else _canonical_gerrit_googlesource_host(host))
            for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
            if None in (i1, i2) and host != '.' + _GOOGLESOURCE)

    def get_conflicting_hosts(self):
        return set(
            host
            for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
            if None not in (i1, i2) and i1 != i2)

    def get_duplicated_hosts(self):
        counters = collections.Counter(
            h for h, _, _ in self.get_hosts_with_creds())
        return set(host for host, count in counters.items() if count > 1)

    @staticmethod
    def _format_hosts(hosts, extra_column_func=None):
        hosts = sorted(hosts)
        assert hosts
        if extra_column_func is None:
            extras = [''] * len(hosts)
        else:
            extras = [extra_column_func(host) for host in hosts]
        tmpl = '%%-%ds    %%-%ds' % (max(map(len, hosts)), max(map(len,
                                                                   extras)))
        lines = []
        for he in zip(hosts, extras):
            lines.append(tmpl % he)
        return lines

    def _find_problems(self):
        if self.has_generic_host():
            yield ('.googlesource.com wildcard record detected', [
                'Chrome Infrastructure team recommends to list full host names '
                'explicitly.'
            ], None)

        dups = self.get_duplicated_hosts()
        if dups:
            yield ('The following hosts were defined twice',
                   self._format_hosts(dups), None)

        partial = self.get_partially_configured_hosts()
        if partial:
            yield ('Credentials should come in pairs for Git and Gerrit hosts. '
                   'These hosts are missing',
                   self._format_hosts(
                       partial, lambda host: 'but %s defined' %
                       _get_counterpart_host(host)), partial)

        conflicting = self.get_conflicting_hosts()
        if conflicting:
            yield (
                'The following Git hosts have differing credentials from their '
                'Gerrit counterparts',
                self._format_hosts(
                    conflicting, lambda host: '%s vs %s' % tuple(
                        self._get_git_gerrit_identity_pairs()[host])),
                conflicting)

    def find_and_report_problems(self):
        """Returns True if there was at least one problem, else False."""
        found = False
        bad_hosts = set()
        for title, sublines, hosts in self._find_problems():
            if not found:
                found = True
                print('\n\n.gitcookies problem report:\n')
            bad_hosts.update(hosts or [])
            print('  %s%s' % (title, (':' if sublines else '')))
            if sublines:
                print()
                print('    %s' % '\n    '.join(sublines))
            print()

        if bad_hosts:
            assert found
            print(
                '  You can manually remove corresponding lines in your %s file and '
                'visit the following URLs with correct account to generate '
                'correct credential lines:\n' %
                gerrit_util.CookiesAuthenticator.get_gitcookies_path())
            print('    %s' % '\n    '.join(
                sorted(
                    set(gerrit_util.CookiesAuthenticator().get_new_password_url(
                        _canonical_git_googlesource_host(host))
                        for host in bad_hosts))))
        return found


@metrics.collector.collect_metrics('git cl creds-check')
def CMDcreds_check(parser, args):
    """Checks credentials and suggests changes."""
    parser.add_option(
        '--global',
        action='store_true',
        dest='force_global',
        help='Check global credentials instead of for the current repo.')
    options, args = parser.parse_args(args)

    if newauth.SwitchedOn():

        def f() -> str:
            cl = Changelist()
            try:
                return cl.GetRemoteUrl()
            except subprocess2.CalledProcessError:
                return ''

        wizard = git_auth.ConfigWizard(ui=git_auth.UserInterface(
            sys.stdin, sys.stdout),
                                       remote_url_func=f)
        wizard.run(force_global=options.force_global)
        return 0
    if newauth.ExplicitlyDisabled():
        git_auth.ClearRepoConfig(os.getcwd(), Changelist())

    # Code below checks .gitcookies. Abort if using something else.
    auth_name, _ = gerrit_util.debug_auth()
    if auth_name != "CookiesAuthenticator":
        message = (
            'This command is not designed for bot environment. It checks '
            '~/.gitcookies file not generally used on bots.')
        # TODO(crbug.com/1059384): Automatically detect when running on
        # cloudtop.
        if auth_name == "GceAuthenticator":
            message += (
                '\n'
                'If you need to run this on GCE or a cloudtop instance, '
                'export SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
        DieWithError(message)

    checker = _GitCookiesChecker()
    checker.ensure_configured_gitcookies()

    checker.print_current_creds()

    if not checker.find_and_report_problems():
        print('\nNo problems detected in your .gitcookies file.')
        return 0
    return 1


@metrics.collector.collect_metrics('git cl baseurl')
def CMDbaseurl(parser, args):
    """Gets or sets base-url for this branch."""
    if gclient_utils.IsEnvCog():
        print('baseurl command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    _, args = parser.parse_args(args)
    branchref = scm.GIT.GetBranchRef(settings.GetRoot())
    branch = scm.GIT.ShortBranchName(branchref)
    if not args:
        print('Current base-url:')
        url = scm.GIT.GetConfig(settings.GetRoot(), f'branch.{branch}.base-url')
        if url is None:
            raise ValueError('Missing base URL.')
        return url

    print('Setting base-url to %s' % args[0])
    scm.GIT.SetConfig(settings.GetRoot(), f'branch.{branch}.base-url', args[0])
    return 0


def color_for_status(status):
    """Maps a Changelist status to color, for CMDstatus and other tools."""
    BOLD = '\033[1m'
    return {
        'unsent': BOLD + Fore.YELLOW,
        'waiting': BOLD + Fore.RED,
        'reply': BOLD + Fore.YELLOW,
        'not lgtm': BOLD + Fore.RED,
        'lgtm': BOLD + Fore.GREEN,
        'commit': BOLD + Fore.MAGENTA,
        'closed': BOLD + Fore.CYAN,
        'error': BOLD + Fore.WHITE,
    }.get(status, Fore.WHITE)


def get_cl_statuses(changes: List[Changelist],
                    fine_grained,
                    max_processes=None):
    """Returns a blocking iterable of (cl, status) for given branches.

    If fine_grained is true, this will fetch CL statuses from the server.
    Otherwise, simply indicate if there's a matching url for the given branches.

    If max_processes is specified, it is used as the maximum number of processes
    to spawn to fetch CL status from the server. Otherwise 1 process per branch
    is spawned, up to max of gerrit_util.MAX_CONCURRENT_CONNECTION.

    See GetStatus() for a list of possible statuses.
    """
    if not changes:
        return

    if not fine_grained:
        # Fast path which doesn't involve querying codereview servers.
        # Do not use get_approving_reviewers(), since it requires an HTTP
        # request.
        for cl in changes:
            yield (cl, 'waiting' if cl.GetIssueURL() else 'error')
        return

    # First, sort out authentication issues.
    logging.debug('ensuring credentials exist')
    for cl in changes:
        cl.EnsureAuthenticated(force=False)

    def fetch(cl):
        try:
            return (cl, cl.GetStatus())
        except:
            # See http://crbug.com/629863.
            logging.exception('failed to fetch status for cl %s:',
                              cl.GetIssue())
            raise

    threads_count = min(gerrit_util.MAX_CONCURRENT_CONNECTION, len(changes))
    if max_processes:
        threads_count = max(1, min(threads_count, max_processes))
    logging.debug('querying %d CLs using %d threads', len(changes),
                  threads_count)

    pool = multiprocessing.pool.ThreadPool(threads_count)
    fetched_cls = set()
    try:
        it = pool.imap_unordered(fetch, changes).__iter__()
        while True:
            try:
                cl, status = it.next(timeout=5)
            except (multiprocessing.TimeoutError, StopIteration):
                break
            fetched_cls.add(cl)
            yield cl, status
    finally:
        pool.close()

    # Add any branches that failed to fetch.
    for cl in set(changes) - fetched_cls:
        yield (cl, 'error')


def upload_branch_deps(cl, args, force=False):
    """Uploads CLs of local branches that are dependents of the current branch.

    If the local branch dependency tree looks like:

        test1 -> test2.1 -> test3.1
                         -> test3.2
              -> test2.2 -> test3.3

    and you run "git cl upload --dependencies" from test1 then "git cl upload" is
    run on the dependent branches in this order:
    test2.1, test3.1, test3.2, test2.2, test3.3

    Note: This function does not rebase your local dependent branches. Use it
        when you make a change to the parent branch that will not conflict
        with its dependent branches, and you would like their dependencies
        updated in Gerrit.
        If the new stacked change flow is used, and ancestor diverged, upload
        will fail. To recover, `git rebase-update [-n]` must be executed.
    """
    if git_common.is_dirty_git_tree('upload-branch-deps'):
        return 1

    root_branch = cl.GetBranch()
    if root_branch is None:
        DieWithError('Can\'t find dependent branches from detached HEAD state. '
                     'Get on a branch!')
    if not cl.GetIssue():
        DieWithError(
            'Current branch does not have an uploaded CL. We cannot set '
            'patchset dependencies without an uploaded CL.')

    branches = RunGit([
        'for-each-ref', '--format=%(refname:short) %(upstream:short)',
        'refs/heads'
    ])
    if not branches:
        print('No local branches found.')
        return 0

    # Create a dictionary of all local branches to the branches that are
    # dependent on it.
    tracked_to_dependents = collections.defaultdict(list)
    for b in branches.splitlines():
        tokens = b.split()
        if len(tokens) == 2:
            branch_name, tracked = tokens
            tracked_to_dependents[tracked].append(branch_name)

    print()
    print('The dependent local branches of %s are:' % root_branch)
    dependents = []

    def traverse_dependents_preorder(branch, padding=''):
        dependents_to_process = tracked_to_dependents.get(branch, [])
        padding += '  '
        for dependent in dependents_to_process:
            print('%s%s' % (padding, dependent))
            dependents.append(dependent)
            traverse_dependents_preorder(dependent, padding)

    traverse_dependents_preorder(root_branch)
    print()

    if not dependents:
        print('There are no dependent local branches for %s' % root_branch)
        return 0

    # Record all dependents that failed to upload.
    failures = {}
    # Go through all dependents, checkout the branch and upload.
    try:
        for dependent_branch in dependents:
            print()
            print('--------------------------------------')
            print('Running "git cl upload" from %s:' % dependent_branch)
            RunGit(['checkout', '-q', dependent_branch])
            print()
            try:
                if CMDupload(OptionParser(), args) != 0:
                    print('Upload failed for %s!' % dependent_branch)
                    failures[dependent_branch] = 1
            except Exception as e:
                print(f"Unexpected exception: {e}")
                failures[dependent_branch] = 1
            print()
    finally:
        # Swap back to the original root branch.
        RunGit(['checkout', '-q', root_branch])

    print()
    print('Upload complete for dependent branches!')
    for dependent_branch in dependents:
        upload_status = 'failed' if failures.get(
            dependent_branch) else 'succeeded'
        print('  %s : %s' % (dependent_branch, upload_status))
    print()

    return 0


def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern):
    """Given a proposed tag name, returns a tag name that is guaranteed to be
    unique. If 'foo' is proposed but already exists, then 'foo-2' is used,
    or 'foo-3', and so on."""

    proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name})
    for suffix_num in itertools.count(1):
        if suffix_num == 1:
            to_check = proposed_tag
        else:
            to_check = '%s-%d' % (proposed_tag, suffix_num)

        if to_check not in existing_tags:
            return to_check


@metrics.collector.collect_metrics('git cl archive')
def CMDarchive(parser, args):
    """Archives and deletes branches associated with closed changelists."""
    if gclient_utils.IsEnvCog():
        print('archive command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    parser.add_option(
        '-j',
        '--maxjobs',
        action='store',
        type=int,
        help='The maximum number of jobs to use when retrieving review status.')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      help='Bypasses the confirmation prompt.')
    parser.add_option('-d',
                      '--dry-run',
                      action='store_true',
                      help='Skip the branch tagging and removal steps.')
    parser.add_option('-t',
                      '--notags',
                      action='store_true',
                      help='Do not tag archived branches. '
                      'Note: local commit history may be lost.')
    parser.add_option('-p',
                      '--pattern',
                      default='git-cl-archived-{issue}-{branch}',
                      help='Format string for archive tags. '
                      'E.g. \'archived-{issue}-{branch}\'.')

    options, args = parser.parse_args(args)
    if args:
        parser.error('Unsupported args: %s' % ' '.join(args))

    branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
    if not branches:
        return 0

    tags = RunGit(['for-each-ref', '--format=%(refname)', 'refs/tags'
                   ]).splitlines() or []
    tags = [t.split('/')[-1] for t in tags]

    print('Finding all branches associated with closed issues...')
    changes = [Changelist(branchref=b) for b in branches.splitlines()]
    alignment = max(5, max(len(c.GetBranch()) for c in changes))
    statuses = get_cl_statuses(changes,
                               fine_grained=True,
                               max_processes=options.maxjobs)
    proposal = [(cl.GetBranch(),
                 GetArchiveTagForBranch(cl.GetIssue(), cl.GetBranch(), tags,
                                        options.pattern))
                for cl, status in statuses
                if status in ('closed', 'rietveld-not-supported')]
    proposal.sort()

    if not proposal:
        print('No branches with closed codereview issues found.')
        return 0

    current_branch = scm.GIT.GetBranch(settings.GetRoot())

    print('\nBranches with closed issues that will be archived:\n')
    if options.notags:
        for next_item in proposal:
            print('  ' + next_item[0])
    else:
        print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name'))
        for next_item in proposal:
            print('%*s   %s' % (alignment, next_item[0], next_item[1]))

    # Quit now on precondition failure or if instructed by the user, either
    # via an interactive prompt or by command line flags.
    if options.dry_run:
        print('\nNo changes were made (dry run).\n')
        return 0

    if any(branch == current_branch for branch, _ in proposal):
        print('You are currently on a branch \'%s\' which is associated with a '
              'closed codereview issue, so archive cannot proceed. Please '
              'checkout another branch and run this command again.' %
              current_branch)
        return 1

    if not options.force:
        answer = gclient_utils.AskForData(
            '\nProceed with deletion (Y/n)? ').lower()
        if answer not in ('y', ''):
            print('Aborted.')
            return 1

    for branch, tagname in proposal:
        if not options.notags:
            RunGit(['tag', tagname, branch])

        if RunGitWithCode(['branch', '-D', branch])[0] != 0:
            # Clean up the tag if we failed to delete the branch.
            RunGit(['tag', '-d', tagname])

    print('\nJob\'s done!')

    return 0


@metrics.collector.collect_metrics('git cl squash-closed')
def CMDsquash_closed(parser, args):
    """Squashes branches associated with closed changelists, and reparents their children."""
    if gclient_utils.IsEnvCog():
        print('squash_closed command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    parser.add_option(
        '-j',
        '--maxjobs',
        action='store',
        type=int,
        help='The maximum number of jobs to use when retrieving review status.')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      help='Bypasses the confirmation prompt.')
    parser.add_option('-d',
                      '--dry-run',
                      action='store_true',
                      help='Skip the branch tagging and removal steps.')

    options, args = parser.parse_args(args)
    if args:
        parser.error('Unsupported args: %s' % ' '.join(args))

    if git_common.is_dirty_git_tree('squash-closed'):
        return 1

    branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
    if not branches:
        return 0

    print('Finding all branches associated with closed issues...')
    changes = [Changelist(branchref=b) for b in branches.splitlines()]
    statuses = get_cl_statuses(changes,
                               fine_grained=True,
                               max_processes=options.maxjobs)
    proposal = [cl.GetBranch() for cl, status in statuses if status == 'closed']
    proposal.sort()

    if not proposal:
        print('No branches with closed codereview issues found.')
        return 0

    print('\nBranches with closed issues that will be squashed:\n')
    for next_item in proposal:
        print('  ' + next_item)

    # Quit now on if this is a dry run.
    if options.dry_run:
        print('\nNo changes were made (dry run).\n')
        return 0

    current_branch = scm.GIT.GetBranch(settings.GetRoot())
    if current_branch in proposal:
        print('You are currently on a branch \'%s\' which is associated with a '
              'closed codereview issue, so squash-closed cannot proceed. '
              'Please checkout another branch and run this command again.' %
              current_branch)
        return 1

    # Prompt the user to continue unless they've specified to always continue.
    if not options.force:
        answer = gclient_utils.AskForData(
            '\nProceed with deletion (Y/n)? ').lower()
        if answer not in ('y', ''):
            print('Aborted.')
            return 1

    # scm.GIT.GetBranch does not work for detached HEAD situations.
    reset_branch = git_common.current_branch()
    for branch in proposal:
        RunGit(['checkout', branch])
        if git_squash_branch.main([]) != 0:
            RunGit(['checkout', reset_branch])
            return 1

    RunGit(['checkout', reset_branch])
    print('\nJob\'s done!')

    return 0


@metrics.collector.collect_metrics('git cl status')
def CMDstatus(parser, args):
    """Show status of changelists.

    Colors are used to tell the state of the CL unless --fast is used:
        - Blue     waiting for review
        - Yellow   waiting for you to reply to review, or not yet sent
        - Green    LGTM'ed
        - Red      'not LGTM'ed
        - Magenta  in the CQ
        - Cyan     was committed, branch can be deleted
        - White    error, or unknown status

    Also see 'git cl comments'.
    """
    if gclient_utils.IsEnvCog():
        print(
            'status command is not supported. Please go to the Gerrit CL '
            'page to check the CL status directly.',
            file=sys.stderr)
        return 1

    parser.add_option('--no-branch-color',
                      action='store_true',
                      help='Disable colorized branch names')
    parser.add_option(
        '--field', help='print only specific field (desc|id|patch|status|url)')
    parser.add_option('-f',
                      '--fast',
                      action='store_true',
                      help='Do not retrieve review status')
    parser.add_option(
        '-j',
        '--maxjobs',
        action='store',
        type=int,
        help='The maximum number of jobs to use when retrieving review status')
    parser.add_option(
        '-i',
        '--issue',
        type=int,
        help='Operate on this issue instead of the current branch\'s implicit '
        'issue. Requires --field to be set.')
    parser.add_option('-d',
                      '--date-order',
                      action='store_true',
                      help='Order branches by committer date.')
    options, args = parser.parse_args(args)
    if args:
        parser.error('Unsupported args: %s' % args)

    if options.issue is not None and not options.field:
        parser.error('--field must be given when --issue is set.')

    if options.field:
        cl = Changelist(issue=options.issue)
        if options.field.startswith('desc'):
            if cl.GetIssue():
                print(cl.FetchDescription())
        elif options.field == 'id':
            issueid = cl.GetIssue()
            if issueid:
                print(issueid)
        elif options.field == 'patch':
            patchset = cl.GetMostRecentPatchset()
            if patchset:
                print(patchset)
        elif options.field == 'status':
            print(cl.GetStatus())
        elif options.field == 'url':
            url = cl.GetIssueURL()
            if url:
                print(url)
        return 0

    branches = RunGit([
        'for-each-ref', '--format=%(refname) %(committerdate:unix)',
        'refs/heads'
    ])
    if not branches:
        print('No local branch found.')
        return 0

    changes = [
        Changelist(branchref=b, commit_date=ct)
        for b, ct in map(lambda line: line.split(' '), branches.splitlines())
    ]
    print('Branches associated with reviews:')
    output = get_cl_statuses(changes,
                             fine_grained=not options.fast,
                             max_processes=options.maxjobs)

    current_branch = scm.GIT.GetBranch(settings.GetRoot())

    def FormatBranchName(branch, colorize=False):
        """Simulates 'git branch' behavior. Colorizes and prefixes branch name with
        an asterisk when it is the current branch."""

        asterisk = ""
        color = Fore.RESET
        if branch == current_branch:
            asterisk = "* "
            color = Fore.GREEN
        branch_name = scm.GIT.ShortBranchName(branch)

        if colorize:
            return asterisk + color + branch_name + Fore.RESET
        return asterisk + branch_name

    branch_statuses = {}

    alignment = max(5,
                    max(len(FormatBranchName(c.GetBranch())) for c in changes))

    if options.date_order or settings.IsStatusCommitOrderByDate():
        sorted_changes = sorted(changes,
                                key=lambda c: c.GetCommitDate(),
                                reverse=True)
    else:
        sorted_changes = sorted(changes, key=lambda c: c.GetBranch())
    for cl in sorted_changes:
        branch = cl.GetBranch()
        while branch not in branch_statuses:
            c, status = next(output)
            branch_statuses[c.GetBranch()] = status
        status = branch_statuses.pop(branch)
        url = cl.GetIssueURL(short=True)
        if url and (not status or status == 'error'):
            # The issue probably doesn't exist anymore.
            url += ' (broken)'

        color = color_for_status(status)
        # Turn off bold as well as colors.
        END = '\033[0m'
        reset = Fore.RESET + END
        if not setup_color.IS_TTY:
            color = ''
            reset = ''
        status_str = '(%s)' % status if status else ''

        branch_display = FormatBranchName(branch)
        padding = ' ' * (alignment - len(branch_display))
        if not options.no_branch_color:
            branch_display = FormatBranchName(branch, colorize=True)

        print('  %s : %s%s %s%s' %
              (padding + branch_display, color, url, status_str, reset))

    print()
    print('Current branch: %s' % current_branch)
    for cl in changes:
        if cl.GetBranch() == current_branch:
            break
    if not cl.GetIssue():
        print('No issue assigned.')
        return 0
    print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
    if not options.fast:
        print('Issue description:')
        print(cl.FetchDescription(pretty=True))
    return 0


def colorize_CMDstatus_doc():
    """To be called once in main() to add colors to git cl status help."""
    colors = [i for i in dir(Fore) if i[0].isupper()]

    def colorize_line(line):
        for color in colors:
            if color in line.upper():
                # Extract whitespace first and the leading '-'.
                indent = len(line) - len(line.lstrip(' ')) + 1
                return line[:indent] + getattr(
                    Fore, color) + line[indent:] + Fore.RESET
        return line

    lines = CMDstatus.__doc__.splitlines()
    CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)


def write_json(path, contents):
    if path == '-':
        json.dump(contents, sys.stdout)
    else:
        with open(path, 'w') as f:
            json.dump(contents, f)


@subcommand.usage('[issue_number]')
@metrics.collector.collect_metrics('git cl issue')
def CMDissue(parser, args):
    """Sets or displays the current code review issue number.

    Pass issue number 0 to clear the current issue.
    """
    if gclient_utils.IsEnvCog():
        print(
            'issue command is not supported. CL number is available in the '
            'primary side bar at the bottom of your editor. Setting the CL '
            'number is not supported, you can open a new workspace from the '
            'Gerrit CL directly.',
            file=sys.stderr)
        return 1

    parser.add_option('-r',
                      '--reverse',
                      action='store_true',
                      help='Lookup the branch(es) for the specified issues. If '
                      'no issues are specified, all branches with mapped '
                      'issues will be listed.')
    parser.add_option('--json',
                      help='Path to JSON output file, or "-" for stdout.')
    options, args = parser.parse_args(args)

    if options.reverse:
        branches = RunGit(['for-each-ref', 'refs/heads',
                           '--format=%(refname)']).splitlines()
        # Reverse issue lookup.
        issue_branch_map = {}

        git_config = {}
        for name, val in scm.GIT.YieldConfigRegexp(
                settings.GetRoot(), re.compile(r'branch\..*issue')):
            git_config[name] = val

        for branch in branches:
            issue = git_config.get(
                'branch.%s.%s' %
                (scm.GIT.ShortBranchName(branch), ISSUE_CONFIG_KEY))
            if issue:
                issue_branch_map.setdefault(int(issue), []).append(branch)
        if not args:
            args = sorted(issue_branch_map.keys())
        result = {}
        for issue in args:
            try:
                issue_num = int(issue)
            except ValueError:
                print('ERROR cannot parse issue number: %s' % issue,
                      file=sys.stderr)
                continue
            result[issue_num] = issue_branch_map.get(issue_num)
            print('Branch for issue number %s: %s' % (issue, ', '.join(
                issue_branch_map.get(issue_num) or ('None', ))))
        if options.json:
            write_json(options.json, result)
        return 0

    if len(args) > 0:
        issue = ParseIssueNumberArgument(args[0])
        if not issue.valid:
            DieWithError(
                'Pass a url or number to set the issue, 0 to unset it, '
                'or no argument to list it.\n'
                'Maybe you want to run git cl status?')
        cl = Changelist()
        cl.SetIssue(issue.issue)
    else:
        cl = Changelist()
    print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
    if options.json:
        write_json(
            options.json, {
                'gerrit_host': cl.GetGerritHost(),
                'gerrit_project': cl.GetGerritProject(),
                'issue_url': cl.GetIssueURL(),
                'issue': cl.GetIssue(),
            })
    return 0


def _create_commit_message(orig_message, bug=None):
    """Returns a commit message for the cherry picked CL."""
    orig_message_lines = orig_message.splitlines()
    subj_line = orig_message_lines[0]
    new_message = (f'Cherry pick "{subj_line}"\n\n'
                   "Original change's description:\n")
    for line in orig_message_lines:
        new_message += f'> {line}\n'
    new_message += '\n'
    if bug:
        new_message += f'Bug: {bug}\n'
    if change_id := git_footers.get_footer_change_id(orig_message):
        new_message += f'Change-Id: {change_id[0]}\n'
    return new_message


# TODO(b/341792235): Add metrics.
@subcommand.usage('[revisions ...]')
def CMDcherry_pick(parser, args):
    """Upload a chain of cherry picks to Gerrit.

    This should either be run inside the git repo you're trying to make changes
    to or "--host" should be provided.
    """
    parser.add_option('--branch', help='Gerrit branch, e.g. refs/heads/main')
    parser.add_option('--bug',
                      help='Bug to add to the description of each change.')
    parser.add_option('--parent-change-num',
                      type='int',
                      help='The parent change of the first cherry-pick CL, '
                      'i.e. the start of the CL chain.')
    parser.add_option('--host',
                      default=None,
                      help='Gerrit host, needed in case the command is used in '
                      'a non-git environment.')
    options, args = parser.parse_args(args)

    host = None
    if options.host:
        try:
            host = urllib.parse.urlparse(options.host).hostname
        except ValueError as e:
            print(f'Unable to parse host: {host}. Error: {e}', file=sys.stderr)
            return 1
    else:
        try:
            host = Changelist().GetGerritHost()
        except subprocess2.CalledProcessError:
            pass

    if not host:
        print('Unable to determine host. cherry-pick command is not supported\n'
              'in non-git environment without "--host" provided',
              file=sys.stderr)
        return 1

    if not options.branch:
        parser.error('Branch is required.')
    if not args:
        parser.error('No revisions to cherry pick.')

    change_ids_to_message = {}
    change_ids_to_commit = {}

    # Gerrit needs a change ID for each commit we cherry pick.
    for commit in args:
        # Don't use the ChangeId in the commit message since it may not be
        # unique. Gerrit will error with "Multiple changes found" if we use a
        # non-unique ID. Instead, query Gerrit with the hash and verify it
        # corresponds to a unique CL.
        changes = gerrit_util.QueryChanges(
            host=host,
            params=[('commit', commit)],
            o_params=['CURRENT_REVISION', 'CURRENT_COMMIT'],
        )
        if not changes:
            raise RuntimeError(f'No changes found for {commit}.')
        if len(changes) > 1:
            raise RuntimeError(f'Multiple changes found for {commit}.')

        change = changes[0]
        change_id = change['id']
        message = change['revisions'][commit]['commit']['message']
        change_ids_to_commit[change_id] = commit
        change_ids_to_message[change_id] = message

    print(f'Creating chain of {len(change_ids_to_message)} cherry pick(s)...')

    def print_any_remaining_commits():
        if not change_ids_to_commit:
            return
        print('Remaining commit(s) to cherry pick:')
        for commit in change_ids_to_commit.values():
            print(f'  {commit}')

    # Gerrit only supports cherry picking one commit per change, so we have
    # to cherry pick each commit individually and create a chain of CLs.
    parent_change_num = options.parent_change_num
    parent_commit_hash = None

    for change_id, orig_message in change_ids_to_message.items():
        message = _create_commit_message(orig_message, options.bug)
        orig_subj_line = orig_message.splitlines()[0]
        original_commit_hash = change_ids_to_commit[change_id]

        # Determine the base commit hash for the current cherry-pick by fetching
        # the details of the previous CL (identified by parent_change_num).
        # Skip if this is the first CL and no initial parent was given.
        if parent_change_num:
            parent_details = gerrit_util.GetChangeDetail(
                host, str(parent_change_num), o_params=['CURRENT_REVISION'])
            parent_commit_hash = parent_details['current_revision']
            print(f'Using base commit {parent_commit_hash} '
                  f'from parent CL {parent_change_num}.')

        # Call CherryPick with the determined base commit hash
        print('Attempting cherry-pick of original commit '
              f'{original_commit_hash} ("{orig_subj_line}") onto base '
              f'{parent_commit_hash or options.branch + " tip"}...')
        try:
            new_change_info = gerrit_util.CherryPick(host,
                                                     change_id,
                                                     options.branch,
                                                     message=message,
                                                     base=parent_commit_hash)
        except gerrit_util.GerritError as e:
            print(f'Failed to create cherry pick "{orig_subj_line}": {e}. '
                  'Please resolve any merge conflicts.')
            print_any_remaining_commits()
            return 1

        change_ids_to_commit.pop(change_id)
        new_change_num = new_change_info['_number']
        new_change_url = gerrit_util.GetChangePageUrl(host, new_change_num)
        print(f'Created cherry pick of "{orig_subj_line}": {new_change_url}')
        parent_change_num = new_change_num

    return 0


@metrics.collector.collect_metrics('git cl comments')
def CMDcomments(parser, args):
    """Shows or posts review comments for any changelist."""
    if gclient_utils.IsEnvCog():
        print(
            'comments command is not supported in non-git environment. '
            'Comments on the CL should show up inline in your editor. To '
            'post comments, please visit Gerrit CL page.',
            file=sys.stderr)
        return 1

    parser.add_option('-a',
                      '--add-comment',
                      dest='comment',
                      help='comment to add to an issue')
    parser.add_option('-p',
                      '--publish',
                      action='store_true',
                      help='marks CL as ready and sends comment to reviewers')
    parser.add_option('-i',
                      '--issue',
                      dest='issue',
                      help='review issue id (defaults to current issue).')
    parser.add_option('-m',
                      '--machine-readable',
                      dest='readable',
                      action='store_false',
                      default=True,
                      help='output comments in a format compatible with '
                      'editor parsing')
    parser.add_option('-j',
                      '--json-file',
                      help='File to write JSON summary to, or "-" for stdout')
    options, args = parser.parse_args(args)

    issue = None
    if options.issue:
        try:
            issue = int(options.issue)
        except ValueError:
            DieWithError('A review issue ID is expected to be a number.')

    cl = Changelist(issue=issue)

    if options.comment:
        cl.AddComment(options.comment, options.publish)
        return 0

    summary = sorted(cl.GetCommentsSummary(readable=options.readable),
                     key=lambda c: c.date)
    for comment in summary:
        if comment.disapproval:
            color = Fore.RED
        elif comment.approval:
            color = Fore.GREEN
        elif comment.sender == cl.GetIssueOwner():
            color = Fore.MAGENTA
        elif comment.autogenerated:
            color = Fore.CYAN
        else:
            color = Fore.BLUE
        print('\n%s%s   %s%s\n%s' %
              (color, comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'),
               comment.sender, Fore.RESET, '\n'.join(
                   '  ' + l for l in comment.message.strip().splitlines())))

    if options.json_file:

        def pre_serialize(c):
            dct = c._asdict().copy()
            dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f')
            return dct

        write_json(options.json_file, [pre_serialize(x) for x in summary])
    return 0


@subcommand.usage('[codereview url or issue id]')
@metrics.collector.collect_metrics('git cl description')
def CMDdescription(parser, args):
    """Brings up the editor for the current CL's description."""
    if gclient_utils.IsEnvCog():
        print(
            'description command is not supported. Please use "Gerrit: Edit '
            'Change Information" functionality in the command palatte to edit '
            'the CL description.',
            file=sys.stderr)
        return 1

    parser.add_option(
        '-d',
        '--display',
        action='store_true',
        help='Display the description instead of opening an editor')
    parser.add_option(
        '-n',
        '--new-description',
        help='New description to set for this issue (- for stdin, '
        '+ to load from local commit HEAD)')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      help='Delete any unpublished Gerrit edits for this issue '
                      'without prompting')

    options, args = parser.parse_args(args)

    target_issue_arg = None
    if len(args) > 0:
        target_issue_arg = ParseIssueNumberArgument(args[0])
        if not target_issue_arg.valid:
            parser.error('Invalid issue ID or URL.')

    kwargs = {}
    if target_issue_arg:
        kwargs['issue'] = target_issue_arg.issue
        kwargs['codereview_host'] = target_issue_arg.hostname

    cl = Changelist(**kwargs)
    if not cl.GetIssue():
        DieWithError('This branch has no associated changelist.')

    if args and not args[0].isdigit():
        logging.info('canonical issue/change URL: %s\n', cl.GetIssueURL())

    description = ChangeDescription(cl.FetchDescription())

    if options.display:
        print(description.description)
        return 0

    if options.new_description:
        text = options.new_description
        if text == '-':
            text = '\n'.join(l.rstrip() for l in sys.stdin)
        elif text == '+':
            base_branch = cl.GetCommonAncestorWithUpstream()
            text = _create_description_from_log([base_branch])

        description.set_description(text)
    else:
        description.prompt()
    if cl.FetchDescription().strip() != description.description:
        cl.UpdateDescription(description.description, force=options.force)
    return 0


def FindFilesForLint(options, args):
    """Returns the base folder and a list of files to lint."""
    files = []
    cwd = os.getcwd()
    if len(args) == 1 and args[0] == '-':
        # the input is from stdin.
        files.append(args[0])
    elif len(args) > 0:
        # If file paths are given in positional args, run the lint tools
        # against them without using git commands. This allows git_cl.py
        # runnable against any files even out of git checkouts.
        for fn in args:
            if os.path.isfile(fn):
                files.append(fn)
            else:
                print('%s is not a file' % fn)
                return None, None
    elif gclient_utils.IsEnvCog():
        print('Error: missing files to lint')
        return None, None
    else:
        # If file names are omitted, use the git APIs to find the files to lint.
        include_regex = re.compile(settings.GetLintRegex())
        ignore_regex = re.compile(settings.GetLintIgnoreRegex())
        cl = Changelist()
        cwd = settings.GetRoot()
        affectedFiles = cl.GetAffectedFiles(cl.GetCommonAncestorWithUpstream())
        if not affectedFiles:
            print('Cannot lint an empty CL')
            return None, None

        for fn in affectedFiles:
            if not include_regex.match(fn):
                print('Skipping file %s' % fn)
            elif ignore_regex.match(fn):
                print('Ignoring file %s' % fn)
            else:
                files.append(fn)

    return cwd, files


@subcommand.usage('[files ...]')
@metrics.collector.collect_metrics('git cl lint')
def CMDlint(parser, args):
    """Runs cpplint on the current changelist or given files.

    positional arguments:
      files           Files to lint. If omitted, lint all the affected files.
                      If -, lint stdin.
    """
    parser.add_option(
        '--filter',
        action='append',
        metavar='-x,+y',
        help='Comma-separated list of cpplint\'s category-filters')
    options, args = parser.parse_args(args)
    root_path, files = FindFilesForLint(options, args)
    if files is None:
        return 1

    # Access to a protected member _XX of a client class
    # pylint: disable=protected-access
    try:
        import cpplint
        import cpplint_chromium

        # Process cpplint arguments, if any.
        filters = presubmit_canned_checks.GetCppLintFilters(options.filter)
        command = ['--filter=' + ','.join(filters)]
        command.extend(files)
        files_to_lint = cpplint.ParseArguments(command)
    except ImportError:
        print(
            'Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.'
        )
        return 1

    # Change the current working directory before calling lint so that it
    # shows the correct base.
    previous_cwd = os.getcwd()
    try:
        os.chdir(root_path)
        extra_check_functions = [
            cpplint_chromium.CheckPointerDeclarationWhitespace
        ]
        for file in files_to_lint:
            cpplint.ProcessFile(file, cpplint._cpplint_state.verbose_level,
                                extra_check_functions)
    finally:
        os.chdir(previous_cwd)

    print('Total errors found: %d\n' % cpplint._cpplint_state.error_count)
    if cpplint._cpplint_state.error_count != 0:
        return 1
    return 0


@metrics.collector.collect_metrics('git cl presubmit')
@subcommand.usage('[base branch]')
def CMDpresubmit(parser, args):
    """Runs presubmit tests on the current changelist."""
    if gclient_utils.IsEnvCog():
        print('presubmit command is not supported in non-git environment. '
              'Please use the "Chromium PRESUBMITS" panel or the "Run '
              'Presubmit Checks" command in the command palette in the editor '
              'instead.',
              file=sys.stderr)
        return 1
    parser.add_option('-u',
                      '--upload',
                      action='store_true',
                      help='Run upload hook instead of the push hook')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      help='Run checks even if tree is dirty')
    parser.add_option(
        '--all',
        action='store_true',
        help='Run checks against all files, not just modified ones')
    parser.add_option('--files',
                      nargs=1,
                      help='Semicolon-separated list of files to be marked as '
                      'modified when executing presubmit or post-upload hooks. '
                      'fnmatch wildcards can also be used.')
    parser.add_option(
        '--parallel',
        action='store_true',
        help='Run all tests specified by input_api.RunTests in all '
        'PRESUBMIT files in parallel.')
    parser.add_option('--resultdb',
                      action='store_true',
                      help='Run presubmit checks in the ResultSink environment '
                      'and send results to the ResultDB database.')
    parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
    parser.add_option('-j',
                      '--json',
                      help='File to write JSON results to, or "-" for stdout')
    options, args = parser.parse_args(args)

    if not options.force and git_common.is_dirty_git_tree('presubmit'):
        print('use --force to check even if tree is dirty.')
        return 1

    cl = Changelist()
    if args:
        base_branch = args[0]
    else:
        # Default to diffing against the common ancestor of the upstream branch.
        base_branch = cl.GetCommonAncestorWithUpstream()

    start = time.time()
    try:
        if not 'PRESUBMIT_SKIP_NETWORK' in os.environ and cl.GetIssue():
            description = cl.FetchDescription()
        else:
            description = _create_description_from_log([base_branch])
    except Exception as e:
        print('Failed to fetch CL description - %s' % str(e))
        description = _create_description_from_log([base_branch])
    elapsed = time.time() - start
    if elapsed > 5:
        print('%.1f s to get CL description.' % elapsed)

    if not base_branch:
        if not options.force:
            print('use --force to check even when not on a branch.')
            return 1
        base_branch = 'HEAD'

    result = cl.RunHook(committing=not options.upload,
                        may_prompt=False,
                        verbose=options.verbose,
                        parallel=options.parallel,
                        upstream=base_branch,
                        description=description,
                        all_files=options.all,
                        files=options.files,
                        resultdb=options.resultdb,
                        realm=options.realm)
    if options.json:
        write_json(options.json, result)
    return 0


def GenerateGerritChangeId(message):
    """Returns the Change ID footer value (Ixxxxxx...xxx).

    Works the same way as
    https://gerrit-review.googlesource.com/tools/hooks/commit-msg
    but can be called on demand on all platforms.

    The basic idea is to generate git hash of a state of the tree, original
    commit message, author/committer info and timestamps.
    """
    lines = []
    tree_hash = RunGitSilent(['write-tree'])
    lines.append('tree %s' % tree_hash.strip())
    code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'],
                                  suppress_stderr=False)
    if code == 0:
        lines.append('parent %s' % parent.strip())
    author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT'])
    lines.append('author %s' % author.strip())
    committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT'])
    lines.append('committer %s' % committer.strip())
    lines.append('')
    # Note: Gerrit's commit-hook actually cleans message of some lines and
    # whitespace. This code is not doing this, but it clearly won't decrease
    # entropy.
    lines.append(message)
    change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
                             stdin=('\n'.join(lines)).encode())
    return 'I%s' % change_hash.strip()


def GetTargetRef(remote, remote_branch, target_branch):
    """Computes the remote branch ref to use for the CL.

    Args:
        remote (str): The git remote for the CL.
        remote_branch (str): The git remote branch for the CL.
        target_branch (str): The target branch specified by the user.
    """
    if not (remote and remote_branch):
        return None

    if target_branch:
        # Canonicalize branch references to the equivalent local full symbolic
        # refs, which are then translated into the remote full symbolic refs
        # below.
        if '/' not in target_branch:
            remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
        else:
            prefix_replacements = (
                ('^((refs/)?remotes/)?branch-heads/',
                 'refs/remotes/branch-heads/'),
                ('^((refs/)?remotes/)?%s/' % remote,
                 'refs/remotes/%s/' % remote),
                ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
            )
            match = None
            for regex, replacement in prefix_replacements:
                match = re.search(regex, target_branch)
                if match:
                    remote_branch = target_branch.replace(
                        match.group(0), replacement)
                    break
            if not match:
                # This is a branch path but not one we recognize; use as-is.
                remote_branch = target_branch
    # pylint: disable=consider-using-get
    elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
        # pylint: enable=consider-using-get
        # Handle the refs that need to land in different refs.
        remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]

    # Create the true path to the remote branch.
    # Does the following translation:
    # * refs/remotes/origin/refs/diff/test -> refs/diff/test
    # * refs/remotes/origin/main -> refs/heads/main
    # * refs/remotes/branch-heads/test -> refs/branch-heads/test
    if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
        remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
    elif remote_branch.startswith('refs/remotes/%s/' % remote):
        remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
                                              'refs/heads/')
    elif remote_branch.startswith('refs/remotes/branch-heads'):
        remote_branch = remote_branch.replace('refs/remotes/', 'refs/')

    return remote_branch


def cleanup_list(l):
    """Fixes a list so that comma separated items are put as individual items.

    So that "--reviewers joe@c,john@c --reviewers joa@c" results in
    options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
    """
    items = sum((i.split(',') for i in l), [])
    stripped_items = (i.strip() for i in items)
    return sorted(filter(None, stripped_items))


@subcommand.usage('[flags]')
@metrics.collector.collect_metrics('git cl upload')
def CMDupload(parser, args):
    """Uploads the current changelist to codereview.

    Can skip dependency patchset uploads for a branch by running:
        git config branch.branch_name.skip-deps-uploads True
    To unset, run:
        git config --unset branch.branch_name.skip-deps-uploads
    Can also set the above globally by using the --global flag.

    If the name of the checked out branch starts with "bug-" or "fix-" followed
    by a bug number, this bug number is automatically populated in the CL
    description.

    If subject contains text in square brackets or has "<text>: " prefix, such
    text(s) is treated as Gerrit hashtags. For example, CLs with subjects:
        [git-cl] add support for hashtags
        Foo bar: implement foo
    will be hashtagged with "git-cl" and "foo-bar" respectively.
    """
    if gclient_utils.IsEnvCog():
        print(
            'upload command is not supported. Please navigate to source '
            'control view in the activity bar to upload changes to Gerrit.',
            file=sys.stderr)
        return 1

    parser.add_option('--bypass-hooks',
                      action='store_true',
                      dest='bypass_hooks',
                      help='bypass upload presubmit hook')
    parser.add_option('--bypass-watchlists',
                      action='store_true',
                      dest='bypass_watchlists',
                      help='bypass watchlists auto CC-ing reviewers')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      dest='force',
                      help="force yes to questions (don't prompt)")
    parser.add_option('--message',
                      '-m',
                      dest='message',
                      help='DEPRECATED: use --commit-description and/or '
                      '--title instead. message for patchset')
    parser.add_option('-b',
                      '--bug',
                      help='pre-populate the bug number(s) for this issue. '
                      'If several, separate with commas')
    parser.add_option('--message-file',
                      dest='message_file',
                      help='DEPRECATED: use `--commit-description -` and pipe '
                      'the file to stdin instead. File which contains message '
                      'for patchset')
    parser.add_option('--title', '-t', dest='title', help='title for patchset')
    parser.add_option('-T',
                      '--skip-title',
                      action='store_true',
                      dest='skip_title',
                      help='Use the most recent commit message as the title of '
                      'the patchset')
    parser.add_option('-r',
                      '--reviewers',
                      action='append',
                      default=[],
                      help='reviewer email addresses')
    parser.add_option('--cc',
                      action='append',
                      default=[],
                      help='cc email addresses')
    parser.add_option('--hashtag',
                      dest='hashtags',
                      action='append',
                      default=[],
                      help=('Gerrit hashtag for new CL; '
                            'can be applied multiple times'))
    parser.add_option('-s',
                      '--send-mail',
                      '--send-email',
                      dest='send_mail',
                      action='store_true',
                      help='send email to reviewer(s) and cc(s) immediately')
    parser.add_option('--target_branch',
                      '--target-branch',
                      metavar='TARGET',
                      help='Apply CL to remote ref TARGET.  ' +
                      'Default: remote branch head, or main')
    parser.add_option('--squash',
                      action='store_true',
                      help='Squash multiple commits into one')
    parser.add_option('--no-squash',
                      action='store_false',
                      dest='squash',
                      help='Don\'t squash multiple commits into one')
    parser.add_option('--topic',
                      default=None,
                      help='Topic to specify when uploading')
    parser.add_option('--r-owners',
                      dest='add_owners_to',
                      action='store_const',
                      const='R',
                      help='add a set of OWNERS to R')
    parser.add_option('-c',
                      '--use-commit-queue',
                      action='store_true',
                      default=False,
                      help='tell the CQ to commit this patchset; '
                      'implies --send-mail')
    parser.add_option('-d',
                      '--dry-run',
                      '--cq-dry-run',
                      action='store_true',
                      dest='cq_dry_run',
                      default=False,
                      help='Send the patchset to do a CQ dry run right after '
                      'upload.')
    parser.add_option('--set-bot-commit',
                      action='store_true',
                      help=optparse.SUPPRESS_HELP)
    parser.add_option('--preserve-tryjobs',
                      action='store_true',
                      help='instruct the CQ to let tryjobs running even after '
                      'new patchsets are uploaded instead of canceling '
                      'prior patchset\' tryjobs')
    parser.add_option(
        '--dependencies',
        action='store_true',
        help='Uploads CLs of all the local branches that depend on '
        'the current branch')
    parser.add_option(
        '-a',
        '--auto-submit',
        '--enable-auto-submit',
        action='store_true',
        dest='enable_auto_submit',
        help='Sends your change to the CQ after an approval. Only '
        'works on repos that have the Auto-Submit label '
        'enabled')
    parser.add_option('--enable-owners-override',
                      action='store_true',
                      help='Adds the Owners-Override label to your change.')
    parser.add_option(
        '--parallel',
        action='store_true',
        help='Run all tests specified by input_api.RunTests in all '
        'PRESUBMIT files in parallel.')
    parser.add_option('--no-autocc',
                      action='store_true',
                      help='Disables automatic addition of CC emails')
    parser.add_option('--private',
                      action='store_true',
                      help='Set the review private. This implies --no-autocc.')
    parser.add_option('-R',
                      '--retry-failed',
                      action='store_true',
                      help='Retry failed tryjobs from old patchset immediately '
                      'after uploading new patchset. Cannot be used with '
                      '--use-commit-queue or --cq-dry-run.')
    parser.add_option('--fixed',
                      '-x',
                      help='List of bugs that will be commented on and marked '
                      'fixed (pre-populates "Fixed:" tag). Same format as '
                      '-b option / "Bug:" tag. If fixing several issues, '
                      'separate with commas.')
    parser.add_option('--edit-description',
                      action='store_true',
                      default=False,
                      help='Modify description before upload. Cannot be used '
                      'with --force or --commit-description. It is a noop when '
                      '--no-squash is set or a new commit is created.')
    parser.add_option('--commit-description',
                      dest='commit_description',
                      help='Description to set for this issue/CL (- for stdin'
                      ', + to load from local commit HEAD). Can not be used '
                      'with --edit-description, --message or --message-file.'
                      'if `-` is provided, force will be implicitly enabled.')
    parser.add_option('--git-completion-helper',
                      action="store_true",
                      help=optparse.SUPPRESS_HELP)
    parser.add_option('-o',
                      '--push-options',
                      action='append',
                      default=[],
                      help='Transmit the given string to the server when '
                      'performing git push (pass-through). See git-push '
                      'documentation for more details.')
    parser.add_option('--no-add-changeid',
                      action='store_true',
                      dest='no_add_changeid',
                      help='Do not add change-ids to messages.')
    parser.add_option('--cherry-pick-stacked',
                      '--cp',
                      dest='cherry_pick_stacked',
                      action='store_true',
                      help='If parent branch has un-uploaded updates, '
                      'automatically skip parent branches and just upload '
                      'the current branch cherry-pick on its parent\'s last '
                      'uploaded commit. Allows users to skip the potential '
                      'interactive confirmation step.')
    # TODO(b/265929888): Add --wip option of --cl-status option.

    orig_args = args
    (options, args) = parser.parse_args(args)

    if options.git_completion_helper:
        print(' '.join(opt.get_opt_string() for opt in parser.option_list
                       if opt.help != optparse.SUPPRESS_HELP))
        return

    cl = Changelist(branchref=options.target_branch)

    # Do a quick RPC to Gerrit to ensure that our authentication is all working
    # properly. Otherwise `git cl upload` will:
    #   * run `git status` (slow for large repos)
    #   * run presubmit tests (likely slow)
    #   * ask the user to edit the CL description (requires thinking)
    #
    # And then attempt to push the change up to Gerrit, which can fail if
    # authentication is not working properly.
    gerrit_util.GetAccountDetails(cl.GetGerritHost())

    # Check whether git should be updated.
    recommendation = git_common.check_git_version()
    if recommendation:
        print(colorama.Fore.RED)
        print(f'WARNING: {recommendation}')
        print(colorama.Style.RESET_ALL)

    # TODO(crbug.com/1475405): Warn users if the project uses submodules and
    # they have fsmonitor enabled.
    if os.path.isfile('.gitmodules'):
        git_common.warn_submodule()

    if git_common.is_dirty_git_tree('upload'):
        return 1

    options.reviewers = cleanup_list(options.reviewers)
    options.cc = cleanup_list(options.cc)

    if options.edit_description and options.force:
        parser.error('Only one of --force and --edit-description allowed')

    if options.edit_description and options.commit_description:
        parser.error('Only one of --commit-description and --edit-description '
                     'allowed')

    if options.message and options.commit_description:
        parser.error('Only one of --commit-description and --message allowed')

    if options.commit_description and options.commit_description == '-':
        options.force = True

    if options.message_file:
        if options.message:
            parser.error('Only one of --message and --message-file allowed.')
        if options.commit_description:
            parser.error('Only one of --commit-description and --message-file '
                         'allowed.')
        options.message = gclient_utils.FileRead(options.message_file)

    if ([options.cq_dry_run, options.use_commit_queue, options.retry_failed
         ].count(True) > 1):
        parser.error('Only one of --use-commit-queue, --cq-dry-run or '
                     '--retry-failed is allowed.')

    if options.skip_title and options.title:
        parser.error('Only one of --title and --skip-title allowed.')

    if options.use_commit_queue:
        options.send_mail = True

    if options.squash is None:
        # Load default for user, repo, squash=true, in this order.
        options.squash = settings.GetSquashGerritUploads()

    # Warm change details cache now to avoid RPCs later, reducing latency for
    # developers.
    if cl.GetIssue():
        cl._GetChangeDetail([
            'DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS'
        ])

    if options.retry_failed and not cl.GetIssue():
        print('No previous patchsets, so --retry-failed has no effect.')
        options.retry_failed = False

    if options.squash:
        if options.cherry_pick_stacked:
            try:
                orig_args.remove('--cherry-pick-stacked')
            except ValueError:
                orig_args.remove('--cp')
        UploadAllSquashed(options, orig_args)
        if options.dependencies:
            orig_args.remove('--dependencies')
            if not cl.GetIssue():
                # UploadAllSquashed stored an issue number for cl, but it
                # doesn't have access to cl object. By unsetting lookedup_issue,
                # we force code path that will read issue from the config.
                cl.lookedup_issue = False
            return upload_branch_deps(cl, orig_args, options.force)
        return 0
    if options.cherry_pick_stacked:
        parser.error(
            '--cherry-pick-stacked is not available without squash=true,')

    # cl.GetMostRecentPatchset uses cached information, and can return the last
    # patchset before upload. Calling it here makes it clear that it's the
    # last patchset before upload. Note that GetMostRecentPatchset will fail
    # if no CL has been uploaded yet.
    if options.retry_failed:
        patchset = cl.GetMostRecentPatchset()

    ret = cl.CMDUpload(options, args, orig_args)

    if options.retry_failed:
        if ret != 0:
            print('Upload failed, so --retry-failed has no effect.')
            return ret
        builds, _ = _fetch_latest_builds(cl,
                                         DEFAULT_BUILDBUCKET_HOST,
                                         latest_patchset=patchset)
        jobs = _filter_failed_for_retry(builds)
        if len(jobs) == 0:
            print('No failed tryjobs, so --retry-failed has no effect.')
            return ret
        _trigger_tryjobs(cl, jobs, options, patchset + 1)

    return ret


def UploadAllSquashed(options: optparse.Values,
                      orig_args: Sequence[str]) -> int:
    """Uploads the current and upstream branches (if necessary)."""
    cls, cherry_pick_current = _UploadAllPrecheck(options, orig_args)

    # Create commits.
    uploads_by_cl: List[Tuple[Changelist, _NewUpload]] = []
    if cherry_pick_current:
        parent = cls[1]._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
        new_upload = cls[0].PrepareCherryPickSquashedCommit(options, parent)
        uploads_by_cl.append((cls[0], new_upload))
    else:
        ordered_cls = list(reversed(cls))

        cl = ordered_cls[0]
        # We can only support external changes when we're only uploading one
        # branch.
        parent: Optional[str] = cl._UpdateWithExternalChanges() if len(
            ordered_cls) == 1 else None
        orig_parent: Optional[str] = None
        if parent is None:
            origin = '.'
            branch = cl.GetBranch()

            while origin == '.':
                # Search for cl's closest ancestor with a gerrit hash.
                origin, upstream_branch_ref = Changelist.FetchUpstreamTuple(
                    branch)
                if origin == '.':
                    upstream_branch = scm.GIT.ShortBranchName(
                        upstream_branch_ref)

                    # Support the `git merge` and `git pull` workflow.
                    if upstream_branch in ['master', 'main']:
                        parent = cl.GetCommonAncestorWithUpstream()
                    else:
                        orig_parent = scm.GIT.GetBranchConfig(
                            settings.GetRoot(), upstream_branch,
                            LAST_UPLOAD_HASH_CONFIG_KEY)
                        parent = scm.GIT.GetBranchConfig(
                            settings.GetRoot(), upstream_branch,
                            GERRIT_SQUASH_HASH_CONFIG_KEY)
                    if parent:
                        break
                    branch = upstream_branch
            else:
                # Either the root of the tree is the cl's direct parent and the
                # while loop above only found empty branches between cl and the
                # root of the tree.
                parent = cl.GetCommonAncestorWithUpstream()

        if orig_parent is None:
            orig_parent = parent
        for i, cl in enumerate(ordered_cls):
            # If we're in the middle of the stack, set end_commit to
            # downstream's direct ancestor.
            if i + 1 < len(ordered_cls):
                child_base_commit = ordered_cls[
                    i + 1].GetCommonAncestorWithUpstream()
            else:
                child_base_commit = None
            new_upload = cl.PrepareSquashedCommit(options,
                                                  parent,
                                                  orig_parent,
                                                  end_commit=child_base_commit)
            uploads_by_cl.append((cl, new_upload))
            parent = new_upload.commit_to_push
            orig_parent = child_base_commit

    # Create refspec options
    cl, new_upload = uploads_by_cl[-1]
    refspec_opts = cl._GetRefSpecOptions(
        options,
        new_upload.change_desc,
        multi_change_upload=len(uploads_by_cl) > 1,
        dogfood_path=True)
    refspec_suffix = ''
    if refspec_opts:
        refspec_suffix = '%' + ','.join(refspec_opts)
        assert ' ' not in refspec_suffix, (
            'spaces not allowed in refspec: "%s"' % refspec_suffix)

    remote, remote_branch = cl.GetRemoteBranch()
    branch = GetTargetRef(remote, remote_branch, options.target_branch)
    refspec = '%s:refs/for/%s%s' % (new_upload.commit_to_push, branch,
                                    refspec_suffix)

    # Git push
    git_push_metadata = {
        'gerrit_host':
        cl.GetGerritHost(),
        'title':
        options.title or '<untitled>',
        'change_id':
        git_footers.get_footer_change_id(new_upload.change_desc.description),
        'description':
        new_upload.change_desc.description,
    }
    push_stdout = cl._RunGitPushWithTraces(refspec, refspec_opts,
                                           git_push_metadata,
                                           options.push_options)

    # Post push updates
    regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
    change_numbers = [
        m.group(1) for m in map(regex.match, push_stdout.splitlines()) if m
    ]

    for i, (cl, new_upload) in enumerate(uploads_by_cl):
        cl.PostUploadUpdates(options, new_upload, change_numbers[i])

    return 0


def _UploadAllPrecheck(
        options: optparse.Values,
        orig_args: Sequence[str]) -> Tuple[Sequence[Changelist], bool]:
    """Checks the state of the tree and gives the user uploading options

    Returns: A tuple of the ordered list of changes that have new commits
        since their last upload and a boolean of whether the user wants to
        cherry-pick and upload the current branch instead of uploading all cls.
    """
    cl = Changelist()
    if cl.GetBranch() is None:
        DieWithError(_NO_BRANCH_ERROR)

    branch_ref = None
    cls: List[Changelist] = []
    must_upload_upstream = False
    first_pass = True

    Changelist._GerritCommitMsgHookCheck(offer_removal=not options.force)

    while True:
        if len(cls) > _MAX_STACKED_BRANCHES_UPLOAD:
            DieWithError(
                'More than %s branches in the stack have not been uploaded.\n'
                'Are your branches in a misconfigured state?\n'
                'If not, please upload some upstream changes first.' %
                (_MAX_STACKED_BRANCHES_UPLOAD))

        cl = Changelist(branchref=branch_ref)

        # Only add CL if it has anything to commit.
        base_commit = cl.GetCommonAncestorWithUpstream()
        end_commit = RunGit(['rev-parse', cl.GetBranchRef()]).strip()

        commit_summary = _GetCommitCountSummary(base_commit, end_commit)
        if commit_summary:
            cls.append(cl)
            if (not first_pass and
                    cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
                    is None):
                # We are mid-stack and the user must upload their upstream
                # branches.
                must_upload_upstream = True
            print(f'Found change with {commit_summary}...')
        elif first_pass:  # The current branch has nothing to commit. Exit.
            DieWithError('Branch %s has nothing to commit' % cl.GetBranch())
        # Else: A mid-stack branch has nothing to commit. We do not add it to
        # cls.
        first_pass = False

        # Cases below determine if we should continue to traverse up the tree.
        origin, upstream_branch_ref = Changelist.FetchUpstreamTuple(
            cl.GetBranch())
        branch_ref = upstream_branch_ref  # set branch for next run.

        upstream_branch = scm.GIT.ShortBranchName(upstream_branch_ref)
        upstream_last_upload = scm.GIT.GetBranchConfig(
            settings.GetRoot(), upstream_branch, LAST_UPLOAD_HASH_CONFIG_KEY)

        # Case 1: We've reached the beginning of the tree.
        if origin != '.':
            break

        # Case 2: If any upstream branches have never been uploaded,
        # the user MUST upload them unless they are empty. Continue to
        # next loop to add upstream if it is not empty.
        if not upstream_last_upload:
            continue

        # Case 3: If upstream's last_upload == cl.base_commit we do
        # not need to upload any more upstreams from this point on.
        # (Even if there may be diverged branches higher up the tree)
        if base_commit == upstream_last_upload:
            break

        # Case 4: If upstream's last_upload < cl.base_commit we are
        # uploading cl and upstream_cl.
        # Continue up the tree to check other branch relations.
        if scm.GIT.IsAncestor(upstream_last_upload, base_commit):
            continue

        # Case 5: If cl.base_commit < upstream's last_upload the user
        # must rebase before uploading.
        if scm.GIT.IsAncestor(base_commit, upstream_last_upload):
            DieWithError(
                'At least one branch in the stack has diverged from its upstream '
                'branch and does not contain its upstream\'s last upload.\n'
                'Please rebase the stack with `git rebase-update` before uploading.'
            )

        # The tree went through a rebase. LAST_UPLOAD_HASH_CONFIG_KEY no longer
        # has any relation to commits in the tree. Continue up the tree until we
        # hit the root.

    # We assume all cls in the stack have the same auth requirements and only
    # check this once.
    cls[0].EnsureAuthenticated(force=options.force)

    cherry_pick = False
    if len(cls) > 1:
        opt_message = ''
        branches = ', '.join([cl.branch for cl in cls])
        if len(orig_args):
            opt_message = ('options %s will be used for all uploads.\n' %
                           orig_args)
        if must_upload_upstream:
            msg = ('At least one parent branch in `%s` has never been uploaded '
                   'and must be uploaded before/with `%s`.\n' %
                   (branches, cls[1].branch))
            if options.cherry_pick_stacked:
                DieWithError(msg)
            if not options.force:
                confirm_or_exit('\n' + opt_message + msg)
        else:
            if options.cherry_pick_stacked:
                print('cherry-picking `%s` on %s\'s last upload' %
                      (cls[0].branch, cls[1].branch))
                cherry_pick = True
            elif not options.force:
                answer = gclient_utils.AskForData(
                    '\n' + opt_message +
                    'Press enter to update branches %s.\nOr type `n` to upload only '
                    '`%s` cherry-picked on %s\'s last upload:' %
                    (branches, cls[0].branch, cls[1].branch))
                if answer.lower() == 'n':
                    cherry_pick = True
    return cls, cherry_pick


@subcommand.usage('--description=<description file>')
@metrics.collector.collect_metrics('git cl split')
def CMDsplit(parser, args):
    """Splits a branch into smaller branches and uploads CLs.

    Creates a branch and uploads a CL for each group of files modified in the
    current branch that share a common OWNERS file. In the CL description and
    comment, the string '$directory' or '$description', is replaced with the
    directory containing the shared OWNERS file.
    """
    if gclient_utils.IsEnvCog():
        print('split command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    parser.add_option('-d',
                      '--description',
                      dest='description_file',
                      help='A text file containing a CL description, in which '
                      'the string $description will be replaced by a '
                      'description of each generated CL (by default, the list '
                      'of directories that CL covers). '
                      'Mandatory except in dry runs.\n'
                      'Usage of the string $directory instead of $description '
                      'is deprecated, and will be removed in the future.')
    parser.add_option('-c',
                      '--comment',
                      dest='comment_file',
                      help='A text file containing a CL comment.')
    parser.add_option(
        '-n',
        '--dry-run',
        dest='dry_run',
        action='store_true',
        default=False,
        help='List the files and reviewers for each CL that would '
        'be created, but don\'t create branches or CLs.\n'
        'You can pass -s in addition to get a more concise summary.')
    parser.add_option('--cq-dry-run',
                      action='store_true',
                      default=False,
                      help='If set, will do a cq dry run for each uploaded CL. '
                      'Please be careful when doing this; more than ~10 CLs '
                      'has the potential to overload our build '
                      'infrastructure. Try to upload these not during high '
                      'load times (usually 11-3 Mountain View time). Email '
                      'infra-dev@chromium.org with any questions.')
    parser.add_option(
        '-a',
        '--auto-submit',
        '--enable-auto-submit',
        action='store_true',
        dest='enable_auto_submit',
        default=True,
        help='Sends your change to the CQ after an approval. Only '
        'works on repos that have the Auto-Submit label '
        'enabled. This is the default option.')
    parser.add_option(
        '--disable-auto-submit',
        action='store_false',
        dest='enable_auto_submit',
        help='Disables automatic sending of the changes to the CQ '
        'after approval. Note that auto-submit only works for '
        'repos that have the Auto-Submit label enabled.')
    parser.add_option(
        '--max-depth',
        type='int',
        default=0,
        help='The max depth to look for OWNERS files. '
        'Controls the granularity of CL splitting by limiting the depth at '
        'which the script searches for OWNERS files. '
        'e.g. let\'s consider file a/b/c/d/e.cc. Without this flag, the '
        'OWNERS file in a/b/c/d/ would be used. '
        'With --max-depth=2, the OWNERS file in a/b/ would be used. '
        'If the OWNERS file is missing in this folder, the first OWNERS file '
        'found in parents is used. '
        'Lower values of --max-depth result in fewer, larger CLs. Higher values '
        'produce more, smaller CLs.')
    parser.add_option('--topic',
                      default=None,
                      help='Topic to specify when uploading')
    parser.add_option(
        '--target-range',
        type='int',
        default=None,
        nargs=2,
        help='Usage: --target-range <min> <max>\n                  '
        'Use the alternate splitting algorithm which tries '
        'to ensure each CL has between <min> and <max> files, inclusive. '
        'Rarely, some CLs may have fewer files than specified.')
    parser.add_option('--from-file',
                      type='str',
                      default=None,
                      help='If present, load the split CLs from the given file '
                      'instead of computing a splitting. These files are '
                      'generated each time the script is run.')
    parser.add_option(
        '-s',
        '--summarize',
        action='store_true',
        default=False,
        help='If passed during a dry run, will print out a summary of the '
        'generated splitting, rather than full details. No effect outside of '
        'a dry run.')
    # If we ever switch from optparse to argparse, we can combine these flags
    # using nargs='*'
    parser.add_option(
        '--reviewers',
        action='append',
        default=None,
        help='If present, all generated CLs will be sent to the specified '
        'reviewer(s) specified, rather than automatically assigned reviewers.\n'
        'Multiple reviewers can be specified as:                               '
        '--reviewers a@b.com --reviewers c@d.com\n')
    parser.add_option(
        '--no-reviewers',
        action='store_true',
        help='If present, generated CLs will not be assigned reviewers. '
        'Overrides --reviewers.')
    parser.add_option(
        '--expect-owners-override',
        action='store_true',
        help='If present, the clustering algorithm will group files by '
        'directory only, without considering ownership.\n'
        'No effect if --target-range is not passed.\n'
        'Recommended to be used alongside --reviewers or --no-reviewers.')
    options, _ = parser.parse_args(args)

    if not options.description_file and not options.dry_run:
        parser.error('No --description flag specified.')

    if (options.target_range
            and options.target_range[0] > options.target_range[1]):
        parser.error('First argument to --target-range cannot '
                     'be greater than the second argument.')

    if options.no_reviewers:
        options.reviewers = []

    def WrappedCMDupload(args):
        return CMDupload(OptionParser(), args)

    return split_cl.SplitCl(options.description_file, options.comment_file,
                            Changelist, WrappedCMDupload, options.dry_run,
                            options.summarize, options.reviewers,
                            options.cq_dry_run, options.enable_auto_submit,
                            options.max_depth, options.topic,
                            options.target_range,
                            options.expect_owners_override, options.from_file,
                            settings.GetRoot())


@subcommand.usage('DEPRECATED')
@metrics.collector.collect_metrics('git cl commit')
def CMDdcommit(parser, args):
    """DEPRECATED: Used to commit the current changelist via git-svn."""
    message = ('git-cl no longer supports committing to SVN repositories via '
               'git-svn. You probably want to use `git cl land` instead.')
    print(message)
    return 1


@subcommand.usage('[upstream branch to apply against]')
@metrics.collector.collect_metrics('git cl land')
def CMDland(parser, args):
    """Commits the current changelist via git.

    In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes
    upstream and closes the issue automatically and atomically.
    """
    if gclient_utils.IsEnvCog():
        print(
            'land command is not supported. Please go to the Gerrit CL '
            'directly to submit the CL',
            file=sys.stderr)
        return 1

    parser.add_option('--bypass-hooks',
                      action='store_true',
                      dest='bypass_hooks',
                      help='bypass upload presubmit hook')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      dest='force',
                      help="force yes to questions (don't prompt)")
    parser.add_option(
        '--parallel',
        action='store_true',
        help='Run all tests specified by input_api.RunTests in all '
        'PRESUBMIT files in parallel.')
    parser.add_option('--resultdb',
                      action='store_true',
                      help='Run presubmit checks in the ResultSink environment '
                      'and send results to the ResultDB database.')
    parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
    (options, args) = parser.parse_args(args)

    cl = Changelist()

    if not cl.GetIssue():
        DieWithError('You must upload the change first to Gerrit.\n'
                     '  If you would rather have `git cl land` upload '
                     'automatically for you, see http://crbug.com/642759')
    return cl.CMDLand(options.force, options.bypass_hooks, options.verbose,
                      options.parallel, options.resultdb, options.realm)


@subcommand.usage('<patch url or issue id or issue url>')
@metrics.collector.collect_metrics('git cl patch')
def CMDpatch(parser, args):
    """Applies (cherry-picks) a Gerrit changelist locally."""
    if gclient_utils.IsEnvCog():
        print(
            'patch command is not supported. Please create a new workspace '
            'from the Gerrit CL directly',
            file=sys.stderr)
        return 1

    parser.add_option('-b',
                      '--branch',
                      dest='newbranch',
                      help='create a new branch off trunk for the patch')
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      help='overwrite state on the current or chosen branch')
    parser.add_option('-n',
                      '--no-commit',
                      action='store_true',
                      dest='nocommit',
                      help='don\'t commit after patch applies.')

    group = optparse.OptionGroup(
        parser,
        'Options for continuing work on the current issue uploaded from a '
        'different clone (e.g. different machine). Must be used independently '
        'from the other options. No issue number should be specified, and the '
        'branch must have an issue number associated with it')
    group.add_option('--reapply',
                     action='store_true',
                     dest='reapply',
                     help='Reset the branch and reapply the issue.\n'
                     'CAUTION: This will undo any local changes in this '
                     'branch')

    group.add_option('--pull',
                     action='store_true',
                     dest='pull',
                     help='Performs a pull before reapplying.')
    parser.add_option_group(group)

    (options, args) = parser.parse_args(args)

    if options.reapply:
        if options.newbranch:
            parser.error('--reapply works on the current branch only.')
        if len(args) > 0:
            parser.error('--reapply implies no additional arguments.')

        cl = Changelist()
        if not cl.GetIssue():
            parser.error('Current branch must have an associated issue.')

        upstream = cl.GetUpstreamBranch()
        if upstream is None:
            parser.error('No upstream branch specified. Cannot reset branch.')

        RunGit(['reset', '--hard', upstream])
        if options.pull:
            RunGit(['pull'])

        target_issue_arg = ParseIssueNumberArgument(cl.GetIssue())
        return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit,
                                          options.force)

    if len(args) != 1 or not args[0]:
        parser.error('Must specify issue number or URL.')

    target_issue_arg = ParseIssueNumberArgument(args[0])
    if not target_issue_arg.valid:
        parser.error('Invalid issue ID or URL.')

    # We don't want uncommitted changes mixed up with the patch.
    if git_common.is_dirty_git_tree('patch'):
        return 1

    if options.newbranch:
        if options.force:
            RunGit(['branch', '-D', options.newbranch],
                   stderr=subprocess2.PIPE,
                   error_ok=True)
        git_new_branch.create_new_branch(options.newbranch)

    cl = Changelist(codereview_host=target_issue_arg.hostname,
                    issue=target_issue_arg.issue)

    if not args[0].isdigit():
        print('canonical issue/change URL: %s\n' % cl.GetIssueURL())

    return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit,
                                      options.force)


def GetTreeStatus(url=None):
    """Fetches the tree status and returns either 'open', 'closed',
    'unknown' or 'unset'."""
    url = url or settings.GetTreeStatusUrl(error_ok=True)
    if url:
        status = str(urllib.request.urlopen(url).read().lower())
        if status.find('closed') != -1 or status == '0':
            return 'closed'

        if status.find('open') != -1 or status == '1':
            return 'open'

        return 'unknown'
    return 'unset'


def GetTreeStatusReason():
    """Fetches the tree status from a json url and returns the message
    with the reason for the tree to be opened or closed."""
    url = settings.GetTreeStatusUrl()
    json_url = urllib.parse.urljoin(url, '/current?format=json')
    connection = urllib.request.urlopen(json_url)
    status = json.loads(connection.read())
    connection.close()
    return status['message']


@metrics.collector.collect_metrics('git cl tree')
def CMDtree(parser, args):
    """Shows the status of the tree."""
    if gclient_utils.IsEnvCog():
        print(
            'tree command is not supported. Please go to the tree '
            'status UI to check the status of the tree directly.',
            file=sys.stderr)
        return 1

    _, args = parser.parse_args(args)
    status = GetTreeStatus()
    if 'unset' == status:
        print(
            'You must configure your tree status URL by running "git cl config".'
        )
        return 2

    print('The tree is %s' % status)
    print()
    print(GetTreeStatusReason())
    if status != 'open':
        return 1
    return 0


@metrics.collector.collect_metrics('git cl try')
def CMDtry(parser, args):
    """Triggers tryjobs using either Buildbucket or CQ dry run."""
    if gclient_utils.IsEnvCog():
        print(
            'try command is not supported. Please go to the Gerrit CL '
            'page to trigger individual builds or CQ dry run.',
            file=sys.stderr)
        return 1

    group = optparse.OptionGroup(parser, 'Tryjob options')
    group.add_option(
        '-b',
        '--bot',
        action='append',
        help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple '
              'times to specify multiple builders. ex: '
              '"-b win_rel -b win_layout". See '
              'the try server waterfall for the builders name and the tests '
              'available.'))
    group.add_option(
        '-B',
        '--bucket',
        default='',
        help=('Buildbucket bucket to send the try requests. Format: '
              '"luci.$LUCI_PROJECT.$LUCI_BUCKET". eg: "luci.chromium.try"'))
    group.add_option(
        '-r',
        '--revision',
        help='Revision to use for the tryjob; default: the revision will '
        'be determined by the try recipe that builder runs, which usually '
        'defaults to HEAD of origin/master or origin/main')
    group.add_option('--category',
                     default='git_cl_try',
                     help='Specify custom build category.')
    group.add_option(
        '--project',
        help='Override which project to use. Projects are defined '
        'in recipe to determine to which repository or directory to '
        'apply the patch')
    group.add_option(
        '-p',
        '--property',
        dest='properties',
        action='append',
        default=[],
        help='Specify generic properties in the form -p key1=value1 -p '
        'key2=value2 etc. The value will be treated as '
        'json if decodable, or as string otherwise. '
        'NOTE: using this may make your tryjob not usable for CQ, '
        'which will then schedule another tryjob with default properties')
    group.add_option('--buildbucket-host',
                     default='cr-buildbucket.appspot.com',
                     help='Host of buildbucket. The default host is %default.')
    parser.add_option_group(group)
    parser.add_option('-R',
                      '--retry-failed',
                      action='store_true',
                      default=False,
                      help='Retry failed jobs from the latest set of tryjobs. '
                      'Not allowed with --bucket and --bot options.')
    parser.add_option(
        '-i',
        '--issue',
        type=int,
        help='Operate on this issue instead of the current branch\'s implicit '
        'issue.')
    options, args = parser.parse_args(args)

    # Make sure that all properties are prop=value pairs.
    bad_params = [x for x in options.properties if '=' not in x]
    if bad_params:
        parser.error('Got properties with missing "=": %s' % bad_params)

    if args:
        parser.error('Unknown arguments: %s' % args)

    cl = Changelist(issue=options.issue)
    if not cl.GetIssue():
        parser.error('Need to upload first.')

    # HACK: warm up Gerrit change detail cache to save on RPCs.
    cl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS'])

    error_message = cl.CannotTriggerTryJobReason()
    if error_message:
        parser.error('Can\'t trigger tryjobs: %s' % error_message)

    if options.bot:
        if options.retry_failed:
            parser.error('--bot is not compatible with --retry-failed.')
        if not options.bucket:
            parser.error('A bucket (e.g. "chromium/try") is required.')

        triggered = [b for b in options.bot if 'triggered' in b]
        if triggered:
            parser.error(
                'Cannot schedule builds on triggered bots: %s.\n'
                'This type of bot requires an initial job from a parent (usually a '
                'builder). Schedule a job on the parent instead.\n' % triggered)

        if options.bucket.startswith('.master'):
            parser.error('Buildbot masters are not supported.')

        project, bucket = _parse_bucket(options.bucket)
        if project is None or bucket is None:
            parser.error('Invalid bucket: %s.' % options.bucket)
        jobs = sorted((project, bucket, bot) for bot in options.bot)
    elif options.retry_failed:
        print('Searching for failed tryjobs...')
        builds, patchset = _fetch_latest_builds(cl, DEFAULT_BUILDBUCKET_HOST)
        if options.verbose:
            print('Got %d builds in patchset #%d' % (len(builds), patchset))
        jobs = _filter_failed_for_retry(builds)
        if not jobs:
            print('There are no failed jobs in the latest set of jobs '
                  '(patchset #%d), doing nothing.' % patchset)
            return 0
        num_builders = len(jobs)
        if num_builders > 10:
            confirm_or_exit('There are %d builders with failed builds.' %
                            num_builders,
                            action='continue')
    else:
        if options.verbose:
            print('git cl try with no bots now defaults to CQ dry run.')
        print('Scheduling CQ dry run on: %s' % cl.GetIssueURL())
        return cl.SetCQState(_CQState.DRY_RUN)

    patchset = cl.GetMostRecentPatchset()
    try:
        _trigger_tryjobs(cl, jobs, options, patchset)
    except BuildbucketResponseException as ex:
        print('ERROR: %s' % ex)
        return 1
    return 0


@metrics.collector.collect_metrics('git cl try-results')
def CMDtry_results(parser, args):
    """Prints info about results for tryjobs associated with the current CL."""
    if gclient_utils.IsEnvCog():
        print(
            'try-results command is not supported. Please go to the Gerrit '
            'CL page to see the tryjob results instead.',
            file=sys.stderr)
        return 1

    group = optparse.OptionGroup(parser, 'Tryjob results options')
    group.add_option('-p',
                     '--patchset',
                     type=int,
                     help='patchset number if not current.')
    group.add_option('--print-master',
                     action='store_true',
                     help='print master name as well.')
    group.add_option('--color',
                     action='store_true',
                     default=setup_color.IS_TTY,
                     help='force color output, useful when piping output.')
    group.add_option('--buildbucket-host',
                     default='cr-buildbucket.appspot.com',
                     help='Host of buildbucket. The default host is %default.')
    group.add_option(
        '--json',
        help=('Path of JSON output file to write tryjob results to,'
              'or "-" for stdout.'))
    parser.add_option_group(group)
    parser.add_option(
        '-i',
        '--issue',
        type=int,
        help='Operate on this issue instead of the current branch\'s implicit '
        'issue.')
    options, args = parser.parse_args(args)
    if args:
        parser.error('Unrecognized args: %s' % ' '.join(args))

    cl = Changelist(issue=options.issue)
    if not cl.GetIssue():
        parser.error('Need to upload first.')

    patchset = options.patchset
    if not patchset:
        patchset = cl.GetMostRecentDryRunPatchset()
        if not patchset:
            parser.error('Code review host doesn\'t know about issue %s. '
                         'No access to issue or wrong issue number?\n'
                         'Either upload first, or pass --patchset explicitly.' %
                         cl.GetIssue())

    try:
        jobs = _fetch_tryjobs(cl, DEFAULT_BUILDBUCKET_HOST, patchset)
    except BuildbucketResponseException as ex:
        print('Buildbucket error: %s' % ex)
        return 1
    if options.json:
        write_json(options.json, jobs)
    else:
        _print_tryjobs(options, jobs)
    return 0


@subcommand.usage('[new upstream branch]')
@metrics.collector.collect_metrics('git cl upstream')
def CMDupstream(parser, args):
    """Prints or sets the name of the upstream branch, if any."""
    if gclient_utils.IsEnvCog():
        print('upstream command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    _, args = parser.parse_args(args)
    if len(args) > 1:
        parser.error('Unrecognized args: %s' % ' '.join(args))

    cl = Changelist()
    if args:
        # One arg means set upstream branch.
        branch = cl.GetBranch()
        RunGit(['branch', '--set-upstream-to', args[0], branch])
        # Clear configured merge-base, if there is one.
        git_common.remove_merge_base(branch)
        cl = Changelist()
        print('Upstream branch set to %s' % (cl.GetUpstreamBranch(), ))
    else:
        print(cl.GetUpstreamBranch())
    return 0


@metrics.collector.collect_metrics('git cl web')
def CMDweb(parser, args):
    """Opens the current CL in the web browser."""
    if gclient_utils.IsEnvCog():
        print(
            'web command is not supported in non-git environment. Please use '
            '"Gerrit: Open Changes in Gerrit" functionality in the command '
            'palette in the editor instead.',
            file=sys.stderr)
        return 1

    parser.add_option('-p',
                      '--print-only',
                      action='store_true',
                      dest='print_only',
                      help='Only print the Gerrit URL, don\'t open it in the '
                      'browser.')
    (options, args) = parser.parse_args(args)
    if args:
        parser.error('Unrecognized args: %s' % ' '.join(args))

    issue_url = Changelist().GetIssueURL()
    if not issue_url:
        print('ERROR No issue to open', file=sys.stderr)
        return 1

    if options.print_only:
        print(issue_url)
        return 0

    # Redirect I/O before invoking browser to hide its output. For example, this
    # allows us to hide the "Created new window in existing browser session."
    # message from Chrome. Based on https://stackoverflow.com/a/2323563.
    saved_stdout = os.dup(1)
    saved_stderr = os.dup(2)
    os.close(1)
    os.close(2)
    os.open(os.devnull, os.O_RDWR)
    try:
        webbrowser.open(issue_url)
    finally:
        os.dup2(saved_stdout, 1)
        os.dup2(saved_stderr, 2)
    return 0


@metrics.collector.collect_metrics('git cl set-commit')
def CMDset_commit(parser, args):
    """Sets the commit bit to trigger the CQ."""
    if gclient_utils.IsEnvCog():
        print(
            'set-commit command is not supported. Please go to the Gerrit CL '
            'page directly to submit the CL.',
            file=sys.stderr)
        return 1

    parser.add_option('-d',
                      '--dry-run',
                      action='store_true',
                      help='trigger in dry run mode')
    parser.add_option('-c',
                      '--clear',
                      action='store_true',
                      help='stop CQ run, if any')
    parser.add_option(
        '-i',
        '--issue',
        type=int,
        help='Operate on this issue instead of the current branch\'s implicit '
        'issue.')
    options, args = parser.parse_args(args)
    if args:
        parser.error('Unrecognized args: %s' % ' '.join(args))
    if [options.dry_run, options.clear].count(True) > 1:
        parser.error('Only one of --dry-run, and --clear are allowed.')

    cl = Changelist(issue=options.issue)
    if not cl.GetIssue():
        parser.error('Must upload the issue first.')

    if options.clear:
        state = _CQState.NONE
    elif options.dry_run:
        state = _CQState.DRY_RUN
    else:
        state = _CQState.COMMIT
    cl.SetCQState(state)
    return 0


@metrics.collector.collect_metrics('git cl set-close')
def CMDset_close(parser, args):
    """Closes the issue."""
    if gclient_utils.IsEnvCog():
        print(
            'set-close command is not supported. Please go to the Gerrit CL '
            'page to abandon the CL instead.',
            file=sys.stderr)
        return 1

    parser.add_option(
        '-i',
        '--issue',
        type=int,
        help='Operate on this issue instead of the current branch\'s implicit '
        'issue.')
    options, args = parser.parse_args(args)
    if args:
        parser.error('Unrecognized args: %s' % ' '.join(args))
    cl = Changelist(issue=options.issue)
    # Ensure there actually is an issue to close.
    if not cl.GetIssue():
        DieWithError('ERROR: No issue to close.')
    cl.CloseIssue()
    return 0


@metrics.collector.collect_metrics('git cl diff')
def CMDdiff(parser, args):
    """Shows differences between local tree and last upload."""
    if gclient_utils.IsEnvCog():
        print(
            'diff command is not supported. Please navigate to source '
            'control view in the activity bar to check the diff.',
            file=sys.stderr)
        return 1

    parser.add_option('--stat',
                      action='store_true',
                      dest='stat',
                      help='Generate a diffstat')
    options, args = parser.parse_args(args)
    if args:
        parser.error('Unrecognized args: %s' % ' '.join(args))

    cl = Changelist()
    issue = cl.GetIssue()
    branch = cl.GetBranch()
    if not issue:
        DieWithError('No issue found for current branch (%s)' % branch)

    base = cl._GitGetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY)
    if not base:
        base = cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
    if not base:
        detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
        revision_info = detail['revisions'][detail['current_revision']]
        fetch_info = revision_info['fetch']['http']
        RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
        base = 'FETCH_HEAD'

    cmd = ['git', 'diff']
    if options.stat:
        cmd.append('--stat')
    cmd.append(base)
    subprocess2.check_call(cmd)

    return 0


@metrics.collector.collect_metrics('git cl owners')
def CMDowners(parser, args):
    """Finds potential owners for reviewing."""
    if gclient_utils.IsEnvCog():
        print('owners command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    parser.add_option(
        '--ignore-current',
        action='store_true',
        help='Ignore the CL\'s current reviewers and start from scratch.')
    parser.add_option('--ignore-self',
                      action='store_true',
                      help='Do not consider CL\'s author as an owners.')
    parser.add_option('--no-color',
                      action='store_true',
                      help='Use this option to disable color output')
    parser.add_option('--batch',
                      action='store_true',
                      help='Do not run interactively, just suggest some')
    # TODO: Consider moving this to another command, since other
    #       git-cl owners commands deal with owners for a given CL.
    parser.add_option('--show-all',
                      action='store_true',
                      help='Show all owners for a particular file')
    options, args = parser.parse_args(args)

    cl = Changelist()
    author = cl.GetAuthor()

    if options.show_all:
        if len(args) == 0:
            print('No files specified for --show-all. Nothing to do.')
            return 0
        owners_by_path = cl.owners_client.BatchListOwners(args)
        for path in args:
            print('Owners for %s:' % path)
            print('\n'.join(
                ' - %s' % owner
                for owner in owners_by_path.get(path, ['No owners found'])))
        return 0

    if args:
        if len(args) > 1:
            parser.error('Unknown args.')
        base_branch = args[0]
    else:
        # Default to diffing against the common ancestor of the upstream branch.
        base_branch = cl.GetCommonAncestorWithUpstream()

    affected_files = cl.GetAffectedFiles(base_branch)

    if options.batch:
        owners = cl.owners_client.SuggestOwners(affected_files,
                                                exclude=[author])
        print('\n'.join(owners))
        return 0

    return owners_finder.OwnersFinder(
        affected_files,
        author, [] if options.ignore_current else cl.GetReviewers(),
        cl.owners_client,
        disable_color=options.no_color,
        ignore_author=options.ignore_self).run()


def _SplitArgsByCmdLineLimit(args):
    """Splits a list of arguments into shorter lists that fit within the command
    line limit."""
    # The maximum command line length is 32768 characters on Windows and 2097152
    # characters on other platforms. Use a lower limit to be safe.
    command_line_limit = 30000 if sys.platform.startswith('win32') else 2000000

    batch_args = []
    batch_length = 0
    for arg in args:
        # Add 1 to account for the space between arguments.
        arg_length = len(arg) + 1
        # If the current argument is too long to fit in a single command line,
        # split it into smaller parts.
        if batch_length + arg_length > command_line_limit and batch_args:
            yield batch_args
            batch_args = []
            batch_length = 0

        batch_args.append(arg)
        batch_length += arg_length

    if batch_args:
        yield batch_args


def RunGitDiffCmd(diff_type,
                  upstream_commit,
                  files,
                  allow_prefix=False,
                  **kwargs):
    """Generates and runs diff command."""
    # Generate diff for the current branch's changes.
    diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff']

    if allow_prefix:
        # explicitly setting --src-prefix and --dst-prefix is necessary in the
        # case that diff.noprefix is set in the user's git config.
        diff_cmd += ['--src-prefix=a/', '--dst-prefix=b/']
    else:
        diff_cmd += ['--no-prefix']

    diff_cmd += diff_type
    diff_cmd += [upstream_commit, '--']

    if not files:
        return RunGit(diff_cmd, **kwargs)

    for file in files:
        if file != '-' and not os.path.isdir(file) and not os.path.isfile(file):
            DieWithError('Argument "%s" is not a file or a directory' % file)

    output = ''
    for files_batch in _SplitArgsByCmdLineLimit(files):
        output += RunGit(diff_cmd + files_batch, **kwargs)

    return output


def _RunClangFormatDiff(opts, clang_diff_files, top_dir, upstream_commit):
    """Runs clang-format-diff and sets a return value if necessary."""
    # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
    # formatted. This is used to block during the presubmit.
    return_value = 0

    # Locate the clang-format binary in the checkout
    try:
        clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
    except clang_format.NotFoundError as e:
        DieWithError(e)

    if opts.full:
        cmd = [clang_format_tool]
        if not opts.dry_run and not opts.diff:
            cmd.append('-i')
        if opts.dry_run:
            for diff_file in clang_diff_files:
                with open(diff_file, 'r') as myfile:
                    code = myfile.read().replace('\r\n', '\n')
                    stdout = RunCommand(cmd + [diff_file], cwd=top_dir)
                    stdout = stdout.replace('\r\n', '\n')
                    if opts.diff:
                        sys.stdout.write(stdout)
                    if code != stdout:
                        return_value = 2
        else:
            stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir)
            if opts.diff:
                sys.stdout.write(stdout)
    else:
        try:
            script = clang_format.FindClangFormatScriptInChromiumTree(
                'clang-format-diff.py')
        except clang_format.NotFoundError as e:
            DieWithError(e)

        cmd = ['vpython3', script, '-p0']
        if not opts.dry_run and not opts.diff:
            cmd.append('-i')

        diff_output = RunGitDiffCmd(['-U0'], upstream_commit, clang_diff_files)

        env = os.environ.copy()
        env['PATH'] = (str(os.path.dirname(clang_format_tool)) + os.pathsep +
                       env['PATH'])
        # If `clang-format-diff.py` is run without `-i` and the diff is
        # non-empty, it returns an error code of 1. This will cause `RunCommand`
        # to die with an error if `error_ok` is not set.
        stdout = RunCommand(cmd,
                            error_ok=True,
                            stdin=diff_output.encode(),
                            cwd=top_dir,
                            env=env,
                            shell=sys.platform.startswith('win32'))
        if opts.diff:
            sys.stdout.write(stdout)
        if opts.dry_run and len(stdout) > 0:
            return_value = 2

    return return_value


def _RunGoogleJavaFormat(opts, paths, top_dir, upstream_commit):
    """Runs google-java-format and sets a return value if necessary."""
    tool = google_java_format.FindGoogleJavaFormat()
    if tool is None:
        # Fail silently. It could be we are on an old chromium revision, or that
        # it is a non-chromium project. https://crbug.com/1491627
        print('google-java-format not found, skipping java formatting.')
        return 0

    base_cmd = [tool, '--aosp']
    if not opts.diff:
        if opts.dry_run:
            base_cmd += ['--dry-run']
        else:
            base_cmd += ['--replace']

    changed_lines_only = not opts.full
    if changed_lines_only:
        # Format two lines around each changed line so that the correct amount
        # of blank lines will be added between symbols.
        line_diffs = _ComputeFormatDiffLineRanges(paths,
                                                  upstream_commit,
                                                  expand=2)

    def RunFormat(cmd, path, range_args, **kwds):
        stdout = RunCommand(cmd + range_args + [path], **kwds)

        if changed_lines_only:
            # google-java-format will not remove unused imports because they
            # do not fall within the changed lines. Run the command again to
            # remove them.
            if opts.diff:
                stdout = RunCommand(cmd + ['--fix-imports-only', '-'],
                                    stdin=stdout.encode(),
                                    **kwds)
            else:
                stdout += RunCommand(cmd + ['--fix-imports-only', path], **kwds)

        # If --diff is passed, google-java-format will output formatted content.
        # Diff it with the existing file in the checkout and output the result.
        if opts.diff:
            stdout = RunGitDiffCmd(['-U3'],
                                   '--no-index', [path, '-'],
                                   stdin=stdout.encode(),
                                   **kwds)
        return stdout

    results = []
    kwds = {'error_ok': True, 'cwd': top_dir}
    with multiprocessing.pool.ThreadPool() as pool:
        for path in paths:
            cmd = base_cmd.copy()
            range_args = []
            if changed_lines_only:
                ranges = line_diffs.get(path)
                if not ranges:
                    # E.g. There were only deleted lines.
                    continue
                range_args = ['--lines={}:{}'.format(a, b) for a, b in ranges]

            results.append(
                pool.apply_async(RunFormat,
                                 args=[cmd, path, range_args],
                                 kwds=kwds))

        return_value = 0
        for result in results:
            stdout = result.get()
            if stdout:
                if opts.diff:
                    sys.stdout.write('Requires formatting: ' + stdout)
                if opts.dry_run:
                    return_value = 2

        return return_value


def _RunRustFmt(opts, rust_diff_files, top_dir, upstream_commit):
    """Runs rustfmt.  Just like _RunClangFormatDiff returns 2 to indicate that
    presubmit checks have failed (and returns 0 otherwise)."""
    # Locate the rustfmt binary.
    try:
        rustfmt_tool = rustfmt.FindRustfmtToolInChromiumTree()
    except rustfmt.NotFoundError as e:
        DieWithError(e)

    chromium_src_path = gclient_paths.GetPrimarySolutionPath()
    rustfmt_toml_path = os.path.join(chromium_src_path, '.rustfmt.toml')

    # TODO(crbug.com/1440869): Support formatting only the changed lines
    # if `opts.full or settings.GetFormatFullByDefault()` is False.
    cmd = [rustfmt_tool, f'--config-path={rustfmt_toml_path}']
    if opts.dry_run:
        cmd.append('--check')
    cmd += rust_diff_files
    rustfmt_exitcode = subprocess2.call(cmd)

    if opts.dry_run and rustfmt_exitcode != 0:
        return 2

    return 0


def _RunSwiftFormat(opts, swift_diff_files, top_dir, upstream_commit):
    """Runs swift-format.  Just like _RunClangFormatDiff returns 2 to indicate
    that presubmit checks have failed (and returns 0 otherwise)."""
    if sys.platform != 'darwin':
        DieWithError('swift-format is only supported on macOS.')
    # Locate the swift-format binary.
    try:
        swift_format_tool = swift_format.FindSwiftFormatToolInChromiumTree()
    except swift_format.NotFoundError as e:
        DieWithError(e)

    cmd = [swift_format_tool]
    if opts.dry_run:
        cmd += ['lint', '-s']
    else:
        cmd += ['format', '-i']
    cmd += swift_diff_files
    swift_format_exitcode = subprocess2.call(cmd)

    if opts.dry_run and swift_format_exitcode != 0:
        return 2

    return 0


def _RunYapf(opts, paths, top_dir, upstream_commit):
    depot_tools_path = os.path.dirname(os.path.abspath(__file__))
    yapf_tool = os.path.join(depot_tools_path, 'yapf')

    # Used for caching.
    yapf_configs = {}
    for p in paths:
        # Find the yapf style config for the current file, defaults to depot
        # tools default.
        _FindYapfConfigFile(p, yapf_configs, top_dir)

    # Turn on python formatting by default if a yapf config is specified.
    # This breaks in the case of this repo though since the specified
    # style file is also the global default.
    if opts.python is None:
        paths = [
            p for p in paths
            if _FindYapfConfigFile(p, yapf_configs, top_dir) is not None
        ]

    # Note: yapf still seems to fix indentation of the entire file
    # even if line ranges are specified.
    # See https://github.com/google/yapf/issues/499
    if not opts.full and paths:
        line_diffs = _ComputeFormatDiffLineRanges(paths, upstream_commit)

    yapfignore_patterns = _GetYapfIgnorePatterns(top_dir)
    paths = _FilterYapfIgnoredFiles(paths, yapfignore_patterns)

    return_value = 0
    for path in paths:
        yapf_style = _FindYapfConfigFile(path, yapf_configs, top_dir)
        # Default to pep8 if not .style.yapf is found.
        if not yapf_style:
            yapf_style = 'pep8'

        cmd = ['vpython3', yapf_tool, '--style', yapf_style, path]

        if not opts.full:
            ranges = line_diffs.get(path)
            if not ranges:
                continue
            # Only run yapf over changed line ranges.
            for diff_start, diff_end in ranges:
                cmd += ['-l', '{}-{}'.format(diff_start, diff_end)]

        if opts.diff or opts.dry_run:
            cmd += ['--diff']
            # Will return non-zero exit code if non-empty diff.
            stdout = RunCommand(cmd,
                                error_ok=True,
                                stderr=subprocess2.PIPE,
                                cwd=top_dir,
                                shell=sys.platform.startswith('win32'))
            if opts.diff:
                sys.stdout.write(stdout)
            if opts.dry_run and len(stdout) > 0:
                return_value = 2
        else:
            cmd += ['-i']
            RunCommand(cmd, cwd=top_dir, shell=sys.platform.startswith('win32'))
    return return_value


def _RunGnFormat(opts, paths, top_dir, upstream_commit):
    cmd = [sys.executable, os.path.join(DEPOT_TOOLS, 'gn.py'), 'format']
    if opts.dry_run or opts.diff:
        cmd.append('--dry-run')
    return_value = 0
    for path in paths:
        gn_ret = subprocess2.call(cmd + [path],
                                  shell=sys.platform.startswith('win'),
                                  cwd=top_dir)
        if opts.diff and gn_ret == 2:
            # TODO this should compute and print the actual diff.
            print('This change has GN build file diff for ' + path)
        if opts.dry_run and gn_ret == 2:
            return_value = 2  # Not formatted.
        elif gn_ret != 0:
            # For non-dry run cases (and non-2 return values for dry-run), a
            # nonzero error code indicates a failure, probably because the
            # file doesn't parse.
            DieWithError('gn format failed on ' + path +
                         '\nTry running `gn format` on this file manually.')
    return return_value


def _RunMojomFormat(opts, paths, top_dir, upstream_commit):
    primary_solution_path = gclient_paths.GetPrimarySolutionPath()
    if not primary_solution_path:
        DieWithError('Could not find the primary solution path (e.g. '
                     'the chromium checkout)')
    mojom_format_path = os.path.join(primary_solution_path, 'mojo', 'public',
                                     'tools', 'mojom', 'mojom_format.py')
    if not os.path.exists(mojom_format_path):
        DieWithError('Could not find mojom formater at '
                     f'"{mojom_format_path}"')

    cmd = ['vpython3', mojom_format_path]
    if opts.dry_run:
        cmd.append('--dry-run')
    cmd.extend(paths)

    ret = subprocess2.call(cmd)
    if opts.dry_run and ret != 0:
        return 2

    return ret


def _RunMetricsXMLFormat(opts, paths, top_dir, upstream_commit):
    # Skip the metrics formatting from the global presubmit hook. These files
    # have a separate presubmit hook that issues an error if the files need
    # formatting, whereas the top-level presubmit script merely issues a
    # warning. Formatting these files is somewhat slow, so it's important not to
    # duplicate the work.
    if opts.presubmit:
        return 0

    return_value = 0
    for path in paths:
        pretty_print_tool = metrics_xml_format.FindMetricsXMLFormatterTool(path)
        if not pretty_print_tool:
            continue

        cmd = [shutil.which('vpython3'), pretty_print_tool, '--non-interactive']
        # If the XML file is histograms.xml or enums.xml, add the xml path
        # to the command as histograms/pretty_print.py now needs a relative
        # path argument after splitting the histograms into multiple
        # directories. For example, in tools/metrics/ukm, pretty-print could
        # be run using: $ python pretty_print.py But in
        # tools/metrics/histogrmas, pretty-print should be run with an
        # additional relative path argument, like: $ python pretty_print.py
        # metadata/UMA/histograms.xml $ python pretty_print.py enums.xml
        metricsDir = metrics_xml_format.GetMetricsDir(top_dir, path)
        histogramsDir = os.path.join(top_dir, 'tools', 'metrics', 'histograms')
        if metricsDir == histogramsDir:
            cmd.append(path)
        if opts.dry_run or opts.diff:
            cmd.append('--diff')

        stdout = RunCommand(cmd, cwd=top_dir)
        if opts.diff:
            sys.stdout.write(stdout)
        if opts.dry_run and stdout:
            return_value = 2  # Not formatted.
    return return_value


def _RunLUCICfgFormat(opts, paths, top_dir, upstream_commit):
    depot_tools_path = os.path.dirname(os.path.abspath(__file__))
    lucicfg = os.path.join(depot_tools_path, 'lucicfg')
    if sys.platform == 'win32':
        lucicfg += '.bat'

    cmd = [lucicfg, 'fmt']
    if opts.dry_run:
        cmd.append('--dry-run')
    cmd.extend(paths)

    ret = subprocess2.call(cmd)
    if opts.dry_run and ret != 0:
        return 2

    return ret


FormatterFunction = Callable[[Any, list[str], str, str], int]


@subcommand.usage('[files or directories to diff]')
@metrics.collector.collect_metrics('git cl format')
def CMDformat(parser: optparse.OptionParser, args: list[str]):
    """Runs auto-formatting tools (clang-format etc.) on the diff."""
    if gclient_utils.IsEnvCog():
        print(
            'format command is not supported in non-git environment. Please '
            'use the "Format Modified Lines in All Files (git cl format)" '
            'functionality in the command palette in the editor instead.',
            file=sys.stderr)
        return 1
    clang_exts = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto']
    GN_EXTS = ['.gn', '.gni', '.typemap']
    parser.add_option('--full',
                      action='store_true',
                      help='Reformat the full content of all touched files')
    parser.add_option('--upstream', help='Branch to check against')
    parser.add_option('--dry-run',
                      action='store_true',
                      help='Don\'t modify any file on disk.')
    parser.add_option(
        '--no-clang-format',
        dest='clang_format',
        action='store_false',
        default=True,
        help='Disables formatting of various file types using clang-format.')
    parser.add_option('--python',
                      action='store_true',
                      help='Enables python formatting on all python files.')
    parser.add_option(
        '--no-python',
        action='store_false',
        dest='python',
        help='Disables python formatting on all python files. '
        'If neither --python or --no-python are set, python files that have a '
        '.style.yapf file in an ancestor directory will be formatted. '
        'It is an error to set both.')
    parser.add_option('--js',
                      action='store_true',
                      help='Format javascript code with clang-format. '
                      'Has no effect if --no-clang-format is set.')
    parser.add_option('--diff',
                      action='store_true',
                      help='Print diff to stdout rather than modifying files.')
    parser.add_option('--presubmit',
                      action='store_true',
                      help='Used when running the script from a presubmit.')

    parser.add_option(
        '--rust-fmt',
        dest='use_rust_fmt',
        action='store_true',
        default=rustfmt.IsRustfmtSupported(),
        help='Enables formatting of Rust file types using rustfmt.')
    parser.add_option(
        '--no-rust-fmt',
        dest='use_rust_fmt',
        action='store_false',
        help='Disables formatting of Rust file types using rustfmt.')

    parser.add_option(
        '--swift-format',
        dest='use_swift_format',
        action='store_true',
        default=swift_format.IsSwiftFormatSupported(),
        help='Enables formatting of Swift file types using swift-format '
        '(macOS host only).')
    parser.add_option(
        '--no-swift-format',
        dest='use_swift_format',
        action='store_false',
        help='Disables formatting of Swift file types using swift-format.')

    parser.add_option('--mojom',
                      action='store_true',
                      help='Enables formatting of .mojom files.')

    parser.add_option('--no-java',
                      action='store_true',
                      help='Disable auto-formatting of .java')

    parser.add_option('--lucicfg',
                      action='store_true',
                      help='Enables formatting of .star files.')

    opts, files = parser.parse_args(args)
    opts.full = opts.full or settings.GetFormatFullByDefault()

    # Normalize files against the current path, so paths relative to the
    # current directory are still resolved as expected.
    files = [os.path.join(os.getcwd(), file) for file in files]

    # git diff generates paths against the root of the repository.  Change
    # to that directory so clang-format can find files even within subdirs.
    rel_base_path = settings.GetRelativeRoot()
    if rel_base_path:
        os.chdir(rel_base_path)

    # Grab the merge-base commit, i.e. the upstream commit of the current
    # branch when it was created or the last time it was rebased. This is
    # to cover the case where the user may have called "git fetch origin",
    # moving the origin branch to a newer commit, but hasn't rebased yet.
    upstream_commit: str | None = None
    upstream_branch: str | None = opts.upstream
    if not upstream_branch:
        cl = Changelist()
        upstream_branch = cl.GetUpstreamBranch()
    if upstream_branch:
        upstream_commit = RunGit(['merge-base', 'HEAD',
                                  upstream_branch]).strip()

    if not upstream_commit:
        DieWithError('Could not find base commit for this branch. '
                     'Are you in detached state?')

    # Filter out deleted files
    diff_output = RunGitDiffCmd(['--name-only', '--diff-filter=d'],
                                upstream_commit, files)
    diff_files = diff_output.splitlines()

    if opts.js:
        clang_exts.extend(['.js', '.ts'])

    formatters: list[tuple[list[str], FormatterFunction]] = [
        (GN_EXTS, _RunGnFormat),
        (['.xml'], _RunMetricsXMLFormat),
    ]
    if not opts.no_java:
        formatters.append((['.java'], _RunGoogleJavaFormat))
    if opts.clang_format:
        formatters.append((clang_exts, _RunClangFormatDiff))
    if opts.use_rust_fmt:
        formatters.append((['.rs'], _RunRustFmt))
    if opts.use_swift_format:
        formatters.append((['.swift'], _RunSwiftFormat))
    if opts.python is not False:
        formatters.append((['.py'], _RunYapf))
    if opts.mojom:
        formatters.append((['.mojom', '.test-mojom'], _RunMojomFormat))
    if opts.lucicfg:
        formatters.append((['.star'], _RunLUCICfgFormat))

    top_dir = settings.GetRoot()
    return_value = 0
    for file_types, format_func in formatters:
        paths = [p for p in diff_files if p.lower().endswith(tuple(file_types))]
        if not paths:
            continue
        ret = format_func(opts, paths, top_dir, upstream_commit)
        return_value = return_value or ret

    return return_value


@subcommand.usage('<codereview url or issue id>')
@metrics.collector.collect_metrics('git cl checkout')
def CMDcheckout(parser, args):
    """Checks out a branch associated with a given Gerrit issue."""
    if gclient_utils.IsEnvCog():
        print('checkout command is not supported in non-git environment.',
              file=sys.stderr)
        return 1

    _, args = parser.parse_args(args)

    if len(args) != 1:
        parser.print_help()
        return 1

    issue_arg = ParseIssueNumberArgument(args[0])
    if not issue_arg.valid:
        parser.error('Invalid issue ID or URL.')

    target_issue = str(issue_arg.issue)

    output = scm.GIT.YieldConfigRegexp(settings.GetRoot(),
                                       r'branch\..*\.' + ISSUE_CONFIG_KEY)

    branches = []
    for key, issue in output:
        if issue == target_issue:
            branches.append(
                re.sub(r'branch\.(.*)\.' + ISSUE_CONFIG_KEY, r'\1', key))

    if len(branches) == 0:
        print('No branch found for issue %s.' % target_issue)
        return 1
    if len(branches) == 1:
        RunGit(['checkout', branches[0]])
    else:
        print('Multiple branches match issue %s:' % target_issue)
        for i in range(len(branches)):
            print('%d: %s' % (i, branches[i]))
        which = gclient_utils.AskForData('Choose by index: ')
        try:
            RunGit(['checkout', branches[int(which)]])
        except (IndexError, ValueError):
            print('Invalid selection, not checking out any branch.')
            return 1

    return 0


def CMDlol(parser, args):
    # This command is intentionally undocumented.
    print(
        zlib.decompress(
            base64.b64decode(
                'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
                'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
                'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
                'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')).decode('utf-8'))
    return 0


def CMDversion(parser, args):
    import utils
    print(utils.depot_tools_version())


class OptionParser(optparse.OptionParser):
    """Creates the option parse and add --verbose support."""
    def __init__(self, *args, **kwargs):
        optparse.OptionParser.__init__(self,
                                       *args,
                                       prog='git cl',
                                       version=__version__,
                                       **kwargs)
        self.add_option('-v',
                        '--verbose',
                        action='count',
                        default=0,
                        help='Use 2 times for more debugging info')

    @typing.overload
    def parse_args(
        self,
        args: None = None,
        values: Optional[optparse.Values] = None
    ) -> tuple[optparse.Values, list[str]]:
        ...

    @typing.overload
    def parse_args(  # pylint: disable=signature-differs
        self,
        args: Sequence[AnyStr],
        values: Optional[optparse.Values] = None
    ) -> tuple[optparse.Values, list[AnyStr]]:
        ...

    def parse_args(self, args: Sequence[AnyStr] | None = None, values=None):
        try:
            return self._parse_args(args)
        finally:
            if metrics.collector.config.should_collect_metrics:
                try:
                    # GetViewVCUrl ultimately calls logging method.
                    project_url = settings.GetViewVCUrl().strip('/+')
                    if project_url in metrics_utils.KNOWN_PROJECT_URLS:
                        metrics.collector.add('project_urls', [project_url])
                except subprocess2.CalledProcessError:
                    # Occurs when command is not executed in a git repository
                    # We should not fail here. If the command needs to be
                    # executed in a repo, it will be raised later.
                    pass

    @typing.overload
    def _parse_args(self, args: None) -> tuple[optparse.Values, list[str]]:
        ...

    @typing.overload
    def _parse_args(
            self,
            args: Sequence[AnyStr]) -> tuple[optparse.Values, list[AnyStr]]:
        ...

    def _parse_args(self, args: Sequence[AnyStr] | None):
        # Create an optparse.Values object that will store only the actual
        # passed options, without the defaults.
        actual_options = optparse.Values()
        _, argslist = optparse.OptionParser.parse_args(self, args,
                                                       actual_options)
        # Create an optparse.Values object with the default options.
        options = optparse.Values(self.get_default_values().__dict__)
        # Update it with the options passed by the user.
        options._update_careful(actual_options.__dict__)
        # Store the options passed by the user in an _actual_options attribute.
        # We store only the keys, and not the values, since the values can
        # contain arbitrary information, which might be PII.
        metrics.collector.add('arguments', list(actual_options.__dict__.keys()))

        levels = [logging.WARNING, logging.INFO, logging.DEBUG]
        logging.basicConfig(
            level=levels[min(options.verbose,
                             len(levels) - 1)],
            format='[%(levelname).1s%(asctime)s %(process)d %(thread)d '
            '%(filename)s] %(message)s')

        return options, argslist


def main(argv):
    colorize_CMDstatus_doc()
    dispatcher = subcommand.CommandDispatcher(__name__)
    try:
        return dispatcher.execute(OptionParser(), argv)
    except gerrit_util.GerritError as e:
        DieWithError(str(e))
    except auth.LoginRequiredError as e:
        DieWithError(str(e))
    except urllib.error.HTTPError as e:
        if e.code != 500:
            raise
        DieWithError((
            'App Engine is misbehaving and returned HTTP %d, again. Keep faith '
            'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
    return 0


if __name__ == '__main__':
    # These affect sys.stdout, so do it outside of main() to simplify mocks in
    # the unit tests.
    setup_color.init()
    with metrics.collector.print_notice_and_exit():
        sys.exit(main(sys.argv[1:]))