summaryrefslogtreecommitdiffstats
path: root/bin/repoman
blob: 7552bc58ff4d5a93088cf94b7c9b1a875452779d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
#!/usr/bin/python -O
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id$

# Next to do: dep syntax checking in mask files
# Then, check to make sure deps are satisfiable (to avoid "can't find match for" problems)
# that last one is tricky because multiple profiles need to be checked.

import commands
import errno
import formatter
from itertools import izip
import os
import sys
import signal
import stat
import re
import tempfile

try:
	import cPickle as pickle
except ImportError:
	import pickle

try:
	import cStringIO as StringIO
except ImportError:
	import StringIO

if not hasattr(__builtins__, "set"):
	from sets import Set as set

exename=os.path.basename(sys.argv[0])	
version="1.2"	

# 14 is the length of DESCRIPTION=""
max_desc_len = 100
allowed_filename_chars="a-zA-Z0-9._-+:"
allowed_filename_chars_set = {}
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('a'), ord('z')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('A'), ord('Z')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, range(ord('0'), ord('9')+1)))
map(allowed_filename_chars_set.setdefault, map(chr, map(ord, [".", "-", "_", "+", ":"])))

os.environ["PORTAGE_LEGACY_GLOBALS"] = "false"
try:
	import portage
except ImportError:
	from os import path as osp
	sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
	import portage
del os.environ["PORTAGE_LEGACY_GLOBALS"]

import portage_checksum
import portage_const
import portage_dep
portage_dep._dep_check_strict = True
import portage_exception
import cvstree
import time
import codecs

from portage_manifest import Manifest
from portage_exception import ParseError
from portage_exec import find_binary, spawn

import output
from output import bold, create_color_func, darkgreen, \
	green, nocolor, red, turquoise, yellow

bad = create_color_func("BAD")

from commands import getstatusoutput
from fileinput import input
from grp import getgrnam
from stat import S_ISDIR, ST_CTIME, ST_GID, ST_MTIME

# A sane umask is needed for files that portage creates.
os.umask(022)
repoman_settings = portage.config(local_config=False,
	config_incrementals=portage_const.INCREMENTALS)
repoman_settings.lock()

if repoman_settings.get("NOCOLOR", "").lower() in ("yes", "true") or \
	not sys.stdout.isatty():
	nocolor()

def warn(txt):
	print exename+": "+txt
def err(txt):
	warn(txt)
	sys.exit(1)

def err_help(txt):
	help(exitstatus=-1,helpfulness=0)
	warn(txt)
	sys.exit(1)

def exithandler(signum=None,frame=None):
	sys.stderr.write("\n"+exename+": Interrupted; exiting...\n")
	sys.exit(1)
	os.kill(0,signal.SIGKILL)
signal.signal(signal.SIGINT,exithandler)

shortmodes={"ci":"commit"}
modeshelp={
"scan"   : "Scan directory tree for QA issues (short listing)",
"manifest" : "Generate a Manifest (fetches files if necessary)",
"fix"    : "Fix simple QA issues (stray digests, missing digests)",
"full"   : "Scan directory tree for QA issues (full listing)",
"help"   : "Show this screen",
"commit" : "Scan directory tree for QA issues; if OK, commit via cvs",
"last"   : "Remember report from last run",
"lfull"  : "Remember report from last run (full listing)"
}
modes=modeshelp.keys()
modes.sort()
repoman_options={
"--commitmsg"      : "Adds a commit message via the command line",
"--commitmsgfile"  : "Adds a commit message from the specified file",
"--help"           : "Show this screen",
"--force"          : "Force commit to proceed, regardless of QA issues",
"--ignore-arches"  : "Ignore arch-specific failures (where arch != host)",
"--ignore-masked"  : "Ignore masked packages (not allowed with commit mode)",
"--pretend"        : "Don't commit or fix anything; just show what would be done",
"--quiet"          : "Be less verbose about extraneous info",
"--verbose"        : "Displays every package name while checking",
"--version"        : "Show version info",
"--xmlparse"       : "Forces the metadata.xml parse check to be carried out"
}
repoman_shortoptions={
"-h" : "--help",
"-i" : "--ignore-masked",
"-I" : "--ignore-arches",
"-m" : "--commitmsg",
"-M" : "--commitmsgfile",
"-p" : "--pretend",
"-q" : "--quiet",
"-v" : "--verbose",
"-V" : "--version",
"-x" : "--xmlparse"
}
repoman_shortoptions_rev=dict([(v,k) for (k,v) in repoman_shortoptions.items()])
options=repoman_options.keys()

qahelp={
	"CVS/Entries.IO_error":"Attempting to commit, and an IO error was encountered access the Entries file",
	"desktop.invalid":"desktop-file-validate reports errors in a *.desktop file",
	"digest.partial":"Digest files do not contain all corresponding URI elements",
	"digest.assumed":"Existing digest must be assumed correct (Package level only)",
	"digestentry.unused":"Digest/Manifest entry has no matching SRC_URI entry",
	"digest.fail":"Digest does not match the specified local file",
	"digest.stray":"Digest files that do not have a corresponding ebuild",
	"digest.missing":"Digest files that are missing (ebuild exists, digest doesn't)",
	"digest.unmatch":"Digests which are incomplete (please check if your USE/ARCH includes all files)",
	"ebuild.invalidname":"Ebuild files with a non-parseable or syntactically incorrect name (or using 2.1 versioning extensions)",
	"ebuild.namenomatch":"Ebuild files that do not have the same name as their parent directory",
	"changelog.missing":"Missing ChangeLog files",
	"ebuild.disjointed":"Ebuilds not added to cvs when the matching digest has been added",
	"ebuild.notadded":"Ebuilds that exist but have not been added to cvs",
	"changelog.notadded":"ChangeLogs that exist but have not been added to cvs",
	"filedir.missing":"Package lacks a files directory",
	"file.executable":"Ebuilds, digests, metadata.xml, Manifest, and ChangeLog do note need the executable bit",
	"file.size":"Files in the files directory must be under 20k",
	"file.name":"File/dir name must be composed of only the following chars: %s " % allowed_filename_chars,
	"file.UTF8":"File is not UTF8 compliant",
	"KEYWORDS.missing":"Ebuilds that have a missing or empty KEYWORDS variable",
	"KEYWORDS.stable":"Ebuilds that have been added directly with stable KEYWORDS",
	"KEYWORDS.stupid":"Ebuilds that use KEYWORDS=-* instead of package.mask", 
	"LICENSE.missing":"Ebuilds that have a missing or empty LICENSE variable",
	"DESCRIPTION.missing":"Ebuilds that have a missing or empty DESCRIPTION variable",
	"DESCRIPTION.toolong":"DESCRIPTION is over %d characters" % max_desc_len,
	"EAPI.unsupported":"Ebuilds that have an unsupported EAPI version (you must upgrade portage)",
	"SLOT.missing":"Ebuilds that have a missing or empty SLOT variable",
	"HOMEPAGE.missing":"Ebuilds that have a missing or empty HOMEPAGE variable",
	"DEPEND.bad":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds)",
	"RDEPEND.bad":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds)",
	"PDEPEND.bad":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds)",
	"DEPEND.badmasked":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds)",
	"RDEPEND.badmasked":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds)",
	"PDEPEND.badmasked":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds)",
	"DEPEND.badindev":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds) in developing arch",
	"RDEPEND.badindev":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds) in developing arch",
	"PDEPEND.badindev":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds) in developing arch",
	"DEPEND.badmaskedindev":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds) in developing arch",
	"RDEPEND.badmaskedindev":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds) in developing arch",
	"PDEPEND.badmaskedindev":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds) in developing arch",
	"DEPEND.syntax":"Syntax error in DEPEND (usually an extra/missing space/parenthesis)",
	"RDEPEND.syntax":"Syntax error in RDEPEND (usually an extra/missing space/parenthesis)",
	"PDEPEND.syntax":"Syntax error in PDEPEND (usually an extra/missing space/parenthesis)",
	"LICENSE.syntax":"Syntax error in LICENSE (usually an extra/missing space/parenthesis)",
	"PROVIDE.syntax":"Syntax error in PROVIDE (usually an extra/missing space/parenthesis)",
	"RESTRICT.syntax":"Syntax error in RESTRICT (usually an extra/missing space/parenthesis)",
	"SRC_URI.syntax":"Syntax error in SRC_URI (usually an extra/missing space/parenthesis)",
	"ebuild.syntax":"Error generating cache entry for ebuild; typically caused by ebuild syntax error or digest verification failure",
	"ebuild.output":"A simple sourcing of the ebuild produces output; this breaks ebuild policy.",
	"ebuild.nesteddie":"Placing 'die' inside ( ) prints an error, but doesn't stop the ebuild.",
	"variable.readonly":"Assigning a readonly variable",
	"LIVEVCS.stable":"This ebuild is a live checkout from a VCS but has stable keywords.",
	"IUSE.invalid":"This ebuild has a variable in IUSE that is not in the use.desc or use.local.desc file",
	"LICENSE.invalid":"This ebuild is listing a license that doesnt exist in portages license/ dir.",
	"KEYWORDS.invalid":"This ebuild contains KEYWORDS that are not listed in profiles/arch.list or for which no valid profile was found",
	"RESTRICT.invalid":"This ebuild contains invalid RESTRICT values.",
	"ebuild.nostable":"There are no ebuilds that are marked as stable for your ARCH",
	"ebuild.allmasked":"All ebuilds are masked for this package (Package level only)",
	"ebuild.majorsyn":"This ebuild has a major syntax error that may cause the ebuild to fail partially or fully",
	"ebuild.minorsyn":"This ebuild has a minor syntax error that contravenes gentoo coding style",
	"ebuild.badheader":"This ebuild has a malformed header",
	"metadata.missing":"Missing metadata.xml files",
	"metadata.bad":"Bad metadata.xml files",
	"virtual.versioned":"PROVIDE contains virtuals with versions",
	"virtual.exists":"PROVIDE contains existing package names",
	"virtual.unavailable":"PROVIDE contains a virtual which contains no profile default",
	"usage.obsolete":"The ebuild makes use of an obsolete construct"
}

qacats = qahelp.keys()
qacats.sort()

qawarnings=[
"changelog.missing",
"changelog.notadded",
"ebuild.notadded",
"ebuild.nostable",
"ebuild.allmasked",
"ebuild.nesteddie",
"desktop.invalid",
"digest.assumed",
"digest.missing",
"digestentry.unused",
"DEPEND.badmasked","RDEPEND.badmasked","PDEPEND.badmasked",
"DEPEND.badindev","RDEPEND.badindev","PDEPEND.badindev",
"DEPEND.badmaskedindev","RDEPEND.badmaskedindev","PDEPEND.badmaskedindev",
"DESCRIPTION.toolong",
"KEYWORDS.stupid",
"KEYWORDS.missing",
"RESTRICT.invalid",
"ebuild.minorsyn",
"ebuild.badheader",
"file.size",
"metadata.missing",
"metadata.bad",
"virtual.versioned",
"virtual.exists",
"virtual.unavailable",
"usage.obsolete",
"LIVEVCS.stable"
]

missingvars=["KEYWORDS","LICENSE","DESCRIPTION","HOMEPAGE","SLOT"]
allvars=portage.auxdbkeys
commitmessage=None
commitmessagefile=None
for x in missingvars:
	x += ".missing"
	if x not in qacats:
		print "* missingvars values need to be added to qahelp ("+x+")"
		qacats.append(x)
		qawarnings.append(x)

valid_restrict = frozenset(["binchecks", "bindist",
	"fetch", "installsources", "mirror",
	"primaryuri", "strip", "test", "userpriv"])

# file.executable
no_exec = frozenset(["Manifest","ChangeLog","metadata.xml"])

verbose=0
quiet=0

def show_version():
	print exename+" "+version
	sys.exit(0)
	
def help(exitstatus=1,helpfulness=1):
	if quiet:
		helpfulness=0
	if helpfulness:
		print
		print green(exename+" "+version)
		print " \"Quality is job zero.\""
		print " Copyright 1999-2006 Gentoo Foundation"
		print " Distributed under the terms of the GNU General Public License v2"
		print
	print bold(" Usage:"),turquoise(exename),"[",green("options"),"] [",green("mode"),"]"
	if helpfulness:
		print bold(" Modes:"),turquoise("full (default)"),
		for x in modes:
			if x == "full":
				continue
			print "|",turquoise(x),
		print
	print
	print " "+green("Options".ljust(20)+" Description")
	for x in options:
		if repoman_shortoptions_rev.has_key(x):
			shopt=repoman_shortoptions_rev[x]+", "+x
		else:
			shopt="    "+x
		print " "+shopt.ljust(20),repoman_options[x]
	print
	print " "+green("Modes".ljust(20)+" Description")
	for x in modes:
		print " "+x.ljust(20),modeshelp[x]
	if helpfulness:
		print
		print " "+green("QA keyword".ljust(20)+" Description")
		for x in qacats:
			print " "+x.ljust(20),qahelp[x]
		print
	if (exitstatus != -1):
		sys.exit(exitstatus)
	else:
		print

def editor_is_executable(editor):
	"""
	Given an EDITOR string, validate that it refers to
	an executable. This uses shlex.split() to split the
	first component and do a PATH lookup if necessary.

	@param editor: An EDITOR value from the environment.
	@type: string
	@rtype: bool
	@returns: True if an executable is found, False otherwise.
	"""
	import shlex
	editor_split = shlex.split(editor)
	if not editor_split:
		return False
	filename = editor_split[0]
	if not os.path.isabs(filename):
		from portage_exec import find_binary
		return find_binary(filename) is not None
	return os.access(filename, os.X_OK) and os.path.isfile(filename)

def get_commit_message_with_editor(editor, message=None):
	"""
	Execute editor with a temporary file as it's argument
	and return the file content afterwards.

	@param editor: An EDITOR value from the environment
	@type: string
	@param message: An iterable of lines to show in the editor.
	@type: iterable
	@rtype: string or None
	@returns: A string on success or None if an error occurs.
	"""
	from tempfile import mkstemp
	fd, filename = mkstemp()
	try:
		os.write(fd, "\n# Please enter the commit message " + \
			"for your changes.\n# (Comment lines starting " + \
			"with '#' will not be included)\n")
		if message:
			os.write(fd, "#\n")
			for line in message:
				os.write(fd, "#" + line)
		os.close(fd)
		retval = os.system(editor + " '%s'" % filename)
		if not (os.WIFEXITED(retval) and os.WEXITSTATUS(retval) == os.EX_OK):
			return None
		try:
			mylines = open(filename).readlines()
		except OSError, e:
			if e.errno != errno.ENOENT:
				raise
			del e
			return None
		return "".join(line for line in mylines if not line.startswith("#"))
	finally:
		try:
			os.unlink(filename)
		except OSError:
			pass

def get_commit_message_with_stdin():
	"""
	Read a commit message from the user and return it.

	@rtype: string or None
	@returns: A string on success or None if an error occurs.
	"""
	print "Please enter a commit message. Use Ctrl-d to finish or Ctrl-c to abort."
	commitmessage = []
	while True:
		commitmessage.append(sys.stdin.readline())
		if not commitmessage[-1]:
			break
	commitmessage = "".join(commitmessage)
	return commitmessage

class ConsoleStyleFile(object):
	"""
	A file-like object that behaves something like the
	portage.output.colorize() function. Style identifiers
	passed in via the new_styles() method will be used to
	apply console codes to output.
	"""
	from output import codes as _codes
	def __init__(self, f):
		self._file = f
		self._styles = None
		self.write_listener = None

	def new_styles(self, styles):
		self._styles = styles

	def write(self, s):
		if output.havecolor and self._styles:
			for style in self._styles:
				self._file.write(self._codes[style])
			self._file.write(s)
			self._file.write(self._codes["reset"])
		else:
			self._file.write(s)
		if self.write_listener:
			self.write_listener.write(s)

	def writelines(self, lines):
		for s in lines:
			self.write(s)

	def flush(self):
		self._file.flush()

	def close(self):
		self._file.close()

class StyleWriter(formatter.DumbWriter):
	"""
	This is just a DumbWriter with a hook in the new_styles() method
	that passes a styles tuple as a single argument to a callable
	style_listener attribute.
	"""
	def __init__(self, **kwargs):
		formatter.DumbWriter.__init__(self, **kwargs)
		self.style_listener = None

	def new_styles(self, styles):
		formatter.DumbWriter.new_styles(self, styles)
		if self.style_listener:
			self.style_listener(styles)

def format_qa_output(f, stats, fails, dofull, dofail):
	full = mymode in ("full", "lfull")
	for x in qacats:
		if not stats[x]:
			continue
		f.add_literal_data("  " + x.ljust(30))
		if x in qawarnings:
			f.push_style("WARN")
		else:
			f.push_style("BAD")
		f.add_literal_data(str(stats[x]))
		f.pop_style()
		f.add_line_break()
		if not dofull:
			if not full and dofail and x in qawarnings:
				# warnings are considered noise when there are failures
				continue
			fails_list = fails[x]
			if not full and len(fails_list) > 12:
				fails_list = fails_list[:12]
			for y in fails_list:
				f.add_literal_data("   "+y)
				f.add_line_break()

def last():
	try:
		#Retrieve and unpickle stats and fails from saved files
		savedf=open('/var/cache/edb/repo.stats','r')
		stats = pickle.load(savedf)
		savedf.close()
		savedf=open('/var/cache/edb/repo.fails','r')
		fails = pickle.load(savedf)
		savedf.close()
	except SystemExit, e:
		raise  # Need to propogate this
	except:
		err("Error retrieving last repoman run data; exiting.")

	#dofail will be set to 1 if we have failed in at least one non-warning category
	dofail=0
	#dowarn will be set to 1 if we tripped any warnings
	dowarn=0
	#dofull will be set if we should print a "repoman full" informational message
	dofull=0

	dofull = mymode not in ("full", "lfull")
	
	for x in qacats:
		if not stats[x]:
			continue
		dowarn = 1
		if x not in qawarnings:
			dofail = 1

	print
	print green("RepoMan remembers...")
	print
	style_file = ConsoleStyleFile(sys.stdout)
	console_writer = StyleWriter(file=style_file, maxcol=9999)
	console_writer.style_listener = style_file.new_styles
	f = formatter.AbstractFormatter(console_writer)
	format_qa_output(f, stats, fails, dofull, dofail)
	print
	if dofull:
		print bold("Note: type \"repoman lfull\" for a complete listing of repomans last run.")
		print
	if dowarn and not dofail:
		print green("RepoMan sez:"),"\"You only gave me a partial QA payment last time?\n              I took it, but I wasn't happy.\""
	elif not dofail:
		print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
	print
	sys.exit(1)

mymode=None
myoptions = {}
if len(sys.argv)>1:
	x=1
	while x < len(sys.argv):
		if sys.argv[x] in shortmodes:
			sys.argv[x]=shortmodes[sys.argv[x]]
		elif sys.argv[x] in repoman_shortoptions:
			sys.argv[x] = repoman_shortoptions[sys.argv[x]]
		if sys.argv[x] in modes:
			if mymode is None:
				mymode=sys.argv[x]
			else:
				err("Please specify either \""+mymode+"\" or \""+sys.argv[x]+"\", but not both.")
		elif sys.argv[x] in options:
			optionx=sys.argv[x]
			if (optionx=="--commitmsg") and (len(sys.argv)>=(x+1)):
				commitmessage=sys.argv[x+1]
				x=x+1
			elif (optionx=="--commitmsgfile") and (len(sys.argv)>=(x+1)):
				commitmessagefile=sys.argv[x+1]
				x=x+1
			elif (optionx=="--verbose"):
				verbose+=1
			elif (optionx=="--quiet"):
				quiet+=1
			else:
				myoptions[optionx] = True
		else:
			err_help("\""+sys.argv[x]+"\" is not a valid mode or option.")
		x=x+1
if mymode is None:
	mymode = "full"
if mymode=="help" or ("--help" in myoptions):
	help(exitstatus=0)
if ("--version" in myoptions):
	show_version()
if mymode=="last" or (mymode=="lfull"):
	last()
if mymode == "commit":
	myoptions.pop("--ignore-masked", None)

# Set this to False when an extraordinary issue (generally
# something other than a QA issue) makes it impossible to
# commit (like if Manifest generation fails).
can_force = True

from portage import normalize_path
isCvs=False
myreporoot=None
if os.path.isdir("CVS"):
	isCvs = True

if isCvs and \
	"commit" == mymode and \
	"RMD160" not in portage_checksum.hashorigin_map:
	from portage_util import grablines
	repo_lines = grablines("./CVS/Repository")
	if repo_lines and \
		"gentoo-x86" == repo_lines[0].strip().split(os.path.sep)[0]:
		msg = "Please install " \
		"pycrypto or enable python's ssl USE flag in order " \
		"to enable RMD160 hash support. See bug #198398 for " \
		"more information."
		prefix = bad(" * ")
		from textwrap import wrap
		for line in wrap(msg, 70):
			print prefix + line
		sys.exit(1)
	del repo_lines

if mymode == "commit" and \
	not isCvs and \
	"--pretend" not in myoptions:
	print
	print darkgreen("Not in a CVS repository; enabling pretend mode.")
	myoptions["--pretend"] = True


def have_profile_dir(path, maxdepth=3):
	while path != "/" and maxdepth:
		if os.path.exists(path + "/profiles/package.mask"):
			return normalize_path(path)
		path = normalize_path(path + "/..")
		maxdepth -= 1

portdir=None
portdir_overlay=None
mydir=os.getcwd()
if "PWD" in os.environ and os.environ["PWD"] != mydir and \
	os.path.realpath(os.environ["PWD"]) == mydir:
	# getcwd() returns the canonical path but that makes it hard for repoman to
	# orient itself if the user has symlinks in their portage tree structure.
	# We use os.environ["PWD"], if available, to get the non-canonical path of
	# the current working directory (from the shell).
	mydir = os.environ["PWD"]
mydir = normalize_path(mydir)
path_ids = {}
p = mydir
s = None
while True:
	s = os.stat(p)
	path_ids[(s.st_dev, s.st_ino)] = p
	if p == "/":
		break
	p = os.path.dirname(p)
if mydir[-1] != "/":
	mydir += "/"

for overlay in repoman_settings["PORTDIR_OVERLAY"].split():
	overlay = os.path.realpath(overlay)
	try:
		s = os.stat(overlay)
	except OSError:
		continue
	overlay = path_ids.get((s.st_dev, s.st_ino))
	if overlay is None:
		continue
	if overlay[-1] != "/":
		overlay += "/"
	if True:
		portdir_overlay = overlay
		subdir = mydir[len(overlay):]
		if subdir and subdir[-1] != "/":
			subdir += "/"
		if have_profile_dir(mydir, subdir.count("/")):
			portdir = portdir_overlay
		break

del p, s, path_ids

if not portdir_overlay:
	if (repoman_settings["PORTDIR"] + os.path.sep).startswith(mydir):
		portdir_overlay = repoman_settings["PORTDIR"]
	else:
		portdir_overlay = have_profile_dir(mydir)
	portdir = portdir_overlay

if not portdir_overlay:
	sys.stderr.write("Repoman is unable to determine PORTDIR or PORTDIR_OVERLAY from" + \
		" the current\nworking directory.\n")
	sys.exit(1)

if not portdir:
	portdir = repoman_settings["PORTDIR"]

portdir = normalize_path(portdir)
portdir_overlay = normalize_path(portdir_overlay)

os.environ["PORTDIR"] = portdir
if portdir_overlay != portdir:
	os.environ["PORTDIR_OVERLAY"] = portdir_overlay
else:
	os.environ["PORTDIR_OVERLAY"] = ""

if quiet < 2:
	print "\nSetting paths:"
	print "PORTDIR = \""+os.environ["PORTDIR"]+"\""
	print "PORTDIR_OVERLAY = \""+os.environ["PORTDIR_OVERLAY"]+"\""

# Now that PORTDIR_OVERLAY is properly overridden, create the portdb.
repoman_settings = portage.config(local_config=False,
	config_incrementals=portage_const.INCREMENTALS)
trees = portage.create_trees()
trees["/"]["porttree"].settings = repoman_settings
portdb = trees["/"]["porttree"].dbapi
portdb.mysettings = repoman_settings
# dep_zapdeps looks at the vardbapi, but it shouldn't for repoman.
del trees["/"]["vartree"]

if not myreporoot:
	myreporoot = os.path.basename(portdir_overlay)
	myreporoot += mydir[len(portdir_overlay):-1]

reposplit=myreporoot.split("/")
repolevel=len(reposplit)

# check if it's in $PORTDIR/$CATEGORY/$PN , otherwise bail if commiting.
# Reason for this is if they're trying to commit in just $FILESDIR/*, the Manifest needs updating.
# this check ensure that repoman knows where it is, and the manifest recommit is at least possible.
if mymode == "commit" and repolevel not in [1,2,3]:
	print red("***")+" Commit attempts *must* be from within a cvs co, category, or package directory."
	print red("***")+" Attempting to commit from a packages files directory will be blocked for instance."
	print red("***")+" This is intended behaviour, to ensure the manifest is recommited for a package."
	print red("***")
	err("Unable to identify level we're commiting from for %s" % '/'.join(reposplit))

startdir = normalize_path(mydir)
repodir = startdir
for x in range(0,repolevel-1):
	repodir = os.path.dirname(repodir)

def caterror(mycat):
	err(mycat+" is not an official category.  Skipping QA checks in this directory.\nPlease ensure that you add "+catdir+" to "+repodir+"/profiles/categories\nif it is a new category.")

def parse_use_local_desc(mylines, usedict=None):
	"""returns a dict of the form {cpv:set(flags)}"""
	if usedict is None:
		usedict = {}
	lineno = 0
	for l in mylines:
		lineno += 1
		if not l or l.startswith("#"):
			continue
		mysplit = l.split(None, 1)
		if not mysplit:
			continue
		mysplit = mysplit[0].split(":")
		if len(mysplit) != 2:
			raise ParseError("line %d: Malformed input: '%s'" % \
				(lineno, l.rstrip("\n")))
		usedict.setdefault(mysplit[0], set())
		usedict[mysplit[0]].add(mysplit[1])
	return usedict

# retreive local USE list
luselist={}
try:
	f = open(os.path.join(portdir, "profiles", "use.local.desc"))
	parse_use_local_desc(f, luselist)
	f.close()
except (IOError, OSError, ParseError), e:
	print >> sys.stderr, str(e)
	err("Couldn't read from use.local.desc")

if portdir_overlay != portdir:
	filename = os.path.join(portdir_overlay, "profiles", "use.local.desc")
	if os.path.exists(filename):
		try:
			f = open(filename)
			parse_use_local_desc(f, luselist)
			f.close()
		except (IOError, OSError, ParseError), e:
			print >> sys.stderr, str(e)
			err("Couldn't read from '%s'" % filename)
	del filename

# setup a uselist from portage
uselist=[]
try:
	uselist=portage.grabfile(portdir+"/profiles/use.desc")
	for l in range(0,len(uselist)):
		uselist[l]=uselist[l].split()[0]
	for var in repoman_settings["USE_EXPAND"].split():
		vardescs = portage.grabfile(portdir+"/profiles/desc/"+var.lower()+".desc")
		for l in range(0, len(vardescs)):
			uselist.append(var.lower() + "_" + vardescs[l].split()[0])
except SystemExit, e:
	raise  # Need to propogate this
except:
	err("Couldn't read USE flags from use.desc")

# retrieve a list of current licenses in portage
liclist = set(portage.listdir(os.path.join(portdir, "licenses")))
if not liclist:
	err("Couldn't find licenses?")
if portdir_overlay != portdir:
	liclist.update(portage.listdir(os.path.join(portdir_overlay, "licenses")))

# retrieve list of offical keywords
kwlist = set(portage.grabfile(os.path.join(portdir, "profiles", "arch.list")))
if not kwlist:
	err("Couldn't read KEYWORDS from arch.list")

manifest1_compat = False
if portdir_overlay != portdir:
	kwlist.update(portage.grabfile(
		os.path.join(portdir_overlay, "profiles", "arch.list")))

scanlist=[]
if repolevel==2:
	#we are inside a category directory
	catdir=reposplit[-1]
	if catdir not in repoman_settings.categories:
		caterror(catdir)
	mydirlist=os.listdir(startdir)
	for x in mydirlist:
		if x == "CVS" or x.startswith("."):
			continue
		if os.path.isdir(startdir+"/"+x):
			scanlist.append(catdir+"/"+x)
elif repolevel==1:
	for x in repoman_settings.categories:
		if not os.path.isdir(startdir+"/"+x):
			continue
		for y in os.listdir(startdir+"/"+x):
			if y == "CVS" or y.startswith("."):
				continue
			if os.path.isdir(startdir+"/"+x+"/"+y):
				scanlist.append(x+"/"+y)
elif repolevel==3:
	catdir = reposplit[-2]
	if catdir not in repoman_settings.categories:
		caterror(catdir)
	scanlist.append(catdir+"/"+reposplit[-1])
scanlist.sort()

profiles={}
descfile=portdir+"/profiles/profiles.desc"
if os.path.exists(descfile):
	for x in portage.grabfile(descfile):
		if x[0]=="#":
			continue
		arch=x.split()
		if len(arch)!=3:
			print "wrong format: \""+red(x)+"\" in "+descfile
			continue
		if not os.path.isdir(portdir+"/profiles/"+arch[1]):
			print "Invalid "+arch[2]+" profile ("+arch[1]+") for arch "+arch[0]
			continue
		if profiles.has_key(arch[0]):
			profiles[arch[0]]+= [[arch[1], arch[2]]]
		else:
			profiles[arch[0]] = [[arch[1], arch[2]]]

	for x in repoman_settings.archlist():
		if x[0] == "~":
			continue
		if not profiles.has_key(x):
			print red("\""+x+"\" doesn't have a valid profile listed in profiles.desc.")
			print red("You need to either \"cvs update\" your profiles dir or follow this")
			print red("up with the "+x+" team.")
			print
else:
	print red("profiles.desc does not exist: "+descfile)
	print red("You need to do \"cvs update\" in profiles dir.")
	print
	sys.exit(1)


stats={}
fails={}

# provided by the desktop-file-utils package
desktop_file_validate = find_binary("desktop-file-validate")
desktop_pattern = re.compile(r'.*\.desktop$')

for x in qacats:
	stats[x]=0
	fails[x]=[]
xmllint_capable = False
metadata_dtd = os.path.join(repoman_settings["DISTDIR"], 'metadata.dtd')
if mymode == "manifest":
	pass
elif not find_binary('xmllint'):
	print red("!!! xmllint not found. Can't check metadata.xml.\n")
	if "--xmlparse" in myoptions or repolevel==3:
		print red("!!!")+" sorry, xmllint is needed.  failing\n"
		sys.exit(1)
else:
	#hardcoded paths/urls suck. :-/
	must_fetch=1
	backup_exists=0
	try:
		# if it's been over a week since fetching (or the system clock is fscked), grab an updated copy of metadata.dtd 
		# clock is fscked or it's been a week. time to grab a new one.
		ct = os.stat(metadata_dtd)[ST_CTIME]
		if abs(time.time() - ct) > (60*60*24*7):
			# don't trap the exception, we're watching for errno 2 (file not found), anything else is a bug.
			backup_exists=1
		else:
			must_fetch=0

	except (OSError,IOError), e:
		if e.errno != 2:
			print red("!!!")+" caught exception '%s' for %s/metadata.dtd, bailing" % (str(e), portage.CACHE_PATH)
			sys.exit(1)

	if must_fetch:
		print 
		print green("***")+" the local copy of metadata.dtd needs to be refetched, doing that now"
		print
		val = 0
		try:
			try:
				os.unlink(metadata_dtd)
			except OSError, e:
				if e.errno != errno.ENOENT:
					raise
				del e
			val=portage.fetch(['http://www.gentoo.org/dtd/metadata.dtd'],repoman_settings,fetchonly=0, \
				try_mirrors=0)

		except SystemExit, e:
			raise  # Need to propogate this
		except Exception,e:
			print
			print red("!!!")+" attempting to fetch 'http://www.gentoo.org/dtd/metadata.dtd', caught"
			print red("!!!")+" exception '%s' though." % str(e)
			val=0
		if not val:
			print red("!!!")+" fetching new metadata.dtd failed, aborting"
			sys.exit(1)
	#this can be problematic if xmllint changes their output
	xmllint_capable=True

