#!/usr/bin/env python3 import argparse import sys import os from subprocess import call import contextlib if __name__ != '__main__': raise Exception("must be used as a main module with a parameter as the input file") parser = argparse.ArgumentParser(description="cleanup /etc/portage/package.* files") parser.add_argument("infile", help="an input file to clean") parser.add_argument("--out", dest="outfile", help="the output is written to this file. if not specified, the output is written to stdout.") parser.add_argument("--inplace", action='store_true', help="overwrite the in file. if specified, --out is ignored.") args = parser.parse_args() def checkInstalled(package): with open(os.devnull, 'w') as devnull: status = call('qlist -IC "' + str(package.split()[0].strip()) + '"', shell=True, stdout=devnull) return status == 0 @contextlib.contextmanager def getOutFile(args): if args.inplace: fh = open(args.infile, 'w') elif args.outfile != None: fh = open(args.outfile, 'w') else: fh = sys.stdout try: yield fh finally: if fh is not sys.stdout: fh.close() commentBuffer = [] lines = [] with open(args.infile, 'r') as f: lines = f.readlines() with getOutFile(args) as out: for line in lines: if line.lstrip().startswith("#"): commentBuffer.append(line) else: if line.strip() == "" or checkInstalled(line): if commentBuffer: out.write("".join(commentBuffer)) out.write(line) commentBuffer = []