Treat * wildcard like tilder
[portpeek.git] / portpeek
1 #!/usr/bin/python
2 #
3 # Copyright 2006 Mike Pagano
4 # Distributed under the terms of the GNU General Public License v2
5 #
6 # $Header$
7 # Author: Mike Pagano <mpagano@gentoo.org>
8 #
9 # Portions written ripped from 
10 # - equery, by Karl Trygve Kalleberg <karltk@gentoo.org>
11 # - gentoolkit.py, by Karl Trygve Kalleberg <karltk@gentoo.org>
12 # - portage.py
13 # - emerge
14 #
15 #
16
17 __author__ = "Michael Pagano"
18 __email__ = "mpagano@gentoo.org"
19 __version__ = "2.1.9"
20 __productname__ = "portpeek"
21 __description__ = "Displays user unmasked ebuilds and installable options from the portage tree"
22
23 import sys, os, portage, fileinput, re, gentoolkit
24 from gentoolkit.versionmatch import VersionMatch,errors
25 from portage.const import USER_CONFIG_PATH
26 from portage.versions import catpkgsplit,pkgcmp,pkgsplit
27 from portage.exception import InvalidAtom
28 from gentoolkit.cpv import CPV
29 from gentoolkit.query import Query
30 from gentoolkit.flag import get_iuse
31
32 # support python 2
33 try:
34     input = raw_input
35 except NameError:
36     pass
37
38 porttree = portage.db[portage.root]["porttree"]
39 settings = portage.config(clone=portage.settings)
40 #settings = portage.config(local_config=False)
41
42 show_changes_only_flag = False
43 checking_package_unmask = False
44 checking_package_mask = False
45 print_overlay_flag = False
46 info = 0
47 debug = 1
48 logLevel = info
49 show_removable_only_flag = False
50 stable_list = []
51 stable_listNg = [] # handle package.accept_keywords
52 unmask_list = []
53 tilde = 0
54 processing_package_use = False
55 using_gentoo_as_overlay = False
56 overlay_list = []
57 fix_confirm = True
58 fix_asked = False
59 use_flag_dict = {}
60 useremove_display = ""
61 invalid_flag_found = False
62
63 try:
64     PORTAGE_CONFIGROOT
65 except NameError:
66     PORTAGE_CONFIGROOT="/"
67
68 USER_CONFIG_PATH=PORTAGE_CONFIGROOT + USER_CONFIG_PATH
69
70 #parameters
71 options = [
72 "--keyword",
73 "--unmask",
74 "--mask",
75 "--all",
76 "--changes-only",
77 "--version",
78 "--version",
79 "--help",
80 "--removable-only",
81 "--debug",
82 "--fix", 
83 "--tilde-check",
84 "--no-color",
85 "--package-use",
86 "--fix-confirm"
87 ]
88
89 mappings = {
90 "k":"--keyword",
91 "u":"--unmask",
92 "m":"--mask",
93 "a":"--all",
94 "c":"--changes-only",
95 "V":"--version",
96 "v":"--version",
97 "h":"--help",
98 "r":"--removable-only",
99 "d":"--debug",
100 "f":"--fix", 
101 "t":"--tilde-check",
102 "n":"--no-color",
103 "s":"--package-use",
104 "q":"--fix-confirm"
105 }
106
107 cmdline = []
108 overlays = [settings["PORTDIR_OVERLAY"]]
109
110 def print_usage():
111     # Print full usage information for this tool to the console.
112     print ("\nUsage: " + portage.output.turquoise(__productname__) +  portage.output.yellow(" command "))
113     print ("       " + portage.output.turquoise(__productname__) + portage.output.green(" [ options ]") +  portage.output.yellow(" command "))
114     print ("       " + portage.output.turquoise(__productname__) + portage.output.green(" [-c]") + portage.output.yellow(" [akmu]"))
115     print ("       " + portage.output.turquoise(__productname__) + portage.output.green(" [-r]") + portage.output.yellow(" [akmu]"))
116     print ("       " + portage.output.turquoise(__productname__) + portage.output.green(" [-f]") + portage.output.yellow(" [akmu]"))
117     print ("       " + portage.output.turquoise(__productname__) + portage.output.green(" [-F]") + portage.output.yellow(" [akmu]"))
118     print (portage.output.yellow(" command ") + " can be ")
119     print (portage.output.yellow(" -a, --all") + "       - show all matches")
120     print (portage.output.yellow(" -k, --keyword") + "       - show matches from package.keywords and package.accept_keywords only")
121     print (portage.output.yellow(" -m, --mask") + "      - show matches from package.mask only")
122     print (portage.output.yellow(" -u, --unmask") + "        - show matched from package.unmask only")
123     print (portage.output.yellow(" -s, --package.use") + "   - show matches from package.use only")
124     
125     print (portage.output.yellow(" -f, --fix") + "       - will remove the stabled and invalid packages without asking for confirmation")
126     print (portage.output.yellow(" -q, --confirm-fix") +"    - will remove the stabled and invalid packages asking for confirmation before doing so")
127     print (portage.output.yellow(" -h, --help") + "      - display this message")
128     print (portage.output.yellow(" -d, --debug") + "         - display more verbose output for debugging")
129     print (portage.output.yellow(" -V, --version") + "       - display version info")
130     print (portage.output.green("options") + " are ")
131     print (portage.output.green(" -c, --changes-only") + \
132         "   - show all matches that have upgrade option, use with " + \
133         "<" + portage.output.yellow(" k ") + "|" + portage.output.yellow(" u ") + \
134         "|" + portage.output.yellow(" m ") + "|" + \
135         portage.output.yellow(" a ") + ">")
136     print (portage.output.green(" -n, --no-color") + \
137         "   - suppress color output")
138     print (portage.output.green(" -r, --removable-only") + \
139         "   - show all matches that can be removed from package files, use with " + \
140         "<" + portage.output.yellow(" k ") + "|" + portage.output.yellow(" u ") + \
141         "|" + portage.output.yellow(" m ") + "|" + \
142         portage.output.yellow(" a ") + ">\n")
143
144 def get_keywords(package, var):
145     mytree = porttree
146     filtered_keywords = ""
147     try:
148         keywords = package.environment("KEYWORDS").split()
149     except KeyError as error:
150         print ("!!! Portpeek caught Exception:" + format(error))
151         print ("!!! This package/version seems to be no longer available, " + \
152         "please check and update/unmerge it") 
153         return "Not Available/Deprecated"
154     
155     #filtered_keywords = filter_keywords(keywords[0])
156     filtered_keywords = filter_keywords(keywords)
157     return filtered_keywords
158
159
160
161 # this is the main function for portpeek
162 # TODO comment this code!
163 def parse_line(line, filename):     
164     global info,debug,using_gentoo_as_overlay
165
166     using_gentoo_as_overlay = False
167     pkgs = None
168     ebuild_output = ""
169     check_pkg = ""
170     not_installed_pkgs = 0
171     pkg_length = 0
172     atom_check="<>=~"
173     original_line = line
174     has_asterick = False
175
176     # if the line has special characters, we need to make sure the original line is used for matching
177     special_line = False
178
179     pattern=r'[<>:*]'
180
181     if ( (re.search(pattern,line) != None) ):
182         special_line = True
183
184     if ( line.find("*") > 0 ):
185         has_asterick = True
186
187     print_output(debug,portage.output.blue("Analyzing line: " + line))
188
189     diffs_found = False
190     display_done = False
191
192     fields = line.replace("\t", " ").split(" ")
193
194     if len(fields) > 0:
195         #if the line does not start with an atom such as (= or >), do not validate 
196         #status as this tool is for check specific versions and not entire packages 
197         # a ~cpv should be handled like an =cpv if requested bythe parameter -t
198         check_pkg = fields[0] # this should be one of <>=~
199         overlay_index = check_pkg.find("::")
200         if ( overlay_index >= 0):
201             overlay_list = check_pkg.rsplit("::")
202             if (len(overlay_list) > 0):
203                 overlay_name = overlay_list[1]
204                 if (overlay_name == "gentoo"):
205                     using_gentoo_as_overlay = True
206             check_pkg = check_pkg[0:check_pkg.find("::")]
207
208         if check_pkg[0] not in atom_check:
209
210             # if this is package_unmask, then check the non-atom containing package to see if any version is masked
211
212             if (checking_package_unmask == True):
213                 
214                 print_output(debug,portage.output.blue("check_pkg is " + check_pkg + " found"))
215                 if (is_any_cpv_masked(check_pkg) == False):
216                     print_output(info,portage.output.red("No masked versions of " + check_pkg + " found. Tagged for removal."))
217                     unmask_list.append(str(check_pkg))
218             return
219         if (tilde == 1):
220             if check_pkg[0] in "~":
221                 check_tilde_masked_pkg(check_pkg, filename)
222                 return
223
224         # determine if the package exists
225         try:
226             package_exists = portage.portdb.xmatch("match-all", fields[0])
227         except InvalidAtom:
228             package_exists = False
229
230         if package_exists:
231             # return a Package List based on the cpv
232             query = Query(check_pkg)
233             #query = Query(fields[0])
234             pkgs = []
235
236             try:
237                 pkgs = query.smart_find(True,True,True,True,False,True)
238             except errors.GentoolkitException as err:
239                 pass
240
241             if (pkgs != None):
242                 pkg_length = len(pkgs)
243                 not_installed_pkgs = 0
244                 display_done = False
245
246                                 # go through each package version for a specific version found above
247                 for current_package in pkgs:
248                     if not current_package.is_installed():
249
250                                                 # we have found a package that is in our file, but not installed
251                         not_installed_pkgs = not_installed_pkgs + 1
252
253                         # check to see if specific version of pkg is not installed 
254                         # and display if true
255                         check_pkg = fields[0]
256                         if check_pkg[0] in atom_check:
257                             check_pkg = check_pkg[1:]
258
259                         if (check_pkg == str(current_package.cpv)):
260                             if (not checking_package_mask):
261                                                                 # package is not instaleld
262                                 print_output(info,portage.output.yellow("\n" + str(current_package.cpv) + ": ") + portage.output.red("Not Installed") , current_package, filename)
263                                 if "package.keywords" in filename:
264                                     stable_list.append(str(current_package.cpv))
265                                 if "package.accept_keywords" in filename:
266                                     stable_listNg.append(str(current_package.cpv))
267                                 unmask_list.append(str(current_package.cpv))
268                             else:
269                                                                 # package is masked, and not installed, this is normal use of package.mask
270                                 print_output(info,portage.output.green("" + str(current_package.cpv) + ": ") + portage.output.yellow("Package Masked"),current_package, filename)
271                             display_done = True
272                         continue
273
274                                         # package is installed
275                                         # retrieve the keywords for a file
276                     keywords = "%s" % (get_keywords(current_package,"KEYWORDS").split())
277                     if (keywords.find("Available/Deprecated") >= 0):
278                         continue
279
280                                         #retrieve the mask status of a specific package
281                     pkgmask = _get_mask_status(current_package, False)
282
283                     #determine if installed package is unmasked, if so, display keywords as green
284                     stable = check_for_stable_release(current_package)
285
286                     # do not display if keywords don't exist
287                     if keywords == "[]":
288                         continue
289
290                     if stable:
291                         if ( not has_asterick): # if it has an asterick, then we don't remove
292                             ebuild_output = portage.output.green("Installed: ") + \
293                                 portage.output.turquoise(str(current_package.cpv)) + \
294                                 portage.output.green("  Keywords " + keywords)
295                             if "package.unmask" in filename:
296                                 unmask_list.append(str(current_package.cpv))
297                             if "package.keywords" in filename:
298                                 stable_list.append(str(current_package.cpv))
299                             if "package.accept_keywords" in filename:
300                                 stable_listNg.append(str(current_package.cpv))
301                     else:
302                         if (not show_removable_only_flag):
303                             if (not checking_package_unmask):
304                                 ebuild_output = portage.output.green("Installed: ") + \
305                                 portage.output.turquoise(str(current_package.cpv)) + \
306                                 portage.output.yellow("  Keywords " + keywords) 
307                         else:
308                             ebuild_output = portage.output.yellow(str(current_package.cpv))
309
310                                         # check package.unmask
311                     if (checking_package_unmask):
312                         if (not is_pkg_package_masked(str(current_package.cpv))):
313
314                                                         # package is in package.unmask unnecessarily
315                             ebuild_output = ebuild_output + ": " + portage.output.yellow("Not package masked")
316                             if "package.unmask" in filename:
317                                 unmask_list.append(str(current_package.cpv))
318                                 print_output (info, "" +  ebuild_output,None, filename)
319                                 continue
320
321                                         # print once
322                     ebuild_search_key_printed = False
323                     if ( not has_asterick): # if it has an asterick, then we don't remove
324                         if stable:
325                             diffs_found = False
326                             ebuild_search_key_printed = True
327                             print_output(info,"\n" + ebuild_output,current_package, filename)
328                         elif not show_changes_only_flag and not show_removable_only_flag:
329                             diffs_found = False
330                             ebuild_search_key_printed = True
331                             print_output(info,"\n" + ebuild_output,current_package)
332
333                                         # go through all versions of a package
334                     query = Query(current_package.category + "/" + current_package.name)
335
336                     all_pkgs = []
337
338                     try:
339                         all_pkgs = query.smart_find(True,True,True,True,False,True)
340                     except errors.GentoolkitException as err:
341                         print_output(debug,portage.output.blue("Package " + current_package.category + "/" + current_package.name + " not found."))
342
343                     for a_package in all_pkgs:
344                         if not a_package.is_installed():
345                                                         # a_package is not installed
346                             pkgmask = _get_mask_status(a_package, False)
347                                                         # print status line of package we are now checking
348                             print_output(debug,portage.output.blue("Checking package: " + str(a_package.cpv) +".pkgmask is " + str(pkgmask)))
349                                                         # if package versions are different
350                             if (VersionMatch(CPV(current_package.cpv)).match(CPV(a_package.cpv))):
351                                 diffs_found = True
352                                 keylist = a_package.environment("KEYWORDS")
353                                 keywords = "%s" % (filter_keywords(keylist)).split()
354                                 #if a_package is masked
355                                 if pkgmask > 0 and not show_removable_only_flag:
356                                     if show_changes_only_flag and not ebuild_search_key_printed:
357                                         print_output (info, "\n" +  ebuild_output, current_package)
358                                         ebuild_search_key_printed = True
359                                         check_for_stable_release(current_package)
360                                     if (pkgmask >= 3):
361                                         print_output (info,portage.output.red("Available: " + str(a_package.cpv) + " [M] Keywords: " + keywords),a_package)
362                                     else:
363                                         print_output (info,portage.output.brown("Available: " + str(a_package.cpv) + " Keywords: " + keywords),a_package)
364                                 else:
365                                     if show_changes_only_flag and not ebuild_search_key_printed:
366                                         print_output (info,"\n" + ebuild_output,current_package)
367                                         ebuild_search_key_printed = True
368                                         print_output(info,portage.output.green("Available: " + str(a_package.cpv) + " Keywords: " + keywords),a_package)
369                 #else:
370                     #print (portage.output.red ("\nCannot find package: " + check_pkg))
371
372                 # if package does not exist, and current_package is None
373                 # then make package using fields[0]
374
375                 # display if pkg/cat is not installed (missing version)
376                 if not_installed_pkgs ==  pkg_length:
377                     if not display_done:
378                         if (not checking_package_mask):
379                             print_output(info,portage.output.yellow("\n" + fields[0] + ": ") + portage.output.red("Not Installed"),current_package)
380                             if "package.keywords" in filename:
381                                 if (special_line == False):
382                                     stable_list.append(str(current_package.cpv))
383                                 else:
384                                     stable_list.append(original_line)
385                             if "package.accept_keywords" in filename:
386                                 if (special_line == False):
387                                     stable_listNg.append(str(current_package.cpv))
388                                 else:
389                                     stable_listNg.append(original_line)
390                             if (special_line == False):
391                                 unmask_list.append(str(current_package.cpv))
392                             else:
393                                 unmask_list.append(original_line)
394                         else:
395                             print_output (info,portage.output.green("\n" + str(current_package.cpv) + ": ") + portage.output.yellow("Package Masked"),current_package)
396         else:
397             diffs_found = True
398             print (portage.output.red ("\nPackage: " + fields[0] + " not found. Please check " + filename + " to validate entry"))
399             if "package.keywords" in filename:
400                 stable_list.append(fields[0])
401             if "package.accept_keywords" in filename:
402                 stable_listNg.append(fields[0])
403             unmask_list.append(fields[0])
404             show_all_versions(fields[0], filename)
405     current_package = ""
406
407     return diffs_found
408
409 # adding support for etc/portage/package.keywords/<whatever>/package.keywords
410 def get_recursive_info(filename):
411
412     # determine if filename is a directory
413     if os.path.isdir(filename):
414         # get listing of directory
415         filenames = os.listdir(filename)
416         for file_name in filenames:
417             get_recursive_info(filename+os.path.sep+file_name)
418     else:   
419         get_info(filename)
420
421 def get_info(filename):
422
423     diffs_found = False
424     no_file = False
425     filedescriptor = None
426
427     try:
428         filedescriptor = open(filename)
429         for line in filedescriptor.readlines():
430             line = line.strip()
431             if len(line) <= 0:
432                 continue
433             elif line.find("#") >= 0:
434                 # found '#' remove comment
435                 if (skipFile(line,filename)):
436                     return
437                 line = line[0:line.find("#")]
438                 line = line.strip()
439                 if len(line) <= 0:
440                     continue
441             if (processing_package_use == False):
442                 diffs_found = parse_line(line, filename)
443             else:
444                 # process package.use
445                 diffs_found = parse_package_use(line,filename)
446     except IOError:
447         print (portage.output.red("Could not find file " + filename))
448         no_file = True
449
450     if not diffs_found and no_file:
451         print (portage.output.brown("No ebuild options found."))
452
453     # close file
454     if (filedescriptor != None):
455         filedescriptor.close()
456
457 # parse the package.use file and look for packages
458 # not installed
459 def parse_package_use(line, filename):
460
461     global info,debug
462     print_output(debug,portage.output.blue("parse_package_use: Line: " + line))
463     pkgs = None
464     check_pkg = ""
465     pkg_length = 0
466     atom_check="<>="
467     any_version = False
468     has_atom = True
469
470     diffs_found = False
471     package_installed = False
472     fields = line.replace("\t", " ").split(" ")
473
474     if len(fields) > 0:
475         check_pkg = fields[0] # this could be one of <>=
476         if check_pkg[0] not in atom_check:
477             has_atom = False
478         else:
479             check_pkg = check_pkg[1:]
480             if check_pkg[0] in atom_check:
481                 check_pkg = check_pkg[1:]
482
483
484         # if there is a wildcard, check to make sure at least one
485         # of the packages is installed
486         if check_pkg.find("/*") >= 0:
487             query = Query(check_pkg)
488             pkgs = []
489             try:
490                 pkgs = query.smart_find(True,True,True,True,False,True)
491             except errors.GentoolkitException as err:
492                 print_output(debug,portage.output.blue("parse_package_use: Package " + check_pkg + " not found."))
493                 return False
494
495             if (pkgs != None):
496                 pkg_length = len(pkgs)
497             for current_package in pkgs:
498                 # on wildcard scenario, return False if one package is installed
499                 if current_package.is_installed():
500                     check_useflags(current_package,line)
501                     return False
502         else:
503             # look for any version of check_pkg installed as there is 
504             # no version specified in package.use
505             package_exists = portage.portdb.xmatch("match-all", check_pkg)
506             if package_exists:
507                 # get all package versions
508                 query = Query(check_pkg)
509                 pkgs = []
510                 try:
511                     pkgs = query.smart_find(True,True,True,True,False,True)
512                 except errors.GentoolkitException as err:
513                     print_output(debug,portage.output.blue("Package " + check_pkg + " not found."))
514     
515                 if (pkgs != None):
516                     pkg_length = len(pkgs)
517     
518                     # go through each package version for a specific 
519                     # version found above
520                     # if one line check returns all ok, we don't need 
521                     #to check the rest. One slot could have different 
522                     #use flags than another
523                     if (has_atom == False):
524                         check_useflags_all_versions(pkgs, line, check_pkg)
525                         package_installed = check_for_any_installed_version(pkgs)
526                         current_package = None
527
528                         #for current_package in pkgs:
529                         #    if current_package.is_installed():
530                         #        check_useflags(current_package,line)
531                         #        package_installed = True
532                         #        if (invalid_flag_found == False):
533                         #            break;
534                     else: 
535                         # go through each package version for a specific version found above
536                         for current_package in pkgs:
537                             if (str(current_package.cpv) == check_pkg):
538                                 if not current_package.is_installed():
539                                     print_output(info,portage.output.yellow("\n" + check_pkg + ": ") + portage.output.red("Not Installed"),current_package)
540                                     if "package.keywords" in filename:
541                                         stable_list.append(check_pkg)
542                                     if "package.accept_keywords" in filename:
543                                         stable_listNg.append(check_pkg)
544                                     unmask_list.append(check_pkg)
545                                     if "package.use" in filename:
546                                         valid_flag_list = []
547                                         valid_flag_list.insert(0,current_package);
548                                         use_flag_dict[line] = valid_flag_list
549                                         check_for_change = use_flag_dict[line]
550                                     return True
551                                 else:
552                                     check_useflags(current_package,line)
553                                     return False
554             else:
555                 print (portage.output.red ("\nPackage: " + fields[0] + " not found. Please check " + filename + " to validate entry"))
556                 if "package.keywords" in filename:
557                     stable_list.append(check_pkg)
558                 if "package.accept_keywords" in filename:
559                     stable_listNg.append(check_pkg)
560                 unmask_list.append(check_pkg)
561                 if "package.use" in filename:
562                     valid_flag_list = []
563                     #valid_flag_list.insert(0,current_package);
564                     valid_flag_list.insert(0,fields[0]);
565                     use_flag_dict[line] = valid_flag_list
566                     check_for_change = use_flag_dict[line]
567                 return True
568
569     if (package_installed == False):
570         # package does not exists
571         print_output(info,portage.output.yellow("\n" + check_pkg + ": ") + portage.output.red("Not Installed"),current_package)
572         if "package.keywords" in filename:
573             stable_list.append(check_pkg)
574         if "package.accept_keywords" in filename:
575             stable_listNg.append(check_pkg)
576         if "package.use" in filename:
577             valid_flag_list = []
578             valid_flag_list.insert(0,current_package);
579             use_flag_dict[line] = valid_flag_list
580             check_for_change = use_flag_dict[line]
581
582         unmask_list.append(check_pkg)
583         return True
584
585     return False
586
587
588
589
590 # skip the file if portpeek-skip found in a comment
591 # you can put this in the middle of a file and it will
592 #skip all entrie below it, this is useful to speed things
593 #up by not checking ~kde versions, for example
594 def skipFile (line, filename):
595     if ( (line == None) or (filename == None)):
596         return False
597
598     if line.find("portpeek-skip") >= 0:
599         return True
600
601     return False
602
603 # parts blatantly stolen from equery
604 # if pure is true, then get "true" mask status that is
605 # not affected by entries in /etc/portage/package.*
606 def _get_mask_status(pkg, pure):
607     pkgmask = 0
608
609     if (pkg == None):
610         return 0
611
612     if pkg.is_masked():
613         pkgmask = pkgmask + 3
614
615     if pure:
616         try:
617             keywords = portage.portdb.aux_get(str(pkg.cpv), ["KEYWORDS"])
618             keywords = keywords[0].split()
619         except KeyError:
620             # cpv does not exist
621             return 0
622     else:
623         keywords = pkg.environment("KEYWORDS").split()
624
625     # first check for stable arch, stop there if it is found
626     if settings["ARCH"] in keywords:
627         return 0
628
629     if "~" + settings["ARCH"] in keywords:
630         pkgmask = pkgmask + 1
631     elif "-*" in keywords or "-" + settings["ARCH"] in keywords:
632         pkgmask = pkgmask + 2
633     
634     return pkgmask
635
636 def is_pkg_package_masked(cpv):
637
638     print_output(debug,portage.output.blue("is_pkg_package_masked called: " + cpv))
639     settings2 = portage.config(local_config=False)
640     portdb2 = portage.portdbapi(None, settings)
641
642     mask_reason_list = None
643     
644     try:
645         for mask_reason_list in portage.getmaskingstatus(cpv, settings2, portdb=portdb2):
646             return True
647     except:
648         return False
649
650     return False
651
652 # filter out keywords for archs other than the current one
653 def filter_keywords(keywords):
654     filtered_keywords = ""
655
656     #for key in key_list:
657     for key in keywords:
658         key = key.replace("[", '')
659         key = key.replace("]", "")
660         key = key.replace(",", "")
661         arch=settings["ARCH"]
662
663         # remove '~' from key for comparison
664         key_comparison = key.lstrip('~')
665         if key_comparison == arch:
666             if len(filtered_keywords) != 0:
667                 filtered_keywords = filtered_keywords + " "
668             filtered_keywords = filtered_keywords + key
669         elif "-*" in key:
670             if len(filtered_keywords) != 0:
671                 filtered_keywords = filtered_keywords + " "
672             filtered_keywords = filtered_keywords + key
673
674
675     return filtered_keywords
676
677
678 # this function takes in a package with no cpv
679 # and returns True if any version is masked
680 def is_any_cpv_masked(package_name):
681     print_output(debug,portage.output.blue("inside is_any_cpv_masked: " + package_name))
682
683     query = Query(package_name, True)
684
685     packages = []
686     try:
687         packages = query.smart_find(True,True,True,True,False,True)
688     except errors.GentoolkitException as err:
689         print_output(debug,portage.output.blue("Package " + package_name + " not found."))
690
691     for package in packages:
692         if is_pkg_package_masked(package.cpv):
693             print_output(debug,portage.output.blue("Package " + package.cpv + " is masked."))
694             return True
695
696     print_output(debug,portage.output.blue("Package " + package_name + ". No masked versions."))
697     return False
698
699
700 # check to see if we have a stable release
701 # in our package.* files that we can remove
702 def check_for_stable_release(pkg):
703     if not is_pkg_package_masked(str(pkg.cpv)):
704         status = _get_mask_status(pkg, True)
705         if status == 0:
706             return True
707     return False
708
709 #print version info
710 def print_version():
711     # Print the version of this tool to the console.
712     print (__productname__ + "(" + __version__ + ") - " + \
713         __description__)
714     print ("Author(s): " + __author__)
715
716 # function to go through a ~cp without a version
717 # and set for removal from file if no masked package version exists
718 def check_tilde_masked_pkg(package_name, filename):
719     ebuild_output=""
720     variable_version = ""
721
722     orig_package_name = package_name
723     package_name = package_name.replace('~','')
724
725     print_output(debug,portage.output.blue("check_tilde_maskd_pkg: orig_package-name is " + orig_package_name))
726     print_output(debug,portage.output.blue("check_tilde_maskd_pkg: package_name is " + package_name))
727
728     query = Query(package_name, True)
729
730     packages = []
731     try:
732         packages = query.smart_find(True,True,True,True,False,True)
733     except errors.GentoolkitException as err:
734         print_output(debug,portage.output.blue("Package " + package_name + " not found."))
735
736     no_versions_installed = True
737     for package in packages:
738         if package.is_installed():
739             no_versions_installed = False
740
741     if (no_versions_installed == True):
742         ebuild_output = portage.output.yellow("\n" + package_name + ": ") + portage.output.red("Not Installed")
743         if "package.unmask" in filename:
744             unmask_list.append(orig_package_name)
745         if "package.keywords" in filename:
746             stable_list.append(orig_package_name)
747         if "package.accept_keywords" in filename:
748             stable_listNg.append(orig_package_name)
749         print (ebuild_output + portage.output.brown(" : " + filename))
750
751         return
752
753     # get all packages matching cat/package
754     if (packages != None):
755         for current_package in packages:
756             print_output(debug,portage.output.blue("check_tilde_maskd_pkg: current_package is " + str(current_package.cpv)))
757             print_output(debug,portage.output.blue("comparing " + package_name + " to " + str(current_package.cpv)))
758             if (pkgcmp(pkgsplit(package_name),pkgsplit(str(current_package.cpv))) <=0 ):
759             #if (pkgcmp(package_name, str(current_package.cpv)) <= 0):
760                 packageObj = gentoolkit.package.Package(str(current_package.cpv))
761                 if (packageObj == None):
762                     # we could not create a package object
763                     return
764
765                 if "package.unmask" in filename:
766                     if (is_pkg_package_masked(str(current_package.cpv))):
767                         # package was found as masked
768                         return
769                     else:
770                         # package is not masked
771                         unmask_list.append(str(current_package.cpv))
772                         ebuild_output = portage.output.yellow(str(current_package.cpv)) + ": " + portage.output.yellow("Not package masked")
773                         print_output(info,ebuild_output, package, filename)
774                         return
775                 else:
776                     if (is_pkg_package_masked(str(current_package.cpv))):
777                         # package was found as masked
778                         return 
779         else:
780             # at this point we have no packages >= ~cpv that are masked, present for removal
781             # package does not have any masked versions
782             ebuild_output = portage.output.green(package_name + " has no masked versions")
783             
784             if "package.unmask" in filename:
785                 unmask_list.append(orig_package_name)
786             if "package.keywords" in filename:
787                 stable_list.append(orig_package_name)
788             if "package.accept_keywords" in filename:
789                 stable_listNg.append(orig_package_name)
790             print_output(info,ebuild_output, package, filename)
791
792 #helper function to print avail pks when version does not exist
793 def show_all_versions(pkg, filename):
794
795     # is package masked
796     is_package_masked = False
797     pkgArr = portage.pkgsplit(pkg)
798
799     if pkgArr is None or len(pkgArr) == 0:
800         return
801
802     # determine if category/package is masked 
803     package = pkgArr[0]
804
805     operator = portage.dep.Atom(pkg).operator
806     if operator is not None:
807         package = package[len(operator):]
808
809     # package is category/package and pkg is category/package-version
810     # is category/package-version we are checking package masked?
811     #if portage.settings.pmaskdict.has_key(package):
812     pmaskdict = settings._mask_manager._pmaskdict
813     if package in pmaskdict:
814         pkg_list = pmaskdict.get(package)
815         # iterate through list array looking for pkg
816         for pkg_check in pkg_list:
817             operator = portage.get_operator(pkg_check)
818             if operator is None:
819                 if pkg_check == package:
820                     is_package_masked = True
821
822     query = Query(package)
823
824     all_pkgs = []
825
826     try:
827         all_pkgs = query.smart_find(True,True,True,True,False,True)
828     except errors.GentoolkitException as err:
829         print_output(debug,portage.output.blue("Package " + package + " not found."))
830
831     for current_package in all_pkgs:
832         keywords = "%s" % (current_package.environment("KEYWORDS").split())
833         keywords = filter_keywords(keywords)
834         keywords = "[%s]" % (keywords)
835         ebuild = current_package.ebuild_path()
836         if ebuild:
837             pkgmask = _get_mask_status(current_package, True)
838             if is_package_masked:
839                 print (portage.output.red("Available: " + str(current_package.cpv) + " [M] Keywords: " + keywords))
840             elif pkgmask > 4:
841                 print (portage.output.red("Available: " + str(current_package.cpv) + " [M] Keywords: " + keywords))
842             elif pkgmask == 4 or pkgmask == 1:
843                 print (portage.output.brown("Available: " + str(current_package.cpv) + " Keywords: " + keywords))
844             else:
845                 print (portage.output.green("Available: " + str(current_package.cpv) + " Keywords: " + keywords))
846                 if "package.keywords" in filename:
847                     stable_list.append(str(current_package.cpv))
848                 if "package.accept_keywords" in filename:
849                     stable_listNg.append(str(current_package.cpv))
850
851
852 def get_useflags(package):
853     iuse = get_iuse(package.cpv)
854     return iuse
855
856 def check_useflags_all_versions(pkgs, line, check_pkgs):
857
858     global useremove_display, invalid_flag_found 
859     invalid_flag_found = False
860    
861     print_output(debug,portage.output.blue("ENTERED check_useflags_all_versions: " + check_pkgs))
862
863     potential_invalid_flag = []
864     valid_flag_list = []
865     for package in pkgs:
866
867         # if package not installed, move on
868         if (not package.is_installed()):
869             continue;
870
871         print_output(debug,portage.output.blue("check_useflags_all_versions: package: " + package.cpv))
872         if ((package is None) or (package == "")):
873             return
874
875         useflag_removal_display=""
876
877         if (len(line) <= 0):
878             return
879
880         list2 = get_useflags(package)
881
882         for uf in list2:
883             print_output(debug,portage.output.blue(("use found " + uf)))
884  
885         iuse_string = package.use()
886         iuse = iuse_string.split(" ")
887
888         for uflag in list2:
889             iuse.append(uflag)
890
891         for iuse_item in iuse:
892             print_output(debug,portage.output.blue(("iuse_item is " + iuse_item)))
893
894         useflags_fromfile = line.replace("\t", " ").split(" ")
895
896         #for useflags_fromfile_item in useflags_fromfile:
897         #    print_output(debug,portage.output.blue(("useflags_fromfile_item is " + useflags_fromfile_item)))
898
899         package_string = useflags_fromfile.pop(0)
900         print_output(debug,portage.output.blue(("package_string is " + package_string)))
901     
902         clean_useflags_list = []
903         # remove + or -
904         atom = "-+"
905     
906         #clean list from portage of + or -
907         clean_iuse = []
908         for item in iuse:
909             if item[0] in atom:
910                 clean_iuse.append(item[1:])
911             else:
912                 clean_iuse.append(item)
913     
914         for original_flag in useflags_fromfile:
915             if (original_flag is None or original_flag == ""):
916                 continue
917             flag = original_flag
918             if original_flag[0] in atom:
919                 flag = original_flag[1:]
920             if flag not in clean_iuse:
921                 print_output(debug,portage.output.blue(("found invalid flag: " + flag)))
922
923                 # only add to invalid list if it's not in valid list
924                 try:
925                     index = valid_flag_list.index(original_flag)
926                 except ValueError as error:
927
928                     try:
929                        index = potential_invalid_flag.index(original_flag)
930                     except ValueError:
931                        print_output(debug,portage.output.blue(original_flag + " not found for " + package.cpv))
932                        potential_invalid_flag.append(original_flag)
933
934             else:
935                 print_output(debug,portage.output.blue(("found valid flag: " + flag)))
936                 try:
937                     index = valid_flag_list.index(original_flag)
938                 except ValueError as error:
939                     valid_flag_list.append(original_flag)
940
941                 try:
942                     index = potential_invalid_flag.index(original_flag)
943                     potential_invalid_flag.remove(original_flag)
944                 except ValueError as error:
945                     continue
946
947
948     # if potential_invalid_flag list is empty, we are done
949     if (len(potential_invalid_flag) <= 0):
950         return
951
952     invalid_flag_found = True
953
954     # build sentence
955     invalid_flags = ""
956     verb = "is"
957     for inv_flag in potential_invalid_flag:
958         if (len(invalid_flags) > 0):
959             invalid_flags += ","
960             verb = "are"
961         invalid_flags += inv_flag
962
963     # if there are no valid flags at all, we remove the line
964     if ( len(valid_flag_list) == 0):
965         print_output (info,portage.output.red("No valid use flags found for package: " + str(package.category) + "/" + str(package.name) + ". Invalid flag(s) found: " + invalid_flags +  "\n"))
966         useremove_display += "Removing line: " + line + "\n"
967         use_flag_dict[line] = ""
968         return
969
970     # if there are values in potential_invalid_flag, we need to remove them
971
972     if (len(potential_invalid_flag) > 0):
973         removal_text = "use flags: "
974     else:
975         removal_text = "use flag: "
976
977     if ( (len(valid_flag_list) > 0)):
978         useremove_display += "Removing " + removal_text + invalid_flags + " for package " + check_pkgs + "\n"
979         print (portage.output.yellow(removal_text) +  portage.output.red(invalid_flags) + portage.output.yellow(" " + verb + " invalid for " + str(package.cpv)))
980
981     valid_flag_list.insert(0,package_string);
982
983     if (len(potential_invalid_flag) > 0):
984         use_flag_dict[line] = valid_flag_list
985         
986     return valid_flag_list
987
988 def check_useflags(package,line):
989
990     global useremove_display, invalid_flag_found 
991     invalid_flag_found = False
992
993     print_output(debug,portage.output.blue("check_useflags: package: " + package.cpv))
994     if ((package is None) or (package == "")):
995         return
996
997     useflag_removal_display=""
998
999     if (len(line) <= 0):
1000         return
1001
1002     iuse = get_useflags(package)
1003
1004     #for iuse_item in iuse:
1005     #    print_output(debug,portage.output.blue(("iuse_item is " + iuse_item)))
1006
1007     useflags_fromfile = line.replace("\t", " ").split(" ")
1008     #for useflags_fromfile_item in useflags_fromfile:
1009     #    print_output(debug,portage.output.blue(("useflags_fromfile_item is " + useflags_fromfile_item)))
1010
1011     package_string = useflags_fromfile.pop(0)
1012     print_output(debug,portage.output.blue(("package_string is " + package_string)))
1013
1014     clean_useflags_list = []
1015     # remove + or -
1016     atom = "-+"
1017
1018     #clean list from portage of + or -
1019     clean_iuse = []
1020     for item in iuse:
1021         if item[0] in atom:
1022             clean_iuse.append(item[1:])
1023         else:
1024             clean_iuse.append(item)
1025
1026     valid_flag_list = []
1027     for original_flag in useflags_fromfile:
1028         if (original_flag is None or original_flag == ""):
1029             continue
1030         flag = original_flag
1031         if original_flag[0] in atom:
1032             flag = original_flag[1:]
1033         if flag not in clean_iuse:
1034             print_output (info,portage.output.red("use flag: " + flag + " is invalid for : " + str(package.cpv)))
1035             useflag_removal_display += "Removing use flag: " + flag + " for package " + str(package.cpv)
1036             invalid_flag_found = True
1037         else:
1038             valid_flag_list.append(original_flag)
1039
1040     # if valid_flag_list is empty, there are no valid flags
1041     if ( (len(valid_flag_list) > 0) and (len(useflag_removal_display) >0)):
1042         useremove_display += useflag_removal_display + "\n"
1043     elif ( len(valid_flag_list) == 0):
1044         useremove_display += "No valid use flags found for package " + str(package.cpv) + ". Removing line: " + line + "\n"
1045         if ( invalid_flag_found != True):
1046             print_output (info,portage.output.red("No valid use flags found for package " + str(package.cpv)))
1047         invalid_flag_found = True
1048
1049     valid_flag_list.insert(0,package_string);
1050     if (invalid_flag_found == True):
1051         use_flag_dict[line] = valid_flag_list
1052
1053     return valid_flag_list
1054
1055
1056 def clean_useflagsFile(filename):
1057
1058     if "--fix-confirm" in cmdline:
1059         if (confirmFix() == False):
1060             return
1061     
1062     display_line = ""
1063     removed_list = []
1064
1065     try:
1066         # determine if filename is a directory
1067         if os.path.isdir(filename):
1068             # get listing of directory
1069             filenames = os.listdir(filename)
1070             for file_name in filenames:
1071                 clean_useflagsFile(filename+os.path.sep+file_name)
1072             return
1073         else:
1074             #go through stable array and remove line if found
1075             for line in fileinput.input(filename,inplace =1):
1076                 itemFound = False
1077                 line = line.strip()
1078
1079                 # make sure line is not empty and do not remove commented out lines
1080                 if len(line) <= 0:
1081                     continue
1082                 elif line.find("#") == 0:
1083                     print (line)
1084                     continue
1085
1086                 check_for_change = ""
1087                 use_flag_dict.get(line,"")
1088                 try:
1089                     check_for_change = use_flag_dict[line]
1090                     removed_list.append(line)
1091                     if ( len(check_for_change) > 1):
1092                         print (" ".join(check_for_change))
1093                 except KeyError as error:
1094                     print (line)
1095
1096             fileinput.close()
1097     except OSError as error:
1098         print (portage.output.red("Modify/Read access to file: " + filename + " failed: " + format(error)))
1099
1100     if (len(removed_list) > 0):
1101         print ("\n")
1102         for package in removed_list:
1103             print (portage.output.red("Removing from: ") + portage.output.yellow(filename + ": Invalid use flag(s) from ")  + portage.output.green(package) + "\n")
1104
1105     return
1106
1107 def handle_if_overlay(package):
1108     overlay_text = ""
1109     global print_overlay_flag,using_gentoo_as_overlay
1110
1111     if (using_gentoo_as_overlay):
1112         return overlay_text
1113
1114     print_overlay_flag = True
1115
1116     ebuild_path,overlay_path = porttree.dbapi.findname2(str(package.cpv))
1117     index = -1
1118     try:
1119         index = overlay_list.index(overlay_path)
1120     except ValueError as error:
1121         overlay_list.append(overlay_path)
1122         index = overlay_list.index(overlay_path)
1123
1124     overlay_text = " [%s]" % (str(index+1))
1125
1126     return overlay_text
1127
1128 # if the overlay_text was displayed to the user
1129 # we need to display the string at the end 
1130 # this array will store the overlays to be displayed
1131 def print_overlay_text():
1132    
1133     global print_overlay_flag
1134     
1135     if (not print_overlay_flag):
1136         return
1137     
1138     if (len(overlay_list) <= 0):
1139         return
1140
1141     index = 1
1142     for x in overlay_list:
1143         print (portage.output.turquoise("[" + str(index) + "] ") + x)
1144         index = index + 1
1145     
1146     print ("\n")
1147
1148 #helper function to print output
1149 def print_output(log_level,output_string, package=None, filename=None):
1150     
1151     global logLevel
1152
1153     if package != None:
1154         if (package.is_overlay()):
1155             output_string = "%s%s" % (output_string,portage.output.turquoise(handle_if_overlay(package)))
1156             #output_string = output_string + portage.output.turquoise(handle_if_overlay(package))
1157         else:
1158             if filename != None:
1159                 output_string = "%s%s" % (output_string,portage.output.brown(" : " + filename))
1160                 #output_string = output_string + portage.output.brown(" : " + filename)
1161
1162     if (log_level <= logLevel):
1163         print (output_string)
1164
1165 # remove stabled files that are no longer needed from package.keywords
1166 # or package.mask
1167 # includes support for etc/portage/package.keywords/<whatever>/package.keywords
1168 def cleanFile (filename):
1169
1170     removeDups = []
1171     removed_list = []
1172
1173     if "--fix-confirm" in cmdline:
1174         if (confirmFix() == False):
1175             return
1176
1177     # if the file or directory does not exist
1178     # exit out
1179     if (os.path.exists(filename) == False):
1180         return
1181     
1182     if "package.keywords" in filename:
1183         if ( len(stable_list) == 0):
1184             return
1185         removeDups = stable_list
1186     elif "package.accept_keywords" in filename:
1187         if ( len(stable_listNg) == 0):
1188             return
1189         removeDups = stable_listNg
1190     else:
1191         if ( len(unmask_list) == 0):
1192             return
1193         removeDups = unmask_list
1194
1195     removedDict = {}
1196
1197     try:
1198         # determine if filename is a directory
1199         if os.path.isdir(filename):
1200             # get listing of directory
1201             filenames = os.listdir(filename)
1202             for file_name in filenames:
1203                 cleanFile(filename+os.path.sep+file_name)
1204             return
1205         else:   
1206             #go through stable array and remove line if found
1207             for line in fileinput.input(filename,inplace =1):
1208                 itemFound = False
1209                 line = line.strip()
1210
1211                 # make sure line is not empty and do not remove commented out lines
1212                 if len(line) <= 0:
1213                     continue
1214                 elif line.find("#") == 0:
1215                     print (line)
1216                     continue
1217
1218                 for item in removeDups:
1219                     if item in line:
1220                         removed_list.append(item)
1221                         removedDict[filename] = item
1222                         itemFound = True
1223                         removeDups.pop(removeDups.index(item))
1224                         break
1225                 if (itemFound == False):
1226                     print (line)
1227             fileinput.close()
1228     except OSError as error:
1229         print (portage.output.red("Modify/Read access to file: " + filename + " failed: " + format(error)))
1230     
1231     if (len(removed_list) > 0):
1232         print ("\n")
1233         for package in removed_list:
1234             print (portage.output.red("Removing from: ") + portage.output.yellow(filename) + ": " + portage.output.green(package) + "\n")
1235
1236 # ask the user if they want to fix their files
1237 # and remove unneeded entries
1238 # Return true if they say yes and False if they say no
1239 def confirmFix():
1240     
1241     global fix_asked,fix_confirm
1242
1243     if (fix_asked == True):
1244         return fix_confirm
1245
1246     # only ask if we actually have anything to check
1247     if ( (len(stable_list) == 0) and 
1248           (len(stable_listNg) == 0) and
1249           (len(unmask_list) == 0) and
1250           (invalid_flag_found == False) and 
1251           (len(use_flag_dict) == 0)):
1252         fix_confirm = True
1253         return fix_confirm
1254
1255     fix_asked = True 
1256
1257     valid = {"yes":"yes",   "y":"yes", 
1258              "no":"no",     "n":"no"}
1259    
1260     prompt = portage.output.bold("Remove entries from files [") + portage.output.green("y") + "/" + portage.output.red("n") + portage.output.bold("]") + " "
1261
1262     while 1:
1263         sys.stdout.write('\n' + prompt)
1264         choice = input().lower()
1265         if choice == '':
1266             fix_confirm = False
1267             break
1268         elif choice in valid.keys():
1269             if (choice == 'y' or choice == 'yes'):
1270                 fix_confirm = True
1271                 break
1272             else:
1273                 fix_confirm = False
1274                 break 
1275         else:
1276             sys.stdout.write("Please respond with 'yes' or 'no' "\
1277                              "(or 'y' or 'n').\n")
1278
1279     return fix_confirm
1280
1281
1282 def check_for_any_installed_version(pkgs):
1283     
1284     for package in pkgs:
1285         if (package.is_installed()):
1286             return True
1287
1288     return False
1289
1290 # main
1291 if __name__ == "__main__":
1292
1293     if len(sys.argv) == 1:
1294         print_usage()
1295         sys.exit(1)
1296
1297     # soooooo stolen from emerge
1298     tmpcmdline = sys.argv[1:]
1299
1300     for cmd in tmpcmdline:
1301         if cmd[0:1] == "-" and cmd[1:2] != "-":
1302             for cmd_item in cmd[1:]:
1303                 if cmd_item in mappings:
1304                     if mappings[cmd_item] in cmdline:
1305                         print ()
1306                         print ("*** Warning: Redundant use of ", mappings[cmd_item])
1307                     else:
1308                         cmdline.append(mappings[cmd_item])
1309                 else:
1310                     print ("!!! Error: -"+cmd_item+" is an invalid option.")
1311                     sys.exit(-1)
1312         else:
1313             cmdline.append(cmd)
1314
1315     #parse long options
1316     for cmd in cmdline:
1317         if len(cmd)>=2 and cmd[0:2]=="--":
1318             try:
1319                 i = options.index(cmd)
1320                 continue
1321             except ValueError:
1322                 print ("!!! Error: -"+cmd+" is an invalid option.")
1323                 sys.exit(-1)
1324
1325     if "--changes-only" in cmdline:
1326         cmdline.remove("--changes-only")
1327         show_changes_only_flag = True
1328
1329     if "--removable-only" in cmdline:
1330         cmdline.remove("--removable-only")
1331         show_removable_only_flag = True
1332
1333     if "--debug" in cmdline:
1334         logLevel = debug
1335
1336     if "--no-color" in cmdline:
1337         portage.output.nocolor()
1338
1339     if "--tilde-check" in cmdline:
1340         tilde=1
1341
1342     if "--version" in cmdline:
1343         print_version()
1344         sys.exit(0)
1345
1346     if "--fix-confirm" in cmdline:
1347         if '--fix' not in cmdline:
1348             cmdline.append("--fix")
1349     
1350     if "--all" in cmdline:
1351         tmpcmdline = ["--all"]
1352         if "--fix" in cmdline:
1353             tmpcmdline.append("--fix")
1354             if "--fix-confirm" in cmdline:
1355                 tmpcmdline.append("--fix-confirm")
1356                 fix_confirm = False
1357         cmdline=tmpcmdline      
1358
1359     if "--help" in cmdline:
1360         print_usage()
1361         sys.exit(0)
1362     
1363     if (show_changes_only_flag and show_removable_only_flag):
1364         print ("Please select only one of --show-removable (-r) or --changes-only")
1365         print ("Use --help for more info.")
1366         sys.exit(0)
1367         
1368     for cmd in cmdline:
1369         if cmd == "--keyword":
1370             print (portage.output.bold("\npackage.keywords:"))
1371             get_recursive_info(USER_CONFIG_PATH + "/package.keywords")
1372             if "--fix" in cmdline:
1373                 cleanFile(USER_CONFIG_PATH + "/package.keywords")
1374             print (portage.output.bold("Done\n"))
1375             print (portage.output.bold("\npackage.accept_keywords:"))
1376             get_recursive_info(USER_CONFIG_PATH + "/package.accept_keywords")
1377             if "--fix" in cmdline:
1378                 cleanFile(USER_CONFIG_PATH + "/package.accept_keywords")
1379             print (portage.output.bold("Done\n"))
1380         elif cmd == "--unmask": 
1381             print (portage.output.bold("\npackage.unmask:"))
1382             checking_package_unmask = True
1383             get_recursive_info(USER_CONFIG_PATH + "/package.unmask")
1384             checking_package_unmask = False
1385             if "--fix" in cmdline:
1386                 cleanFile(USER_CONFIG_PATH + "/package.unmask")
1387         elif cmd == "--mask":
1388             checking_package_mask = True
1389             print (portage.output.bold("\npackage.mask:"))
1390             get_recursive_info(USER_CONFIG_PATH + "/package.mask")
1391             print (portage.output.bold("Done\n"))
1392             checking_package_mask = False
1393             if "--fix" in cmdline:
1394                 cleanFile(USER_CONFIG_PATH + "/package.mask")
1395         elif cmd == "--package-use":
1396             print (portage.output.bold("\npackage.use:"))
1397             processing_package_use = True
1398             get_recursive_info(USER_CONFIG_PATH + "/package.use")
1399             if "--fix" in cmdline:
1400                 cleanFile(USER_CONFIG_PATH + "/package.use")
1401                 clean_useflagsFile(USER_CONFIG_PATH + "/package.use")
1402             print (portage.output.bold("Done\n"))
1403         elif cmd == "--all":
1404             print (portage.output.bold("\npackage.keywords:"))
1405             get_recursive_info(USER_CONFIG_PATH + "/package.keywords")
1406             print (portage.output.bold("\npackage.accept_keywords:"))
1407             get_recursive_info(USER_CONFIG_PATH + "/package.accept_keywords")
1408             print (portage.output.bold("\npackage.unmask:"))
1409             checking_package_unmask = True
1410             get_recursive_info(USER_CONFIG_PATH + "/package.unmask")
1411             checking_package_unmask = False
1412             checking_package_mask = True
1413             print (portage.output.bold("\npackage.mask:"))
1414             get_recursive_info(USER_CONFIG_PATH + "/package.mask")
1415             print (portage.output.bold("\npackage.use:"))
1416             processing_package_use = True
1417             get_recursive_info(USER_CONFIG_PATH + "/package.use")
1418             if "--fix" in cmdline:
1419                 cleanFile(USER_CONFIG_PATH + "/package.keywords")
1420                 cleanFile(USER_CONFIG_PATH + "/package.accept_keywords")
1421                 cleanFile(USER_CONFIG_PATH + "/package.unmask")
1422                 cleanFile(USER_CONFIG_PATH + "/package.use")
1423                 cleanFile(USER_CONFIG_PATH + "/package.mask")
1424                 clean_useflagsFile(USER_CONFIG_PATH + "/package.use")
1425             print (portage.output.bold("\nDone\n"))
1426
1427     print_overlay_text()
1428
1429     if len(cmdline) == 0:
1430         if show_changes_only_flag or show_removable_only_flag:
1431             if (show_changes_only_flag):
1432                 print (portage.output.green("-c") + " or " + portage.output.green("--changes-only") + " must be accompanied by one of the following:")
1433             else:
1434                 print (portage.output.green("-r") + " or " + portage.output.green("--removable-only") + " must be accompanied by one of the following:")
1435
1436             print ("     " + portage.output.yellow("-k") + " or " + portage.output.yellow("--keyword"))
1437             print ("     " + portage.output.yellow("-u") + " or " + portage.output.yellow("--unmask"))
1438             print ("     " + portage.output.yellow("-m") + " or " + portage.output.yellow("--mask"))
1439             print ("     " + portage.output.yellow("-a") + " or " + portage.output.yellow("--all"))
1440
1441             print_usage()
1442