Created
January 8, 2013 09:19
-
-
Save ssato/4482416 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# | |
# List package groups and packages in comps XML. | |
# | |
# Copyright (C) 2013 Satoru SATOH <ssato at redhat.com> | |
# License: MIT | |
# | |
from logging import DEBUG, INFO | |
import xml.etree.cElementTree as ET | |
import gzip | |
import logging | |
import optparse | |
import sys | |
PTYPE_MANDATORY = "mandatory" | |
PTYPE_DEFAULT = "default" | |
PTYPE_OPTIONAL = "optional" | |
PTYPE_CONDITIONAL = "conditional" | |
PTYPES = [ | |
PTYPE_MANDATORY, | |
PTYPE_DEFAULT, | |
PTYPE_OPTIONAL, | |
PTYPE_CONDITIONAL, | |
] | |
def _tree_from_xml(xmlfile): | |
return ET.parse( | |
gzip.open(xmlfile) if xmlfile.endswith(".gz") else open(xmlfile) | |
) | |
def get_package_groups(xmlfile, byid=False, ptype=PTYPE_DEFAULT): | |
""" | |
Parse given comps file (`xmlfile`) and return a list of package group and | |
packages pairs. | |
:param xmlfile: comps xml file path | |
:param byid: Identify package groups by ID or name | |
:return: [(group_id_or_name, [package_names])] | |
""" | |
gk = "./group" | |
kk = "./id" if byid else "./name" | |
pk = "./packagelist/packagereq/[@type='%s']" % ptype | |
gps = ( | |
(g.find(kk).text, [p.text for p in g.findall(pk)]) for g in | |
_tree_from_xml(xmlfile).findall(gk) | |
) | |
# filter out groups having no packages as such group is useless: | |
return [(g, ps) for g, ps in gps if ps] | |
def option_parser(): | |
defaults = dict(byid=False, ptype="default", verbose=False) | |
p = optparse.OptionParser("%prog COMPS_XML_PATH") | |
p.set_defaults(**defaults) | |
p.add_option('', "--byid", action="store_true", | |
help="List package groups by ID instead of NAME", ) | |
p.add_option('', "--ptype", choices=PTYPES, | |
help="Type of packages ['%default']. " + | |
"Choices=%s" % ", ".join(PTYPES)) | |
p.add_option("-v", "--verbose", action="store_true", help="Verbose mode") | |
return p | |
def main(): | |
p = option_parser() | |
(options, args) = p.parse_args() | |
logging.getLogger().setLevel(DEBUG if options.verbose else INFO) | |
if not args: | |
p.print_usage() | |
sys.exit(1) | |
compsxml = args[0] | |
logging.info("Comps XML: " + compsxml) | |
gpss = get_package_groups(compsxml, byid=options.byid, ptype=options.ptype) | |
for g, ps in gpss: | |
logging.debug("group=%s, packages=%s" % (g, str(ps))) | |
print "%s: %s" % (g, ", ".join(ps)) | |
if __name__ == "__main__": | |
main() | |
# vim:sw=4:ts=4:et: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment