aboutsummaryrefslogtreecommitdiff
blob: fd8fa4f47344d23fc2a8fde82fc06cee846c2603 (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
#!/usr/bin/python
#
# Copyright 2003-2004 Karl Trygve Kalleberg
# Copyright 2003-2004 Gentoo Technologies, Inc.
# Distributed under the terms of the GNU General Public License v2
#
# $Header$
# Author: Karl Trygve Kalleberg <karltk@gentoo.org>

__author__ = "Karl Trygve Kalleberg"
__email__ = "karltk@gentoo.org"
__version__ = "0.1.4"
__productname__ = "equery"
__description__ = "Gentoo Package Query Tool"

import os
import re
import sys
import time
from glob import glob

# portage (output module) and gentoolkit need special path modifications
sys.path.insert(0, "/usr/lib/gentoolkit/pym")

import gentoolkit
try:
	import portage
except ImportError:
	sys.path.insert(0, "/usr/lib/portage/pym")
	import portage

try:
	import portage.checksum as checksum
	from portage.util import unique_array
except ImportError:
	import portage_checksum as checksum
	from portage_util import unique_array

import gentoolkit.pprinter as pp
from gentoolkit.pprinter import print_info, print_error, print_warn, die

# Auxiliary functions

def fileAsStr(name, fdesc, showType=0, showMD5=0, showTimestamp=0):
	"""
	Return file in fdesc as a filename
	@param name: 
	@param fdesc:
	@param showType:
	@param showMD5:
	@param showTimestamp:
	@rtype: string
	"""
	type = ""; fname = ""; stamp = ""; md5sum = ""

	if fdesc[0] == 'obj':
		type = "file"
		fname = name
		stamp = timestampAsStr(int(fdesc[1]))
		md5sum = fdesc[2]
	elif fdesc[0] == "dir":
		type = "dir"
		fname = pp.path(name)
	elif fdesc[0] == "sym":
		type = "symlink"
		stamp = timestampAsStr(int(fdesc[1].replace(")","")))
		tgt = fdesc[2].split()[0]
		if Config["piping"]:
			fname = name
		else:
			fname = pp.path_symlink(name + " -> " + tgt)
	elif fdesc[0] == "fif":
		type = "fifo"
		fname = name
	elif fdesc[0] == "dev":
		type = "device"
		fname = name
	else:
		raise Exception(name + " has unknown type: " + fdesc[0])

	s = ""
	if showType:
		s += "%6s " % type
	s += fname
	if showTimestamp:
		s += " " + stamp + " "
	if showMD5:
		s += " " + md5sum + " "
	return s

def timestampAsStr(timestamp):
	return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))

	
class Command:
	"""
	Abstract root class for all equery commands
	"""
	def __init__(self):
		pass
	def shortHelp(self):
		"""Return a help formatted to fit a single line, approx 70 characters.
		Must be overridden in the subclass."""
		return " - not implemented yet"
	def longHelp(self):
		"""Return full, multiline, color-formatted help.
		Must be overridden in the subclass."""
		return "help for syntax and options"
	def perform(self, args):
		"""Stub code for performing the command.
		Must be overridden in the subclass"""
		pass
	def parseArgs(self, args):
		"""Stub code for parsing command line arguments for this command.
		Must be overridden in the subclass."""
		pass

	
class CmdListFiles(Command):
	"""List files owned by a particular package"""
	def __init__(self):
		self.default_options = {
			"showType": 0,
			"showTimestamp": 0,
			"showMD5": 0,
			"tree": 0,
			"filter": None
			}

	def parseArgs(self,args):
		query = ""
		need_help = 0
		opts = self.default_options
		for x in args:
			if x in ["-h", "--help"]:
				need_help = 1
			elif x in ["--md5sum"]:
				opts["showMD5"] = 1
			elif x in ["--timestamp"]:
				opts["showTimestamp"] = 1
			elif x in ["--type"]:
				opts["showType"] = 1
			elif x in ["--tree"]:
				opts["tree"] = 1
			elif x[:9] == "--filter=":
				opts["filter"] = x[9:].split(',')
			elif x[0] == "/":
				die(2, "The query '" + pp.pkgquery(x) + "' does not appear to be a valid package specification")
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help or query == "":
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)

	def filterContents(self, cnt, filter):
		if filter in [None,[]]:
			return cnt
		
		mycnt = {}
		
		for mytype in filter:
			# Filter elements by type (as recorded in CONTENTS).
			if mytype in ["dir","obj","sym","dev","fif"]:
				for mykey in cnt.keys():
					if cnt[mykey][0] == mytype:
						mycnt[mykey] = cnt[mykey]
		
		if "cmd" in filter:
			# List files that are in $PATH.
			userpath = map(os.path.normpath,os.environ["PATH"].split(os.pathsep))
			for mykey in cnt.keys():
				if cnt[mykey][0] in ['obj','sym'] \
				   and os.path.dirname(mykey) in userpath:
					mycnt[mykey] = cnt[mykey]
		
		if "path" in filter:
			# List only dirs where some files where actually installed,
			# and also skip their subdirs.
			mykeys = cnt.keys()
			mykeys.sort()
			while len(mykeys):
				mykey = mykeys.pop(0)
				if cnt[mykey][0] == 'dir':
					i = 0
					while i < len(mykeys) :
						if cnt[mykeys[i]][0] != "dir" \
						   and os.path.dirname(mykeys[i]) == mykey:
							mycnt[mykey] = cnt[mykey]
							break
						i += 1
					if i < len(mykeys):
						while len(mykeys) \
							  and len(mykey+"/") < len(mykeys[0]) \
							  and mykey+"/" == mykeys[0][:len(mykey)+1]:
							mykeys.pop(0)
		
		if "conf" in filter:
			# List configuration files.
			conf_path = gentoolkit.settings["CONFIG_PROTECT"].split()
			conf_mask_path = gentoolkit.settings["CONFIG_PROTECT_MASK"].split()
			conf_path = map(os.path.normpath, conf_path)
			conf_mask_path = map(os.path.normpath, conf_mask_path)
			for mykey in cnt.keys():
				is_conffile = False
				if cnt[mykey][0] == 'obj':
					for conf_dir in conf_path:
						if conf_dir+"/" == mykey[:len(conf_dir)+1]:
							is_conffile = True
							for conf_mask_dir in conf_mask_path:
								if conf_mask_dir+"/" == mykey[:len(conf_mask_dir)+1]:
									is_conffile = False
									break
							break
					if is_conffile:
						mycnt[mykey] = cnt[mykey]
			  
		
		for mydoctype in ["doc","man","info"]:
			# List only files from /usr/share/{doc,man,info}
			mydocpath = "/usr/share/"+mydoctype+"/"
			if mydoctype in filter:
				for mykey in cnt.keys():
					if cnt[mykey][0] == 'obj' \
					   and mykey[:len(mydocpath)] == mydocpath :
						mycnt[mykey] = cnt[mykey]
		
		return mycnt

	def perform(self, args):

		(query, opts) = self.parseArgs(args)

		# Turn off filtering for tree output
		if opts["tree"]:
			opts["filter"] = None

		if not Config["piping"] and Config["verbosityLevel"] >= 3:
			print_info(3, "[ Searching for packages matching " + pp.pkgquery(query) + "... ]")
			
		pkgs = gentoolkit.find_installed_packages(query, True)
		for x in pkgs:
			if not x.is_installed():
				continue
		
			if not Config["piping"] and Config["verbosityLevel"] >= 3:
				print_info(1, pp.section("* ") + "Contents of " + pp.cpv(x.get_cpv()) + ":")

			cnt = self.filterContents(x.get_contents(),opts["filter"])

			filenames = cnt.keys()
			filenames.sort()
			
			last=[]
			for name in filenames:
				if not opts["tree"]:
					print_info(0, fileAsStr(name,
								cnt[name],
								showType=opts["showType"],
								showTimestamp=opts["showTimestamp"],
								showMD5=opts["showMD5"]))
				else:
					c = name.split( "/" )[1:]
					if cnt[name][0] == "dir":
						if len(last) == 0:
							last = c
							print pp.path(" /" + c[0])
							continue
						numol = 0
						for d in c:
							if d in last:
								numol = last.index(d) + 1
								continue
							last = c
							if len(last) == 1:
								print pp.path(" " + last[0])
								continue
							print pp.path(" " * ( numol * 3 ) + "> " + "/" + last[-1])
					elif cnt[name][0] == "sym":
						print pp.path(" " * ( bl * 3 ) + "+ ") + pp.path_symlink(c[-1] + " -> " +  cnt[name][2])
					else:
						bl = len(last)
						print pp.path(" " * ( bl * 3 ) + "+ ") + c[-1]

	def longHelp(self):
		return "List files owned by a particular package\n" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("files") + pp.localoption(" <local-opts> ") + pp.pkgquery("<cat/>packagename<-version>") + "\n" + \
			   "\n" + \
			   "Note: category and version parts are optional. \n" + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is either of: \n" + \
			   "  " + pp.localoption("--timestamp") + "      - append timestamp\n" + \
			   "  " + pp.localoption("--md5sum") + "         - append md5sum\n" + \
			   "  " + pp.localoption("--type") + "           - prepend file type\n" + \
			   "  " + pp.localoption("--tree") + "           - display results in a tree (turns off other options)\n" + \
			   "  " + pp.localoption("--filter=<rules>") + " - filter output\n" + \
			   "  " + pp.localoption("<rules>") + " is a comma separated list of elements you want to see:\n" + \
			   "  " + "  " + pp.localoption("dir") + \
					  ", " + pp.localoption("obj") + \
					  ", " + pp.localoption("sym") + \
					  ", " + pp.localoption("dev") + \
					  ", " + pp.localoption("fifo") + \
					  ", " + pp.localoption("path") + \
					  ", " + pp.localoption("conf") + \
					  ", " + pp.localoption("cmd") + \
					  ", " + pp.localoption("doc") + \
					  ", " + pp.localoption("man") + \
					  ", " + pp.localoption("info")

	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - list files owned by " + pp.pkgquery("pkgspec")

	
class CmdListBelongs(Command):
	"""List all packages owning a particular file"""
	def __init__(self):
		self.default_opts = {
			"category": "*",
			"fullRegex": 0,
			"earlyOut": 0,
			"nameOnly": 0
			}

	def parseArgs(self, args):

		query = []
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-c", "--category"]:
				opts["category"] = args[i+1]
				skip = 1
			elif x in ["-e", "--earlyout"]:
				opts["earlyOut"] = 1
			elif x in ["-f", "--full-regex"]:
				opts["fullRegex"] = 1
			elif x in ["-n", "--name-only"]:
				opts["nameOnly"] = 1
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query.append(x)

		if need_help or query == []:
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)
				
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		if opts["fullRegex"]:
			q = query
		else:
			# Trim trailing and multiple slashes from query 
			for i in range(0, len(query)):
				query[i] = re.compile('/+').sub('/', query[i])
				query[i] = query[i].rstrip('/')
			q = map(lambda x: ((len(x) and x[0] == "/") and "^" or "/")
			                   + re.escape(x) + "$", query)
		try:
			q = "|".join(q)
			rx = re.compile(q)
		except:
			die(2, "The query '" + pp.regexpquery(q) + "' does not appear to be a valid regular expression")

		# Pick out only selected categories
		cat = opts["category"]
		filter_fn = None
		if cat != "*":
			filter_fn = lambda x: x.find(cat+"/")==0

		if not Config["piping"] and Config["verbosityLevel"] >= 3:
			print_info(3, "[ Searching for file(s) " + pp.regexpquery(",".join(query)) + " in " + pp.cpv(cat) + "... ]")
		
		matches = portage.db["/"]["vartree"].dbapi.cpv_all()
		#matches = gentoolkit.find_all_installed_packages(filter_fn)

		found = 0

		def dumpToPipe(pkg):
			mysplit = pkg.split("/")
			cnt = portage.dblink(mysplit[0], mysplit[1], "/", gentoolkit.settings).getcontents()
			#cnt = pkg.get_contents()
			if not cnt: return
			for file in cnt.keys():
				if rx.search(file) and (opts["category"] == "*" or portage.catpkgsplit(pkg)[0] == opts["category"]):
					if opts["nameOnly"]:
						x = portage.catpkgsplit(pkg)
						print x[0]+"/"+x[1]
					else:
						print pkg
					return

		class DummyExp:
			pass
			
		def dumpToScreen(pkg):
			mysplit = pkg.split("/")
			cnt = portage.dblink(mysplit[0], mysplit[1], "/", gentoolkit.settings).getcontents()
			#cnt = pkg.get_contents()
			if not cnt: return
			for file in cnt.keys():
				if rx.search(file) and (opts["category"] == "*" or portage.catpkgsplit(pkg)[0] == opts["category"]):
					if opts["nameOnly"]:
						x = portage.catpkgsplit(pkg)
						s = x[0]+"/"+x[1]
					else:
						s = pkg
					s += " (" + pp.path(fileAsStr(file, cnt[file])) + ")"
					print_info(0, s)
					if opts["earlyOut"]:
						raise DummyExp

		try: 
			if Config["piping"]:
				map(dumpToPipe, matches)
			else:
				map(dumpToScreen, matches)
		except DummyExp:
			pass
			
	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.path("files...") + " - list all packages owning " + pp.path("files...")
	def longHelp(self):
		return "List all packages owning a particular set of files" + \
			   "\n" + \
			   "\n" + \
			   pp.emph("Note: ") + "Normally, only one package will own a file. If multiple packages own the same file, it usually consitutes a problem, and should be reported.\n" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("belongs") + pp.localoption(" <local-opts> ") + pp.path("filename") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is either of: \n" + \
					"  " + pp.localoption("-c, --category cat") + " - only search in category " + \
						pp.pkgquery("cat") + "\n" + \
					"  " + pp.localoption("-f, --full-regex") + "   - supplied query is a regex\n" + \
					"  " + pp.localoption("-e, --earlyout") + "     - stop when first match is found\n" + \
					"  " + pp.localoption("-n, --name-only") + "    - don't print the version."

class CmdDisplayUSEs(Command):
	"""Advanced report of a package's USE flags"""
	def __init__(self):
		self.default_opts = {
			"allPackages" : False
			}
	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-a", "--all"]:
				opts["allPackages"] = True
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help or query == "":
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)

	def perform(self, args):

		(query, opts) = self.parseArgs(args)

		if not Config["piping"] and Config["verbosityLevel"] >= 3:
			print_info(3, "[ Searching for packages matching " + pp.pkgquery(query) + "... ]")
		
		if not opts["allPackages"]:
			matches = gentoolkit.find_installed_packages(query, True)
			if not matches:
				matches = gentoolkit.find_packages(query, False)
				if matches:
					matches = gentoolkit.sort_package_list(matches)
					matches = matches[-1:]
		else:
			matches = gentoolkit.find_packages(query, True)

		if not matches:
			die(3, "No matching packages found for \"" + pp.pkgquery(query) + "\"")


		useflags = gentoolkit.settings["USE"].split()	
		usedesc = {}
		uselocaldesc = {}

		# Load global USE flag descriptions
		try:
			fd = open(gentoolkit.settings["PORTDIR"]+"/profiles/use.desc")
			usedesc = {}
			for line in fd.readlines():
				if line[0] == "#":
					continue
				fields = line.split(" - ", 1)
				if len(fields) == 2:
					usedesc[fields[0].strip()] = fields[1].strip()
		except IOError:
			print_warn(5, "Could not load USE flag descriptions from " + ppath(gentoolkit.settings["PORTDIR"] + "/profiles/use.desc"))

		# TODO: Add USE_EXPANDED variables to usedesc hash -- Bug #238005
		# Pseudo-code:
		# for all files in gentoolkit.settings["PORTDIR"]+"/desc/*.desc
		# variable name = <filename>_<field1>
		# description = <field 2>
		for descfile in glob(gentoolkit.settings["PORTDIR"]+"/profiles/desc/*.desc"):
			try:
				fd = open(descfile)
				for line in fd.readlines():
					if line[0] == "#":
						continue
					fields = [field.strip() for field in line.split(" - ", 1)]
					if len(fields) == 2:
							usedesc["%s_%s" % (descfile.split("/")[-1][0:-5], fields[0],)] = fields[1]
			except IOError:
				print_warn(5, "Could not load USE flag descriptions from " + descfile)

		# Load local USE flag descriptions
		try:
			fd = open(gentoolkit.settings["PORTDIR"]+"/profiles/use.local.desc")
			for line in fd.readlines():
				if line[0] == "#":
					continue
				fields = line.split(" - ", 1)
				if len(fields) == 2:
					catpkguse = re.search("(.*):(.*)", fields[0])
					if catpkguse:
						if not uselocaldesc.has_key(catpkguse.group(1).strip()):
							uselocaldesc[catpkguse.group(1).strip()] = {catpkguse.group(2).strip() : fields[1].strip()}
						else:
							uselocaldesc[catpkguse.group(1).strip()][catpkguse.group(2).strip()] = fields[1].strip()
		except IOError:
				print_warn(5, "Could not load USE flag descriptions from " + path(gentoolkit.settings["PORTDIR"] + "/profiles/use.local.desc"))

		if not Config["piping"] and Config["verbosityLevel"] >= 3: 
			print_info(3, "[ Colour Code : " + pp.useflagon("set") + " " + pp.useflagoff("unset") + " ]")
			print_info(3, "[ Legend : Left column  (U) - USE flags from make.conf              ]")
			print_info(3, "[        : Right column (I) - USE flags packages was installed with ]")

		# Iterate through matches, printing a report for each package
		matches = gentoolkit.sort_package_list(matches)
		matches_found = 0
		for p in matches:

			matches_found += 1
			
			bestver = p.get_cpv()
			iuse = p.get_env_var("IUSE")
		  
			if iuse:
				# Fix Bug #91623 by making sure the list of USE flags is unique
				# Added sort to make output prettier
				usevar = unique_array(iuse.split())

				# Remove prefixed +/- from flags in IUSE, Bug #232019
				for i in range(len(usevar)):
					if usevar[i][0] == "+" or usevar[i][0] == "-":
						usevar[i] = usevar[i][1:]

				usevar.sort()
			else:
				usevar = []

			inuse = []
			if p.is_installed():
				used = p.get_use_flags().split()
			else:
				# cosmetic issue here as noninstalled packages don't have "used" flags
				used = useflags

			# store (inuse, inused, flag, desc)
			output = []

			for u in usevar:
				inuse = 0
				inused = 0
				try:
					desc = usedesc[u]
				except KeyError:
					try:
						desc = uselocaldesc[p.get_category() + "/" + p.get_name()][u]
					except KeyError:
						desc = ""

				if u in p.get_settings("USE").split():
					inuse = 1
				if u in used:
					inused = 1

				output.append((inuse, inused, u, desc))

			# pretty print
			if output:
				if not Config["piping"] and Config["verbosityLevel"] >= 3:
					print_info(0, "[ Found these USE variables for " + pp.cpv(bestver) + " ]")
					print_info(3, pp.emph(" U I"))
				maxflag_len = 0
				for inuse, inused, u, desc in output:
					if len(u) > maxflag_len:
						maxflag_len = len(u)

				for in_makeconf, in_installed, flag, desc in output:
					markers = ["-","+"]
					colour = [pp.useflagoff, pp.useflagon]
					if Config["piping"]:
						print_info(0, markers[in_makeconf] + flag)
					else:
						if in_makeconf != in_installed:
							print_info(0, pp.emph(" %s %s" % (markers[in_makeconf], markers[in_installed])), False)
						else:
							print_info(0, " %s %s" % (markers[in_makeconf], markers[in_installed]), False)
	
						print_info(0, " " + colour[in_makeconf](flag.ljust(maxflag_len)), False)

						# print description
						if desc:
							print_info(0, " : " + desc)
						else:
							print_info(0, " : <unknown>")
			else:
				if not Config["piping"] and Config["verbosityLevel"] >= 3:
					print_info(1, "[ No USE flags found for " + pp.cpv(p.get_cpv()) + "]")

		if Config["verbosityLevel"] >= 2:
			if matches_found == 0:
				s = ""
				die(3, "No " + s + "packages found for " + pp.pkgquery(query))
				
					
	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - display USE flags for " + pp.pkgquery("pkgspec")
	def longHelp(self):
		return "Display USE flags for a given package\n" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("uses") + pp.localoption(" <local-opts> ") + pp.pkgquery("pkgspec") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is: \n" + \
			   "  " + pp.localoption("-a, --all") + " - include all package versions\n"


