bgneal@607: """
bgneal@607: Application to read the ISO-3166 country data and output a JSON datastructure
bgneal@607: for use in the SG101 code. We also print a report of any missing country
bgneal@607: icons. If we don't have an icon for a country, we don't include it in our JSON
bgneal@607: data.
bgneal@607: 
bgneal@607: """
bgneal@607: import argparse
bgneal@607: import json
bgneal@607: import os.path
bgneal@609: import sys
bgneal@607: from xml.etree.ElementTree import ElementTree
bgneal@607: 
bgneal@607: 
bgneal@607: def main():
bgneal@607:     parser = argparse.ArgumentParser(description=("Transform Debian's ISO-3166 "
bgneal@607:         "data into JSON for use on SG101"))
bgneal@607:     parser.add_argument('--xml', '-x', required=True, help='path to XML file')
bgneal@607:     parser.add_argument('--icon-dir', '-i', required=True,
bgneal@607:             help='path to icon directory')
bgneal@607: 
bgneal@607:     args = parser.parse_args()
bgneal@607: 
bgneal@607:     xml_file = os.path.expanduser(args.xml)
bgneal@607:     icon_dir = os.path.expanduser(args.icon_dir)
bgneal@607: 
bgneal@607:     with open(xml_file, 'r') as fp:
bgneal@607:         et = ElementTree(file=fp)
bgneal@607: 
bgneal@607:     country_data = {}
bgneal@607:     for node in et.iterfind('iso_3166_entry'):
bgneal@607:         code = node.get('alpha_2_code').lower()
bgneal@607:         name = node.get('common_name', node.get('name'))
bgneal@607: 
bgneal@607:         # see if we have an icon for this country
bgneal@607: 
bgneal@607:         if not os.path.exists(os.path.join(icon_dir, '%s.png' % code)):
bgneal@609:             sys.stderr.write("Could not find icon for %s (%s)\n" % (name, code))
bgneal@607:         else:
bgneal@607:             country_data[code] = name
bgneal@607: 
bgneal@607:     s = json.dumps(country_data, indent=4, sort_keys=True, ensure_ascii=False)
bgneal@607:     print s.encode('utf-8')
bgneal@607: 
bgneal@607: 
bgneal@607: if __name__ == '__main__':
bgneal@607:     main()