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
|
#!/usr/bin/python -O
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id$
import sys
# This block ensures that ^C interrupts are handled quietly.
try:
import signal
def exithandler(signum,frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
sys.exit(1)
signal.signal(signal.SIGINT, exithandler)
signal.signal(signal.SIGTERM, exithandler)
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except KeyboardInterrupt:
sys.exit(1)
import os
os.environ["PORTAGE_CALLER"]="emerge"
sys.path = ["/usr/lib/portage/pym"]+sys.path
import portage
import emergehelp, xpak, commands, errno, re, socket, string, time, types
from output import blue, bold, colorize, darkblue, darkgreen, darkred, green, \
havecolor, nc_len, nocolor, red, teal, turquoise, white, xtermTitle, \
xtermTitleReset, yellow
import portage_util
import portage_locks
import portage_exception
from portage_data import secpass
class stdout_spinner(object):
scroll_msgs = [
"Gentoo Rocks ("+os.uname()[0]+")",
"Thank you for using Gentoo. :)",
"Are you actually trying to read this?",
"How many times have you stared at this?",
"We are generating the cache right now",
"You are paying too much attention.",
"A theory is better than its explanation.",
"Phasers locked on target, Captain.",
"Thrashing is just virtual crashing.",
"To be is to program.",
"Real Users hate Real Programmers.",
"When all else fails, read the instructions.",
"Functionality breeds Contempt.",
"The future lies ahead.",
"3.1415926535897932384626433832795028841971694",
"Sometimes insanity is the only alternative.",
"Inaccuracy saves a world of explanation.",
]
twirl_sequence = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
def __init__(self):
self.spinpos = 0
self.update = self.update_twirl
self.scroll_sequence = self.scroll_msgs[
int(time.time() * 100) % len(self.scroll_msgs)]
def update_basic(self):
self.spinpos = (self.spinpos + 1) % 500
if (self.spinpos % 100) == 0:
if self.spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll(self):
if(self.spinpos >= len(self.scroll_sequence)):
sys.stdout.write(darkgreen(" \b\b\b" + self.scroll_sequence[
len(self.scroll_sequence) - 1 - (self.spinpos % len(self.scroll_sequence))]))
else:
sys.stdout.write(green("\b " + self.scroll_sequence[self.spinpos]))
sys.stdout.flush()
self.spinpos = (self.spinpos + 1) % (2 * len(self.scroll_sequence))
def update_twirl(self):
self.spinpos = (self.spinpos + 1) % len(self.twirl_sequence)
sys.stdout.write("\b\b " + self.twirl_sequence[self.spinpos])
sys.stdout.flush()
def update_quiet(self):
return
def normpath(mystr):
"""
os.path.normpath("//foo") returns "//foo" instead of "/foo"
We dislike this behavior so we create our own normpath func
to fix it.
"""
if mystr and (mystr[0]=='/'):
return os.path.normpath("///"+mystr)
else:
return os.path.normpath(mystr)
def userquery(prompt, responses=None, colours=None):
"""Displays a prompt and a set of responses, then waits for a response
which is checked against the responses and the first to match is
returned. An empty response will match the first value in responses. The
input buffer is *not* cleared prior to the prompt!
prompt: a String.
responses: a List of Strings.
colours: a List of Functions taking and returning a String, used to
process the responses for display. Typically these will be functions
like red() but could be e.g. lambda x: "DisplayString".
If responses is omitted, defaults to ["Yes", "No"], [green, red].
If only colours is omitted, defaults to [bold, ...].
Returns a member of the List responses. (If called without optional
arguments, returns "Yes" or "No".)
KeyboardInterrupt is converted to SystemExit to avoid tracebacks being
printed."""
if responses is None:
responses, colours = ["Yes", "No"], [green, red]
elif colours is None:
colours=[bold]
colours=(colours*len(responses))[:len(responses)]
print bold(prompt),
try:
while True:
response=raw_input("["+string.join([colours[i](responses[i]) for i in range(len(responses))],"/")+"] ")
for key in responses:
# An empty response will match the first value in responses.
if response.upper()==key[:len(response)].upper():
return key
print "Sorry, response '%s' not understood." % response,
except (EOFError, KeyboardInterrupt):
print "Interrupted."
sys.exit(1)
def sorted_versions(verlist):
ret = []
for ver in verlist:
verparts = ver.split("-")
if len(verparts) == 2:
verrev = int(verparts[1][1:])
else:
verrev = 0
x = 0
while x < len(ret):
retparts = ret[x].split("-")
verdiff = portage.vercmp(retparts[0], verparts[0])
if verdiff > 0:
break
elif verdiff == 0:
if len(retparts) == 2:
retrev = int(retparts[1][1:])
else:
retrev = 0
if retrev >= verrev:
break
x += 1
ret.insert(x, ver)
return ret
actions=[
"clean", "config", "depclean",
"info", "metadata",
"prune", "regen", "search",
"sync", "system", "unmerge", "world",
]
options=[
"--ask", "--alphabetical",
"--buildpkg", "--buildpkgonly",
"--changelog", "--columns", "--cols",
"--debug", "--deep",
"--digest",
"--emptytree",
"--fetchonly", "--fetch-all-uri",
"--getbinpkg", "--getbinpkgonly",
"--help", "--ignore-default-opts",
"--noconfmem",
"--newuse", "--nocolor",
"--nodeps", "--noreplace",
"--nospinner", "--oneshot",
"--onlydeps", "--pretend",
"--quiet", "--resume",
"--searchdesc", "--selective",
"--skipfirst", "--skip-first",
"--tree",
"--update",
"--usepkg", "--usepkgonly",
"--verbose", "--version"
]
shortmapping={
"1":"--oneshot",
"a":"--ask",
"b":"--buildpkg", "B":"--buildpkgonly",
"c":"--clean", "C":"--unmerge",
"d":"--debug", "D":"--deep",
"e":"--emptytree",
"f":"--fetchonly", "F":"--fetch-all-uri",
"g":"--getbinpkg", "G":"--getbinpkgonly",
"h":"--help",
"k":"--usepkg", "K":"--usepkgonly",
"l":"--changelog",
"n":"--noreplace", "N":"--newuse",
"o":"--onlydeps", "O":"--nodeps",
"p":"--pretend", "P":"--prune",
"q":"--quiet",
"s":"--search", "S":"--searchdesc",
't':"--tree",
"u":"--update",
"v":"--verbose", "V":"--version"
}
def emergelog(mystr,short_msg=None):
if "notitles" not in portage.settings.features:
if short_msg:
xtermTitle(short_msg)
else:
xtermTitle(mystr)
try:
file_path = "/var/log/emerge.log"
mylogfile = open(file_path, "a")
portage_util.apply_secpass_permissions(file_path,
uid=portage.portage_uid, gid=portage.portage_gid,
mode=0660)
l=portage_locks.lockfile(mylogfile)
# seek because we may have gotten held up by the lock.
# if so, we may not be positioned at the end of the file.
mylogfile.seek(0,2)
mylogfile.write(str(time.time())[:10]+": "+mystr+"\n")
mylogfile.flush()
portage_locks.unlockfile(l)
mylogfile.close()
except (IOError,OSError,portage_exception.PortageException), e:
if secpass >= 1:
print >> sys.stderr, "emergelog():",e
def countdown(secs=5, doing="Starting"):
if secs:
print ">>> Waiting",secs,"seconds before starting..."
print ">>> (Control-C to abort)...\n"+doing+" in: ",
ticks=range(secs)
ticks.reverse()
for sec in ticks:
sys.stdout.write(red(str(sec+1)+" "))
sys.stdout.flush()
time.sleep(1)
print
# formats a size given in bytes nicely
def format_size(mysize):
if type(mysize) not in [types.IntType,types.LongType]:
return str(mysize)
mystr=str(mysize/1024)
mycount=len(mystr)
while (mycount > 3):
mycount-=3
mystr=mystr[:mycount]+","+mystr[mycount:]
return mystr+" kB"
def getgccversion(chost):
"""
rtype: C{str}
return: the current in-use gcc version
"""
gcc_ver_command = 'gcc -dumpversion'
gcc_ver_prefix = 'gcc-'
gcc_not_found_error = red(
"!!! No gcc found. You probably need to 'source /etc/profile'\n" +
"!!! to update the environment of this terminal and possibly\n" +
"!!! other terminals also.\n"
)
mystatus, myoutput = commands.getstatusoutput("eselect compiler show")
if mystatus == os.EX_OK and len(myoutput.split("/")) == 2:
part1, part2 = myoutput.split("/")
if part1.startswith(chost + "-"):
return myoutput.replace(chost + "-", gcc_ver_prefix, 1)
mystatus, myoutput = commands.getstatusoutput("gcc-config -c")
if mystatus == os.EX_OK and len(myoutput.split("-")) > 0:
return gcc_ver_prefix + myoutput.split("-")[-1]
mystatus, myoutput = commands.getstatusoutput(
chost + "-" + gcc_ver_command)
if mystatus == os.EX_OK:
return gcc_ver_prefix + myoutput
mystatus, myoutput = commands.getstatusoutput(gcc_ver_command)
if mystatus == os.EX_OK:
return gcc_ver_prefix + myoutput
portage.writemsg(gcc_not_found_error, noiselevel=-1)
return "[unavailable]"
def getportageversion(portdir, target_root, profile, chost):
try:
import re
profilever = os.path.normpath("///"+os.readlink(profile))
basepath = os.path.normpath("///" + portdir + "/profiles")
if re.match(basepath,profilever):
profilever = profilever[len(basepath)+1:]
else:
profilever = "!"+profilever
del basepath
except (OSError,IOError):
profilever="unavailable"
libcver=[]
libclist = portage.vardbapi(target_root).match("virtual/libc")
libclist += portage.vardbapi(target_root).match("virtual/glibc")
libclist = portage_util.unique_array(libclist)
for x in libclist:
xs=portage.catpkgsplit(x)
if libcver:
libcver+=","+string.join(xs[1:], "-")
else:
libcver=string.join(xs[1:], "-")
if libcver==[]:
libcver="unavailable"
gccver = getgccversion(chost)
unameout=os.uname()[2]+" "+os.uname()[4]
return "Portage " + portage.VERSION +" ("+profilever+", "+gccver+", "+libcver+", "+unameout+")"
def create_depgraph_params(myopts, myaction):
#configure emerge engine parameters
#
# self: include _this_ package regardless of if it is merged.
# selective: exclude the package if it is merged
# recurse: go into the dependencies
# deep: go into the dependencies of already merged packages
# empty: pretend nothing is merged
myparams=["self","recurse"]
add=[]
sub=[]
if "--update" in myopts or myaction in ("system", "world"):
add.extend(["selective","empty"])
if "--emptytree" in myopts:
add.extend(["empty"])
sub.extend(["selective"])
if "--nodeps" in myopts:
sub.extend(["recurse"])
if "--noreplace" in myopts:
add.extend(["selective"])
if "--deep" in myopts:
add.extend(["deep"])
if "--selective" in myopts:
add.extend(["selective"])
if myaction in ["world","system"]:
add.extend(["selective"])
elif myaction in ["depclean"]:
add.extend(["empty"])
sub.extend(["selective"])
for x in add:
if (x not in myparams) and (x not in sub):
myparams.append(x)
for x in sub:
if x in myparams:
myparams.remove(x)
return myparams
# search functionality
class search:
#
# class constants
#
VERSION_SHORT=1
VERSION_RELEASE=2
#
# public interface
#
def __init__(self, settings, portdb, vartree, spinner, searchdesc,
verbose):
"""Searches the available and installed packages for the supplied search key.
The list of available and installed packages is created at object instantiation.
This makes successive searches faster."""
self.settings = settings
self.portdb = portdb
self.vartree = vartree
self.spinner = spinner
self.verbose = verbose
self.searchdesc = searchdesc
def execute(self,searchkey):
"""Performs the search for the supplied search key"""
match_category = 0
self.searchkey=searchkey
self.packagematches = []
if self.searchdesc:
self.searchdesc=1
self.matches = {"pkg":[], "desc":[]}
else:
self.searchdesc=0
self.matches = {"pkg":[]}
print "Searching... ",
if self.searchkey[0] == '@':
match_category = 1
self.searchkey = self.searchkey[1:]
if self.searchkey=="*":
#hack for people who aren't regular expression gurus
self.searchkey==".*"
if re.search("\+\+", self.searchkey):
#hack for people who aren't regular expression gurus
self.searchkey=re.sub("\+\+","\+\+",self.searchkey)
self.searchre=re.compile(self.searchkey.lower(),re.I)
for package in self.portdb.cp_all():
self.spinner.update()
if match_category:
match_string = package[:]
else:
match_string = package.split("/")[-1]
masked=0
if self.searchre.search(match_string):
if not self.portdb.xmatch("match-visible", package):
masked=1
self.matches["pkg"].append([package,masked])
elif self.searchdesc: # DESCRIPTION searching
full_package = self.portdb.xmatch("bestmatch-visible", package)
if not full_package:
#no match found; we don't want to query description
full_package = portage.best(
self.portdb.xmatch("match-all", package))
if not full_package:
continue
else:
masked=1
try:
full_desc = self.portdb.aux_get(
full_package, ["DESCRIPTION"])[0]
except KeyError:
print "emerge: search: aux_get() failed, skipping"
continue
if self.searchre.search(full_desc):
self.matches["desc"].append([full_package,masked])
self.mlen=0
for mtype in self.matches.keys():
self.matches[mtype].sort()
self.mlen += len(self.matches[mtype])
def output(self):
"""Outputs the results of the search."""
print "\b\b \n[ Results for search key : "+white(self.searchkey)+" ]"
print "[ Applications found : "+white(str(self.mlen))+" ]"
print " "
for mtype in self.matches.keys():
for match,masked in self.matches[mtype]:
if mtype=="pkg":
catpack=match
full_package = self.portdb.xmatch(
"bestmatch-visible", match)
if not full_package:
#no match found; we don't want to query description
masked=1
full_package = portage.best(
self.portdb.xmatch("match-all",match))
else:
full_package = match
match = portage.pkgsplit(match)[0]
if full_package:
try:
desc, homepage, license = self.portdb.aux_get(
full_package, ["DESCRIPTION","HOMEPAGE","LICENSE"])
except KeyError:
print "emerge: search: aux_get() failed, skipping"
continue
if masked:
print green("*")+" "+white(match)+" "+red("[ Masked ]")
else:
print green("*")+" "+white(match)
myversion = self.getVersion(full_package, search.VERSION_RELEASE)
mysum = [0,0]
mycat = match.split("/")[0]
mypkg = match.split("/")[1]
mycpv = match + "-" + myversion
myebuild = self.portdb.findname(mycpv)
pkgdir = os.path.dirname(myebuild)
import portage_manifest
mf = portage_manifest.Manifest(
pkgdir, self.settings["DISTDIR"])
fetchlist = self.portdb.getfetchlist(mycpv,
mysettings=self.settings, all=True)[1]
try:
mysum[0] = mf.getDistfilesSize(fetchlist)
mystr = str(mysum[0]/1024)
mycount=len(mystr)
while (mycount > 3):
mycount-=3
mystr=mystr[:mycount]+","+mystr[mycount:]
mysum[0]=mystr+" kB"
except KeyError, e:
mysum[0] = "Unknown (missing digest for %s)" % str(e)
if self.verbose:
print " ", darkgreen("Latest version available:"),myversion
print " ", self.getInstallationStatus(mycat+'/'+mypkg)
print " ", darkgreen("Size of files:"),mysum[0]
print " ", darkgreen("Homepage:")+" ",homepage
print " ", darkgreen("Description:")+" ",desc
print " ", darkgreen("License:")+" ",license
print
print
#
# private interface
#
def getInstallationStatus(self,package):
installed_package = self.vartree.dep_bestmatch(package)
result = ""
version = self.getVersion(installed_package,search.VERSION_RELEASE)
if len(version) > 0:
result = darkgreen("Latest version installed:")+" "+version
else:
result = darkgreen("Latest version installed:")+" [ Not Installed ]"
return result
def getVersion(self,full_package,detail):
if len(full_package) > 1:
package_parts = portage.catpkgsplit(full_package)
if detail == search.VERSION_RELEASE and package_parts[3] != 'r0':
result = package_parts[2]+ "-" + package_parts[3]
else:
result = package_parts[2]
else:
result = ""
return result
#build our package digraph
def getlist(settings, mode):
if mode=="system":
mylines = settings.packages
elif mode=="world":
try:
file_path = os.path.join(settings["ROOT"], portage.WORLD_FILE)
myfile = open(file_path, "r")
mylines = myfile.readlines()
myfile.close()
except (OSError, IOError), e:
if e.errno == errno.ENOENT:
portage.writemsg("\n!!! World file does not exist: '%s'\n" % file_path)
mylines=[]
else:
raise
mynewlines=[]
for x in mylines:
myline=string.join(string.split(x))
if not len(myline):
continue
elif myline[0]=="#":
continue
elif mode=="system":
if myline[0]!="*":
continue
myline=myline[1:]
mynewlines.append(myline.strip())
# Remove everything that is package.provided from our list
for atom in mynewlines[:]:
for expanded_atom in portage.flatten(
portage.dep_virtual([atom], settings)):
mykey = portage.dep_getkey(expanded_atom)
if mykey in settings.pprovideddict and \
portage.match_from_list(
expanded_atom, settings.pprovideddict[mykey]):
mynewlines.remove(atom)
break
return mynewlines
def genericdict(mylist):
mynewdict={}
for x in mylist:
mynewdict[portage.dep_getkey(x)]=x
return mynewdict
class depgraph:
def __init__(self, settings, portdb, trees, myopts, myparams, spinner):
self.settings = settings
self.portdb = portdb
self.trees = trees
self.myopts = myopts
self.myparams = myparams
self.edebug = 0
if settings.get("PORTAGE_DEBUG", "") == "1":
self.edebug = 1
self.spinner = spinner
self.pkgsettings = portage.config(clone=settings)
if not self.pkgsettings["ARCH"]:
portage.writemsg(red("\a!!! ARCH is not set... Are you missing the /etc/make.profile symlink?\n"),
noiselevel=-1)
portage.writemsg(red("\a!!! Is the symlink correct? Is your portage tree complete?\n\n"),
noiselevel=-1)
sys.exit(9)
self.applied_useflags = {}
self.missingbins=[]
self.digraph=portage.digraph()
self.orderedkeys=[]
self.outdatedpackages=[]
self.mydbapi={}
self.mydbapi["/"] = portage.fakedbapi()
if "empty" not in self.myparams or settings["ROOT"] != "/":
for pkg in self.trees["/"]["vartree"].getallcpv():
self.mydbapi["/"].cpv_inject(pkg)
if settings["ROOT"] != "/":
self.mydbapi[settings["ROOT"]] = portage.fakedbapi()
if "empty" not in self.myparams:
for pkg in self.trees[settings["ROOT"]]["vartree"].getallcpv():
self.mydbapi[settings["ROOT"]].cpv_inject(pkg)
if "--usepkg" in self.myopts:
trees["/"]["bintree"].populate(
"--getbinpkg" in self.myopts, "--getbinpkgonly" in self.myopts)
def create(self,mybigkey,myparent=None,addme=1,myuse=None):
"""creates the actual digraph of packages to merge. return 1 on success, 0 on failure
mybigkey = specification of package to merge; myparent = parent package (one depending on me);
addme = should I be added to the tree? (for the --onlydeps mode)"""
#stuff to add:
#SLOT-aware emerge
#IUSE-aware emerge
#"no downgrade" emerge
#print "mybigkey:",mybigkey
jbigkey=string.join(mybigkey)
if self.digraph.hasnode(jbigkey+" merge") or self.digraph.hasnode(jbigkey+" nomerge"):
#this conditional is needed to prevent infinite recursion on already-processed deps
return 1
self.spinner.update()
mytype,myroot,mykey=mybigkey
# select the correct /var database that we'll be checking against
vardbapi = self.trees[myroot]["vartree"].dbapi
# if the package is already on the system, we add a "nomerge"
# directive, otherwise we add a "merge" directive.
if mytype=="blocks":
# we've encountered a "blocks" node. We will totally ignore this
# node and not add it to our digraph if it doesn't apply to us.
if addme and "--buildpkgonly" not in self.myopts and myparent and \
(self.mydbapi[myroot].match(mykey) or vardbapi.match(mykey)):
mybigkey.append(myparent.split()[2])
self.digraph.addnode(string.join(mybigkey),myparent)
return 1
if myuse is None:
self.pkgsettings.setcpv(mykey)
myuse = self.pkgsettings["USE"].split()
self.applied_useflags[mykey] = myuse
merging=1
if addme:
# this is where we add the node to the list of packages to merge
if not myparent:
# command-line specified or part of a world list...
if "self" not in self.myparams or \
("selective" in self.myparams and \
vardbapi.cpv_exists(mykey)):
# the package is on the system, so don't merge it.
merging=0
elif "selective" in self.myparams and vardbapi.cpv_exists(mykey):
merging=0
if merging == 0 and "--newuse" in self.myopts and \
vardbapi.cpv_exists(mykey):
old_use = vardbapi.aux_get(mykey, ["USE"])[0].split()
if mytype == "binary":
iuses = self.trees["/"]["bintree"].dbapi.aux_get(
mykey, ["IUSE"])[0].split()
else:
iuses = self.trees["/"]["porttree"].dbapi.aux_get(
mykey, ["IUSE"])[0].split()
for x in iuses:
if (old_use.count(x) and not myuse.count(x)) or (not old_use.count(x) and myuse.count(x)):
merging=1
break
else:
#onlydeps mode; don't merge
merging=2
if merging==1:
mybigkey.append("merge")
else:
mybigkey.append("nomerge")
# whatever the case, we need to add the node to our digraph so
# that children can depend upon it.
self.digraph.addnode(string.join(mybigkey),myparent)
if "deep" not in self.myparams and not merging:
return 1
elif "recurse" not in self.myparams:
return 1
edepend={}
if mytype=="binary":
mypkgparts=portage.catpkgsplit(mykey)
tbz2name = string.split(mykey, "/")[1]+".tbz2"
if tbz2name in self.trees[
self.settings["ROOT"]]["bintree"].invalids:
sys.stderr.write("\nINVALID PACKAGE (is required to continue): "+str(mykey)+"\n")
sys.exit(1)
if self.trees[self.settings["ROOT"]]["bintree"].isremote(mykey):
edepend = self.trees[
self.settings["ROOT"]]["bintree"].remotepkgs[tbz2name]
edepend["DEPEND"] =""
edepend["RDEPEND"]=string.join(string.split(edepend["RDEPEND"])," ")
edepend["PDEPEND"]=string.join(string.split(edepend["PDEPEND"])," ")
edepend["SLOT"] =string.strip(edepend["SLOT"])
#portage.db[portage.root]["bintree"].gettbz2(mykey)
else: # It's local.
mytbz2 = xpak.tbz2(self.trees[
self.settings["ROOT"]]["bintree"].getname(mykey))
edepend["DEPEND"] =""
edepend["RDEPEND"]=string.join(mytbz2.getelements("RDEPEND")," ")
edepend["PDEPEND"]=string.join(mytbz2.getelements("PDEPEND")," ")
edepend["SLOT"] =mytbz2.getfile("SLOT",mypkgparts[2])
elif mytype=="ebuild":
try:
mymeta = ["DEPEND","RDEPEND","PDEPEND"]
myfoo = self.portdb.aux_get(mykey, mymeta)
for index in range(0,len(mymeta)):
edepend[mymeta[index]] = myfoo[index]
if "--buildpkgonly" in self.myopts:
edepend["RDEPEND"] = ""
edepend["PDEPEND"] = ""
except (KeyError,IOError):
print "emerge: create(): aux_get() error on",mykey+"; aborting..."
sys.exit(1)
mydep={}
mp=string.join(mybigkey)
try:
if myroot=="/":
mydep["/"]=edepend["DEPEND"]+" "+edepend["RDEPEND"]
if not self.select_dep("/",mydep["/"],myparent=mp,myuse=myuse):
return 0
else:
mydep["/"]=edepend["DEPEND"]
mydep[myroot]=edepend["RDEPEND"]
if not self.select_dep("/",mydep["/"],myparent=mp,myuse=myuse):
return 0
if not self.select_dep(myroot,mydep[myroot],myparent=mp,myuse=myuse):
return 0
if edepend.has_key("PDEPEND") and edepend["PDEPEND"]:
# Post Depend -- Add to the list without a parent, as it depends
# on a package being present AND must be built after that package.
if not self.select_dep(myroot,edepend["PDEPEND"],myuse=myuse):
return 0
except ValueError, e:
pkgs = e.args[0]
portage.writemsg("\n\n!!! An atom in the dependencies " + \
"is not fully-qualified. Multiple matches:\n\n", noiselevel=-1)
for cpv in pkgs:
portage.writemsg(" %s\n" % cpv, noiselevel=-1)
portage.writemsg("\n", noiselevel=-1)
if mytype == "binary":
portage.writemsg(
"!!! This binary package cannot be installed: '%s'\n" % \
mykey, noiselevel=-1)
elif mytype == "ebuild":
myebuild, mylocation = self.portdb.findname2(mykey)
portage.writemsg("!!! This ebuild cannot be installed: " + \
"'%s'\n" % myebuild, noiselevel=-1)
portage.writemsg("!!! Please notify the package maintainer " + \
"that atoms must be fully-qualified.\n", noiselevel=-1)
return 0
return 1
def select_files(self,myfiles):
"given a list of .tbz2s, .ebuilds and deps, create the appropriate depgraph and return a favorite list"
myfavorites=[]
for x in myfiles:
ext = os.path.splitext(x)[1]
if ext==".tbz2":
if not os.path.exists(x):
if os.path.exists(self.pkgsettings["PKGDIR"]+"/All/"+x):
x=self.pkgsettings["PKGDIR"]+"/All/"+x
elif os.path.exists(self.pkgsettings["PKGDIR"]+"/"+x):
x=self.pkgsettings["PKGDIR"]+"/"+x
else:
print "\n\n!!! Binary package '"+str(x)+"' does not exist."
print "!!! Please ensure the tbz2 exists as specified.\n"
sys.exit(1)
mytbz2=xpak.tbz2(x)
mykey=mytbz2.getelements("CATEGORY")[0]+"/"+os.path.splitext(os.path.basename(x))[0]
if os.path.realpath(x) != \
os.path.realpath(self.trees["/"]["bintree"].getname(mykey)):
print red("\n*** You need to adjust PKGDIR to emerge this package.\n")
sys.exit(1)
if not self.create(["binary", self.settings["ROOT"], mykey],
None, "--onlydeps" not in self.myopts):
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(mykey)
elif ext==".ebuild":
x = os.path.realpath(x)
mykey=os.path.basename(os.path.normpath(x+"/../.."))+"/"+os.path.splitext(os.path.basename(x))[0]
ebuild_path = self.trees["/"]["porttree"].dbapi.findname(mykey)
if ebuild_path:
if os.path.realpath(ebuild_path) != x:
print red("\n*** You need to adjust PORTDIR or PORTDIR_OVERLAY to emerge this package.\n")
sys.exit(1)
if mykey not in self.trees["/"]["porttree"].dbapi.xmatch(
"match-visible", portage.dep_getkey(mykey)):
print red("\n*** You are emerging a masked package. It is MUCH better to use")
print red("*** /etc/portage/package.* to accomplish this. See portage(5) man")
print red("*** page for details.")
countdown(int(self.settings["EMERGE_WARNING_DELAY"]),
"Continuing...")
else:
raise portage_exception.PackageNotFound(
"%s is not in a valid portage tree hierarchy or does not exist" % x)
if not self.create(["ebuild", self.settings["ROOT"], mykey],
None, "--onlydeps" not in self.myopts):
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(mykey)
else:
if not is_valid_package_atom(x):
portage.writemsg("\n\n!!! '%s' is not a valid package atom.\n" % x,
noiselevel=-1)
portage.writemsg("!!! Please check ebuild(5) for full details.\n")
portage.writemsg("!!! (Did you specify a version but forget to prefix with '='?)\n")
return (0,[])
try:
mykey = portage.dep_expand(x, mydb=self.portdb)
except ValueError, errpkgs:
print "\n\n!!! The short ebuild name \"" + x + "\" is ambiguous. Please specify"
print "!!! one of the following fully-qualified ebuild names instead:\n"
for i in errpkgs[0]:
print " " + green(i)
print
sys.exit(1)
# select needs to return 0 on dep_check failure
sys.stdout.flush()
sys.stderr.flush()
try:
self.mysd = self.select_dep(
self.settings["ROOT"], mykey, arg=x)
except portage_exception.MissingSignature, e:
portage.writemsg("\n\n!!! A missing gpg signature is preventing portage from calculating the\n")
portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
sys.exit(1)
except portage_exception.InvalidSignature, e:
portage.writemsg("\n\n!!! An invalid gpg signature is preventing portage from calculating the\n")
portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
sys.exit(1)
except SystemExit, e:
raise # Needed else can't exit
except Exception, e:
if "--debug" in self.myopts:
raise
print "\n\n!!! Problem in",mykey,"dependencies."
print "!!!",str(e),e.__module__
sys.exit(1)
if not self.mysd:
return (0,myfavorites)
elif not "--oneshot" in self.myopts:
myfavorites.append(portage.dep_getkey(mykey))
missing=0
if "--usepkgonly" in self.myopts:
for x in self.digraph.dict.keys():
xs=string.split(x," ")
if (xs[0] != "binary") and (xs[3]=="merge"):
if missing == 0:
print
missing += 1
print "Missing binary for:",xs[2]
# We're true here unless we are missing binaries.
return (not missing,myfavorites)
def is_newer_ver_installed(self,myroot,pkg,pkgver):
"if there is a version of pkg installed newer than pkgver, return it"
vardbapi = self.trees[myroot]["vartree"].dbapi
matches = self.trees[myroot]["vartree"].dbapi.match(pkg)
if matches:
myslot = self.trees["/"]["porttree"].getslot(pkgver)
for match in matches:
if portage.pkgcmp(portage.catpkgsplit(pkgver)[1:], portage.catpkgsplit(match)[1:]) < 0:
curslot = self.trees[myroot]["vartree"].getslot(match)
if curslot == myslot:
return match
def select_dep(self,myroot,depstring,myparent=None,arg=None,myuse=None,raise_on_missing=False):
"given a dependency string, create the appropriate depgraph and return 1 on success and 0 on failure"
if "--debug" in self.myopts:
print
print "Parent: ",myparent
print "Depstring:",depstring
if not arg:
#processing dependencies
mycheck = portage.dep_check(depstring, self.mydbapi[myroot],
self.pkgsettings, myuse=myuse,
use_binaries=("--usepkgonly" in self.myopts),
myroot=myroot)
if not mycheck[0]:
mymerge=[]
else:
mymerge=mycheck[1]
else:
#we're processing a command-line argument; unconditionally merge it even if it's already merged
mymerge=[depstring]
# dep_check has been run so we can now add our parent to our
# build state to update virtuals and other settings. This
# happens after the package is added to the tree so that a
# package can depend on a virtual which it satisfies.
if myparent:
myp = myparent.split()
if myp[3]=="merge":
self.mydbapi[myroot].cpv_inject(myp[2])
if myp[0]=="binary":
self.pkgsettings.setinst(
myp[2], self.trees["/"]["bintree"].dbapi)
else:
self.pkgsettings.setinst(
myp[2], self.trees[myroot]["porttree"].dbapi)
if not mymerge:
return 1
if "--debug" in self.myopts:
print "Candidates:",mymerge
for x in mymerge:
myk=None
binpkguseflags=None
if x[0]=="!":
# if this package is myself, don't append it to block list.
if "--debug" in self.myopts:
print "Myparent",myparent
if (myparent):
if myparent.split()[2] in self.portdb.xmatch(
"match-all", x[1:]):
# myself, so exit.
continue
# adding block
myk=["blocks",myroot,x[1:]]
else:
#We are not processing a blocker but a normal dependency
myeb=None
myeb_matches = self.portdb.xmatch("match-visible", x)
if "--usepkgonly" not in self.myopts:
myeb=portage.best(myeb_matches)
myeb_pkg=None
if "--usepkg" in self.myopts:
# The next line assumes the binarytree has been populated.
# XXX: Need to work out how we use the binary tree with roots.
myeb_pkg_matches=self.trees["/"]["bintree"].dbapi.match(x)
if "--usepkgonly" not in self.myopts:
# Remove any binary package entries that are masked in the portage tree (#55871)
for idx in range(len(myeb_pkg_matches)-1,-1,-1):
if myeb_pkg_matches[idx] not in myeb_matches:
del myeb_pkg_matches[idx]
myeb_pkg = portage.best(myeb_pkg_matches)
if not myeb_pkg:
myeb_pkg = None
elif "--newuse" in self.myopts:
iuses = self.trees["/"]["bintree"].dbapi.aux_get(
myeb_pkg, ["IUSE"])[0].split()
old_use = self.trees["/"]["bintree"].dbapi.aux_get(
myeb_pkg, ["USE"])[0].split()
self.pkgsettings.setcpv(myeb_pkg)
now_use=string.split(self.pkgsettings["USE"])
for x in iuses:
if (old_use.count(x) and not now_use.count(x)) or (not old_use.count(x) and now_use.count(x)):
myeb_pkg = None
break
if (not myeb) and (not myeb_pkg):
if raise_on_missing:
raise ValueError
if not arg:
xinfo='"'+x+'"'
else:
xinfo='"'+arg+'"'
if myparent:
xfrom = '(dependency required by '+green('"'+myparent.split()[2]+'"')+red(' ['+myparent.split()[0]+"]")+')'
alleb = self.portdb.xmatch("match-all", x)
if alleb:
if "--usepkgonly" not in self.myopts:
print "\n!!! "+red("All ebuilds that could satisfy ")+green(xinfo)+red(" have been masked.")
print "!!! One of the following masked packages is required to complete your request:"
oldcomment = ""
for p in alleb:
mreasons = portage.getmaskingstatus(p)
print "- "+p+" (masked by: "+string.join(mreasons, ", ")+")"
comment = portage.getmaskingreason(p)
if comment and comment != oldcomment:
print comment
oldcomment = comment
print
print "For more information, see MASKED PACKAGES section in the emerge man page or "
print "refer to the Gentoo Handbook."
else:
print "\n!!! "+red("There are no packages available to satisfy: ")+green(xinfo)
print "!!! Either add a suitable binary package or compile from an ebuild."
else:
print "\nemerge: there are no ebuilds to satisfy "+green(xinfo)+"."
if myparent:
print xfrom
print
return 0
if "--debug" in self.myopts:
print "ebuild:",myeb
print "binpkg:",myeb_pkg
if myeb and myeb_pkg:
myeb_s = portage.catpkgsplit(myeb)
myeb_s = [myeb_s[0]+"/"+myeb_s[1], myeb_s[2], myeb_s[3]]
myeb_pkg_s = portage.catpkgsplit(myeb_pkg)
myeb_pkg_s = [myeb_pkg_s[0]+"/"+myeb_pkg_s[1], myeb_pkg_s[2], myeb_pkg_s[3]]
if portage.pkgcmp(myeb_s, myeb_pkg_s) == 0: # pkg is same version as ebuild
myeb = None
else:
myeb_pkg = None
if myeb:
myk=["ebuild",myroot,myeb]
elif myeb_pkg:
binpkguseflags = self.trees[
self.settings["ROOT"]]["bintree"].get_use(myeb_pkg)
myk=["binary",myroot,myeb_pkg]
else:
sys.stderr.write("!!! Confused... Don't know what's being used for dependency info. :(\n")
sys.exit(1)
#if "--usepkg" in myopts:
# #If we want to use packages, see if we have a pre-built one...
# mypk=portage.db["/"]["bintree"].dbapi.match(x)
# if myeb in mypk:
# #Use it only if it's exactly the version we want.
# myk=["binary",myroot,myeb]
# else:
# myk=["ebuild",myroot,myeb]
#else:
# myk=["ebuild",myroot,myeb]
if myparent:
#we are a dependency, so we want to be unconditionally added
if not self.create(myk,myparent,myuse=binpkguseflags):
return 0
else:
#if mysource is not set, then we are a command-line dependency and should not be added
#if --onlydeps is specified.
if not self.create(myk, myparent,
"--onlydeps" not in self.myopts, myuse=binpkguseflags):
return 0
if "--debug" in self.myopts:
print "Exiting...",myparent
return 1
def altlist(self):
mygraph=self.digraph.copy()
dolist=["/"]
retlist=[]
for x in self.trees.keys():
self.trees[x]["merge"] = []
if x not in dolist:
dolist.append(x)
while (not mygraph.empty()):
mycurkey=mygraph.firstzero()
if not mycurkey:
print "!!! Error: circular dependencies:"
print
for x in mygraph.dict.keys():
for y in mygraph.dict[x][1]:
print y,"depends on",x
print
sys.exit(1)
splitski=string.split(mycurkey)
#I'm not sure of the significance of the following lines (vestigal?) so I'm commenting 'em out.
#These lines remove already-merged things from our alt-list
#if "--update" in myopts:
# if not portage.db["/"]["vartree"].exists_specific(splitski[2]):
# portage.db["/"]["merge"].append(splitski)
#else:
self.trees[splitski[1]]["merge"].append(splitski)
mygraph.delnode(mycurkey)
for x in dolist:
for y in self.trees[x]["merge"]:
retlist.append(y)
return retlist
def xcreate(self,mode="system"):
world_problems = False
if mode=="system":
mylist = getlist(self.settings, "system")
else:
#world mode
worldlist = getlist(self.settings, "world")
sysdict = genericdict(getlist(self.settings, "system"))
worlddict=genericdict(worldlist)
for x in worlddict.keys():
if not portage.isvalidatom(x):
world_problems = True
elif not self.trees["/"]["vartree"].dbapi.match(x):
world_problems = True
else:
sysdict[x]=worlddict[x]
mylist = sysdict.keys()
newlist = []
for atom in mylist:
if portage.dep_getkey(atom).split("/")[-1] == "portage":
newlist.insert(0, atom)
else:
newlist.append(atom)
mylist = newlist
missing_atoms = []
for mydep in mylist:
try:
if not self.select_dep(
self.settings["ROOT"], mydep, raise_on_missing=True):
print "\n\n!!! Problem resolving dependencies for", mydep
return 0
except ValueError:
missing_atoms.append(mydep)
if world_problems:
print "\n!!! Problems have been detected with your world file"
print "!!! Please run "+green("emaint --check world")+"\n"
if missing_atoms and "--verbose" in self.myopts:
print "\n!!! Packages for the following atoms are either all"
print "!!! masked or don't exist:"
print " ".join(missing_atoms) + "\n"
return 1
def match(self, mydep, myroot=None, mykey=None):
# support mutual exclusive deps
if myroot is None:
myroot = self.settings["ROOT"]
mydep2=mydep
if mydep2[0]=="!":
mydep2=mydep[1:]
if mydep[0]=="!":
#add our blocker; it will be ignored later if necessary (if we are remerging the same pkg, for example)
myk="blocks "+myroot+" "+mydep2
else:
myeb = self.trees[
self.settings["ROOT"]]["porttree"].dep_bestmatch(mydep2)
if not myeb:
if not mykey:
print "\n!!! Error: couldn't find match for",mydep
else:
print "\n!!! Error: couldn't find match for",mydep,"in",mykey
print
sys.exit(1)
if "--usepkg" in self.myopts:
mypk = self.trees[
self.settings["ROOT"]]["bintree"].dep_bestmatch(mydep)
if myeb==mypk:
myk = " ".join(("binary", self.settings["ROOT"], mypk))
else:
myk = " ".join(("ebuild", myroot, myeb))
else:
myk="ebuild "+myroot+" "+myeb
return myk
def display(self,mylist,verbosity=None):
if verbosity is None:
verbosity = ("--quiet" in self.myopts and 1 or \
"--verbose" in self.myopts and 3 or 2)
changelogs=[]
p=[]
totalsize=0
if verbosity == 1:
def create_use_string(*args):
return ""
else:
def create_use_string(name, cur_iuse, cur_use, old_iuse, old_use,
is_new, all_flags=(verbosity == 3),
alphabetical=("--alphabetical" in self.myopts)):
enabled = []
if alphabetical:
disabled = enabled
else:
disabled = []
for flag in cur_iuse:
if flag in cur_use:
if is_new or flag in old_use and all_flags:
enabled.append(red(flag))
elif flag not in old_iuse:
enabled.append(yellow(flag)+"%")
elif flag not in old_use:
enabled.append(green(flag)+"*")
else:
if is_new or flag in old_iuse and flag not in old_use and all_flags:
disabled.append(blue("-"+flag))
elif flag not in old_iuse:
disabled.append(yellow("-"+flag)+"%")
elif flag in old_use:
disabled.append(green("-"+flag)+"*")
enabled = " ".join(enabled)
if alphabetical:
disabled = ""
else:
disabled = " ".join(disabled)
if enabled and disabled:
ret = enabled + " " + disabled
elif enabled:
ret = enabled
else:
ret = disabled
if ret:
ret = '%s="%s" ' % (name, ret)
return ret
if verbosity == 3:
overlays = self.pkgsettings["PORTDIR_OVERLAY"].split()
overlays_real = [os.path.realpath(t) \
for t in self.pkgsettings["PORTDIR_OVERLAY"].split()]
if "--tree" in self.myopts:
mylist.reverse()
mygraph=self.digraph.copy()
i = 0
while i < len(mylist):
if mylist[i][-1]=="nomerge":
if "--tree" not in self.myopts:
# we don't care about this elements
mylist.pop(i)
continue
if (i == (len(mylist) - 1)) \
or (mygraph.depth(string.join(mylist[i])) \
>= mygraph.depth(string.join(mylist[i+1]))):
# end of a useless branch (may be the last one)
# -> delete the element and test the previous one
mylist.pop(i)
if i > 0:
i -= 1
continue
# the branch continues, or we've found a good element.
# -> let's see what's next, if anything
i += 1
display_overlays=False
# files to fetch list - avoids counting a same file twice
# in size display (verbose mode)
myfetchlist=[]
for x in mylist:
pkg_type = x[0]
pkg_key = x[2]
if pkg_key not in self.applied_useflags:
if "binary" == pkg_type:
self.applied_useflags[pkg_key] = \
self.trees["/"]["bintree"].dbapi.aux_get(
pkg_key, ["USE"])[0].split()
elif "ebuild" == pkg_type:
self.pkgsettings.setcpv(pkg_key)
self.applied_useflags[pkg_key] = self.pkgsettings["USE"].split()
fetch=" "
if x[0]=="blocks":
addl=""+red("B")+" "+fetch+" "
resolved = self.trees[x[1]]["vartree"].resolve_key(x[2])
print "["+x[0]+" "+addl+"]",red(resolved),
if resolved!=x[2]:
if x[3]:
print red("(\""+x[2]+"\" is blocking "+x[3]+")")
else:
print red("(\""+x[2]+"\")")
else:
if x[3]:
print red("(is blocking "+x[3]+")")
else:
print
else:
if x[0] != "binary" and \
"fetch" in self.portdb.aux_get(
x[2], ["RESTRICT"])[0].split():
fetch = red("F")
if self.portdb.fetch_check(
x[2], self.applied_useflags[x[2]]):
fetch = green("f")
#we need to use "--emptrytree" testing here rather than "empty" param testing because "empty"
#param is used for -u, where you still *do* want to see when something is being upgraded.
myoldbest=""
if "--emptytree" not in self.myopts and \
self.trees[x[1]]["vartree"].exists_specific(x[2]):
addl=" "+yellow("R")+fetch+" "
elif "--emptytree" not in self.myopts and \
self.trees[x[1]]["vartree"].exists_specific_cat(x[2]):
if x[0] == "binary":
mynewslot = self.trees["/"]["bintree"].getslot(x[2])
elif x[0] == "ebuild":
mynewslot = self.trees["/"]["porttree"].getslot(x[2])
myoldlist = self.trees[x[1]]["vartree"].dbapi.match(
portage.pkgsplit(x[2])[0])
myinslotlist = [inst_pkg for inst_pkg in myoldlist
if mynewslot == self.trees[
self.settings["ROOT"]]["vartree"].getslot(inst_pkg)]
if myinslotlist:
myoldbest=portage.best(myinslotlist)
addl=" "+fetch
if portage.pkgcmp(portage.pkgsplit(x[2]), portage.pkgsplit(myoldbest)) < 0:
# Downgrade in slot
addl+=turquoise("U")+blue("D")
else:
# Update in slot
addl+=turquoise("U")+" "
else:
# New slot, mark it new.
addl=" "+green("NS")+fetch+" "
if "--changelog" in self.myopts:
changelogs.extend(self.calc_changelog(
self.portdb.findname(x[2]),
self.trees[x[1]]["vartree"].dep_bestmatch(
'/'.join(portage.catpkgsplit(x[2])[:2])), x[2]))
else:
addl=" "+green("N")+" "+fetch+" "
verboseadd=""
if x[2] in self.applied_useflags:
# USE flag display
if x[0] == "binary":
cur_iuse = self.trees["/"]["bintree"].dbapi.aux_get(
x[2],["IUSE"])[0].split()
elif x[0] == "ebuild":
cur_iuse = self.portdb.aux_get(
x[2], ["IUSE"])[0].split()
else:
cur_iuse = []
cur_iuse = portage.unique_array(cur_iuse)
cur_iuse = [flag for flag in cur_iuse
if flag not in self.settings.usemask]
cur_iuse.sort()
cur_use = self.applied_useflags[x[2]]
cur_use = [flag for flag in cur_use if flag in cur_iuse]
if myoldbest:
pkg = myoldbest
else:
pkg = x[2]
if self.trees[x[1]]["vartree"].dbapi.cpv_exists(pkg):
old_iuse, old_use = \
self.trees[x[1]]["vartree"].dbapi.aux_get(
pkg, ["IUSE", "USE"])
old_iuse = portage.unique_array(old_iuse.split())
old_iuse.sort()
old_use = old_use.split()
is_new = False
else:
old_iuse = []
old_use = []
is_new = True
old_iuse = [flag for flag in old_iuse
if flag not in self.settings.usemask]
old_use = [flag for flag in old_use if flag in old_iuse]
use_expand = self.settings["USE_EXPAND"].lower().split()
use_expand.sort()
use_expand.reverse()
use_expand_hidden = \
self.settings["USE_EXPAND_HIDDEN"].lower().split()
def map_to_use_expand(myvals):
ret = {}
for exp in use_expand:
ret[exp] = []
for val in myvals[:]:
if val.startswith(exp.lower()+"_"):
ret[exp].append(val[len(exp)+1:])
myvals.remove(val)
ret["USE"] = myvals
for exp in use_expand_hidden:
if exp in ret:
del ret[exp]
return ret
cur_iuse_map = map_to_use_expand(cur_iuse)
cur_use_map = map_to_use_expand(cur_use)
old_iuse_map = map_to_use_expand(old_iuse)
old_use_map = map_to_use_expand(old_use)
use_expand.sort()
use_expand.insert(0, "USE")
for key in use_expand:
if key in use_expand_hidden:
continue
verboseadd += create_use_string(key.upper(), cur_iuse_map[key], cur_use_map[key],
old_iuse_map[key], old_use_map[key], is_new)
if verbosity == 3:
# size verbose
mysize=0
if x[0] == "ebuild" and x[-1]!="nomerge":
myfilesdict = self.portdb.getfetchsizes(
x[2], useflags=self.applied_useflags[x[2]],
debug=self.edebug)
if myfilesdict is None:
myfilesdict="[empty/missing/bad digest]"
else:
for myfetchfile in myfilesdict.keys():
if myfetchfile not in myfetchlist:
mysize+=myfilesdict[myfetchfile]
myfetchlist.append(myfetchfile)
totalsize+=mysize
verboseadd+=format_size(mysize)+" "
# overlay verbose
# XXX: Invalid binaries have caused tracebacks here. 'if file_name'
# x = ['binary', '/', 'sys-apps/pcmcia-cs-3.2.7.2.6', 'merge']
file_name = self.portdb.findname(x[2])
if file_name: # It might not exist in the tree
dir_name=os.path.abspath(os.path.dirname(file_name)+"/../..")
if (overlays_real.count(dir_name)>0):
verboseadd+=teal("["+str(overlays_real.index(
os.path.normpath(dir_name))+1)+"]")+" "
display_overlays=True
else:
verboseadd += "[No ebuild?]"
xs=portage.pkgsplit(x[2])
if xs[2]=="r0":
xs[2]=""
else:
xs[2]="-"+xs[2]
if self.pkgsettings.has_key("COLUMNWIDTH"):
mywidth=int(self.pkgsettings.settings["COLUMNWIDTH"])
else:
mywidth=130
oldlp=mywidth-30
newlp=oldlp-30
indent=""
if "--tree" in self.myopts:
indent=" "*mygraph.depth(string.join(x))
if myoldbest:
myoldbest=portage.pkgsplit(myoldbest)[1]+"-"+portage.pkgsplit(myoldbest)[2]
if myoldbest[-3:]=="-r0":
myoldbest=myoldbest[:-3]
myoldbest=blue("["+myoldbest+"]")
if x[1]!="/":
if myoldbest:
myoldbest +=" "
if "--columns" in self.myopts:
if "--quiet" in self.myopts:
myprint=addl+" "+indent+darkgreen(xs[0])
myprint=myprint+darkblue(" "+xs[1]+xs[2])+" "
myprint=myprint+myoldbest
myprint=myprint+darkgreen("to "+x[1])
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(xs[0])
if (newlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(newlp-nc_len(myprint)))
myprint=myprint+"["+darkblue(xs[1]+xs[2])+"] "
if (oldlp-nc_len(myprint)) > 0:
myprint=myprint+" "*(oldlp-nc_len(myprint))
myprint=myprint+myoldbest
myprint=myprint+darkgreen("to "+x[1])+" "+verboseadd
else:
myprint="["+x[0]+" "+addl+"] "+darkgreen(x[2])+" "+myoldbest+darkgreen("to "+x[1])+" "+verboseadd
else:
if "--columns" in self.myopts:
if "--quiet" in self.myopts:
myprint=addl+" "+indent+darkgreen(xs[0])
myprint=myprint+" "+green(xs[1]+xs[2])+" "
myprint=myprint+myoldbest
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(xs[0])
if (newlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(newlp-nc_len(myprint)))
myprint=myprint+green(" ["+xs[1]+xs[2]+"] ")
if (oldlp-nc_len(myprint)) > 0:
myprint=myprint+(" "*(oldlp-nc_len(myprint)))
myprint=myprint+myoldbest+" "+verboseadd
else:
if x[3]=="nomerge":
myprint=darkblue("[nomerge ] "+indent+x[2]+" "+myoldbest+" ")+verboseadd
else:
myprint="["+x[0]+" "+addl+"] "+indent+darkgreen(x[2])+" "+myoldbest+" "+verboseadd
p.append(myprint)
mysplit = portage.pkgsplit(x[2])
if "--tree" not in self.myopts and mysplit and \
len(mysplit) == 3 and mysplit[0] == "sys-apps/portage" and \
x[1] == "/":
if mysplit[2] == "r0":
myversion = mysplit[1]
else:
myversion = "%s-%s" % (mysplit[1], mysplit[2])
if myversion != portage.VERSION :
if "--emptytree" in self.myopts:
p.append(red("***")+" Please update portage to the above version before proceeding.")
p.append(" Failure to do so may result in failed or improper merges.")
p.append(" A simple '"+green("emerge portage")+"' is sufficient.")
p.append("")
elif mylist.index(x) < len(mylist) - 1 and \
"livecvsportage" not in self.settings.features:
p.append(red("*** Portage will stop merging at this point and reload itself,"))
p.append(red(" then resume the merge."))
print
del mysplit
for x in p:
print x
if verbosity == 3:
print
print "Total size of downloads: "+format_size(totalsize)
if overlays and display_overlays:
print "Portage overlays:"
y=0
for x in overlays:
y=y+1
print " "+teal("["+str(y)+"]"),x
if "--changelog" in self.myopts:
print
for revision,text in changelogs:
print bold('*'+revision)
sys.stdout.write(text)
def calc_changelog(self,ebuildpath,current,next):
current = '-'.join(portage.catpkgsplit(current)[1:])
if current.endswith('-r0'): current = current[:-3]
next = '-'.join(portage.catpkgsplit(next)[1:])
if next.endswith('-r0'): next = next[:-3]
changelogpath = os.path.join(os.path.split(ebuildpath)[0],'ChangeLog')
try:
changelog = open(changelogpath).read()
except SystemExit, e:
raise # Needed else can't exit
except:
return []
divisions = self.find_changelog_tags(changelog)
#print 'XX from',current,'to',next
#for div,text in divisions: print 'XX',div
# skip entries for all revisions above the one we are about to emerge
for i in range(len(divisions)):
if divisions[i][0]==next:
divisions = divisions[i:]
break
# find out how many entries we are going to display
for i in range(len(divisions)):
if divisions[i][0]==current:
divisions = divisions[:i]
break
else:
# couldnt find the current revision in the list. display nothing
return []
return divisions
def find_changelog_tags(self,changelog):
divs = []
release = None
while 1:
match = re.search(r'^\*\ ?([-a-zA-Z0-9_.+]*)(?:\ .*)?\n',changelog,re.M)
if match is None:
if release is not None:
divs.append((release,changelog))
return divs
if release is not None:
divs.append((release,changelog[:match.start()]))
changelog = changelog[match.end():]
release = match.group(1)
if release.endswith('.ebuild'):
release = release[:-7]
if release.endswith('-r0'):
release = release[:-3]
def outdated(self):
return self.outdatedpackages
def merge(self, mylist, favorites):
returnme=0
mymergelist=[]
#check for blocking dependencies
if "--fetchonly" not in self.myopts and \
"--buildpkgonly" not in self.myopts:
for x in mylist:
if x[0]=="blocks":
print "\n!!! Error: the "+x[2]+" package conflicts with another package;"
print "!!! the two packages cannot be installed on the same system together."
print "!!! Please use 'emerge --pretend' to determine blockers."
print
if "--pretend" not in self.myopts:
try:
del portage.mtimedb["resume"]
except KeyError:
pass
sys.exit(1)
#buildsyspkg: I need mysysdict also on resume (moved from the else block)
mysysdict = genericdict(getlist(self.settings, "system"))
if "--resume" in self.myopts:
# We're resuming.
print green("*** Resuming merge...")
emergelog(" *** Resuming merge...")
mymergelist=portage.mtimedb["resume"]["mergelist"][:]
if "--skipfirst" in self.myopts and mymergelist:
del portage.mtimedb["resume"]["mergelist"][0]
del mymergelist[0]
validate_merge_list(mymergelist)
else:
myfavs = portage.grabfile(
os.path.join(self.settings["ROOT"], portage.WORLD_FILE))
myfavdict=genericdict(myfavs)
for x in range(len(mylist)):
if mylist[x][3]!="nomerge":
# Add to the mergelist
mymergelist.append(mylist[x])
else:
myfavkey=portage.cpv_getkey(mylist[x][2])
if "--onlydeps" in self.myopts:
continue
# Add to the world file. Since we won't be able to later.
if "--fetchonly" not in self.myopts and \
myfavkey in favorites:
#don't record if already in system profile or already recorded
if (not mysysdict.has_key(myfavkey)) and (not myfavdict.has_key(myfavkey)):
#we don't have a favorites entry for this package yet; add one
myfavdict[myfavkey]=myfavkey
print ">>> Recording",myfavkey,"in \"world\" favorites file..."
if "--fetchonly" not in self.myopts:
portage.write_atomic(
os.path.join(self.settings["ROOT"], portage.WORLD_FILE),
"\n".join(myfavdict.values()))
portage.mtimedb["resume"]["mergelist"]=mymergelist[:]
# We need to yank the harmful-to-new-builds settings from features.
myorigfeat=self.pkgsettings["FEATURES"]
myfeat=myorigfeat.split()
while ("keeptemp" in myfeat):
del myfeat[myfeat.index("keeptemp")]
while ("keepwork" in myfeat):
del myfeat[myfeat.index("keepwork")]
self.pkgsettings["FEATURES"]=string.join(myfeat)
if "parallel-fetch" in myfeat and \
not ("--ask" in self.myopts or "--pretend" in self.myopts or \
"--fetchonly" in self.myopts):
if "distlocks" not in myfeat:
print red("!!!")
print red("!!!")+" parallel-fetching requires the distlocks feature enabled"
print red("!!!")+" you have it disabled, thus parallel-fetching is being disabled"
print red("!!!")
elif len(mymergelist) > 1:
print ">>> starting parallel fetching"
pid = os.fork()
if not pid:
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
time.sleep(3) # allow the parent to have first fetch
fetchlog = "/var/log/emerge-fetch.log"
sys.stdout = open(fetchlog, "w")
sys.stderr = sys.stdout
os.dup2(sys.stdout.fileno(), 1)
os.dup2(sys.stderr.fileno(), 2)
portage_util.apply_secpass_permissions(fetchlog,
uid=portage.portage_uid, gid=portage.portage_gid,
mode=0660)
# wipe the mtimedb so that portage doesn't attempt to flush it.
# do not convert this code away from a fork without correcting this.
portage.mtimedb = None
for x in ("autoaddcvs", "cvs"):
try: myfeat.remove(x)
except ValueError: pass
self.pkgsettings["FEATURES"] = " ".join(myfeat)
ret = 0
for x in mymergelist:
if x[0] != "ebuild":
continue
self.pkgsettings.reset()
self.pkgsettings.setcpv(x[2])
try:
ret = portage.doebuild(self.portdb.findname(x[2]),
"fetch", x[1], self.pkgsettings,
cleanup=0, fetchonly=True, tree="porttree")
except SystemExit:
raise
except Exception:
ret = 1
sys.exit(0)
portage.portage_exec.spawned_pids.append(pid)
mergecount=0
for x in mymergelist:
mergecount+=1
myroot=x[1]
pkgindex=2
if x[0]=="blocks":
pkgindex=3
y = self.portdb.findname(x[pkgindex])
if "--pretend" not in self.myopts:
print ">>> Emerging ("+str(mergecount)+" of "+str(len(mymergelist))+")",x[pkgindex],"to",x[1]
emergelog(" >>> emerge ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" to "+x[1])
self.pkgsettings["EMERGE_FROM"] = x[0][:]
self.pkgsettings.backup_changes("EMERGE_FROM")
self.pkgsettings.reset()
#buildsyspkg: Check if we need to _force_ binary package creation
issyspkg = ("buildsyspkg" in myfeat) \
and x[0] != "blocks" \
and mysysdict.has_key(portage.cpv_getkey(x[2])) \
and "--buildpkg" not in self.myopts
if x[0] in ["ebuild","blocks"]:
if x[0] == "blocks" and "--fetchonly" not in self.myopts:
raise Exception, "Merging a blocker"
elif "--fetchonly" in self.myopts or \
"--fetch-all-uri" in self.myopts:
if "--fetch-all-uri" in self.myopts:
retval = portage.doebuild(y, "fetch", myroot,
self.pkgsettings, self.edebug,
"--pretend" in self.myopts, fetchonly=1,
fetchall=1, tree="porttree")
else:
retval = portage.doebuild(y, "fetch", myroot,
self.pkgsettings, self.edebug,
"--pretend" in self.myopts, fetchonly=1,
tree="porttree")
if (retval is None) or retval:
print
print "!!! Fetch for",y,"failed, continuing..."
print
returnme=1
continue
elif "--buildpkg" in self.myopts or issyspkg:
#buildsyspkg: Sounds useful to display something, but I don't know if we should also log it
if issyspkg:
print ">>> This is a system package, let's pack a rescue tarball."
#emergelog(">>> This is a system package, let's pack a rescue tarball.")
#create pkg, then merge pkg
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Clean"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Cleaning ("+x[pkgindex]+"::"+y+")", short_msg=short_msg)
retval = portage.doebuild(y, "clean", myroot,
self.pkgsettings, self.edebug, cleanup=1,
tree="porttree")
if (retval is None):
portage_util.writemsg("Unable to run required binary.\n",
noiselevel=-1)
sys.exit(127)
if retval:
sys.exit(retval)
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Compile"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Compiling/Packaging ("+x[pkgindex]+"::"+y+")", short_msg=short_msg)
retval = portage.doebuild(y, "package", myroot,
self.pkgsettings, self.edebug, tree="porttree")
if (retval is None):
portage_util.writemsg("Unable to run required binary.\n",
noiselevel=-1)
sys.exit(127)
if retval:
sys.exit(retval)
#dynamically update our database
if "--buildpkgonly" not in self.myopts:
self.trees[
self.settings["ROOT"]]["bintree"].inject(x[2])
mytbz2 = self.trees[
self.settings["ROOT"]]["bintree"].getname(x[2])
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Merge"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Merging ("+x[pkgindex]+"::"+y+")", short_msg=short_msg)
self.pkgsettings["EMERGE_FROM"] = "binary"
self.pkgsettings.backup_changes("EMERGE_FROM")
retval=portage.pkgmerge(mytbz2,myroot,self.pkgsettings)
if retval is None:
sys.exit(1)
elif "noclean" not in self.pkgsettings.features:
portage.doebuild(y, "clean", myroot, self.pkgsettings,
self.edebug, tree="porttree")
else:
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Clean"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Cleaning ("+x[pkgindex]+"::"+y+")", short_msg=short_msg)
retval = portage.doebuild(y, "clean", myroot,
self.pkgsettings, self.edebug, cleanup=1,
tree="porttree")
if (retval is None):
portage_util.writemsg("Unable to run required binary.\n",
noiselevel=-1)
sys.exit(127)
if retval:
sys.exit(retval)
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Compile"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Compiling/Merging ("+x[pkgindex]+"::"+y+")", short_msg=short_msg)
retval = portage.doebuild(y, "merge", myroot,
self.pkgsettings, self.edebug, tree="porttree")
if (retval is None):
portage_util.writemsg("Unable to run required binary.\n",
noiselevel=-1)
sys.exit(127)
if retval:
sys.exit(retval)
#dynamically update our database
elif x[0]=="binary":
#merge the tbz2
mytbz2 = self.trees[
self.settings["ROOT"]]["bintree"].getname(x[2])
if self.trees[self.settings["ROOT"]]["bintree"].isremote(x[2]):
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Fetch"
emergelog(" --- ("+str(mergecount)+" of "+str(len(mymergelist))+") Fetching Binary ("+x[pkgindex]+"::"+mytbz2+")", short_msg=short_msg)
if not self.trees[
self.settings["ROOT"]]["bintree"].gettbz2(x[2]):
sys.exit(1)
if "--fetchonly" in self.myopts or \
"--fetch-all-uri" in self.myopts:
continue
short_msg = "emerge: ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[pkgindex]+" Merge Binary"
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Merging Binary ("+x[pkgindex]+"::"+mytbz2+")", short_msg=short_msg)
retval=portage.pkgmerge(mytbz2,x[1],self.pkgsettings)
if retval is None:
sys.exit(1)
#need to check for errors
if "--buildpkgonly" not in self.myopts:
self.trees[x[1]]["vartree"].inject(x[2])
myfavkey=portage.cpv_getkey(x[2])
if "--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts and \
myfavkey in favorites:
myfavs = portage.grabfile(os.path.join(myroot, portage.WORLD_FILE))
myfavdict=genericdict(myfavs)
#don't record if already in system profile or already recorded
if (not mysysdict.has_key(myfavkey)) and (not myfavdict.has_key(myfavkey)):
#we don't have a favorites entry for this package yet; add one
myfavdict[myfavkey]=myfavkey
print ">>> Recording",myfavkey,"in \"world\" favorites file..."
emergelog(" === ("+str(mergecount)+" of "+str(len(mymergelist))+") Updating world file ("+x[pkgindex]+")")
portage.write_atomic(
os.path.join(myroot, portage.WORLD_FILE),
"\n".join(myfavdict.values()))
if "--pretend" not in self.myopts and \
"--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts:
# Clean the old package that we have merged over top of it.
if self.pkgsettings["AUTOCLEAN"]=="yes":
xsplit=portage.pkgsplit(x[2])
emergelog(" >>> AUTOCLEAN: "+xsplit[0])
retval = unmerge_overlapping(x[2], x[1],
self.pkgsettings, self.trees[x[1]]["vartree"])
if not retval:
emergelog(" --- AUTOCLEAN: Nothing unmerged.")
else:
portage.writemsg_stdout(colorize("WARN", "WARNING:")
+ " AUTOCLEAN is disabled. This can cause serious"
+ " problems due to overlapping packages.\n")
# Figure out if we need a restart.
mysplit=portage.pkgsplit(x[2])
if mysplit[0] == "sys-apps/portage" and x[1] == "/":
myver=mysplit[1]+"-"+mysplit[2]
if myver[-3:]=='-r0':
myver=myver[:-3]
if (myver != portage.VERSION) and \
"livecvsportage" not in self.settings.features:
if len(mymergelist) > mergecount:
emergelog(" ::: completed emerge ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[2]+" to "+x[1])
emergelog(" *** RESTARTING emerge via exec() after change of portage version.")
del portage.mtimedb["resume"]["mergelist"][0]
portage.run_exitfuncs()
mynewargv=[sys.argv[0],"--resume"]
badlongopts = ("--ask","--tree","--changelog","--skipfirst","--resume")
for arg in self.myopts:
if arg in badlongopts:
continue
mynewargv.append(arg)
# priority only needs to be adjusted on the first run
os.environ["PORTAGE_NICENESS"] = "0"
os.execv(mynewargv[0], mynewargv)
if "--pretend" not in self.myopts and \
"--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts:
if "noclean" not in self.settings.features:
short_msg = "emerge: (%s of %s) %s Clean Post" % \
(mergecount, len(mymergelist), x[pkgindex])
emergelog(" === (%s of %s) Post-Build Cleaning (%s::%s)" % \
(mergecount, len(mymergelist), x[pkgindex], y), short_msg=short_msg)
emergelog(" ::: completed emerge ("+str(mergecount)+" of "+str(len(mymergelist))+") "+x[2]+" to "+x[1])
# Unsafe for parallel merges
del portage.mtimedb["resume"]["mergelist"][0]
# Commit after each merge so that --resume may still work in
# in the event that portage is not allowed to exit normally
# due to power failure, SIGKILL, etc...
portage.commit_mtimedb()
emergelog(" *** Finished. Cleaning up...")
# We're out of the loop... We're done. Delete the resume data.
if portage.mtimedb.has_key("resume"):
del portage.mtimedb["resume"]
if "--pretend" not in self.myopts:
if "--fetchonly" not in self.myopts and \
"--fetch-all-uri" not in self.myopts:
if (mergecount>0):
if retval:
portage.env_update()
#by doing an exit this way, --fetchonly can continue to try to
#fetch everything even if a particular download fails.
if "--fetchonly" in self.myopts or "--fetch-all-uri" in self.myopts:
if returnme:
print "\n\n!!! Some fetch errors were encountered. Please see above for details.\n\n"
sys.exit(returnme)
else:
sys.exit(0)
def unmerge_overlapping(pkg_key, myroot, mysettings, vartree):
"""Unmerge any packages that overlap with the given package (overlapping
packages fill the same SLOT). Unlike emerge's unmerge() function, this
function does not assume that packages are to be unmerged from the target
ROOT. This function is only needed in the case where ROOT!=/ and the
previous version of a build time dependency (that has been upgraded) needs
to be cleaned from / (instead of the target ROOT). When the incorrect
assumptions in unmerge() have been fixed, this function can be removed."""
overlapping = []
ommitted_versions = []
mydbapi = vartree.dbapi
myslot = mydbapi.aux_get(pkg_key, ["SLOT"])[0]
mycp = portage.pkgsplit(pkg_key)[0]
for other_pkg in mydbapi.cp_list(mycp):
if other_pkg == pkg_key:
continue
other_slot = mydbapi.aux_get(other_pkg, ["SLOT"])[0]
if myslot == other_slot:
overlapping.append(other_pkg)
else:
ommitted_versions.append(other_pkg)
if overlapping:
def get_version(pkg_key):
cp, pv, rev = portage.pkgsplit(pkg_key)
if rev == "r0":
return pv
else:
return "%s-%s" % (pv, rev)
selected_versions = ",".join(map(get_version, overlapping))
protected_version = get_version(pkg_key)
if ommitted_versions:
ommitted_versions = ",".join(map(get_version, ommitted_versions))
else:
ommitted_versions = "none"
portage.writemsg_stdout("\n %s\n" % bold(mycp), noiselevel=-1)
portage.writemsg_stdout("selected: ".rjust(14) + selected_versions + \
"\n", noiselevel=-1)
portage.writemsg_stdout("protected: ".rjust(14) + protected_version + \
"\n", noiselevel=-1)
portage.writemsg_stdout("omitted: ".rjust(14) + ommitted_versions + \
"\n", noiselevel=-1)
portage.writemsg_stdout("\n>>>" + red("'Selected'") + \
" packages are slated for removal.\n", noiselevel=0)
portage.writemsg_stdout(">>>" + green("'Protected'") + " and " + \
green("'omitted'") + " packages will not be removed.\n\n",
noiselevel=0)
countdown(int(mysettings["CLEAN_DELAY"]), ">>> Unmerging")
for other_pkg in overlapping:
portage.writemsg_stdout(">>> Unmerging %s...\n" % other_pkg ,
noiselevel=-1)
emergelog("=== Unmerging... (%s)" % other_pkg)
mysplit = other_pkg.split("/")
retval = portage.unmerge(mysplit[0], mysplit[1], myroot,
mysettings, mytrimworld=False, vartree=vartree)
if retval:
emergelog(" !!! unmerge FAILURE: " + other_pkg)
else:
emergelog(" >>> unmerge success: " + other_pkg)
return 1
return 0
def unmerge(settings, myopts, vartree, unmerge_action, unmerge_files,
raise_on_missing=True):
candidate_catpkgs=[]
global_unmerge=0
realsyslist = getlist(settings, "system")
syslist = []
for x in realsyslist:
mycp = portage.dep_getkey(x)
if mycp in settings.getvirtuals():
providers = []
for provider in settings.getvirtuals()[mycp]:
if vartree.dbapi.match(provider):
providers.append(provider)
if len(providers) == 1:
syslist.extend(providers)
else:
syslist.append(mycp)
mysettings = portage.config(clone=settings)
if not unmerge_files or "world" in unmerge_files or "system" in unmerge_files:
if "unmerge"==unmerge_action:
print
print bold("emerge unmerge")+" can only be used with specific package names, not with "+bold("world")+" or"
print bold("system")+" targets."
print
return 0
else:
global_unmerge=1
localtree = vartree
# process all arguments and add all valid db entries to candidate_catpkgs
if global_unmerge:
if not unmerge_files or "world" in unmerge_files:
candidate_catpkgs.extend(localtree.getallnodes())
elif "system" in unmerge_files:
candidate_catpkgs.extend(getlist(settings, "system"))
else:
#we've got command-line arguments
if not unmerge_files:
print "\nNo packages to unmerge have been provided.\n"
return 0
for x in unmerge_files:
arg_parts=x.split('/')
if (x[0] not in [".","/"]) and (arg_parts[-1][-7:] != ".ebuild"):
#possible cat/pkg or dep; treat as such
candidate_catpkgs.append(x)
elif unmerge_action in ["prune","clean"]:
print "\n!!! Prune and clean do not accept individual ebuilds as arguments;\n skipping.\n"
continue
else:
# it appears that the user is specifying an installed ebuild and we're in "unmerge" mode, so it's
# ok.
if not os.path.exists(x):
print "\n!!! The path '"+x+"' doesn't exist.\n"
return 0
absx = os.path.abspath(x)
sp_absx = absx.split("/")
if sp_absx[-1][-7:] == ".ebuild":
del sp_absx[-1]
absx = string.join(sp_absx,"/")
sp_absx_len = len(sp_absx)
vdb_path = os.path.join(settings["ROOT"], portage.VDB_PATH)
vdb_len = len(vdb_path)
sp_vdb = vdb_path.split("/")
sp_vdb_len = len(sp_vdb)
if not os.path.exists(absx+"/CONTENTS"):
print "!!! Not a valid db dir: "+str(absx)
return 0
if sp_absx_len <= sp_vdb_len:
# The Path is shorter... so it can't be inside the vdb.
print sp_absx
print absx
print "\n!!!",x,"cannot be inside "+vdb_path+"; aborting.\n"
return 0
for idx in range(0,sp_vdb_len):
if (idx >= sp_absx_len) or (sp_vdb[idx] != sp_absx[idx]):
print sp_absx
print absx
print "\n!!!",x,"is not inside "+vdb_path+"; aborting.\n"
return 0
print "="+string.join(sp_absx[sp_vdb_len:],"/")
candidate_catpkgs.append("="+string.join(sp_absx[sp_vdb_len:],"/"))
newline=""
if (not "--quiet" in myopts):
newline="\n"
if settings["ROOT"] != "/":
print darkgreen(newline+">>> Using system located in ROOT tree "+settings["ROOT"])
if (("--pretend" in myopts) or ("--ask" in myopts)) and not ("--quiet" in myopts):
print darkgreen(newline+">>> These are the packages that would be unmerged:")
pkgmap={}
numselected=0
for x in candidate_catpkgs:
#cycle through all our candidate deps and determine what will and will not get unmerged
try:
mymatch=localtree.dep_match(x)
except KeyError:
mymatch=None
except ValueError, errpkgs:
print "\n\n!!! The short ebuild name \"" + x + "\" is ambiguous. Please specify"
print "!!! one of the following fully-qualified ebuild names instead:\n"
for i in errpkgs[0]:
print " " + green(i)
print
sys.exit(1)
if not mymatch and x[0] not in "<>=~":
#add a "=" if missing
mymatch=localtree.dep_match("="+x)
if not mymatch:
if raise_on_missing:
raise portage_exception.PackageNotFound(x)
else:
portage.writemsg("\n--- Couldn't find '%s' to %s.\n" % \
(x, unmerge_action), noiselevel=-1)
continue
mykey = portage.key_expand(
portage.dep_getkey(
mymatch[0]), mydb=vartree.dbapi, settings=settings)
if not pkgmap.has_key(mykey):
pkgmap[mykey]={"protected":[], "selected":[], "omitted":[] }
if unmerge_action=="unmerge":
for y in mymatch:
if y not in pkgmap[mykey]["selected"]:
pkgmap[mykey]["selected"].append(y)
numselected=numselected+len(mymatch)
else:
#unmerge_action in ["prune", clean"]
slotmap={}
for mypkg in mymatch:
if unmerge_action=="clean":
myslot=localtree.getslot(mypkg)
else:
#since we're pruning, we don't care about slots and put all the pkgs in together
myslot=0
if not slotmap.has_key(myslot):
slotmap[myslot]={}
slotmap[myslot][localtree.dbapi.cpv_counter(mypkg)]=mypkg
for myslot in slotmap.keys():
counterkeys=slotmap[myslot].keys()
counterkeys.sort()
if not counterkeys:
continue
counterkeys.sort()
pkgmap[mykey]["protected"].append(slotmap[myslot][counterkeys[-1]])
del counterkeys[-1]
#be pretty and get them in order of merge:
for ckey in counterkeys:
pkgmap[mykey]["selected"].append(slotmap[myslot][ckey])
numselected=numselected+1
#ok, now the last-merged package is protected, and the rest are selected
if global_unmerge and not numselected:
print "\n>>> No outdated packages were found on your system.\n"
return 0
if not numselected:
print "\n>>> No packages selected for removal by",unmerge_action+".\n"
return 0
for x in pkgmap.keys():
for y in localtree.dep_match(x):
if y not in pkgmap[x]["omitted"] and \
y not in pkgmap[x]["selected"] and \
y not in pkgmap[x]["protected"]:
pkgmap[x]["omitted"].append(y)
if global_unmerge and not pkgmap[x]["selected"]:
#avoid cluttering the preview printout with stuff that isn't getting unmerged
continue
if not (pkgmap[x]["protected"] or pkgmap[x]["omitted"]) and (x in syslist):
print red("\a\n\n!!! '%s' is part of your system profile." % x)
print yellow("\a!!! Unmerging it may be damaging to your system.\n")
if "--pretend" not in myopts and "--ask" not in myopts:
countdown(int(settings["EMERGE_WARNING_DELAY"]),
colorize("WARN", "Press Ctrl-C to Stop"))
print "\n "+white(x)
for mytype in ["selected","protected","omitted"]:
print string.rjust(mytype,12)+":",
if pkgmap[x][mytype]:
for mypkg in pkgmap[x][mytype]:
mysplit=portage.catpkgsplit(mypkg)
if mysplit[3]=="r0":
myversion=mysplit[2]
else:
myversion=mysplit[2]+"-"+mysplit[3]
if mytype=="selected":
print red(myversion),
else:
print green(myversion),
else:
print "none",
print
if (not "--quiet" in myopts):
print "\n>>>",red("'Selected'"),"packages are slated for removal."
print ">>>",green("'Protected'"),"and",green("'omitted'"),"packages will not be removed.\n"
if "--pretend" in myopts:
#we're done... return
return 0
if "--ask" in myopts:
if userquery("Would you like to unmerge these packages?")=="No":
# enter pretend mode for correct formatting of results
myopts+=["--pretend"]
print
print "Quitting."
print
return 0
#the real unmerging begins, after a short delay....
countdown(int(settings["CLEAN_DELAY"]), ">>> Unmerging")
for x in pkgmap.keys():
for y in pkgmap[x]["selected"]:
print ">>> Unmerging "+y+"..."
emergelog("=== Unmerging... ("+y+")")
mysplit=string.split(y,"/")
#unmerge...
retval = portage.unmerge(mysplit[0], mysplit[1], settings["ROOT"],
mysettings, unmerge_action not in ["clean","prune"])
if retval:
emergelog(" !!! unmerge FAILURE: "+y)
else:
emergelog(" >>> unmerge success: "+y)
#run ldconfig, etc...
portage.env_update()
if not numselected:
return 0
else:
return 1
def chk_updated_info_files(root, infodirs, prev_mtimes, retval):
print
if os.path.exists("/usr/bin/install-info"):
regen_infodirs=[]
for z in infodirs:
if z=='':
continue
inforoot=normpath(root+z)
if os.path.isdir(inforoot):
infomtime = os.stat(inforoot).st_mtime
if inforoot not in prev_mtimes or \
prev_mtimes[inforoot] != infomtime:
regen_infodirs.append(inforoot)
if not regen_infodirs:
print " "+green("*")+" GNU info directory index is up-to-date."
else:
print " "+green("*")+" Regenerating GNU info directory index..."
icount=0
badcount=0
for inforoot in regen_infodirs:
if inforoot=='':
continue
try:
os.rename(inforoot+"/dir",inforoot+"/dir.old")
except SystemExit, e:
raise # Needed else can't exit
except:
pass
if not os.path.isdir(inforoot):
continue
errmsg = ""
for x in os.listdir(inforoot):
if (x[0] == ".") or (x in ["dir","dir.old"]) or (os.path.isdir(inforoot+"/"+x)):
continue
myso=commands.getstatusoutput("LANG=C LANGUAGE=C /usr/bin/install-info --dir-file="+inforoot+"/dir "+inforoot+"/"+x)[1]
existsstr="already exists, for file `"
if myso!="":
if re.search(existsstr,myso):
# Already exists... Don't increment the count for this.
pass
elif myso[:44]=="install-info: warning: no info dir entry in ":
# This info file doesn't contain a DIR-header: install-info produces this
# (harmless) warning (the --quiet switch doesn't seem to work).
# Don't increment the count for this.
pass
else:
badcount=badcount+1
errmsg += myso + "\n"
icount=icount+1
#update mtime so we can potentially avoid regenerating.
prev_mtimes[inforoot] = os.stat(inforoot).st_mtime
if badcount:
print " "+yellow("*")+" Processed",icount,"info files;",badcount,"errors."
print errmsg
else:
print " "+green("*")+" Processed",icount,"info files."
def post_emerge(settings, info_mtimes, retval):
target_root = settings["ROOT"]
config_protect = settings.get("CONFIG_PROTECT","").split()
infodirs = settings.get("INFOPATH","").split(":") + \
settings.get("INFODIR","").split(":")
os.chdir("/")
emergelog(" *** exiting successfully.")
if "noinfo" not in portage.settings.features:
chk_updated_info_files(target_root, infodirs, info_mtimes, retval)
chk_updated_cfg_files(target_root, config_protect)
sys.exit(retval)
def chk_updated_cfg_files(target_root, config_protect):
if config_protect:
#number of directories with some protect files in them
procount=0
for x in config_protect:
x = os.path.join(target_root, x.lstrip(os.path.sep))
if os.path.isdir(x):
a=commands.getstatusoutput("cd "+x+"; find . -iname '._cfg????_*'")
if a[0]!=0:
print " "+red("*")+" error scanning",x
else:
files=string.split(a[1])
if files:
procount=procount+1
print " "+yellow("* IMPORTANT:")+"",len(files),"config files in",x,"need updating."
if procount:
#print " "+yellow("*")+" Type "+green("emerge --help config")+" to learn how to update config files."
print " "+yellow("*")+" Type "+green("emerge --help config")+" to learn how to update config files."
print
def is_valid_package_atom(x):
testkey = portage.dep_getkey(x)
if testkey.startswith("null/"):
testatom = x.replace(testkey[5:], "cat/"+testkey[5:])
elif "/" not in x:
testatom = "cat/"+x
else:
testatom = x
return portage.isvalidatom(testatom)
def validate_merge_list(mergelist):
"""Validate the list to make sure all the packages are still available.
This is needed for --resume."""
for (pkg_type, myroot, pkg_key, action) in mergelist:
if pkg_type == "binary" and not portage.db["/"]["bintree"].dbapi.match("="+pkg_key) or \
pkg_type == "ebuild" and not portage.db["/"]["porttree"].dbapi.xmatch("match-all", "="+pkg_key):
print red("!!! Error: The resume list contains packages that are no longer")
print red("!!! available to be emerged. Please restart/continue")
print red("!!! the merge operation manually.")
sys.exit(1)
def action_sync(myopts, myaction):
emergelog(" === "+str(myaction))
myportdir=portage.settings["PORTDIR"]
if myportdir[-1]=="/":
myportdir=myportdir[:-1]
if not os.path.exists(myportdir):
print ">>>",myportdir,"not found, creating it."
os.makedirs(myportdir,0755)
syncuri=string.rstrip(portage.settings["SYNC"])
os.umask(0022)
if myaction == "metadata":
print "skipping sync"
updatecache_flg = True
tmpservertimestampfile = None
elif syncuri[:8]=="rsync://":
if not os.path.exists("/usr/bin/rsync"):
print "!!! /usr/bin/rsync does not exist, so rsync support is disabled."
print "!!! Type \"emerge net-misc/rsync\" to enable rsync support."
sys.exit(1)
mytimeout=180
rsync_opts = []
if portage.settings["PORTAGE_RSYNC_OPTS"] == "":
portage.writemsg("PORTAGE_RSYNC_OPTS empty or unset, using hardcoded defaults\n")
rsync_opts.extend([
"--recursive", # Recurse directories
"--links", # Consider symlinks
"--safe-links", # Ignore links outside of tree
"--perms", # Preserve permissions
"--times", # Preserive mod times
"--compress", # Compress the data transmitted
"--force", # Force deletion on non-empty dirs
"--whole-file", # Don't do block transfers, only entire files
"--delete", # Delete files that aren't in the master tree
"--delete-after", # Delete only after everything else is done
"--stats", # Show final statistics about what was transfered
"--timeout="+str(mytimeout), # IO timeout if not done in X seconds
"--exclude='/distfiles'", # Exclude distfiles from consideration
"--exclude='/local'", # Exclude local from consideration
"--exclude='/packages'", # Exclude packages from consideration
])
else:
# The below validation is not needed when using the above hardcoded
# defaults.
portage.writemsg("Using PORTAGE_RSYNC_OPTS instead of hardcoded defaults\n", 1)
rsync_opts.extend(portage.settings["PORTAGE_RSYNC_OPTS"].split())
for opt in ("--recursive", "--times"):
if opt not in rsync_opts:
portage.writemsg(yellow("WARNING:") + " adding required option " + \
"%s not included in PORTAGE_RSYNC_OPTS\n" % opt)
rsync_opts.append(opt)
for exclude in ("distfiles", "local", "packages"):
opt = "--exclude='/%s'" % exclude
if opt not in rsync_opts:
portage.writemsg(yellow("WARNING:") + \
" adding required option %s not included in " % opt + \
"PORTAGE_RSYNC_OPTS (can be overridden with --exclude='!')\n")
rsync_opts.append(opt)
if portage.settings["RSYNC_TIMEOUT"] != "":
portage.writemsg("WARNING: usage of RSYNC_TIMEOUT is deprecated, " + \
"use PORTAGE_RSYNC_EXTRA_OPTS instead\n")
try:
mytimeout = int(portage.settings["RSYNC_TIMEOUT"])
rsync_opts.append("--timeout=%d" % mytimeout)
except ValueError, e:
portage.writemsg("!!! %s\n" % str(e))
# TODO: determine options required for official servers
if syncuri.rstrip("/").endswith(".gentoo.org/gentoo-portage"):
def rsync_opt_startswith(opt_prefix):
for x in rsync_opts:
if x.startswith(opt_prefix):
return True
return False
if not rsync_opt_startswith("--timeout="):
rsync_opts.append("--timeout=%d" % mytimeout)
for opt in ("--compress", "--whole-file"):
if opt not in rsync_opts:
portage.writemsg(yellow("WARNING:") + " adding required option " + \
"%s not included in PORTAGE_RSYNC_OPTS\n" % opt)
rsync_opts.append(opt)
if "--quiet" in myopts:
rsync_opts.append("--quiet") # Shut up a lot
else:
rsync_opts.append("--verbose") # Print filelist
if "--verbose" in myopts:
rsync_opts.append("--progress") # Progress meter for each file
if "--debug" in myopts:
rsync_opts.append("--checksum") # Force checksum on all files
if portage.settings["RSYNC_EXCLUDEFROM"] != "":
portage.writemsg(yellow("WARNING:") + \
" usage of RSYNC_EXCLUDEFROM is deprecated, use " + \
"PORTAGE_RSYNC_EXTRA_OPTS instead\n")
if os.path.exists(portage.settings["RSYNC_EXCLUDEFROM"]):
rsync_opts.append("--exclude-from=%s" % \
portage.settings["RSYNC_EXCLUDEFROM"])
else:
portage.writemsg("!!! RSYNC_EXCLUDEFROM specified," + \
" but file does not exist.\n")
if portage.settings["RSYNC_RATELIMIT"] != "":
portage.writemsg(yellow("WARNING:") + \
" usage of RSYNC_RATELIMIT is deprecated, use " + \
"PORTAGE_RSYNC_EXTRA_OPTS instead")
rsync_opts.append("--bwlimit=%s" % \
portage.settings["RSYNC_RATELIMIT"])
servertimestampdir = portage.settings.depcachedir+"/"
servertimestampfile = portage.settings.depcachedir+"/timestamp.chk"
tmpservertimestampdir = portage.settings["PORTAGE_TMPDIR"]+"/"
tmpservertimestampfile = portage.settings["PORTAGE_TMPDIR"]+"/timestamp.chk"
# We only use the backup if a timestamp exists in the portdir.
content=None
if os.path.exists(myportdir+"/metadata/timestamp.chk"):
content=portage.grabfile(servertimestampfile)
if (not content):
content=portage.grabfile(myportdir+"/metadata/timestamp.chk")
if (content):
try:
mytimestamp=time.mktime(time.strptime(content[0], "%a, %d %b %Y %H:%M:%S +0000"))
except ValueError:
mytimestamp=0
else:
mytimestamp=0
if not os.path.exists(servertimestampdir):
os.mkdir(servertimestampdir)
os.chown(servertimestampdir, os.getuid(), portage.portage_gid)
os.chmod(servertimestampdir, 02775)
#exitcode=0
try:
if portage.settings.has_key("RSYNC_RETRIES"):
print yellow("WARNING:")+" usage of RSYNC_RETRIES is deprecated, use PORTAGE_RSYNC_RETRIES instead"
maxretries=int(portage.settings["RSYNC_RETRIES"])
else:
maxretries=int(portage.settings["PORTAGE_RSYNC_RETRIES"])
except SystemExit, e:
raise # Needed else can't exit
except:
maxretries=3 #default number of retries
retries=0
hostname, port=re.split("rsync://([^:/]*)(:[0-9]+)?", syncuri)[1:3];
if port is None:
port=""
updatecache_flg=True
ips=[]
while (1):
if ips:
del ips[0]
if ips==[]:
try:
ips=socket.gethostbyname_ex(hostname)[2]
except SystemExit, e:
raise # Needed else can't exit
except Exception, e:
print "Notice:",str(e)
dosyncuri=syncuri
if ips:
try:
dosyncuri=string.replace(syncuri, "//"+hostname+port+"/", "//"+ips[0]+port+"/", 1)
except SystemExit, e:
raise # Needed else can't exit
except Exception, e:
print "Notice:",str(e)
dosyncuri=syncuri
if (retries==0):
if "--ask" in myopts:
if userquery("Do you want to sync your Portage tree with the mirror at\n" + blue(dosyncuri) + bold("?"))=="No":
print
print "Quitting."
print
sys.exit(0)
emergelog(">>> Starting rsync with "+dosyncuri)
if "--quiet" not in myopts:
print ">>> Starting rsync with "+dosyncuri+"..."
else:
emergelog(">>> Starting retry %d of %d with %s" % (retries,maxretries,dosyncuri))
print "\n\n>>> Starting retry %d of %d with %s" % (retries,maxretries,dosyncuri)
if "--quiet" not in myopts:
print ">>> Checking server timestamp ..."
rsynccommand = " ".join(["/usr/bin/rsync",
portage.settings["PORTAGE_RSYNC_EXTRA_OPTS"],
" ".join(rsync_opts)])
if "--debug" in myopts:
print rsynccommand
mycommand = " ".join([rsynccommand,
dosyncuri + "/metadata/timestamp.chk",
tmpservertimestampdir])
exitcode=portage.spawn(mycommand,portage.settings,free=1)
if (exitcode==0):
try:
servertimestamp = time.mktime(time.strptime(portage.grabfile(tmpservertimestampfile)[0], "%a, %d %b %Y %H:%M:%S +0000"))
except SystemExit, e:
raise # Needed else can't exit
except:
servertimestamp = 0
if (servertimestamp != 0) and (servertimestamp == mytimestamp):
emergelog(">>> Cancelling sync -- Already current.")
print
print ">>>"
print ">>> Timestamps on the server and in the local repository are the same."
print ">>> Cancelling all further sync action. You are already up to date."
print ">>>"
print
sys.exit(0)
elif (servertimestamp != 0) and (servertimestamp < mytimestamp):
emergelog(">>> Server out of date: %s" % dosyncuri)
print
print ">>>"
print ">>> SERVER OUT OF DATE: %s" % dosyncuri
print ">>>"
print
elif (servertimestamp == 0) or (servertimestamp > mytimestamp):
# actual sync
mycommand=rsynccommand+" "+dosyncuri+"/ "+myportdir
exitcode=portage.spawn(mycommand,portage.settings,free=1)
if exitcode in [0,1,2,3,4,11,14,20,21]:
break
elif exitcode in [0,1,2,3,4,11,14,20,21]:
break
retries=retries+1
if retries<=maxretries:
print ">>> Retrying..."
time.sleep(11)
else:
# over retries
# exit loop
updatecache_flg=False
break
if (exitcode==0):
emergelog("=== Sync completed with %s" % dosyncuri)
# save timestamp.chk for next timestamp check.
try:
if tmpservertimestampfile is not None:
portage.movefile(tmpservertimestampfile,
servertimestampfile)
except SystemExit, e:
raise
except Exception, e:
portage.writemsg("!!! Failed to save current timestamp.\n",
noiselevel=-1)
portage.writemsg("!!! %s\n" % str(e), noiselevel=-1)
del e
elif (exitcode>0):
print
if exitcode==1:
print darkred("!!!")+green(" Rsync has reported that there is a syntax error. Please ensure")
print darkred("!!!")+green(" that your SYNC statement is proper.")
print darkred("!!!")+green(" SYNC="+portage.settings["SYNC"])
elif exitcode==11:
print darkred("!!!")+green(" Rsync has reported that there is a File IO error. Normally")
print darkred("!!!")+green(" this means your disk is full, but can be caused by corruption")
print darkred("!!!")+green(" on the filesystem that contains PORTDIR. Please investigate")
print darkred("!!!")+green(" and try again after the problem has been fixed.")
print darkred("!!!")+green(" PORTDIR="+portage.settings["PORTDIR"])
elif exitcode==20:
print darkred("!!!")+green(" Rsync was killed before it finished.")
else:
print darkred("!!!")+green(" Rsync has not successfully finished. It is recommended that you keep")
print darkred("!!!")+green(" trying or that you use the 'emerge-webrsync' option if you are unable")
print darkred("!!!")+green(" to use rsync due to firewall or other restrictions. This should be a")
print darkred("!!!")+green(" temporary problem unless complications exist with your network")
print darkred("!!!")+green(" (and possibly your system's filesystem) configuration.")
print
sys.exit(exitcode)
elif syncuri[:6]=="cvs://":
if not os.path.exists("/usr/bin/cvs"):
print "!!! /usr/bin/cvs does not exist, so CVS support is disabled."
print "!!! Type \"emerge dev-util/cvs\" to enable CVS support."
sys.exit(1)
cvsroot=syncuri[6:]
cvsdir=os.path.dirname(myportdir)
if not os.path.exists(myportdir+"/CVS"):
#initial checkout
print ">>> Starting initial cvs checkout with "+syncuri+"..."
if os.path.exists(cvsdir+"/gentoo-x86"):
print "!!! existing",cvsdir+"/gentoo-x86 directory; exiting."
sys.exit(1)
if portage.spawn("cd "+cvsdir+"; cvs -z0 -d "+cvsroot+" co -P gentoo-x86",portage.settings,free=1):
print "!!! cvs checkout error; exiting."
sys.exit(1)
if cvsdir!=myportdir:
portage.movefile(cvsdir,portage.settings["PORTDIR"])
sys.exit(0)
else:
#cvs update
print ">>> Starting cvs update with "+syncuri+"..."
sys.exit(portage.spawn("cd "+myportdir+"; cvs -z0 -q update -dP",portage.settings,free=1))
else:
print "!!! rsync setting: ",syncuri,"not recognized; exiting."
sys.exit(1)
if updatecache_flg and \
myaction != "metadata" and \
"metadata-transfer" not in portage.settings.features:
updatecache_flg = False
if os.path.exists(myportdir+"/metadata/cache") and updatecache_flg:
action_metadata(myopts)
portage.portageexit()
reload(portage)
portage.global_updates(
portage.settings, portage.db, portage.mtimedb["updates"])
mybestpv=portage.portdb.xmatch("bestmatch-visible","sys-apps/portage")
mypvs=portage.best(portage.db[portage.root]["vartree"].dbapi.match("sys-apps/portage"))
chk_updated_cfg_files()
if myaction != "metadata":
if os.access(portage.USER_CONFIG_PATH + "/bin/post_sync", os.X_OK):
try:
portage.spawn(portage.USER_CONFIG_PATH + "/bin/post_sync " + dosyncuri, portage.settings, free=1)
except:
print red(" * ")+bold("spawn failed of "+ portage.USER_CONFIG_PATH + "/bin/post_sync")
if(mybestpv != mypvs) and not "--quiet" in myopts:
print
print red(" * ")+bold("An update to portage is available.")+" It is _highly_ recommended"
print red(" * ")+"that you update portage now, before any other packages are updated."
print red(" * ")+"Please run 'emerge portage' and then update "+bold("ALL")+" of your"
print red(" * ")+"configuration files."
print red(" * ")+"To update portage, run 'emerge portage'."
print
def action_metadata(myopts):
portage.writemsg_stdout("\n>>> Updating Portage cache: ")
old_umask = os.umask(0002)
cachedir = os.path.normpath(portage.settings.depcachedir)
if cachedir in ["/", "/bin", "/dev", "/etc", "/home",
"/lib", "/opt", "/proc", "/root", "/sbin",
"/sys", "/tmp", "/usr", "/var"]:
print >> sys.stderr, "!!! PORTAGE_DEPCACHEDIR IS SET TO A PRIMARY " + \
"ROOT DIRECTORY ON YOUR SYSTEM."
print >> sys.stderr, \
"!!! This is ALMOST CERTAINLY NOT what you want: '%s'" % cachedir
sys.exit(73)
if not os.path.exists(cachedir):
os.mkdir(cachedir)
portage.portdb.flush_cache()
ec = portage.eclass_cache.cache(portage.portdb.porttree_root)
myportdir = os.path.realpath(portage.settings["PORTDIR"])
cm = portage.settings.load_best_module("portdbapi.metadbmodule")(
myportdir, "metadata/cache", portage.auxdbkeys[:])
# we don't make overlay trees cache here, plus we don't trust
# portage.settings.categories
porttree_root = portage.portdb.porttree_root
conf = portage.config(
config_profile_path=portage.settings.profile_path[:], \
config_incrementals=portage.settings.incrementals[:])
conf["PORTDIR_OVERLAY"] = ''
conf.categories = portage.grabfile(
os.path.join(porttree_root, "profiles", "categories"))
try:
i = conf.categories.index("virtual")
if i != -1:
conf.categories.remove(i)
except (ValueError, IndexError):
pass
pdb = portage.portdbapi(porttree_root, conf)
cp_all_list = pdb.cp_all()
import cache.util
class percentage_noise_maker(cache.util.quiet_mirroring):
def __init__(self, dbapi):
self.dbapi = dbapi
self.cp_all = dbapi.cp_all()
l = len(self.cp_all)
self.call_update_min = 100000000
self.min_cp_all = l/100.0
self.count = 1
self.pstr = ''
def __iter__(self):
for x in self.cp_all:
self.count += 1
if self.count > self.min_cp_all:
self.call_update_min = 0
self.count = 0
for y in self.dbapi.cp_list(x):
yield y
self.call_update_mine = 0
def update(self, *arg):
try: self.pstr = int(self.pstr) + 1
except ValueError: self.pstr = 1
sys.stdout.write("%s%i%%" % \
("\b" * (len(str(self.pstr))+1), self.pstr))
sys.stdout.flush()
self.call_update_min = 10000000
def finish(self, *arg):
sys.stdout.write("\b\b\b\b100%\n")
sys.stdout.flush()
if "--quiet" in myopts:
def quicky_cpv_generator(cp_all_list):
for x in cp_all_list:
for y in pdb.cp_list(x):
yield y
source = quicky_cpv_generator(pdb.cp_all())
noise_maker = cache.util.quiet_mirroring()
else:
noise_maker = source = percentage_noise_maker(pdb)
cache.util.mirror_cache(source, cm, pdb.auxdb[porttree_root],
eclass_cache=ec, verbose_instance=noise_maker)
sys.stdout.flush()
os.umask(old_umask)
def action_regen():
emergelog(" === regen")
#regenerate cache entries
print "Regenerating cache entries... "
try:
os.close(sys.stdin.fileno())
except SystemExit, e:
raise # Needed else can't exit
except:
pass
sys.stdout.flush()
mynodes=portage.portdb.cp_all()
for x in mynodes:
mymatches=portage.portdb.xmatch("match-all",x)
portage.writemsg_stdout("processing %s\n" % x)
for y in mymatches:
try:
foo=portage.portdb.aux_get(y,["DEPEND"])
except SystemExit, e:
# sys.exit is an exception... And consequently, we can't catch it.
raise
except Exception, e:
print "\n error processing %(cpv)s, continuing... (%(e)s)" % {"cpv":y,"e":str(e)}
print "done!"
def action_config(myopts, myfiles):
if len(myfiles) != 1 or "system" in myfiles or "world" in myfiles:
print red("!!! config can only take a single package atom at this time\n")
sys.exit(1)
if not is_valid_package_atom(myfiles[0]):
portage.writemsg("!!! '%s' is not a valid package atom.\n" % myfiles[0],
noiselevel=-1)
portage.writemsg("!!! Please check ebuild(5) for full details.\n")
portage.writemsg("!!! (Did you specify a version but forget to prefix with '='?)\n")
sys.exit(1)
print
try:
pkgs = portage.db[portage.root]["vartree"].dbapi.match(myfiles[0])
except ValueError, e:
# Multiple matches thrown from cpv_expand
pkgs = e.args[0]
if len(pkgs) == 0:
print "No packages found.\n"
sys.exit(0)
elif len(pkgs) > 1:
if "--ask" in myopts:
options = []
print "Please select a package to configure:"
idx = 0
for pkg in pkgs:
idx += 1
options.append(str(idx))
print options[-1]+") "+pkg
print "X) Cancel"
options.append("X")
idx = userquery("Selection?", options)
if idx == "X":
sys.exit(0)
pkg = pkgs[int(idx)-1]
else:
print "The following packages available:"
for pkg in pkgs:
print "* "+pkg
print "\nPlease use a specific atom or the --ask option."
sys.exit(1)
else:
pkg = pkgs[0]
print
if "--ask" in myopts:
if userquery("Ready to configure "+pkg+"?") == "No":
sys.exit(0)
else:
print "Configuring pkg..."
print
ebuildpath = portage.db[portage.root]["vartree"].dbapi.findname(pkg)
mysettings = portage.config(clone=portage.settings)
portage.doebuild(ebuildpath,"config",portage.root,mysettings,debug=("--debug" in myopts),cleanup=True,tree="vartree")
print
def action_info(myopts):
unameout=commands.getstatusoutput("uname -mrp")[1]
settings = portage.settings
print getportageversion(settings["PORTDIR"], settings["ROOT"],
settings.profile_path, settings["CHOST"])
print "================================================================="
print "System uname: "+unameout
if os.path.exists("/etc/gentoo-release"):
os.system("cat /etc/gentoo-release")
else:
print "Unknown Host Operating System"
output=commands.getstatusoutput("distcc --version")
if not output[0]:
print str(string.split(output[1],"\n",1)[0]),
if "distcc" in portage.settings.features:
print "[enabled]"
else:
print "[disabled]"
output=commands.getstatusoutput("ccache -V")
if not output[0]:
print str(string.split(output[1],"\n",1)[0]),
if "ccache" in portage.settings.features:
print "[enabled]"
else:
print "[disabled]"
myvars = ["sys-devel/autoconf", "sys-devel/automake", "virtual/os-headers",
"sys-devel/binutils", "sys-devel/libtool", "dev-lang/python"]
myvars += portage_util.grabfile(portage.settings["PORTDIR"]+"/profiles/info_pkgs")
myvars = portage_util.unique_array(myvars)
myvars.sort()
for x in myvars:
if portage.isvalidatom(x):
pkg_matches = portage.db["/"]["vartree"].dbapi.match(x)
pkgs = []
for y in pkg_matches:
mycpv = portage.catpkgsplit(y)
if(mycpv[3] != "r0"):
pkgs += [mycpv[2] + "-" + mycpv[3]]
else:
pkgs += [mycpv[2]]
if not pkgs:
pkgs = "[Not Present]"
else:
pkgs = ", ".join(sorted_versions(pkgs))
print "%-20s %s" % (x+":", pkgs)
else:
print "%-20s %s" % (x+":", "[NOT VALID]")
libtool_vers = string.join(portage.db["/"]["vartree"].dbapi.match("sys-devel/libtool"), ",")
if "--verbose" in myopts:
myvars=portage.settings.keys()
else:
myvars = ['GENTOO_MIRRORS', 'CONFIG_PROTECT', 'CONFIG_PROTECT_MASK',
'PORTDIR', 'DISTDIR', 'PKGDIR', 'PORTAGE_TMPDIR',
'PORTDIR_OVERLAY', 'USE', 'CHOST', 'CFLAGS', 'CXXFLAGS',
'ACCEPT_KEYWORDS', 'SYNC', 'FEATURES', 'EMERGE_DEFAULT_OPTS']
myvars.extend(portage_util.grabfile(portage.settings["PORTDIR"]+"/profiles/info_vars"))
myvars = portage_util.unique_array(myvars)
unset_vars = []
myvars.sort()
for x in myvars:
if portage.settings.has_key(x):
print x+'="'+portage.settings[x]+'"'
else:
unset_vars.append(x)
if unset_vars:
print "Unset: "+", ".join(unset_vars)
print
if "--debug" in myopts:
for x in dir(portage):
module = getattr(portage, x)
if "cvs_id_string" in dir(module):
print "%s: %s" % (str(x), str(module.cvs_id_string))
def action_search(myopts, myfiles, spinner):
if not myfiles:
print "emerge: no search terms provided."
else:
searchinstance = search(portage.settings, portage.portdb,
portage.db["/"]["vartree"], spinner, "--searchdesc" in myopts,
"--quiet" not in myopts)
for mysearch in myfiles:
try:
searchinstance.execute(mysearch)
except re.error, comment:
print "\n!!! Regular expression error in \"%s\": %s" % ( mysearch, comment )
sys.exit(1)
searchinstance.output()
def action_depclean(myopts, spinner):
# Kill packages that aren't explicitly merged or are required as a
# dependency of another package. World file is explicit.
print
print red("*** WARNING ***")+" --depclean is known to be broken. It is highly recommended"
print red("*** WARNING ***")+" that "+green("`emerge --update --newuse --deep world`")+" be ran before"
print red("*** WARNING ***")+" commencing. However, using --depclean may still break link"
print red("*** WARNING ***")+" level consistency within your system. "+green("`revdep-rebuild`")
print red("*** WARNING ***")+" from app-portage/gentoolkit can help to detect breakage."
print red("*** WARNING ***")
print red("*** WARNING ***")+" Also study the list of packages to be cleaned for any"
print red("*** WARNING ***")+" obvious mistakes. Packages can be manually added to the"
print red("*** WARNING ***")+" world list by running "+green("`emerge --noreplace <atom>`")+"."
print red("*** WARNING ***")
print red("*** WARNING ***")+" It is normal for packages that are masked or listed in"
print red("*** WARNING ***")+" package.provided to be removed by depclean. These are the most"
print red("*** WARNING ***")+" likely reasons that depclean will remove a package even though"
print red("*** WARNING ***")+" it is in the world or system package set. In order to"
print red("*** WARNING ***")+" troubleshoot these types of problems, it is often helpful to"
print red("*** WARNING ***")+" look at the output of "+green("`grep -r <atom> /etc/portage`")+"."
print red("*** WARNING ***")
print red("*** WARNING ***")+" "+bold("Make sure you have a backup.")
settings = portage.settings
vartree = portage.db[settings["ROOT"]]["vartree"]
info_mtimes = portage.mtimedb["info"]
syslist = getlist(settings, "system")
worldlist = getlist(settings, "world")
myvarlist=portage.vardbapi(portage.root).cp_all()
if not syslist:
print "\n!!! You have no system list.",
if not worldlist:
print "\n!!! You have no world file.",
if not myvarlist:
print "\n!!! You have no installed package database (%s)." % portage.VDB_PATH,
if not (syslist and worldlist and myvarlist):
print "\n!!! Proceeding will break your installation.\n"
countdown(int(settings["EMERGE_WARNING_DELAY"]), ">>> Depclean")
if not "--pretend" in myopts: #just check pretend, since --ask implies pretend
emergelog(" >>> depclean")
myparams = create_depgraph_params(myopts, "depclean")
mydepgraph = depgraph(portage.settings, portage.portdb, portage.db,
myopts, myparams, spinner)
if not ("--quiet" in myopts):
print "\nCalculating dependencies ",
if not mydepgraph.xcreate("world"):
print "\n!!! Failed to create deptree."
sys.exit(1)
if not ("--quiet" in myopts):
print "\b\b... done!"
if ("--usepkgonly" in myopts) and mydepgraph.missingbins:
sys.stderr.write(red("The following binaries are not available for merging...\n"))
for x in mydepgraph.missingbins:
sys.stderr.write(" "+str(x)+"\n")
sys.stderr.write("\nThese are required by '--usepkgonly' -- Terminating.\n\n")
sys.exit(1)
alldeps=mydepgraph.digraph.allnodes()
if not alldeps:
print "!!! You have no dependencies. Impossible. Bug."
sys.exit(1)
reallist=[]
for x in alldeps:
myparts=portage.catpkgsplit(string.split(x)[2])
if not myparts:
sys.stderr.write(
red("!!! There appears to be a problem with the following package:\n")+
red("!!! "+str(string.split(x)[2])+"\n\n")+
"!!! Please ensure that blocking/conflicting packages are not merged."+
"!!! 'emerge -p "+str(string.split(x)[2])+"\n\n")
if ("--pretend" not in myopts) and ("--ask" not in myopts):
countdown(int(settings["EMERGE_WARNING_DELAY"]),
"*** Continuing")
continue
catpack=myparts[0]+"/"+myparts[1]
if catpack not in reallist:
reallist.append(catpack)
cleanlist=[]
for x in myvarlist:
if x not in reallist:
if x not in cleanlist:
cleanlist.append(x)
for x in syslist+worldlist:
myparts = portage.catpkgsplit(x)
if myparts:
if myparts[0][0] in ('<','>','='):
myparts[0] = myparts[0][1:]
if myparts[0][0] in ('<','>','='):
myparts[0] = myparts[0][1:]
catpack=myparts[0]+"/"+myparts[1]
else:
catpack=x
if catpack in cleanlist:
cleanlist.remove(catpack)
#print "\n\n\nCleaning: "
#for x in cleanlist:
# print x
#print
if len(cleanlist):
unmerge(settings, myopts, vartree, "unmerge", cleanlist)
print
print "Packages installed: "+str(len(myvarlist))
print "Packages in world: "+str(len(worldlist))
print "Packages in system: "+str(len(syslist))
print "Unique package names: "+str(len(reallist))
print "Required packages: "+str(len(alldeps))
if "--pretend" in myopts:
print "Number to remove: "+str(len(cleanlist))
else:
print "Number removed: "+str(len(cleanlist))
post_emerge(settings, info_mtimes, 0)
def action_build(myopts, myaction, myfiles, spinner):
settings = portage.settings
trees = portage.db
info_mtimes = portage.mtimedb["info"]
favorites=[]
if ("--ask" in myopts or "--pretend" in myopts) and not "--quiet" in myopts:
action = ""
if "--fetchonly" in myopts or "--fetch-all-uri" in myopts:
action = "fetched"
else:
action = "merged"
if "--tree" in myopts and action != "fetched": # Tree doesn't work with fetching
print
print darkgreen("These are the packages that would be %s, in reverse order:") % action
print
else:
print
print darkgreen("These are the packages that would be %s, in order:") % action
print
if "--resume" in myopts and \
("resume" in portage.mtimedb or
"resume_backup" in portage.mtimedb):
if "resume" not in portage.mtimedb:
portage.mtimedb["resume"] = portage.mtimedb["resume_backup"]
del portage.mtimedb["resume_backup"]
portage.commit_mtimedb()
myresumeopts=portage.mtimedb["resume"]["myopts"][:]
for opt in ("--skipfirst", "--ask", "--tree"):
while opt in myresumeopts:
myresumeopts.remove(opt)
for myopt in myopts:
if myopt not in myresumeopts:
myresumeopts.append(myopt)
myopts=myresumeopts
myparams = create_depgraph_params(myopts, myaction)
mydepgraph = depgraph(portage.settings, portage.portdb, portage.db,
myopts, myparams, spinner)
if "--resume" not in myopts:
myopts+=["--resume"]
else:
if ("--resume" in myopts):
del myopts[myopts.index("--resume")]
print darkgreen("emerge: It seems we have nothing to resume...")
sys.exit(0)
myparams = create_depgraph_params(myopts, myaction)
mydepgraph = depgraph(portage.settings, portage.portdb, portage.db,
myopts, myparams, spinner)
if myaction in ["system","world"]:
if not ("--quiet" in myopts):
print "Calculating",myaction,"dependencies ",
sys.stdout.flush()
if not mydepgraph.xcreate(myaction):
print "!!! Depgraph creation failed."
sys.exit(1)
if not ("--quiet" in myopts):
print "\b\b... done!"
else:
if not ("--quiet" in myopts):
print "Calculating dependencies ",
sys.stdout.flush()
try:
retval, favorites = mydepgraph.select_files(myfiles)
except portage_exception.PackageNotFound, e:
portage.writemsg("\n!!! %s\n" % str(e), noiselevel=-1)
sys.exit(1)
if not retval:
sys.exit(1)
if not ("--quiet" in myopts):
print "\b\b... done!"
if ("--usepkgonly" in myopts) and mydepgraph.missingbins:
sys.stderr.write(red("The following binaries are not available for merging...\n"))
if mydepgraph.missingbins:
for x in mydepgraph.missingbins:
sys.stderr.write(" "+str(x)+"\n")
sys.stderr.write("\nThese are required by '--usepkgonly' -- Terminating.\n\n")
sys.exit(1)
if "--ask" in myopts:
if "--resume" in myopts:
validate_merge_list(portage.mtimedb["resume"]["mergelist"])
mydepgraph.display(portage.mtimedb["resume"]["mergelist"])
prompt="Would you like to resume merging these packages?"
else:
mydepgraph.display(mydepgraph.altlist())
mergecount=0
for x in mydepgraph.altlist():
if x[3]!="nomerge":
mergecount+=1
#check for blocking dependencies
if x[0]=="blocks" and "--fetchonly" not in myopts and "--fetch-all-uri" not in myopts:
print "\n!!! Error: The above package list contains packages which cannot be installed"
print "!!! at the same time on the same system."
print
sys.exit(1)
if mergecount==0:
if portage.settings["AUTOCLEAN"] and "yes"==portage.settings["AUTOCLEAN"]:
prompt="Nothing to merge; would you like to auto-clean packages?"
else:
print
print "Nothing to merge; quitting."
print
sys.exit(0)
elif "--fetchonly" in myopts or "--fetch-all-uri" in myopts:
prompt="Would you like to fetch the source files for these packages?"
else:
prompt="Would you like to merge these packages?"
print
if userquery(prompt)=="No":
print
print "Quitting."
print
sys.exit(0)
# Don't ask again (e.g. when auto-cleaning packages after merge)
myopts.remove("--ask")
if ("--pretend" in myopts) and not ("--fetchonly" in myopts or "--fetch-all-uri" in myopts):
if ("--resume" in myopts):
validate_merge_list(portage.mtimedb["resume"]["mergelist"])
mydepgraph.display(portage.mtimedb["resume"]["mergelist"])
else:
mydepgraph.display(mydepgraph.altlist())
else:
if ("--buildpkgonly" in myopts):
if not mydepgraph.digraph.hasallzeros():
print "\n!!! --buildpkgonly requires all dependencies to be merged."
print "!!! Cannot merge requested packages. Merge deps and try again.\n"
sys.exit(1)
if ("--resume" in myopts):
favorites=portage.mtimedb["resume"]["favorites"]
mydepgraph.merge(portage.mtimedb["resume"]["mergelist"], favorites)
else:
if "resume" in portage.mtimedb and \
"mergelist" in portage.mtimedb["resume"] and \
len(portage.mtimedb["resume"]["mergelist"]) > 1:
portage.mtimedb["resume_backup"] = portage.mtimedb["resume"]
del portage.mtimedb["resume"]
portage.commit_mtimedb()
portage.mtimedb["resume"]={}
portage.mtimedb["resume"]["myopts"]=myopts
portage.mtimedb["resume"]["favorites"]=favorites
if ("--digest" in myopts) and not ("--fetchonly" in myopts or "--fetch-all-uri" in myopts):
for pkgline in mydepgraph.altlist():
if pkgline[0]=="ebuild" and pkgline[3]=="merge":
y=portage.portdb.findname(pkgline[2])
tmpsettings = portage.config(clone=portage.settings)
edebug = 0
if settings.get("PORTAGE_DEBUG", "") == "1":
edebug = 1
retval = portage.doebuild(
y, "digest", settings["ROOT"], tmpsettings, edebug,
("--pretend" in myopts), tree="porttree")
if "--fetchonly" in myopts or "--fetch-all-uri" in myopts:
pkglist = []
for pkg in mydepgraph.altlist():
if pkg[0] != "blocks":
pkglist.append(pkg)
else:
pkglist = mydepgraph.altlist()
mydepgraph.merge(pkglist, favorites)
if portage.mtimedb.has_key("resume"):
del portage.mtimedb["resume"]
if portage.settings["AUTOCLEAN"] and "yes"==portage.settings["AUTOCLEAN"]:
print ">>> Auto-cleaning packages..."
vartree = trees[settings["ROOT"]]["vartree"]
unmerge(settings, myopts, vartree, "clean", ["world"])
else:
portage.writemsg_stdout(colorize("WARN", "WARNING:")
+ " AUTOCLEAN is disabled. This can cause serious"
+ " problems due to overlapping packages.\n")
if "--pretend" not in myopts:
post_emerge(settings, info_mtimes, 0)
def parse_opts(tmpcmdline):
myaction=None
myopts=[]
myfiles=[]
cmdline=[]
for x in tmpcmdline:
if x[0:1]=="-" and x[1:2]!="-":
for y in x[1:]:
if shortmapping.has_key(y):
if shortmapping[y] in cmdline:
if not shortmapping[y] in ("--verbose", "--pretend"):
print
print "*** Warning: Redundant use of",shortmapping[y]
else:
cmdline.append(shortmapping[y])
else:
print "!!! Error: -"+y+" is an invalid short action or option."
sys.exit(1)
else:
cmdline.append(x)
# process the options and command arguments
for x in cmdline:
if not x:
continue
if len(x)>=2 and x[0:2]=="--":
if x == "--cols":
x = "--columns"
elif x == "--skip-first":
x = "--skipfirst"
if x in options:
if x not in myopts:
myopts.append(x)
elif x[2:] in actions:
if myaction:
if myaction not in ["system", "world"]:
myaction="--"+myaction
print
print red("!!!")+green(" Multiple actions requested... Please choose one only.")
print red("!!!")+" '"+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
print
sys.exit(1)
myaction=x[2:]
else:
print "!!! Error:",x,"is an invalid option."
sys.exit(1)
elif (not myaction) and (x in actions):
if x not in ["system", "world"]:
print red("*** Deprecated use of action '%s', use '--%s' instead" % (x,x))
if myaction:
print
print red("!!!")+green(" Multiple actions requested... Please choose one only.")
print red("!!! '")+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
print
sys.exit(1)
myaction=x
elif x[-1]=="/":
# this little conditional helps tab completion
myfiles.append(x[:-1])
else:
myfiles.append(x)
return myaction, myopts, myfiles
def emerge_main():
settings = portage.settings
trees = portage.db
info_mtimes = portage.mtimedb["info"]
settings.unlock()
# To enhance usability, make some vars case insensitive by forcing them to
# lower case.
for myvar in ("AUTOCLEAN", "NOCOLOR"):
if myvar in settings:
settings[myvar] = settings[myvar].lower()
settings.backup_changes(myvar)
del myvar
# Kill noauto as it will break merges otherwise.
if "noauto" in settings.features:
while "noauto" in settings.features:
settings.features.remove("noauto")
settings["FEATURES"] = " ".join(settings.features)
settings.backup_changes("FEATURES")
CLEAN_DELAY = 5
try:
CLEAN_DELAY = int(settings.get("CLEAN_DELAY", str(CLEAN_DELAY)))
except ValueError, e:
portage.writemsg("!!! %s\n" % str(e), noiselevel=-1)
portage.writemsg("!!! Unable to parse integer: CLEAN_DELAY='%s'\n" % \
settings["CLEAN_DELAY"], noiselevel=-1)
settings["CLEAN_DELAY"] = str(CLEAN_DELAY)
settings.backup_changes("CLEAN_DELAY")
EMERGE_WARNING_DELAY = 10
try:
EMERGE_WARNING_DELAY = int(settings.get(
"EMERGE_WARNING_DELAY", str(EMERGE_WARNING_DELAY)))
except ValueError, e:
portage.writemsg("!!! %s\n" % str(e), noiselevel=-1)
portage.writemsg("!!! Unable to parse integer: EMERGE_WARNING_DELAY='%s'\n" % \
settings["EMERGE_WARNING_DELAY"], noiselevel=-1)
settings["EMERGE_WARNING_DELAY"] = str(EMERGE_WARNING_DELAY)
settings.backup_changes("EMERGE_WARNING_DELAY")
settings.lock()
if settings.get("NOCOLOR","") in ("yes","true"):
nocolor()
elif (not sys.stdout.isatty()) and \
settings.get("NOCOLOR","") != "no":
# revdep-rebuild exports NOCOLOR=false, so for now, don't allow
# NOCOLOR=false to override the isatty() check. This can be fixed
# in revdep-rebuild by using the --nocolor option when appropriate
# instead of exporting NOCOLOR.
nocolor()
tmpcmdline = sys.argv[1:]
if "--ignore-default-opts" not in tmpcmdline:
tmpcmdline.extend(settings["EMERGE_DEFAULT_OPTS"].split())
myaction, myopts, myfiles = parse_opts(tmpcmdline)
edebug = 0
portage.global_updates(settings, trees, portage.mtimedb["updates"])
spinner = stdout_spinner()
if "candy" in settings.features:
spinner.update = spinner.update_scroll
portage.deprecated_profile_check()
try:
os.nice(int(settings.get("PORTAGE_NICENESS", "0")))
except (OSError, ValueError), e:
portage.writemsg("!!! Failed to change nice value to '%s'\n" % \
settings["PORTAGE_NICENESS"])
portage.writemsg("!!! %s\n" % str(e))
del e
#Freeze the portdbapi for enhanced performance:
portage.portdb.freeze()
if "moo" in myfiles:
print """
Larry loves Gentoo (""" + os.uname()[0] + """)
_______________________
< Have you mooed today? >
-----------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
"""
if (myaction in ["world", "system"]) and myfiles:
print "emerge: please specify a package class (\"world\" or \"system\") or individual packages, but not both."
sys.exit(1)
for x in myfiles:
ext = os.path.splitext(x)[1]
if (ext == ".ebuild" or ext == ".tbz2") and os.path.exists(os.path.abspath(x)):
print "emerging by path implies --oneshot... adding --oneshot to options."
print red("\n*** emerging by path is broken and may not always work!!!\n")
break
if ("--tree" in myopts) and ("--columns" in myopts):
print "emerge: can't specify both of \"--tree\" and \"--columns\"."
sys.exit(1)
if ("--quiet" in myopts):
spinner.update = spinner.update_quiet
portage_util.noiselimit = -1
portage.settings.unlock()
portage.settings["PORTAGE_QUIET"]="1"
portage.settings.backup_changes("PORTAGE_QUIET")
portage.settings.lock()
# Always create packages if FEATURES=buildpkg
# Imply --buildpkg if --buildpkgonly
if ("buildpkg" in portage.settings.features) or ("--buildpkgonly" in myopts):
if "--buildpkg" not in myopts:
myopts.append("--buildpkg")
# --tree only makes sense with --pretend
if "--tree" in myopts and not (("--pretend" in myopts) or ("--ask" in myopts)):
print ">>> --tree implies --pretend... adding --pretend to options."
myopts.append("--pretend")
# Also allow -S to invoke search action (-sS)
if ("--searchdesc" in myopts):
if myaction and myaction != "search":
myfiles.append(myaction)
if "--search" not in myopts:
myopts.append("--search")
myaction = "search"
# Always try and fetch binary packages if FEATURES=getbinpkg
if ("getbinpkg" in portage.settings.features):
myopts.append("--getbinpkg")
if "--skipfirst" in myopts and "--resume" not in myopts:
myopts.append("--resume")
if ("--getbinpkgonly" in myopts) and not ("--usepkgonly" in myopts):
myopts.append("--usepkgonly")
if ("--getbinpkgonly" in myopts) and not ("--getbinpkg" in myopts):
myopts.append("--getbinpkg")
if ("--getbinpkg" in myopts) and not ("--usepkg" in myopts):
myopts.append("--usepkg")
# Also allow -K to apply --usepkg/-k
if ("--usepkgonly" in myopts) and not ("--usepkg" in myopts):
myopts.append("--usepkg")
if ("--newuse" in myopts) and not ("--update" in myopts):
print ">>> --newuse implies --update... adding --update to options."
myopts.append("--update")
# Also allow -l to apply --pretend/-p, but if already in --ask mode
if ("--changelog" in myopts) and not (("--pretend" in myopts) or ("--ask" in myopts)):
print ">>> --changelog implies --pretend... adding --pretend to options."
myopts.append("--pretend")
# Allow -p to remove --ask
if ("--pretend" in myopts) and ("--ask" in myopts):
print ">>> --pretend disables --ask... removing --ask from options."
myopts.remove("--ask")
# forbid --ask when not in a terminal
# note: this breaks `emerge --ask | tee logfile`, but that doesn't work anyway.
if ("--ask" in myopts) and (not sys.stdin.isatty()):
portage.writemsg("!!! \"--ask\" should only be used in a terminal. Exiting.\n",
noiselevel=-1)
sys.exit(1)
# Set so that configs will be merged regardless of remembered status
if ("--noconfmem" in myopts):
portage.settings.unlock()
portage.settings["NOCONFMEM"]="1"
portage.settings.backup_changes("NOCONFMEM")
portage.settings.lock()
# Set various debug markers... They should be merged somehow.
settings.unlock()
PORTAGE_DEBUG = 0
try:
PORTAGE_DEBUG = int(settings.get("PORTAGE_DEBUG", str(PORTAGE_DEBUG)))
if PORTAGE_DEBUG not in (0, 1):
portage.writemsg("!!! Invalid value: PORTAGE_DEBUG='%i'\n" % \
PORTAGE_DEBUG, noiselevel=-1)
portage.writemsg("!!! PORTAGE_DEBUG must be either 0 or 1\n",
noiselevel=-1)
PORTAGE_DEBUG = 0
except ValueError, e:
portage.writemsg("!!! %s\n" % str(e), noiselevel=-1)
portage.writemsg("!!! Unable to parse integer: PORTAGE_DEBUG='%s'\n" %\
settings["PORTAGE_DEBUG"], noiselevel=-1)
del e
if "--debug" in myopts:
PORTAGE_DEBUG = 1
settings["PORTAGE_DEBUG"] = str(PORTAGE_DEBUG)
settings.backup_changes("PORTAGE_DEBUG")
settings.lock()
if settings.get("PORTAGE_DEBUG", "") == "1":
portage.debug=1
if "python-trace" in settings.features:
import portage_debug
portage_debug.set_trace(True)
if ("--resume" in myopts):
if "--tree" in myopts:
print "* --tree is currently broken with --resume. Disabling..."
myopts.remove("--tree")
# Set color output
if "--nocolor" in myopts or \
portage.settings["NOCOLOR"] in ("yes","true"):
nocolor()
if "NOCOLOR" not in portage.settings:
portage.settings.unlock()
portage.settings["NOCOLOR"] = "true"
portage.settings.backup_changes("NOCOLOR")
portage.settings.lock()
if not ("--quiet" in myopts):
if not sys.stdout.isatty() or ("--nospinner" in myopts):
spinner.update = spinner.update_basic
if "--version" in myopts:
settings = portage.settings
print getportageversion(settings["PORTDIR"], settings["ROOT"],
settings.profile_path, settings["CHOST"])
sys.exit(0)
elif "--help" in myopts:
emergehelp.help(myaction, myopts, havecolor)
sys.exit(0)
if portage.wheelgid == portage.portage_gid:
print "emerge: wheel group use is being deprecated. Please update group and passwd to"
print " include the portage user as noted above, and then use group portage."
if "--debug" in myopts:
print "myaction", myaction
print "myopts", myopts
if not myaction and not myfiles and "--resume" not in myopts:
emergehelp.help(myaction, myopts, havecolor)
sys.exit(1)
# check if root user is the current user for the actions where emerge needs this
if portage.secpass < 2:
# We've already allowed "--version" and "--help" above.
if "--pretend" not in myopts and \
myaction not in ("search","info"):
if portage.secpass >= 1:
if "--fetchonly" not in myopts and \
"--fetch-all-uri" not in myopts and \
myaction not in ("metadata", "regen"):
print "emerge: root access required."
sys.exit(1)
else:
print "emerge: root access required."
sys.exit(1)
if not "--pretend" in myopts:
emergelog("Started emerge on: "+time.strftime("%b %d, %Y %H:%M:%S", time.localtime()))
myelogstr=""
if myopts:
myelogstr=string.join(myopts, " ")
if myaction:
myelogstr+=" "+myaction
if myfiles:
myelogstr+=" "+string.join(myfiles, " ")
emergelog(" *** emerge "+myelogstr)
def emergeexitsig(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
portage_util.writemsg("\n\nExiting on signal %(signal)s\n" % {"signal":signum})
sys.exit(100+signum)
signal.signal(signal.SIGINT, emergeexitsig)
signal.signal(signal.SIGTERM, emergeexitsig)
def emergeexit():
"""This gets out final log message in before we quit."""
if "--pretend" not in myopts:
emergelog(" *** terminating.")
if "notitles" not in portage.settings.features:
xtermTitleReset()
portage.atexit_register(emergeexit)
if myaction in ["sync","metadata"] and "--help" not in myopts:
if "--pretend" in myopts:
print "emerge: \"sync\" actions do not support \"--pretend.\""
sys.exit(1)
if "sync" == myaction:
action_sync(myopts, myaction)
else:
action_metadata(myopts)
elif myaction=="regen":
action_regen()
# HELP action
elif "config"==myaction:
action_config(myopts, myfiles)
# INFO action
elif "info"==myaction:
action_info(myopts)
# SEARCH action
elif "search"==myaction:
action_search(myopts, myfiles)
elif "unmerge"==myaction or "prune"==myaction or "clean"==myaction:
vartree = trees[settings["ROOT"]]["vartree"]
if 1 == unmerge(settings, myopts, vartree, myaction, myfiles,
raise_on_missing=False):
if "--pretend" not in myopts:
post_emerge(settings, info_mtimes, 0)
elif "depclean"==myaction:
action_depclean(myopts, spinner)
# "update", "system", or just process files:
else:
action_build(myopts, myaction, myfiles, spinner)
if __name__ == "__main__":
emerge_main()
|