MISSING_QUOTES_ERROR = 'Unquoted Variable on line: %d'
NESTED_DIE_ERROR = 'Ebuild calls die in a subshell on line: %d'
REDUNDANT_CD_S_ERROR = 'Ebuild has redundant cd ${S} statement on line: %d'

class LineCheck(object):
	"""Run a check on a line of an ebuild."""
	"""A regular expression to determine whether to ignore the line"""
	ignore_line = False

	def check(self, num, line):
		"""Run the check on line and return error if there is one"""
		pass

class EbuildQuote(LineCheck):
	"""Ensure ebuilds have valid quoting around things like D,FILESDIR, etc..."""

	repoman_check_name = 'ebuild.minorsyn'
	ignore_line = re.compile(r'(^$)|(^\s*#.*)|(^\s*\w+=.*)|(^\s*(local|export)\s+)')
	var_names = r'(D|DISTDIR|FILESDIR|S|T|ROOT|WORKDIR)'
	var_reference = re.compile(r'\$(\{'+var_names+'\}|' + \
		var_names + '\W)')
	missing_quotes = re.compile(r'(\s|^)[^"\'\s]*\$\{?' + var_names + \
		r'\}?[^"\'\s]*(\s|$)')
	cond_begin =  re.compile(r'(^|\s+)\[\[($|\\$|\s+)')
	cond_end =  re.compile(r'(^|\s+)\]\]($|\\$|\s+)')
	
	def check(self, num, line):
		if self.var_reference.search(line) is None:
			return
		# There can be multiple matches / violations on a single line. We
		# have to make sure none of the matches are violators. Once we've
		# found one violator, any remaining matches on the same line can
		# be ignored.
		pos = 0
		while pos <= len(line) - 1:
			missing_quotes = self.missing_quotes.search(line, pos)
			if not missing_quotes:
				break
			# If the last character of the previous match is a whitespace
			# character, that character may be needed for the next
			# missing_quotes match, so search overlaps by 1 character.
			group = missing_quotes.group()
			pos = missing_quotes.end() - 1

			# Filter out some false positives that can
			# get through the missing_quotes regex.
			if self.var_reference.search(group) is None:
				continue

			# This is an attempt to avoid false positives without getting
			# too complex, while possibly allowing some (hopefully
			# unlikely) violations to slip through. We just assume
			# everything is correct if the there is a ' [[ ' or a ' ]] '
			# anywhere in the whole line (possibly continued over one
			# line).
			if self.cond_begin.search(line) is not None:
				continue
			if self.cond_end.search(line) is not None:
				continue

			# Any remaining matches on the same line can be ignored.
			return MISSING_QUOTES_ERROR

class EbuildNestedDie(LineCheck):
	"""Check ebuild for nested die statements (die statements in subshells"""
	
	repoman_check_name = 'ebuild.nesteddie'
	nesteddie_re = re.compile(r'^[^#]*\([^)]*\bdie\b')
	
	def check(self, num, line):
		if self.nesteddie_re.match(line):
			return NESTED_DIE_ERROR

class EbuildUselessDodoc(LineCheck):
	"""Check ebuild for useless files in dodoc arguments."""
	repoman_check_name = 'ebuild.minorsyn'
	uselessdodoc_re = re.compile(
		r'^\s*dodoc(\s+|\s+.*\s+)(ABOUT-NLS|COPYING|LICENSE)($|\s)')

	def check(self, num, line):
		match = self.uselessdodoc_re.match(line)
		if match:
			return "Useless dodoc '%s'" % (match.group(2), ) + " on line: %d"

class EbuildUselessCdS(LineCheck):
	"""Check for redundant cd ${S} statements"""
	repoman_check_name = 'ebuild.minorsyn'
	method_re = re.compile(r'^\s*src_(compile|install|test)\s*\(\)')
	cds_re = re.compile(r'^\s*cd\s+("\$(\{S\}|S)"|\$(\{S\}|S))\s')

	def __init__(self):
		self.check_next_line = False

	def check(self, num, line):
		if self.check_next_line:
			self.check_next_line = False
			if self.cds_re.match(line):
				return REDUNDANT_CD_S_ERROR
		elif self.method_re.match(line):
			self.check_next_line = True

class EbuildQuotedA(LineCheck):
	"""Ensure ebuilds have no quoting around ${A}"""

	repoman_check_name = 'ebuild.minorsyn'
	a_quoted = re.compile(r'.*\"\$(\{A\}|A)\"')

	def check(self, num, line):
		match = self.a_quoted.match(line)
		if match:
			return "Quoted \"${A}\" on line: %d"

_constant_checks = tuple((c() for c in (
	EbuildQuote, EbuildUselessDodoc, EbuildUselessCdS,
	EbuildNestedDie, EbuildQuotedA)))

def run_checks(contents):
	for num, line in enumerate(contents):
		for lc in _constant_checks:
			ignore = lc.ignore_line
			if not ignore or not ignore.match(line):
				e = lc.check(num, line)
				if e:
					yield lc.repoman_check_name, e % (num + 1)

if mymode == "commit":
	retval = ("","")
	if isCvs:
		print
		print "Performing a " + green("cvs -n up") + \
			" with a little magic grep to check for updates."
		retval = getstatusoutput("/usr/bin/cvs -n up 2>&1 | " + \
			"egrep '^[^\?] .*' | " + \
			"egrep -v '^. .*/digest-[^/]+|^cvs server: .* -- ignored$'")

	mylines = retval[1].splitlines()
	myupdates = []
	for x in mylines:
		if not x:
			continue
		if x[0] not in "UPMAR": # Updates,Patches,Modified,Added,Removed
			print red("!!! Please fix the following issues reported " + \
				"from cvs: ")+green("(U,P,M,A,R are ok)")
			print red("!!! Note: This is a pretend/no-modify pass...")
			print retval[1]
			print
			sys.exit(1)
		elif x[0] in "UP":
			myupdates.append(x[2:])

	if myupdates:
		print green("Fetching trivial updates...")
		if "--pretend" in myoptions:
			print "(/usr/bin/cvs up "+" ".join(myupdates)+")"
			retval = os.EX_OK
		else:
			retval = os.system("/usr/bin/cvs up " + " ".join(myupdates))
		if retval != os.EX_OK:
			print "!!! cvs exited with an error. Terminating."
			sys.exit(retval)

if mymode == "manifest":
	pass
elif "--pretend" in myoptions:
	print green("\nRepoMan does a once-over of the neighborhood...")
elif quiet < 1:
	print green("\nRepoMan scours the neighborhood...")

new_ebuilds = set()
if isCvs:
	mycvstree = cvstree.getentries("./", recursive=1)
	mynew = cvstree.findnew(mycvstree, recursive=1, basedir="./")
	new_ebuilds.update(x for x in mynew if x.endswith(".ebuild"))
	del mycvstree, mynew

dofail = 0
arch_caches={}
arch_xmatch_caches = {}
shared_xmatch_caches = {"cp-list":{}}

for x in scanlist:
	#ebuilds and digests added to cvs respectively.
	if verbose:
		print "checking package " + x
	eadded=[]
	dadded=[]
	catdir,pkgdir=x.split("/")
	checkdir=repodir+"/"+x

	if mymode == "manifest" or \
		mymode in ("commit", "fix") and "--pretend" not in myoptions:
		repoman_settings["O"] = checkdir
		if not portage.digestgen([], repoman_settings, myportdb=portdb):
			print "Unable to generate manifest."
			dofail = 1
		if mymode == "manifest":
			continue
		elif dofail:
			sys.exit(1)

	checkdirlist=os.listdir(checkdir)
	ebuildlist=[]
	ebuild_metadata = {}
	for y in checkdirlist:
		if y in no_exec and \
			stat.S_IMODE(os.stat(os.path.join(checkdir, y)).st_mode) & 0111:
				stats["file.executable"] += 1
				fails["file.executable"].append(os.path.join(checkdir, y))
		if y.endswith(".ebuild"):
			pf = y[:-7]
			ebuildlist.append(pf)
			cpv = "%s/%s" % (catdir, pf)
			try:
				myaux = dict(izip(allvars, portdb.aux_get(cpv, allvars)))
			except KeyError:
				stats["ebuild.syntax"] += 1
				fails["ebuild.syntax"].append(os.path.join(x, y))
				continue
			except IOError:
				stats["ebuild.output"] += 1
				fails["ebuild.output"].append(os.path.join(x, y))
				continue
			if not portage.eapi_is_supported(myaux["EAPI"]):
				stats["EAPI.unsupported"] += 1
				fails["EAPI.unsupported"].append(os.path.join(x, y))
				continue
			ebuild_metadata[pf] = myaux
	ebuildlist.sort()

	if len(ebuild_metadata) != len(ebuildlist):
		# If we can't access all the metadata then it's totally unsafe to
		# commit since there's no way to generate a correct Manifest.
		# Do not try to do any more QA checks on this package since missing
		# metadata leads to false positives for several checks, and false
		# positives confuse users.
		can_force = False
		continue

	for y in checkdirlist:
		for c in y.strip(os.path.sep):
			if c not in allowed_filename_chars_set:
				stats["file.name"] += 1
				fails["file.name"].append("%s/%s: char '%s'" % (checkdir, y, c))
				break

		if not (y in ("ChangeLog", "metadata.xml") or y.endswith(".ebuild")):
			continue
		try:
			line = 1
			for l in codecs.open(checkdir+"/"+y, "r", "utf8"):
				line +=1
		except UnicodeDecodeError, ue:
			stats["file.UTF8"] += 1
			s = ue.object[:ue.start]
			l2 = s.count("\n")
			line += l2
			if l2 != 0:
				s = s[s.rfind("\n") + 1:]
			fails["file.UTF8"].append("%s/%s: line %i, just after: '%s'" % (checkdir, y, line, s))

	has_filesdir = True
	if not os.path.isdir(os.path.join(checkdir, "files")):
		has_filesdir = False
		if manifest1_compat:
			stats["filedir.missing"] += 1
			fails["filedir.missing"].append(checkdir)

	if isCvs:
		try:
			myf=open(checkdir+"/CVS/Entries","r")
			myl=myf.readlines()
			for l in myl:
				if l[0]!="/":
					continue
				splitl=l[1:].split("/")
				if not len(splitl):
					continue
				if splitl[0][-7:]==".ebuild":
					eadded.append(splitl[0][:-7])
		except IOError:
			if mymode=="commit":
				stats["CVS/Entries.IO_error"] += 1
				fails["CVS/Entries.IO_error"].append(checkdir+"/CVS/Entries")
			continue

	if isCvs and has_filesdir:
		try:
			myf=open(checkdir+"/files/CVS/Entries","r")
			myl=myf.readlines()
			for l in myl:
				if l[0]!="/":
					continue
				splitl=l[1:].split("/")
				if not len(splitl):
					continue
				if splitl[0][:7]=="digest-":
					dadded.append(splitl[0][7:])
		except IOError:
			if mymode=="commit":
				stats["CVS/Entries.IO_error"] += 1
				fails["CVS/Entries.IO_error"].append(checkdir+"/files/CVS/Entries")
			continue

	mf = Manifest(checkdir, repoman_settings["DISTDIR"])
	mydigests=mf.getTypeDigests("DIST")

	fetchlist_dict = portage.FetchlistDict(checkdir, repoman_settings, portdb)
	myfiles_all = []
	src_uri_error = False
	for mykey in fetchlist_dict:
		try:
			myfiles_all.extend(fetchlist_dict[mykey])
		except portage_exception.InvalidDependString, e:
			src_uri_error = True
			try:
				portdb.aux_get(mykey, ["SRC_URI"])
			except KeyError:
				# This will be reported as an "ebuild.syntax" error.
				pass
			else:
				stats["SRC_URI.syntax"] = stats["SRC_URI.syntax"] + 1
				fails["SRC_URI.syntax"].append(
					"%s.ebuild SRC_URI: %s" % (mykey, e))
	del fetchlist_dict
	if not src_uri_error:
		# This test can produce false positives if SRC_URI could not
		# be parsed for one or more ebuilds. There's no point in
		# producing a false error here since the root cause will
		# produce a valid error elsewhere, such as "SRC_URI.syntax"
		# or "ebuild.sytax".
		myfiles_all = set(myfiles_all)
		for entry in mydigests:
			if entry not in myfiles_all:
				stats["digestentry.unused"] += 1
				fails["digestentry.unused"].append(checkdir+"::"+entry)
	del myfiles_all

	if os.path.exists(checkdir+"/files"):
		filesdirlist=os.listdir(checkdir+"/files")
		if manifest1_compat:
			for y in filesdirlist:
				if not y.startswith("digest-"):
					continue
				relative_path = os.path.join(x, "files", y)
				full_path = os.path.join(repodir, relative_path)
				if stat.S_IMODE(os.stat(full_path).st_mode) & 0111:
					stats["file.executable"] += 1
					fails["file.executable"].append(relative_path)
				
				mykey = catdir + "/" + y[7:]
				if y[7:] not in ebuildlist:
					#stray digest
					if mymode=="fix":
						if "--pretend" in myoptions:
							print "(cd "+repodir+"/"+x+"/files; cvs rm -f "+y+")"
						else:
							os.system("(cd "+repodir+"/"+x+"/files; cvs rm -f "+y+")")
					else:
						stats["digest.stray"]=stats["digest.stray"]+1
						fails["digest.stray"].append(x+"/files/"+y)
				else:
					# We have an ebuild
					try:
						myuris, myfiles = portdb.getfetchlist(mykey, all=True)
					except portage_exception.InvalidDependString, e:
						# Already handled above.
						continue

					uri_dict = {}
					for myu in myuris:
						myubn = os.path.basename(myu)
						if myubn not in uri_dict:
							uri_dict[myubn]  = [myu]
						else:
							uri_dict[myubn] += [myu]

					for myf in uri_dict:
						myff = repoman_settings["DISTDIR"] + "/" + myf
						if not mydigests.has_key(myf):
							uri_settings = portage.config(clone=repoman_settings)
							if mymode == "fix":
								if not portage.fetch(uri_dict[myf], uri_settings):
									stats["digest.unmatch"] += 1
									fails["digest.unmatch"].append(y+"::"+myf)
								else:
									eb_name = portdb.findname2(mykey)[0]
									portage.doebuild(eb_name, "digest", "/",
										uri_settings, tree="porttree",
										mydbapi=portdb)
							else:
								stats["digest.partial"] += 1
								fails["digest.partial"].append(y+"::"+myf)
						elif "assume-digests" not in repoman_settings.features:
							if os.path.exists(myff):
								if not portage_checksum.verify_all(myff, mydigests[myf])[0]:
									stats["digest.fail"] += 1
									fails["digest.fail"].append(y+"::"+myf)
							elif repolevel == 3:
								stats["digest.assumed"] += 1
								fails["digest.assumed"].append(y+"::"+myf)

		# recurse through files directory
		# use filesdirlist as a stack, appending directories as needed so people can't hide > 20k files in a subdirectory.
		while filesdirlist:
			y = filesdirlist.pop(0)
			relative_path = os.path.join(x, "files", y)
			full_path = os.path.join(repodir, relative_path)
			try:
				mystat = os.stat(full_path)
			except OSError, oe:
				if oe.errno == 2:
					# don't worry about it.  it likely was removed via fix above.
					continue
				else:
					raise oe
			if S_ISDIR(mystat.st_mode):
				if y == "CVS":
					continue
				for z in os.listdir(checkdir+"/files/"+y):
					if z == "CVS":
						continue
					filesdirlist.append(y+"/"+z)
			# current policy is no files over 20k, this is the check.
			elif mystat.st_size > 20480:
				stats["file.size"] += 1
				fails["file.size"].append("("+ str(mystat.st_size/1024) + "K) "+x+"/files/"+y)

			for c in os.path.basename(y.rstrip(os.path.sep)):
				if c not in allowed_filename_chars_set:
					stats["file.name"] += 1
					fails["file.name"].append("%s/files/%s: char '%s'" % (checkdir, y, c))
					break

			if desktop_file_validate and desktop_pattern.match(y):
				status, cmd_output = commands.getstatusoutput(
					"'%s' '%s'" % (desktop_file_validate, full_path))
				if os.WIFEXITED(status) and os.WEXITSTATUS(status) != os.EX_OK:
					# Note: in the future we may want to grab the
					# warnings in addition to the errors. We're
					# just doing errors now since we don't want
					# to generate too much noise at first.
					error_re = re.compile(r'.*\s*error:\s*(.*)')
					for line in cmd_output.splitlines():
						error_match = error_re.match(line)
						if error_match is None:
							continue
						stats["desktop.invalid"] += 1
						fails["desktop.invalid"].append(
							relative_path + ': %s' % error_match.group(1))

	del mydigests

	if "ChangeLog" not in checkdirlist:
		stats["changelog.missing"]+=1
		fails["changelog.missing"].append(x+"/ChangeLog")
	
	#metadata.xml file check
	if "metadata.xml" not in checkdirlist:
		stats["metadata.missing"]+=1
		fails["metadata.missing"].append(x+"/metadata.xml")
	#metadata.xml parse check
	else:
		#Only carry out if in package directory or check forced
		if xmllint_capable:
			# xmlint can produce garbage output even on success, so only dump
			# the ouput when it fails.
			st, out = getstatusoutput(
				"xmllint --nonet --noout --dtdvalid '%s' '%s'" % \
				 (metadata_dtd, os.path.join(checkdir, "metadata.xml")))
			if st != os.EX_OK:
				print red("!!!") + " metadata.xml is invalid:"
				for z in out.splitlines():
					print red("!!! ")+z
				stats["metadata.bad"]+=1
				fails["metadata.bad"].append(x+"/metadata.xml")

	allmasked = True

	for y in ebuildlist:
		relative_path = os.path.join(x, y + ".ebuild")
		full_path = os.path.join(repodir, relative_path)
		if stat.S_IMODE(os.stat(full_path).st_mode) & 0111:
			stats["file.executable"] += 1
			fails["file.executable"].append(relative_path)
		if isCvs and y not in eadded:
			#ebuild not added to cvs
			stats["ebuild.notadded"]=stats["ebuild.notadded"]+1
			fails["ebuild.notadded"].append(x+"/"+y+".ebuild")
			if y in dadded:
				stats["ebuild.disjointed"]=stats["ebuild.disjointed"]+1
				fails["ebuild.disjointed"].append(x+"/"+y+".ebuild")
		if manifest1_compat and \
			not os.path.exists(os.path.join(checkdir, "files", "digest-"+y)):
			if mymode=="fix":
				if "--pretend" in myoptions:
					print "You will need to run:"
					print "  /usr/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest"
				else:
					retval=os.system("/usr/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest")
					if retval:
						print "!!! Exiting on ebuild digest (shell) error code:",retval
						sys.exit(retval)
			else:
				stats["digest.missing"]=stats["digest.missing"]+1
				fails["digest.missing"].append(x+"/files/digest-"+y)
		myesplit=portage.pkgsplit(y)
		if myesplit is None or myesplit[0] != x.split("/")[-1]:
			stats["ebuild.invalidname"]=stats["ebuild.invalidname"]+1
			fails["ebuild.invalidname"].append(x+"/"+y+".ebuild")
			continue
		elif myesplit[0]!=pkgdir:
			print pkgdir,myesplit[0]
			stats["ebuild.namenomatch"]=stats["ebuild.namenomatch"]+1
			fails["ebuild.namenomatch"].append(x+"/"+y+".ebuild")
			continue

		myaux = ebuild_metadata[y]

		# Test for negative logic and bad words in the RESTRICT var.
		#for x in myaux[allvars.index("RESTRICT")].split():
		#	if x.startswith("no"):
		#		print "Bad RESTRICT value: %s" % x
		try:
			myaux["PROVIDE"] = portage_dep.use_reduce(
				portage_dep.paren_reduce(myaux["PROVIDE"]), matchall=1)
		except portage_exception.InvalidDependString, e:
			stats["PROVIDE.syntax"] = stats["PROVIDE.syntax"] + 1
			fails["PROVIDE.syntax"].append(mykey+".ebuild PROVIDE: "+str(e))
			del e
			continue
		myaux["PROVIDE"] = " ".join(portage.flatten(myaux["PROVIDE"]))
		for myprovide in myaux["PROVIDE"].split():
			prov_cp = portage.dep_getkey(myprovide)
			if prov_cp != myprovide:
				stats["virtual.versioned"]+=1
				fails["virtual.versioned"].append(x+"/"+y+".ebuild: "+myprovide)
			prov_pkg = portage.dep_getkey(
				portage.best(portdb.xmatch("match-all", prov_cp)))
			if prov_cp == prov_pkg:
				stats["virtual.exists"]+=1
				fails["virtual.exists"].append(x+"/"+y+".ebuild: "+prov_cp)

		for pos, missing_var in enumerate(missingvars):
			if not myaux.get(missing_var):
				if catdir == "virtual" and \
					missing_var in ("HOMEPAGE", "LICENSE"):
					continue
				myqakey=missingvars[pos]+".missing"
				stats[myqakey]=stats[myqakey]+1
				fails[myqakey].append(x+"/"+y+".ebuild")

		# 14 is the length of DESCRIPTION=""
		if len(myaux['DESCRIPTION']) > max_desc_len:
			stats['DESCRIPTION.toolong'] += 1
			fails['DESCRIPTION.toolong'].append(
				"%s: DESCRIPTION is %d characters (max %d)" % \
				(relative_path, len(myaux['DESCRIPTION']), max_desc_len))

		keywords = myaux["KEYWORDS"].split()
		stable_keywords = []
		for keyword in keywords:
			if not keyword.startswith("~") and \
				not keyword.startswith("-"):
				stable_keywords.append(keyword)
		if stable_keywords:
			ebuild_path = y + ".ebuild"
			if repolevel < 3:
				ebuild_path = os.path.join(pkgdir, ebuild_path)
			if repolevel < 2:
				ebuild_path = os.path.join(catdir, ebuild_path)
			ebuild_path = os.path.join(".", ebuild_path)
			if ebuild_path in new_ebuilds:
				stable_keywords.sort()
				stats["KEYWORDS.stable"] += 1
				fails["KEYWORDS.stable"].append(
					x + "/" + y + ".ebuild added with stable keywords: %s" % \
						" ".join(stable_keywords))

		# KEYWORDS="-*" is a stupid replacement for package.mask and screws general KEYWORDS semantics
		if "-*" in keywords:
			haskeyword = False
			for kw in keywords:
				if kw[0] == "~":
					kw = kw[1:]
				if kw in kwlist:
					haskeyword = True
			if not haskeyword:
				stats["KEYWORDS.stupid"] += 1
				fails["KEYWORDS.stupid"].append(x+"/"+y+".ebuild")

		"""
		Ebuilds that inherit a "Live" eclasss (darcs,subversion,git,cvs,etc..) should
		not be allowed to be marked stable
		"""
		if set(["darcs","cvs","subversion","git"]).intersection(
			myaux["INHERITED"].split()):
			bad_stable_keywords = []
			for keyword in myaux["KEYWORDS"].split():
				if not keyword.startswith("~") and \
					not keyword.startswith("-"):
					bad_stable_keywords.append(keyword)
				del keyword
			if bad_stable_keywords:
				stats["LIVEVCS.stable"] += 1
				fails["LIVEVCS.stable"].append(
					x + "/" + y + ".ebuild with stable keywords:%s " % \
						bad_stable_keywords)
			del bad_stable_keywords

		if "--ignore-arches" in myoptions:
			arches = [[repoman_settings["ARCH"], repoman_settings["ARCH"],
				repoman_settings["ACCEPT_KEYWORDS"].split()]]
		else:
			arches=[]
			for keyword in myaux["KEYWORDS"].split():
				if (keyword[0]=="-"):
					continue
				elif (keyword[0]=="~"):
					arches.append([keyword, keyword[1:], [keyword[1:], keyword]])
				else:
					arches.append([keyword, keyword, [keyword]])
					allmasked = False

		baddepsyntax = False
		badlicsyntax = False
		badprovsyntax = False
		catpkg = catdir+"/"+y
		myiuse = set(repoman_settings.archlist())
		for myflag in myaux["IUSE"].split():
			if myflag.startswith("+"):
				myflag = myflag[1:]
			myiuse.add(myflag)

		operator_tokens = set(["||", "(", ")"])
		type_list, badsyntax = [], []
		for mytype in ("DEPEND", "RDEPEND", "PDEPEND", "LICENSE", "PROVIDE"):
			mydepstr = myaux[mytype]
			
			if mydepstr.find(" ?") != -1:
				badsyntax.append("'?' preceded by space")

			try:
				# Missing closing parenthesis will result in a ValueError
				mydeplist = portage_dep.paren_reduce(mydepstr)
				# Missing opening parenthesis will result in a final "" element
				if "" in mydeplist or "(" in mydeplist:
					raise ValueError
			except ValueError:
				badsyntax.append("parenthesis mismatch")
				mydeplist = []
			except portage_exception.InvalidDependString, e:
				badsyntax.append(str(e))
				del e
				mydeplist = []

			try:
				portage_dep.use_reduce(mydeplist, excludeall=myiuse)
			except portage_exception.InvalidDependString, e:
				badsyntax.append(str(e))

			for token in operator_tokens:
				if mydepstr.startswith(token+" "):
					myteststr = mydepstr[len(token):]
				else:
					myteststr = mydepstr
				if myteststr.endswith(" "+token):
					myteststr = myteststr[:-len(token)]
				while myteststr.find(" "+token+" ") != -1:
					myteststr = " ".join(myteststr.split(" "+token+" ", 1))
				if myteststr.find(token) != -1:
					badsyntax.append("'%s' not separated by space" % (token))


			if mytype in ("DEPEND", "RDEPEND", "PDEPEND"):
				for token in mydepstr.split():
					if token in operator_tokens or \
						token.endswith("?"):
						continue
					if not portage.isvalidatom(token, allow_blockers=True) or \
						":" in token and myaux["EAPI"] == "0":
						badsyntax.append("'%s' not a valid atom" % token)

			type_list.extend([mytype] * (len(badsyntax) - len(type_list)))

		for m,b in zip(type_list, badsyntax):
			stats[m+".syntax"] += 1
			fails[m+".syntax"].append(catpkg+".ebuild "+m+": "+b)

		badlicsyntax = len(filter(lambda x:x=="LICENSE", type_list))
		badprovsyntax = len(filter(lambda x:x=="PROVIDE", type_list))
		baddepsyntax = len(type_list) != badlicsyntax + badprovsyntax 
		badlicsyntax = badlicsyntax > 0
		badprovsyntax = badprovsyntax > 0

		# uselist checks - global
		myuse = []
		default_use = []
		for myflag in myaux["IUSE"].split():
			flag_name = myflag.lstrip("+-")
			if myflag != flag_name:
				default_use.append(myflag)
			if flag_name not in uselist:
				myuse.append(flag_name)

		# uselist checks - local
		mykey = portage.dep_getkey(catpkg)
		if luselist.has_key(mykey):
			for mypos in range(len(myuse)-1,-1,-1):
				if myuse[mypos] and (myuse[mypos] in luselist[mykey]):
					del myuse[mypos]
		if default_use and myaux["EAPI"] == "0":
			myuse += default_use
		for mypos in range(len(myuse)):
			stats["IUSE.invalid"]=stats["IUSE.invalid"]+1
			fails["IUSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])	

		# license checks
		if not badlicsyntax:
			myuse = myaux["LICENSE"]
			# Parse the LICENSE variable, remove USE conditions and
			# flatten it.
			myuse=portage_dep.use_reduce(portage_dep.paren_reduce(myuse), matchall=1)
			myuse=portage.flatten(myuse)
			# Check each entry to ensure that it exists in PORTDIR's
			# license directory.
			for mypos in range(0,len(myuse)):
				# Need to check for "||" manually as no portage
				# function will remove it without removing values.
				if myuse[mypos] not in liclist and myuse[mypos] != "||":
					stats["LICENSE.invalid"]=stats["LICENSE.invalid"]+1
					fails["LICENSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])

		#keyword checks
		myuse = myaux["KEYWORDS"].split()
		for mykey in myuse:
			myskey=mykey[:]
			if myskey[0]=="-":
				myskey=myskey[1:]
			if myskey[0]=="~":
				myskey=myskey[1:]
			if mykey!="-*":
				if myskey not in kwlist:
					stats["KEYWORDS.invalid"] += 1
					fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s" % mykey)
				elif not profiles.has_key(myskey):
					stats["KEYWORDS.invalid"] += 1
					fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s (profile invalid)" % mykey)

		#restrict checks
		myrestrict = None
		try:
			myrestrict = portage_dep.use_reduce(
				portage_dep.paren_reduce(myaux["RESTRICT"]), matchall=1)
		except portage_exception.InvalidDependString, e:
			stats["RESTRICT.syntax"] = stats["RESTRICT.syntax"] + 1
			fails["RESTRICT.syntax"].append(mykey+".ebuild RESTRICT: "+str(e))
			del e
		if myrestrict:
			myrestrict = set(portage.flatten(myrestrict))
			mybadrestrict = myrestrict.difference(valid_restrict)
			if mybadrestrict:
				stats["RESTRICT.invalid"] += len(mybadrestrict)
				for mybad in mybadrestrict:
					fails["RESTRICT.invalid"].append(x+"/"+y+".ebuild: %s" % mybad)
		# Syntax Checks
		f = open(full_path, 'rb')
		try:
			contents = f.readlines()
			for check_name, e in run_checks(contents):
				stats[check_name] += 1
				fails[check_name].append(relative_path + ': %s' % e)
		finally:
			f.close()
			del f

		myear = time.gmtime(os.stat(full_path)[ST_MTIME])[0]
		gentoo_copyright = re.compile(r'^# Copyright ((1999|200\d)-)?' + str(myear) + r' Gentoo Foundation')
		gentoo_license = re.compile(r'^# Distributed under the terms of the GNU General Public License v2$')
		cvs_header = re.compile(r'^#\s*\$Header.*\$$')
		ignore_line = re.compile(r'(^$)|(^(\t)*#)')
		leading_spaces = re.compile(r'^[\S\t]')
		trailing_whitespace = re.compile(r'.*([\S]$)')
		readonly_assignment = re.compile(r'^\s*(export\s+)?(A|CATEGORY|P|PV|PN|PR|PVR|PF|D|WORKDIR|FILESDIR|FEATURES|USE)=')
		line_continuation = re.compile(r'([^#]*\S)(\s+|\t)\\$')
		linenum=0
		previous_line = None
		for line in contents:
			linenum += 1
			# Gentoo copyright check
			if linenum == 1:
				match = gentoo_copyright.match(line)
				if not match:
					myerrormsg = "Copyright header Error. Possibly date related."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			# Gentoo license check
			elif linenum == 2:
				match = gentoo_license.match(line)
				if not match:
					myerrormsg = "Gentoo License Error."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			# CVS Header check
			elif linenum == 3:
				match = cvs_header.match(line)
				if not match:
					myerrormsg = "CVS Header Error."
					stats["ebuild.badheader"] +=1
					fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			else:
				match = ignore_line.match(line)
				if not match:
					# Excluded Blank lines and full line comments. Good!
					# Leading Spaces Check
					match = leading_spaces.match(line)
					if not match:
						#Line has got leading spaces. Bad!
						myerrormsg = "Leading Space Syntax Error. Line %d" % linenum
						stats["ebuild.minorsyn"] +=1
						fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
					# Trailing whitespace check
					match = trailing_whitespace.match(line)
					if not match:
						#Line has got trailing whitespace. Bad!
						myerrormsg = "Trailing whitespace Syntax Error. Line %d" % linenum
						stats["ebuild.minorsyn"] +=1
						fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
					# Readonly variable assignment check
					match = readonly_assignment.match(line)
					# The regex can give a false positive for continued lines,
					# so we check the previous line to see if it was continued.
					if match and (not previous_line or not line_continuation.match(previous_line)):
						# invalid assignment, very bad!
						myerrormsg = "Readonly variable assignment to %s on line %d" % (match.group(2), linenum)
						stats["variable.readonly"] += 1
						fails["variable.readonly"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
			previous_line = line
		del previous_line

		if "--force" in myoptions:
			# The dep_check() calls are the most expensive QA test. If --force
			# is enabled, there's no point in wasting time on these since the
			# user is intent on forcing the commit anyway.
			continue

		for keyword,arch,groups in arches:

			if not profiles.has_key(arch):
				# A missing profile will create an error further down
				# during the KEYWORDS verification.
				continue
				
			for prof in profiles[arch]:

				if prof[1] not in ("stable", "dev"):
					continue

				profdir = portdir+"/profiles/"+prof[0]
	
				if prof[0] in arch_caches:
					dep_settings = arch_caches[prof[0]]
				else:
					dep_settings = portage.config(
						config_profile_path=profdir,
						config_incrementals=portage_const.INCREMENTALS,
						local_config=False)
					arch_caches[prof[0]] = dep_settings
					while True:
						try:
							# Protect ACCEPT_KEYWORDS from config.regenerate()
							# (just in case)
							dep_settings.incrementals.remove("ACCEPT_KEYWORDS")
						except ValueError:
							break

				xmatch_cache_key = (prof[0], tuple(groups))
				xcache = arch_xmatch_caches.get(xmatch_cache_key)
				if xcache is None:
					portdb.melt()
					portdb.freeze()
					xcache = portdb.xcache
					xcache.update(shared_xmatch_caches)
					arch_xmatch_caches[xmatch_cache_key] = xcache

				trees["/"]["porttree"].settings = dep_settings
				portdb.mysettings = dep_settings
				portdb.xcache = xcache
				# for package.use.mask support inside dep_check
				dep_settings.setcpv("/".join((catdir, y)))
				dep_settings["ACCEPT_KEYWORDS"] = " ".join(groups)
				# just in case, prevent config.reset() from nuking these.
				dep_settings.backup_changes("ACCEPT_KEYWORDS")

				for myprovide in myaux["PROVIDE"].split():
					prov_cp = portage.dep_getkey(myprovide)
					if prov_cp not in dep_settings.getvirtuals():
						stats["virtual.unavailable"]+=1
						fails["virtual.unavailable"].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+prov_cp)

				if not baddepsyntax:
					ismasked = os.path.join(catdir, y) not in \
						portdb.xmatch("list-visible", x)
					if ismasked:
						if "--ignore-masked" in myoptions:
							continue
						#we are testing deps for a masked package; give it some lee-way
						suffix="masked"
						matchmode = "minimum-all"
					else:
						suffix=""
						matchmode = "minimum-visible"
	
					if prof[1] == "dev":
						suffix=suffix+"indev"

					for mytype,mypos in [["DEPEND",len(missingvars)],["RDEPEND",len(missingvars)+1],["PDEPEND",len(missingvars)+2]]:
						
						mykey=mytype+".bad"+suffix
						myvalue = myaux[mytype]
						if not myvalue:
							continue
						try:
							mydep = portage.dep_check(myvalue, portdb,
								dep_settings, use="all", mode=matchmode,
								trees=trees)
						except KeyError, e:
							stats[mykey]=stats[mykey]+1
							fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(e[0]))
							continue
	
						if mydep[0]==1:
							if mydep[1]!=[]:
								#we have some unsolvable deps
								#remove ! deps, which always show up as unsatisfiable
								d=0
								while d<len(mydep[1]):
									if mydep[1][d][0]=="!":
										del mydep[1][d]
									else:
										d += 1
								#if we emptied out our list, continue:
								if not mydep[1]:
									continue
								stats[mykey]=stats[mykey]+1
								fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))
						else:
							stats[mykey]=stats[mykey]+1
							fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))

	# Check for 'all unstable' or 'all masked' -- ACCEPT_KEYWORDS is stripped
	# XXX -- Needs to be implemented in dep code. Can't determine ~arch nicely.
	#if not portage.portdb.xmatch("bestmatch-visible",x):
	#    stats["ebuild.nostable"]+=1
	#    fails["ebuild.nostable"].append(x)
	if allmasked and repolevel == 3:
		stats["ebuild.allmasked"]+=1
		fails["ebuild.allmasked"].append(x)

if mymode == "manifest":
	sys.exit(dofail)

#Pickle and save results for instant reuse in last and lfull
if os.access(portage_const.CACHE_PATH, os.W_OK):
	for myobj, fname in (stats, "repo.stats"), (fails, "repo.fails"):
		fpath = os.path.join(portage_const.CACHE_PATH, fname)
		savef = open(fpath, 'w')
		pickle.dump(myobj, savef)
		savef.close()
		portage.apply_secpass_permissions(fpath, gid=portage.portage_gid,
			mode=0664)
if quiet < 2:
	print
#dofail will be set to 1 if we have failed in at least one non-warning category
dofail=0
#dowarn will be set to 1 if we tripped any warnings
dowarn=0
#dofull will be set if we should print a "repoman full" informational message
dofull = mymode not in ("full", "lfull")

for x in qacats:
	if not stats[x]:
		continue
	dowarn = 1
	if x not in qawarnings:
		dofail = 1

if dofail or \
	(dowarn and not (quiet or mymode == "scan")):
	dofull = 0

# Save QA output so that it can be conveniently displayed
# in $EDITOR while the user creates a commit message.
# Otherwise, the user would not be able to see this output
# once the editor has taken over the screen.
qa_output = StringIO.StringIO()
style_file = ConsoleStyleFile(sys.stdout)
if mymode == 'commit' and \
	(not commitmessage or not commitmessage.strip()):
	style_file.write_listener = qa_output