class CmdDisplayDepGraph(Command):
	"""Display tree graph of dependencies for a query"""

	def __init__(self):
		self.default_opts = {
			"displayUSEFlags": 1,
			"fancyFormatting": 1,
			"depth": 0
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-U","--no-useflags"]:
				opts["displayUSEFlags"] = 0
			elif x in ["-l","--linear"]:
				opts["fancyFormatting"] = 0
			elif x[:8] == "--depth=":
				opts["depth"] = int(x[8:])
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help or query == "":
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)

	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		if not Config["piping"] and Config["verbosityLevel"] >= 3:
			print_info(3, "[ Searching for packages matching " + pp.pkgquery(query) + "... ]")

		matches = gentoolkit.find_packages(query, True)

		for pkg in matches:
			if not Config["piping"] and Config["verbosityLevel"] >= 3:
				print_info(3, pp.section("* ") + "dependency graph for " + pp.cpv(pkg.get_cpv()))
			else:
				print_info(0, pkg.get_cpv() + ":")

			stats = { "maxdepth": 0, "packages": 0 }
			self._graph(pkg, opts, stats, 0, [], "")
			if not Config["piping"] and Config["verbosityLevel"] >= 3:
				print_info(0, "[ " + pp.cpv(pkg.get_cpv()) + " stats: packages (" + pp.number(str(stats["packages"])) + \
				"), max depth (" + pp.number(str(stats["maxdepth"])) + ") ]")
		
	def _graph(self, pkg, opts, stats, level=0, pkgtbl=[], suffix=""):
	
		stats["packages"] += 1
		stats["maxdepth"] = max(stats["maxdepth"], level)
		
		cpv = pkg.get_cpv()

		pfx = ""
		if opts["fancyFormatting"]:
			pfx = level * " " + "`-- " 
		print_info(0, pfx + cpv + suffix)
		
		pkgtbl.append(cpv)
		
		pkgdeps = pkg.get_runtime_deps() + pkg.get_compiletime_deps() + pkg.get_postmerge_deps()
		for x in pkgdeps:
			suffix = ""
			cpv = x[2]
			pkg = gentoolkit.find_best_match(x[0] + cpv)
			if not pkg:
				print pfx + x[0] + cpv + " (unable to resolve to a package / package masked or removed)"
				continue
			if pkg.get_cpv() in pkgtbl:
				continue
			if cpv.find("virtual") == 0:
				suffix += " (" + pp.cpv(cpv) + ")"
			if len(x[1]) and opts["displayUSEFlags"]:
				suffix += " [ " + pp.useflagon(' '.join(x[1])) + " ]"
			if (level < opts["depth"] or opts["depth"] <= 0):
				pkgtbl = self._graph(pkg, opts, stats, level+1, pkgtbl, suffix)
		return pkgtbl

	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - display a dependency tree for " + pp.pkgquery("pkgspec")
	def longHelp(self):
		return "Display a dependency tree for a given package\n" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("depgraph") + pp.localoption(" <local-opts> ") + pp.pkgquery("pkgspec") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is either of: \n" + \
			   "  " + pp.localoption("-U, --no-useflags") + " - do not show USE flags\n" + \
			   "  " + pp.localoption("-l, --linear") + "      - do not use fancy formatting\n" + \
			   "  " + pp.localoption("    --depth=n") + "     - limit dependency graph to specified depth"


class CmdDisplaySize(Command):
	"""Display disk size consumed by a package"""
	def __init__(self):
		self.default_opts = {
			"regex": 0,
			"exact": 0,
			"reportSizeInBytes": 0
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-b","--bytes"]:
				opts["reportSizeInBytes"] = 1
			elif x in ["-f", "--full-regex"]:
				opts["regex"] = 1
			elif x in ["-e", "--exact-name"]:
				opts["exact"] = 1
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

#		if need_help or query == "":
		if need_help:
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)
				
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		rev = ""
		name = ""
		ver = ""
		cat = ""

		if query != "":
			(cat, name, ver, rev) = gentoolkit.split_package_name(query)
			if rev == "r0": rev = ""

		# replace empty strings with .* and escape regular expression syntax
		if query != "":
			if not opts["regex"]:
				cat, name, ver, rev = [re.sub('^$', ".*", re.escape(x)) for x in cat, name, ver, rev]
			else:
				cat, name, ver, rev = [re.sub('^$', ".*", x) for x in cat, name, ver, rev]

			try:
				if opts["exact"]:
					filter_fn = lambda x: re.match(cat+"/"+name, x)
				else:
					filter_fn = lambda x: re.match(cat+"/.*"+name, x)
				matches = gentoolkit.find_all_installed_packages(filter_fn)
			except:
				die(2, "The query '" + pp.regexpquery(query) + "' does not appear to be a valid regular expression")
		else:
			cat, name, ver, rev = [re.sub('^$', ".*", x) for x in cat, name, ver, rev]
			matches = gentoolkit.find_all_installed_packages()

		matches = gentoolkit.sort_package_list(matches)

		if not Config["piping"] and Config["verbosityLevel"] >= 3:
			print_info(3, "[ Searching for packages matching " + pp.pkgquery(query) + "... ]")

		# If no version supplied, fix regular expression
		if ver == ".*": ver = "[0-9]+[^-]*"

		if rev != ".*":	# revision supplied
			ver = ver + "-" + rev

		if opts["exact"]:
			rx = re.compile(cat + "/" + name + "-" + ver)
		else:
			rx = re.compile(cat + "/.*" + name + ".*-" + ver)

		for pkg in matches:
			if rx.search(pkg.get_cpv()):
				(size, files, uncounted) = pkg.size()

				if Config["piping"]:
					print_info(0, pkg.get_cpv() + ": total(" + str(files) + "), inaccessible(" + str(uncounted) + \
						"), size(" + str(size) + ")")
				else:
					print_info(0, pp.section("* ") + "size of " + pp.cpv(pkg.get_cpv()))
					print_info(0, " Total files : ".rjust(25) + pp.number(str(files)))

					if uncounted:
						print_info(0, " Inaccessible files : ".rjust(25) + pp.number(str(uncounted)))

					sz = "%.2f KiB" % (size/1024.0)				
					if opts["reportSizeInBytes"]:
						sz = pp.number(str(size)) + " bytes"

					print_info(0, "Total size  : ".rjust(25) + pp.number(sz))

					
	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - print size of files contained in package " + pp.pkgquery("pkgspec")
	def longHelp(self):
		return "Print size total size of files contained in a given package" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("size") + pp.localoption(" <local-opts> ") + pp.pkgquery("pkgspec") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is: \n" + \
			   "  " + pp.localoption("-b, --bytes") + "      - report size in bytes\n" \
			   "  " + pp.localoption("-f, --full-regex") + " - query is a regular expression\n" + \
			   "  " + pp.localoption("-e, --exact-name") + " - list only those packages that exactly match\n"

class CmdDisplayChanges(Command):
	"""Display changes for pkgQuery"""
	pass

class CheckException:
	def __init__(self, s):
		self.s = s
	
