#!/usr/bin/env python"""Copyright (c) 2008 SystemInPlace (parser)Copyright (c) 2012, 2013 TortoiseLabs LLCPermission to use, copy, modify, and/or distribute this software for anypurpose with or without fee is hereby granted, provided that the abovecopyright notice and this permission notice appear in all copies.This software is provided 'as is' and without any warranty, express orimplied. In no event shall the authors be liable for any damages arisingfrom the use of this software."""fromappliancekit.compilerimportcompile_ir_stringimportxml.parsers.expatimporturllibimportjsondefget_appliancexml_from_xml_file(filepath):"""Parse an XML file into an appliance config."""currentTag=[]xmlConfig={}defstartTag(name,attrs):currentTag.append({'name':name,'attrs':attrs})defendTag(name):currentTag.pop()defgetTagPath():st=""fortagincurrentTag:ifst!="":st+=".%s"%tag['name']else:st=tag['name']returnstdefcharacterData(data):ifgetTagPath()=="appliance.packagelist":passelifgetTagPath()=="appliance.packagelist.package":try:xmlConfig["appliance.packagelist"].append(data)except:xmlConfig["appliance.packagelist"]=[data]elifgetTagPath()=="appliance.scriptlet.preinstall":try:xmlConfig["appliance.scriptlet.preinstall"].append(data)except:xmlConfig["appliance.scriptlet.preinstall"]=[data]elifgetTagPath()=="appliance.scriptlet.postinstall":try:xmlConfig["appliance.scriptlet.postinstall"].append(data)except:xmlConfig["appliance.scriptlet.postinstall"]=[data]else:xmlConfig[getTagPath()]=dataf=urllib.URLopener().open(filepath)data=f.read()f.close()p=xml.parsers.expat.ParserCreate()p.StartElementHandler=startTagp.EndElementHandler=endTagp.CharacterDataHandler=characterDatap.Parse(data)returnxmlConfigdefget_appliance_config_from_xml_file(filepath):xmlConfig=get_appliancexml_from_xml_file(filepath)config={}try:config['packageList']=xmlConfig['appliance.packagelist']except:config['packageList']=[]try:config['scriptlet.preinstall']=xmlConfig['appliance.scriptlet.preinstall']except:config['scriptlet.preinstall']=[]try:config['scriptlet.postinstall']=xmlConfig['appliance.scriptlet.postinstall']except:config['scriptlet.postinstall']=[]config['distribution']=xmlConfig['appliance.distribution']returnconfigdeftranslate_axml_file(filepath):axmlconfig=get_appliance_config_from_xml_file(filepath)distMap={'lenny':'debian-5','squeeze':'debian-6','wheezy':'debian-7','sid':'debian-base','lucid':'ubuntu-10.04',}defget_distname(name):ifdistMap.has_key(name):returndistMap[name]returnnametrans='{% extends "'+get_distname(axmlconfig['distribution'])+'.spec" %}\r\n'ifaxmlconfig.has_key('packageList')andlen(axmlconfig['packageList'])>0:trans+="{% "+"set packages={}".format(json.dumps(axmlconfig['packageList']))+" %}\r\n"returntransdefcompile_axml_file(filepath,**kwargs):trans_ir=translate_axml_file(filepath)weaved_ir=compile_ir_string(trans_ir,**kwargs)returnjson.loads(weaved_ir)