console_writer = StyleWriter(file=style_file, maxcol=9999)
console_writer.style_listener = style_file.new_styles

f = formatter.AbstractFormatter(console_writer)

format_qa_output(f, stats, fails, dofull, dofail)

style_file.flush()
del console_writer, f, style_file
qa_output = qa_output.getvalue()
qa_output = qa_output.splitlines(True)

def grouplist(mylist,seperator="/"):
	"""(list,seperator="/") -- Takes a list of elements; groups them into
	same initial element categories. Returns a dict of {base:[sublist]}
	From: ["blah/foo","spork/spatula","blah/weee/splat"]
	To:   {"blah":["foo","weee/splat"], "spork":["spatula"]}"""
	mygroups={}
	for x in mylist:
		xs=x.split(seperator)
		if xs[0]==".":
			xs=xs[1:]
		if xs[0] not in mygroups:
			mygroups[xs[0]]=[seperator.join(xs[1:])]
		else:
			mygroups[xs[0]]+=[seperator.join(xs[1:])]
	return mygroups

if mymode!="commit":
	if dofull:
		print bold("Note: type \"repoman full\" for a complete listing.")
		if quiet < 1:
			print
	if dowarn and not dofail:
		if quiet < 2:
			print green("RepoMan sez:"),"\"You're only giving me a partial QA payment?\n              I'll take it this time, but I'm not happy.\""
		else:
			print green("RepoMan sez:"),"\"OK for now, but I'll be back ...\""
	elif not dofail:
		print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
	elif dofail:
		print turquoise("Please fix these important QA issues first.")
		print green("RepoMan sez:"),"\"Make your QA payment on time and you'll never see the likes of me.\"\n"
		sys.exit(1)
	if quiet < 1:
		print