class CmdCheckIntegrity(Command):
	"""Check timestamps and md5sums for files owned by pkgspec"""
	def __init__(self):
		self.default_opts = {
			"showSummary" : 1,
			"showGoodFiles" : 0,
			"showBadFiles" : 1,
			"checkTimestamp" : 1,
			"checkMD5sum": 1
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):
			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help:
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)

	def getMD5sum(self, file):
		return checksum.perform_md5(file, calc_prelink=1)
	
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		if query == "":
			matches=gentoolkit.find_all_installed_packages()
		else:
			matches = gentoolkit.find_packages(query, True)

		matches = gentoolkit.sort_package_list(matches)

		for pkg in matches:
			if not pkg.is_installed():
				continue
			if not Config["piping"] and Config["verbosityLevel"] >= 3:
				print_info(1, "[ Checking " + pp.cpv(pkg.get_cpv()) + " ]")
			else:
				print_info(0, pkg.get_cpv() + ":")
				
			files = pkg.get_contents()
			checked_files = 0
			good_files = 0
			for file in files.keys():
				type = files[file][0]
				try:
					st = os.lstat(file)
					if type == "dir":
						if not os.path.isdir(file):
							raise CheckException(file + " exists, but is not a directory")
					elif type == "obj":
						mtime = files[file][1]
						md5sum = files[file][2]
						if opts["checkMD5sum"]:
							try: 
								actual_checksum = self.getMD5sum(file)
							except:
								raise CheckException("Failed to calculate MD5 sum for " + file)
								
							if self.getMD5sum(file) != md5sum:
								raise CheckException(file + " has incorrect md5sum")
						if opts["checkTimestamp"]:
							if int(st.st_mtime) != int(mtime):
								raise CheckException(file + (" has wrong mtime (is %d, should be %s)" % (st.st_mtime, mtime)))
					elif type == "sym":
						# FIXME: nastry strippery; portage should have this fixed!
						t = files[file][2]
						# target = os.path.normpath(t.strip())
						target = t.strip()
						if not os.path.islink(file):
							raise CheckException(file + " exists, but is not a symlink")
						tgt = os.readlink(file)
						if tgt != target:
							raise CheckException(file + " does not point to " + target)
					elif type == "fif":
						pass
					else:
						pp.print_error(file)
						pp.print_error(files[file])
						pp.print_error(type)
						raise CheckException(file + " has unknown type " + type)
					good_files += 1
				except CheckException, (e):
					print_error(e.s)
				except OSError:
					print_error(file + " does not exist")
				checked_files += 1
			print_info(0, pp.section(" * ") + pp.number(str(good_files)) + " out of " +  pp.number(str(checked_files)) + " files good")
					
	def shortHelp(self):
		return pp.pkgquery("pkgspec") + " - check MD5sums and timestamps of " + pp.pkgquery("pkgspec") + "'s files"
	def longHelp(self):
		return "Check package's files against recorded MD5 sums and timestamps" + \
				"\n" + \
				"Syntax:\n" + \
				"  " + pp.command("check") + pp.pkgquery(" pkgspec")

class CmdDisplayStatistics(Command):
	"""Display statistics about installed and uninstalled packages"""
	pass

class CmdWhich(Command):
	"""Display the filename of the ebuild for a given package
	   that would be used by Portage with the current configuration."""
	def __init__(self):
		self.default_opts = {
			"includeMasked": False
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-m", "--include-masked"]:
				opts["includeMasked"] = True
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help or query == "":
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)
				
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		matches = gentoolkit.find_packages(query, opts["includeMasked"])
		matches = gentoolkit.sort_package_list(matches)

		if matches:
			pkg = matches[-1]
			ebuild_path = pkg.get_ebuild_path()
			if ebuild_path:
				print_info(0, os.path.normpath(ebuild_path))
			else:
				print_warn("There are no ebuilds to satisfy %s" % pkg.get_name())
		else:
			print_error("No masked or unmasked packages found for " + pp.pkgquery(query))
					
	def shortHelp(self):
		return pp.pkgquery("pkgspec") + " - print full path to ebuild for package " + pp.pkgquery("pkgspec")
	def longHelp(self):
		# Not documenting --include-masked at this time, since I'm not sure that it is needed. - FuzzyRay
		return "Print full path to ebuild for a given package" + \
			"\n" + \
			"Syntax:\n" + \
			"  " + pp.command("which ") + pp.pkgquery("pkgspec")

class CmdListGLSAs(Command):
	"""List outstanding GLSAs."""
	pass

class CmdListDepends(Command):
	"""List all packages directly or indirectly depending on pkgQuery"""
	def __init__(self):
		self.default_opts = {
			"onlyDirect": 1,
			"onlyInstalled": 1,
			"spacing": 0,
			"depth": -1
			}
		# Used to cache and detect looping
		self.pkgseen = []
		self.pkglist = []
		self.pkgdeps = {}
		self.deppkgs = {}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		 
		for i in xrange(len(args)):
			if skip:
				skip -= 1
				continue
			x = args[i]
			 
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-d", "--direct"]:
				opts["onlyDirect"] = 1
			elif x in ["-D", "--indirect"]:
				opts["onlyDirect"] = 0
			elif x in ["-a", "--all-packages"]:
				opts["onlyInstalled"] = 0
			elif x[:10] == "--spacing=":
				opts["spacing"] = int(x[10:])
			elif x[:8] == "--depth=":
				opts["depth"] = int(x[8:])
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x
	 
		if need_help or query == "":
			print self.longHelp()
			sys.exit(-1)
		return (query, opts)
 
	def perform(self, args):

		(query, opts) = self.parseArgs(args)

		# We call ourself recursively if --indirect specified. spacing is used to control printing the tree.
		spacing = opts["spacing"]

		if not Config["piping"] and Config["verbosityLevel"] >= 3 and not spacing:
			print_info(3, "[ Searching for packages depending on " + pp.pkgquery(query) + "... ]")

		isdepend = gentoolkit.split_package_name(query)
		isdepends = map((lambda x: x.get_cpv()), gentoolkit.find_packages(query))
		if not isdepends:
			print_warn("Warning: No packages found matching %s" % query)
		
		# Cache the list of packages
		if not self.pkglist:
			if opts["onlyInstalled"]:
				packages = gentoolkit.find_all_installed_packages()
			else:
				packages = gentoolkit.find_all_packages()

			packages = gentoolkit.sort_package_list(packages)
			self.pkglist = packages
		else:
			packages = self.pkglist

		for pkg in packages:
			pkgcpv = pkg.get_cpv()
			if not pkgcpv in self.pkgdeps:
				try:
					deps = pkg.get_runtime_deps() + pkg.get_compiletime_deps() + pkg.get_postmerge_deps()
				except KeyError, e:
					# If the ebuild is not found... 
					continue
				# Remove duplicate deps
				deps = unique_array(deps)
				self.pkgdeps[pkgcpv] = deps
			else:
				deps = self.pkgdeps[pkgcpv]
			isdep = 0
			for dependency in deps:
				# TODO determine if dependency is enabled by USE flag
				# Find all packages matching the dependency
				depstr = dependency[0]+dependency[2]
				if not depstr in self.deppkgs:
					try:
						depcpvs = map((lambda x: x.get_cpv()), gentoolkit.find_packages(depstr))
						self.deppkgs[depstr] = depcpvs
					except KeyError, e:
						print_warn("")
						print_warn("Package: " + pkgcpv + " contains invalid dependency specification.")
						print_warn("Portage error: " + str(e))
						print_warn("")
						continue
				else:
					depcpvs = self.deppkgs[depstr]
				for x in depcpvs:
					cpvs=gentoolkit.split_package_name(x)
					if x in isdepends:
						cat_match=1
						name_match=1
						ver_match=1
					else:
						cat_match=0
						name_match=0
						ver_match=0
						# Match Category
						if not isdepend[0] or cpvs[0] == isdepend[0]:
							cat_match=1
						# Match Name
						if cpvs[1] == isdepend[1]:
							name_match=1
						# Match Version
						if not isdepend[2] or ( cpvs[2] == isdepend[2] and (isdepend[3] \
						   or isdepend[3] == "r0" or cpvs[3] == isdepend[3])):
							ver_match=1

					if cat_match and ver_match and name_match:
						if not isdep:
							if dependency[1]:
								if not Config["piping"] and Config["verbosityLevel"] >= 3:
									print " " * (spacing * 2) + pp.cpv(pkg.get_cpv()),
								   	print "(" + \
									pp.useflag(" & ".join(dependency[1]) + "? ") + \
									pp.pkgquery(dependency[0]+dependency[2]) + ")"
								else:
									print " " * (spacing * 2) + pkg.get_cpv()
							else:
								if not Config["piping"] and Config["verbosityLevel"] >= 3:
									print " " * (spacing * 2) + pp.cpv(pkg.get_cpv()),
									print "(" + pp.pkgquery(dependency[0]+dependency[2]) + ")"
								else:
									print " " * (spacing * 2) + pkg.get_cpv()
							isdep = 1
						elif not Config["piping"] and Config["verbosityLevel"] >= 3:
							if dependency[1]:
								print " "*len(pkg.get_cpv()) + " " * (spacing * 2) + \
								      " (" + pp.useflag("&".join(dependency[1]) + "? ") + \
								      pp.pkgquery(dependency[0]+dependency[2]) + ")"
							else:
								print " "*len(pkg.get_cpv()) + " " * (spacing * 2) + " (" + \
								      pp.pkgquery(dependency[0]+dependency[2]) + ")"	

						break

			# if --indirect specified, call ourselves again with the dependency
			# Do not call, if we have already called ourselves.
			if isdep and not opts["onlyDirect"] and pkg.get_cpv() not in self.pkgseen \
			   and (spacing < opts["depth"] or opts["depth"] == -1):
				self.pkgseen.append(pkg.get_cpv())
				self.perform(['=' + pkg.get_cpv(), '--indirect', '--spacing=' + str(int(opts["spacing"]+1))])
				opts["spacing"] = spacing;
 
 
	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - list all direct dependencies matching " + \
		       pp.pkgquery("pkgspec")
	 
	def longHelp(self):
		 return "List all direct dependencies matching a query pattern" + \
				"\n" + \
				"Syntax:\n" + \
				"  " + pp.command("depends") + pp.localoption(" <local-opts> ") + pp.pkgquery("pkgspec") + \
				"\n" + \
				pp.localoption("<local-opts>") + " is either of: \n" + \
				"  " + pp.localoption("-a, --all-packages") + " - search in all available packages (slow)\n" + \
				"  " + pp.localoption("-d, --direct") + "       - search direct dependencies only (default)\n" + \
				"  " + pp.localoption("-D, --indirect") + "     - search indirect dependencies (VERY slow)\n" + \
				"  " + pp.localoption("    --depth=n") + "      - limit indirect dependency tree to specified depth"


class CmdListPackages(Command):
	"""List packages satisfying pkgQuery"""
	def __init__(self):
		self.default_opts = {
			"category": "*",
			"includeInstalled": 1,
			"includePortTree": 0,
			"includeOverlayTree": 0,
			"includeMasked": 1,
			"regex": 0,
			"exact": 0,
			"duplicates": 0
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-i", "--installed"]:
				opts["includeInstalled"] = 1
			elif x in ["-I", "--exclude-installed"]:
				# If -I is the only option, warn
				# (warning located in perform())
				opts["includeInstalled"] = 0
			elif x in ["-p", "--portage-tree"]:
				opts["includePortTree"] = 1
			elif x in ["-o", "--overlay-tree"]:
				opts["includeOverlayTree"] = 1
			elif x in ["-m", "--exclude-masked"]:
				opts["includeMasked"] = 0
			elif x in ["-f", "--full-regex"]:
				opts["regex"] = 1
			elif x in ["-e", "--exact-name"]:
				opts["exact"] = 1
			elif x in ["-d", "--duplicates"]:
				opts["duplicates"] = 1
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		# Only search installed packages when listing duplicated packages
		if opts["duplicates"]:
			opts["includeInstalled"] = 1
			opts["includePortTree"] = 0
			opts["includeOverlayTree"] = 0

		if need_help:
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)
				
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		rev = ""
		name = ""
		ver = ""
		cat = ""

		if query != "":
			try: (cat, name, ver, rev) = gentoolkit.split_package_name(query)
			except ValueError, e:
				if str(e) == 'too many values to unpack':
					print_error("A pattern to match against package names was expected, ")
					warn_msg = "but %s has too many slashes ('/') to match any package."
					die (1, warn_msg % query)
				else: raise ValueError(e)
			if rev == "r0": rev = ""

		package_finder = None

		if opts["includeInstalled"]:
			if opts["includePortTree"] or opts["includeOverlayTree"]:
				package_finder = gentoolkit.find_all_packages
			else:
				package_finder = gentoolkit.find_all_installed_packages
		elif opts["includePortTree"] or opts["includeOverlayTree"]:
			package_finder = gentoolkit.find_all_uninstalled_packages
		else:
			# -I was specified, and no selection of what packages to list was made
			print_warn("With -I you must specify one of -i, -p or -o. Assuming -p")
			opts["includePortTree"] = 1
			package_finder = gentoolkit.find_all_uninstalled_packages

		filter_fn = None

		if Config["verbosityLevel"] >= 3:
			scat = "'" + cat + "'"
			if not cat:
				scat = "all categories"
			sname = "package '" + name + "'"
			if not name:
				sname = "all packages"
			if not Config["piping"] and Config["verbosityLevel"] >= 3:
				print_info(1, "[ Searching for " + pp.cpv(sname) + " in " + pp.cpv(scat) + " among: ]")

		# replace empty strings with .* and escape regular expression syntax
		if query != "":
			if not opts["regex"]:
				cat, name, ver, rev = [re.sub('^$', ".*", re.escape(x)) for x in cat, name, ver, rev]
			else:
				cat, name, ver, rev = [re.sub('^$', ".*", x) for x in cat, name, ver, rev]

			try:
				if opts["exact"]:
					filter_fn = lambda x: re.match(cat+"/"+name, x)
				else:
					filter_fn = lambda x: re.match(cat+"/.*"+name, x)
				matches = package_finder(filter_fn)
			except:
				die(2, "The query '" + pp.regexpquery(query) + "' does not appear to be a valid regular expression")
		else:
			cat, name, ver, rev = [re.sub('^$', ".*", x) for x in cat, name, ver, rev]
			filter_fn = lambda x: True
			matches = package_finder(filter_fn)

		# Find duplicate packages
		if opts["duplicates"]:
			dups = {}
			newmatches = []
			for pkg in matches:
				mykey = pkg.get_category() + "/" + pkg.get_name() 
				if dups.has_key(mykey):
					dups[mykey].append(pkg)
				else:
					dups[mykey] = [pkg]

			for mykey in dups.keys():
				if len(dups[mykey]) > 1:
					newmatches += dups[mykey]

			matches = newmatches

		matches = gentoolkit.sort_package_list(matches)

		# If no version supplied, fix regular expression
		if ver == ".*": ver = "[0-9]+[^-]*"

		if rev != ".*":	# revision supplied
			ver = ver + "-" + rev

		if opts["exact"]:
			rx = re.compile(cat + "/" + name + "-" + ver)
		else:
			rx = re.compile(cat + "/.*" + name + ".*-" + ver)

		if opts["includeInstalled"]:
			self._print_installed(matches, rx)
		
		if opts["includePortTree"]:
			self._print_porttree(matches, rx)
		
		if opts["includeOverlayTree"]:
			self._print_overlay(matches, rx)

	def _get_mask_status(self, pkg):
		pkgmask = 0
		if pkg.is_masked():
		# Uncomment to only have package masked files show an 'M'
		# maskreasons = portage.getmaskingstatus(pkg.get_cpv())
		# if "package.mask" in maskreasons:
			pkgmask = pkgmask + 3
		keywords = pkg.get_env_var("KEYWORDS").split()
		if gentoolkit.settings["ARCH"] not in keywords:
			if "~" + gentoolkit.settings["ARCH"] in keywords:
				pkgmask = pkgmask + 1
			elif "-" + gentoolkit.settings["ARCH"] in keywords or "-*" in keywords:
				pkgmask = pkgmask + 2
		return pkgmask

	def _generic_print(self, header, exclude, matches, rx, status):
		if Config["verbosityLevel"] >= 3:
			print_info(1, header)

		pfxmodes = [ "---", "I--", "-P-", "--O" ]
		maskmodes = [ "  ", " ~", " -", "M ", "M~", "M-" ]

		for pkg in matches:
			if exclude(pkg):
				continue

			pkgmask = self._get_mask_status(pkg)
			
			slot = pkg.get_env_var("SLOT")

			if rx.search(pkg.get_cpv()):
				if Config["piping"]:
					print_info(0, pkg.get_cpv())
				else:
					print_info(0, "[" + pp.installedflag(pfxmodes[status]) + "] [" + pp.maskflag(maskmodes[pkgmask]) + "] " + pp.cpv(pkg.get_cpv()) + " (" + pp.slot(slot) + ")")

	def _print_overlay(self, matches, rx):
		self._generic_print(
			pp.section(" *") + " overlay tree (" + pp.path(gentoolkit.settings["PORTDIR_OVERLAY"]) + ")",
			lambda x: not x.is_overlay(),
			matches, rx, 3)
			
	def _print_porttree(self, matches, rx):
		self._generic_print(
			pp.section(" *") + " Portage tree (" + pp.path(gentoolkit.settings["PORTDIR"]) + ")",
			lambda x: x.is_overlay() or x.is_installed(),
			matches, rx, 2)
				
	def _print_installed(self, matches, rx):
		self._generic_print(
			pp.section(" *") + " installed packages",
			lambda x: not x.is_installed(),
			matches, rx, 1)

	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("pkgspec") + " - list all packages matching " + pp.pkgquery("pkgspec")
	def longHelp(self):
		return "List all packages matching a query pattern" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("list") + pp.localoption(" <local-opts> ") + pp.pkgquery("pkgspec") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is either of: \n" + \
			   "  " + pp.localoption("-i, --installed") + "         - search installed packages (default)\n" + \
			   "  " + pp.localoption("-I, --exclude-installed") + " - do not search installed packages\n" + \
			   "  " + pp.localoption("-p, --portage-tree") + "      - also search in portage tree (" + gentoolkit.settings["PORTDIR"] + ")\n" + \
			   "  " + pp.localoption("-o, --overlay-tree") + "      - also search in overlay tree (" + gentoolkit.settings["PORTDIR_OVERLAY"] + ")\n" + \
			   "  " + pp.localoption("-f, --full-regex") + "        - query is a regular expression\n" + \
			   "  " + pp.localoption("-e, --exact-name") + "        - list only those packages that exactly match\n" + \
			   "  " + pp.localoption("-d, --duplicates") + "        - list only installed duplicate packages\n"

class CmdFindUSEs(Command):
	"""Find all packages with a particular USE flag."""
	def __init__(self):
		self.default_opts = {
			"category": "*",
			"includeInstalled": 1,
			"includePortTree": 0,
			"includeOverlayTree": 0,
			"includeMasked": 1,
			"regex": 0
			}

	def parseArgs(self, args):

		query = ""
		need_help = 0
		opts = self.default_opts
		skip = 0
		
		for i in xrange(len(args)):

			if skip:
				skip -= 1
				continue
			x = args[i]
			
			if x in ["-h","--help"]:
				need_help = 1
				break
			elif x in ["-i", "--installed"]:
				opts["includeInstalled"] = 1
			elif x in ["-I", "--exclude-installed"]:
				opts["includeInstalled"] = 0
			elif x in ["-p", "--portage-tree"]:
				opts["includePortTree"] = 1
			elif x in ["-o", "--overlay-tree"]:
				opts["includeOverlayTree"] = 1
			elif x in ["-m", "--exclude-masked"]:
				opts["includeMasked"] = 0
			elif x[0] == "-":
				print_warn("unknown local option %s, ignoring" % x)
			else:
				query = x

		if need_help:
			print_info(0, self.longHelp())
			sys.exit(-1)
			
		return (query, opts)
				
	def perform(self, args):
		(query, opts) = self.parseArgs(args)

		rev = ".*"
		name = ".*"
		ver = ".*"
		cat = ".*"
		
		package_finder = None

		if opts["includeInstalled"] and (opts["includePortTree"] or opts["includeOverlayTree"]):
			package_finder = gentoolkit.find_all_packages
		elif opts["includeInstalled"]:
			package_finder = gentoolkit.find_all_installed_packages
		elif opts["includePortTree"] or opts["includeOverlayTree"]:
			package_finder = gentoolkit.find_all_uninstalled_packages

		if not package_finder:
			die(2,"You must specify one of -i, -p or -o")

		filter_fn = lambda x: True
			
		if Config["verbosityLevel"] >= 3:
			scat = "'" + cat + "'"
			if cat == ".*":
				scat = "all categories"
			if not Config["piping"]:
				print_info(2, "[ Searching for USE flag " + pp.useflag(query)  + " in " + pp.cpv(scat) + " among: ]")
				if opts["includeInstalled"]:
					print_info(1, pp.section(" *") + " installed packages")
				if opts["includePortTree"]:
					print_info(1, pp.section(" *") + " Portage tree (" + pp.path(gentoolkit.settings["PORTDIR"]) + ")")
				if opts["includeOverlayTree"]:
					print_info(1, pp.section(" *") + " overlay tree (" + pp.path(gentoolkit.settings["PORTDIR_OVERLAY"]) + ")")
		
		matches = package_finder(filter_fn)

		rx = re.compile(cat + "/" + name + "-" + ver + "(-" + rev + ")?")
		pfxmodes = [ "---", "I--", "-P-", "--O" ]
		maskmodes = [ "  ", " ~", " -", "M ", "M~", "M-" ]
		for pkg in matches:
			status = 0
			if pkg.is_installed():
				status = 1
			elif pkg.is_overlay():
				status = 3
			else:
				status = 2

			useflags = pkg.get_env_var("IUSE").split()
			useflags = [f.lstrip("+-") for f in useflags]

			if query not in useflags:
				continue 
				
			# Determining mask status
			pkgmask = 0
			if pkg.is_masked():
				pkgmask = pkgmask + 3
			keywords = pkg.get_env_var("KEYWORDS").split()
			if "~"+gentoolkit.settings["ARCH"] in keywords:
				pkgmask = pkgmask + 1
			elif "-*" in keywords or "-"+gentoolkit.settings["ARCH"] in keywords:
				pkgmask = pkgmask + 2

			# Determining SLOT value
			slot = pkg.get_env_var("SLOT")

			if (status == 1 and opts["includeInstalled"]) or \
			   (status == 2 and opts["includePortTree"]) or \
			   (status == 3 and opts["includeOverlayTree"]):
				if Config["piping"]:
					print_info(0, pkg.get_cpv())
				else:
					print_info(0, "[" + pp.installedflag(pfxmodes[status]) + "] [" + pp.maskflag(maskmodes[pkgmask]) + "] " + pp.cpv(pkg.get_cpv()) + " (" + pp.slot(slot) + ")")
					
	def shortHelp(self):
		return pp.localoption("<local-opts> ") + pp.pkgquery("useflag") + " - list all packages with " + pp.pkgquery("useflag")
	def longHelp(self):
		return "List all packages with a particular USE flag" + \
			   "\n" + \
			   "Syntax:\n" + \
			   "  " + pp.command("list") + pp.localoption(" <local-opts> ") + pp.pkgquery("useflag") + \
			   "\n" + \
			   pp.localoption("<local-opts>") + " is either of: \n" + \
			   "  " + pp.localoption("-i, --installed") + "		 - search installed packages (default)\n" + \
			   "  " + pp.localoption("-I, --exclude-installed") + " - do not search installed packages\n" + \
			   "  " + pp.localoption("-p, --portage-tree") + "	  - also search in portage tree (" + gentoolkit.settings["PORTDIR"] + ")\n" + \
			   "  " + pp.localoption("-o, --overlay-tree") + "	  - also search in overlay tree (" + gentoolkit.settings["PORTDIR_OVERLAY"] + ")\n"