else:
	if dofail and can_force and "--force" in myoptions and "--pretend" not in myoptions:
		print green("RepoMan sez:") + \
			" \"You want to commit even with these QA issues?\n" + \
			"              I'll take it this time, but I'm not happy.\"\n"
	elif dofail:
		if "--force" in myoptions and not can_force:
			print bad("The --force option has been disabled due to extraordinary issues.")
		print turquoise("Please fix these important QA issues first.")
		print green("RepoMan sez:"),"\"Make your QA payment on time and you'll never see the likes of me.\"\n"
		sys.exit(1)

	if "--pretend" in myoptions:
		print green("RepoMan sez:"), "\"So, you want to play it safe. Good call.\"\n"

	if fails["digest.missing"]:
		print green("Creating missing digests...")
	for x in fails["digest.missing"]:
		xs=x.split("/")
		del xs[-2]
		myeb="/".join(xs[:-1])+"/"+xs[-1][7:]
		if "--pretend" in myoptions:
			print "(ebuild "+portdir+"/"+myeb+".ebuild digest)"
		else:
			retval=os.system("ebuild "+portdir+"/"+myeb+".ebuild digest")
			if retval:
				print "!!! Exiting on ebuild digest (shell) error code:",retval
				sys.exit(retval)

	mycvstree=cvstree.getentries("./",recursive=1)
	if isCvs and not mycvstree:
		print "!!! It seems we don't have a cvs tree?"
		sys.exit(3)

	myunadded=cvstree.findunadded(mycvstree,recursive=1,basedir="./")
	myautoadd=[]
	if myunadded:
		for x in range(len(myunadded)-1,-1,-1):
			xs=myunadded[x].split("/")
			if xs[-1]=="files":
				print "!!! files dir is not added! Please correct this."
				sys.exit(-1)
			elif xs[-1]=="Manifest":
				# It's a manifest... auto add
				myautoadd+=[myunadded[x]]
				del myunadded[x]
			elif len(xs[-1])>=7:
				if xs[-1][:7]=="digest-":
					del xs[-2]
					myeb="/".join(xs[:-1]+[xs[-1][7:]])+".ebuild"
					if os.path.exists(myeb):
						# Ebuild exists for digest... So autoadd it.
						myautoadd+=[myunadded[x]]
						del myunadded[x]
		
	if myautoadd:
		print ">>> Auto-Adding missing digests..."
		if "--pretend" in myoptions:
			print "(/usr/bin/cvs add "+" ".join(myautoadd)+")"
			retval=0
		else:
			retval=os.system("/usr/bin/cvs add "+" ".join(myautoadd))
		if retval:
			print "!!! Exiting on cvs (shell) error code:",retval
			sys.exit(retval)

	if myunadded:
		print red("!!! The following files are in your cvs tree but are not added to the master")
		print red("!!! tree. Please remove them from the cvs tree or add them to the master tree.")
		for x in myunadded:
			print "   ",x
		print
		print
		sys.exit(1)

	if True:
		mycvstree=cvstree.getentries("./",recursive=1)
		mychanged=cvstree.findchanged(mycvstree,recursive=1,basedir="./")
		mynew=cvstree.findnew(mycvstree,recursive=1,basedir="./")
		myremoved=cvstree.findremoved(mycvstree,recursive=1,basedir="./")
		bin_blob_pattern = re.compile("^-kb$")
		bin_blobs = set(cvstree.findoption(mycvstree,
			bin_blob_pattern, recursive=1, basedir="./"))
		if not (mychanged or mynew or myremoved):
			print green("RepoMan sez:"), "\"Doing nothing is not always good for QA.\""
			print
			print "(Didn't find any changed files...)"
			print
			sys.exit(0)

	# Manifests need to be regenerated after all other commits, so don't commit
	# them now even if they have changed.
	mymanifests = [f for f in mychanged if "Manifest" == os.path.basename(f)]
	mychanged = [f for f in mychanged if "Manifest" != os.path.basename(f)]
	myupdates=mychanged+mynew
	myheaders=[]
	mydirty=[]
	headerstring="'\$(Header|Id)"
	headerstring+=".*\$'"
	for myfile in myupdates:
		if myfile in bin_blobs:
			continue
		myout=getstatusoutput("egrep -q "+headerstring+" "+myfile)
		if myout[0]==0:
			myheaders.append(myfile)

	print "*",green(str(len(myupdates))),"files being committed...",green(str(len(myheaders))),"have headers that will change."
	print "*","Files with headers will cause the manifests to be made and recommited."
	if quiet == 0:
		print "myupdates:",myupdates
		print "myheaders:",myheaders
		print

	if commitmessagefile:
		try:
			f = open(commitmessagefile)
			commitmessage = f.read()
			f.close()
			del f
		except (IOError, OSError), e:
			if e.errno == errno.ENOENT:
				portage.writemsg("!!! File Not Found: --commitmsgfile='%s'\n" % commitmessagefile)
			else:
				raise
		# We've read the content so the file is no longer needed.
		commitmessagefile = None
	if not commitmessage or not commitmessage.strip():
		try:
			editor = os.environ.get("EDITOR")
			if editor and editor_is_executable(editor):
				commitmessage = get_commit_message_with_editor(
					editor, message=qa_output)
			else:
				commitmessage = get_commit_message_with_stdin()
		except KeyboardInterrupt:
			exithandler()
		if not commitmessage or not commitmessage.strip():
			print "* no commit message?  aborting commit."
			sys.exit(1)
	commitmessage = commitmessage.rstrip()
	portage_version = getattr(portage, "VERSION", None)
	if portage_version is None:
		sys.stderr.write("Failed to insert portage version in message!\n")
		sys.stderr.flush()
		portage_version = "Unknown"
	commitmessage += "\n(Portage version: "+str(portage_version)
	if "--force" in myoptions:
		commitmessage += ", RepoMan options: --force"
	commitmessage += ")"

	if myupdates or myremoved:
		myfiles = myupdates + myremoved
		fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
		mymsg = os.fdopen(fd, "w")
		mymsg.write(commitmessage)
		mymsg.close()

		print
		print green("Using commit message:")
		print green("------------------------------------------------------------------------------")
		print commitmessage
		print green("------------------------------------------------------------------------------")
		print

		retval = None
		if "--pretend" in myoptions:
			print "(/usr/bin/cvs -q commit -F %s %s)" % \
				(commitmessagefile, " ".join(myfiles))
		else:
			retval = spawn(["/usr/bin/cvs", "-q", "commit",
				"-F", commitmessagefile] + myfiles,
				env=os.environ)
		try:
			os.unlink(commitmessagefile)
		except OSError:
			pass
		if retval:
			print "!!! Exiting on cvs (shell) error code:",retval
			sys.exit(retval)

	# Setup the GPG commands
	def gpgsign(filename):
		if "PORTAGE_GPG_KEY" not in repoman_settings:
			raise portage_exception.MissingParameter("PORTAGE_GPG_KEY is unset!")
		if "PORTAGE_GPG_DIR" not in repoman_settings:
			if os.environ.has_key("HOME"):
				repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(os.environ["HOME"], ".gnupg")
				if quiet < 1:
					print "Automatically setting PORTAGE_GPG_DIR to",repoman_settings["PORTAGE_GPG_DIR"]
			else:
				raise portage_exception.MissingParameter("PORTAGE_GPG_DIR is unset!")
		gpg_dir = repoman_settings["PORTAGE_GPG_DIR"]
		if gpg_dir.startswith("~") and "HOME" in os.environ:
			repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(
				os.environ["HOME"], gpg_dir[1:].lstrip(os.path.sep))
		if not os.access(repoman_settings["PORTAGE_GPG_DIR"], os.X_OK):
			raise portage_exception.InvalidLocation(
				"Unable to access directory: PORTAGE_GPG_DIR='%s'" % \
				repoman_settings["PORTAGE_GPG_DIR"])
		gpgcmd = "gpg --sign --clearsign --yes "
		gpgcmd+= "--default-key "+repoman_settings["PORTAGE_GPG_KEY"]
		if repoman_settings.has_key("PORTAGE_GPG_DIR"):
			gpgcmd += " --homedir "+repoman_settings["PORTAGE_GPG_DIR"]
		if "--pretend" in myoptions:
			print "("+gpgcmd+" "+filename+")"
		else:
			rValue = os.system(gpgcmd+" "+filename)
			if rValue == os.EX_OK:
				os.rename(filename+".asc", filename)
			else:
				raise portage_exception.PortageException("!!! gpg exited with '" + str(rValue) + "' status")

	# When files are removed and re-added, the cvs server will put /Attic/
	# inside the $Header path. This code detects the problem and corrects it
	# so that the Manifest will generate correctly. See bug #169500.
	from portage_util import write_atomic
	cvs_header = re.compile(r'^#\s*\$Header.*\$$')
	for x in myheaders:
		f = open(x)
		mylines = f.readlines()
		f.close()
		modified = False
		for i, line in enumerate(mylines):
			if cvs_header.match(line) and "/Attic/" in line:
				mylines[i] = line.replace("/Attic/", "/")
				modified = True
		if modified:
			write_atomic(x, "".join(mylines))

	manifest_commit_required = True
	if myheaders or myupdates or myremoved or mynew:
		myfiles=myheaders+myupdates+myremoved+mynew
		for x in range(len(myfiles)-1, -1, -1):
			if myfiles[x].count("/") < 4-repolevel:
				del myfiles[x]
		mydone=[]
		if repolevel==3:   # In a package dir
			repoman_settings["O"] = startdir
			portage.digestgen([], repoman_settings, manifestonly=1,
				myportdb=portdb)
		elif repolevel==2: # In a category dir
			for x in myfiles:
				xs=x.split("/")
				if len(xs) < 4-repolevel:
					continue
				if xs[0]==".":
					xs=xs[1:]
				if xs[0] in mydone:
					continue
				mydone.append(xs[0])
				repoman_settings["O"] = os.path.join(startdir, xs[0])
				if not os.path.isdir(repoman_settings["O"]):
					continue
				portage.digestgen([], repoman_settings, manifestonly=1,
					myportdb=portdb)
		elif repolevel==1: # repo-cvsroot
			print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
			for x in myfiles:
				xs=x.split("/")
				if len(xs) < 4-repolevel:
					continue
				if xs[0]==".":
					xs=xs[1:]
				if "/".join(xs[:2]) in mydone:
					continue
				mydone.append("/".join(xs[:2]))
				repoman_settings["O"] = os.path.join(startdir, xs[0], xs[1])
				if not os.path.isdir(repoman_settings["O"]):
					continue
				portage.digestgen([], repoman_settings, manifestonly=1,
					myportdb=portdb)
		else:
			print red("I'm confused... I don't know where I am!")
			sys.exit(1)

		# Force an unsigned commit when more than one Manifest needs to be signed.
		if repolevel < 3 and "sign" in repoman_settings.features:
			if "--pretend" in myoptions:
				print "(/usr/bin/cvs -q commit -F commitmessagefile)"
			else:
				fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
				mymsg = os.fdopen(fd, "w")
				mymsg.write(commitmessage)
				mymsg.write("\n (Unsigned Manifest commit)")
				mymsg.close()
				retval=os.system("/usr/bin/cvs -q commit -F "+commitmessagefile)
				try:
					os.unlink(commitmessagefile)
				except OSError:
					pass
				if retval:
					print "!!! Exiting on cvs (shell) error code:",retval
					sys.exit(retval)
			manifest_commit_required = False

	signed = False
	if "sign" in repoman_settings.features:
		signed = True
		myfiles = myupdates + myremoved + mymanifests
		try:
			if repolevel==3:   # In a package dir
				repoman_settings["O"] = "."
				gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
			elif repolevel==2: # In a category dir
				mydone=[]
				for x in myfiles:
					xs=x.split("/")
					if len(xs) < 4-repolevel:
						continue
					if xs[0]==".":
						xs=xs[1:]
					if xs[0] in mydone:
						continue
					mydone.append(xs[0])
					repoman_settings["O"] = os.path.join(".", xs[0])
					if not os.path.isdir(repoman_settings["O"]):
						continue
					gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
			elif repolevel==1: # repo-cvsroot
				print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
				mydone=[]
				for x in myfiles:
					xs=x.split("/")
					if len(xs) < 4-repolevel:
						continue
					if xs[0]==".":
						xs=xs[1:]
					if "/".join(xs[:2]) in mydone:
						continue
					mydone.append("/".join(xs[:2]))
					repoman_settings["O"] = os.path.join(".", xs[0], xs[1])
					if not os.path.isdir(repoman_settings["O"]):
						continue
					gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
		except portage_exception.PortageException, e:
			portage.writemsg("!!! %s\n" % str(e))
			portage.writemsg("!!! Disabled FEATURES='sign'\n")
			signed = False

	if manifest_commit_required or signed:
		if "--pretend" in myoptions:
			print "(/usr/bin/cvs -q commit -F commitmessagefile)"
		else:
			fd, commitmessagefile = tempfile.mkstemp(".repoman.msg")
			mymsg = os.fdopen(fd, "w")
			mymsg.write(commitmessage)
			if signed:
				mymsg.write("\n (Signed Manifest commit)")
			else:
				mymsg.write("\n (Unsigned Manifest commit)")
			mymsg.close()
			retval=os.system("/usr/bin/cvs -q commit -F "+commitmessagefile)
			try:
				os.unlink(commitmessagefile)
			except OSError:
				pass
			if retval:
				print "!!! Exiting on cvs (shell) error code:",retval
				sys.exit(retval)

	print
	if isCvs:
		print "CVS commit complete."
	else:
		print "repoman was too scared by not seeing any familiar cvs file that he forgot to commit anything"
	print green("RepoMan sez:"), "\"If everyone were like you, I'd be out of business!\"\n"
sys.exit(0)