#
# Command line tokens to commands mapping
#

Known_commands = {
	"list" : CmdListPackages(),
	"files" : CmdListFiles(),
	"belongs" : CmdListBelongs(),
	"depends" : CmdListDepends(),
	"hasuse" : CmdFindUSEs(),
	"uses" : CmdDisplayUSEs(),
	"depgraph" : CmdDisplayDepGraph(),
	"changes" : CmdDisplayChanges(),
	"size" : CmdDisplaySize(),
	"check" : CmdCheckIntegrity(),
	"stats" : CmdDisplayStatistics(),
	"glsa" : CmdListGLSAs(),
	"which": CmdWhich()
	}

# Short command line tokens

Short_commands = {
	"a" : "glsa",
	"b" : "belongs",
	"c" : "changes",
	"d" : "depends",
	"f" : "files",
	"g" : "depgraph",
	"h" : "hasuse",
	"k" : "check",
	"l" : "list",
	"s" : "size",
	"t" : "stats",
	"u" : "uses",
	"w" : "which"
}

from gentoolkit import Config

Config = {
	# Query will include packages installed on the system
	"installedPackages":  1,
	# Query will include packages available for installation
	"uninstalledPackages": 0,
	# Query will include overlay packages (iff uninstalledPackages==1)
	"overlayPackages": 1,
	# Query will include masked packages (iff uninstalledPackages==1)
	"maskedPackages": 0,
	# Query will only consider packages in the following categories, empty means all.
	"categoryFilter": [],
	# Enable color output (-1 = use Portage setting, 0 = force off, 1 = force on)
	"color": -1,
	# Level of detail on the output
	"verbosityLevel": 3,
	# Query will display info for multiple SLOTed versions
	"considerDuplicates": 1,
	# Are we writing to a pipe?
	"piping": 0
}
	
def printVersion():
	"""Print the version of this tool to the console."""
	print_info(0, __productname__ + "(" + __version__ + ") - " + \
		  __description__)
	print_info(0, "Author(s): " + __author__)

def buildReverseMap(m):
	r = {}
	for x in m.keys():
		r[m[x]] = x
	return r
	
def printUsage():
	"""Print full usage information for this tool to the console."""
	
	short_cmds = buildReverseMap(Short_commands);
	
	print_info(0, pp.emph("Usage: ") + pp.productname(__productname__) + pp.globaloption(" <global-opts> ") + pp.command("command") + pp.localoption(" <local-opts>"))
	print_info(0, "where " + pp.globaloption("<global-opts>") + " is one of")
	print_info(0, pp.globaloption(" -q, --quiet") + "   - minimal output")
	print_info(0, pp.globaloption(" -C, --nocolor") + " - turn off colours")
	print_info(0, pp.globaloption(" -h, --help") + "    - this help screen")
	print_info(0, pp.globaloption(" -V, --version") + " - display version info")
	print_info(0, pp.globaloption(" -N, --no-pipe") + " - turn off pipe detection")
	
	print_info(0, "where " + pp.command("command") + "(" + pp.command("short") + ") is one of")
	keys = Known_commands.keys()
	keys.sort()
	for x in keys:
		print_info(0, " " + pp.command(x) + "(" + pp.command(short_cmds[x]) + ") " + \
			Known_commands[x].shortHelp())
	print
	
def configure():
	"""Set up default configuration.
	"""

	# Guess colour output
	if (Config["color"] == -1 and \
		((not sys.stdout.isatty()) or (gentoolkit.settings["NOCOLOR"] in ["yes","true"]))):
			pp.output.nocolor()

	# Guess piping output
	if not sys.stdout.isatty():
		Config["piping"] = True
	else:
		Config["piping"] = False
		
	
def parseArgs(args):
	"""Parse tool-specific arguments. 
	
	Arguments are on the form equery <tool-specific> [command] <command-specific>
	
	This function will only parse the <tool-specific> bit.
	"""
	command = None
	local_opts = []
	showhelp = 0

	def expand(x):
		if x in Short_commands.keys():
			return Short_commands[x]
		return x
		
	for i in xrange(len(args)):
		x = args[i]
		if 0:
			pass
		elif x in ["-h", "--help"]:
			showhelp = True
		elif x in ["-V", "--version"]:
			printVersion()
			sys.exit(0)
		elif x in ["-C", "--nocolor"]:
			Config["color"] = 0
			pp.output.nocolor()
		elif x in ["-N", "--no-pipe"]:
			Config["piping"] = False
		elif x in ["-q","--quiet"]:
			Config["verbosityLevel"] = 0
		elif expand(x) in Known_commands.keys():
			command = Known_commands[expand(x)]
			local_opts.extend(args[i+1:])
			if showhelp:
				local_opts.append("--help")
			break
		else:
			print_warn("unknown global option %s, reusing as local option" % x)
			local_opts.append(x)
		
	if not command and showhelp:
		printUsage()
		sys.exit(0)

	return (command, local_opts)
   
if __name__ == "__main__":
	configure()
	(cmd, local_opts) = parseArgs(sys.argv[1:])
	if cmd:
		try:
			cmd.perform(local_opts)
		except KeyError, e:
			if e and e[0].find("Specific key requires an operator") >= 0:
				print_error("Invalid syntax: missing operator")
				print_error("If you want only specific versions please use one of")
				print_error("the following operators as prefix for the package name:")
				print_error("   >  >=  =  <=  <")
				print_error("Example to only match gcc versions greater or equal 3.2:")
				print_error("   >=sys-devel/gcc-3.2")
				print_error("")
				print_error("Note: The symbols > and < are used for redirection in the shell")
				print_error("and must be quoted if either one is used.")

			else:
				print_error("Internal portage error, terminating")
				if len(e[0]):
					print_error(str(e))
			sys.exit(2)
		except ValueError, e:
			if isinstance(e[0], list):
				print_error("Ambiguous package name " + pp.emph("\"" + local_opts[0] + "\""))
				print_error("Please use one of the following long names:")
				for p in e[0]:
					print_error("	" + str(p))
			else:
				print_error("Internal portage error, terminating")
				if len(e[0]):
					print_error(str(e[0]))
			sys.exit(2)
		except KeyboardInterrupt:
			print_info(0, "Interrupted by user, aborting.")
	else:
		print_error("No command or unknown command given")
		printUsage()