#!/usr/bin/python import sys # Command line argument handling import getopt # Parsing of command line options from lxml import etree def main(): # Command line arguments parsing opt_verbose = 0 try: opts, filename = getopt.getopt(sys.argv[1:], "hv") except getopt.GetoptError, err: print(str(err)) usage() sys.exit(2) for o, a in opts: if o in ("-h"): usage() sys.exit() elif o in ("-v"): opt_verbose = 1 else: print("Unknown option \"%s\"" %o) usage() sys.exit() if len(filename) != 1: print("ERROR: The function requires exactly one filename as argument") usage() # Initialise etree filename = filename[0] print('Renumbering file: ', filename) f = file(filename) tree = (etree.parse(f)) root = tree.getroot() current_effect_order = [] new_effects_order = dict() # Loop through the XML tree to find all Jessyink element order numbers for element in root.iter(tag=etree.Element): # Find the jessyink elements effect = element.get('{https://launchpad.net/jessyink}element') # Get the effect type if effect is not None: for subelement in element.iter(tag=etree.Element): # Look for the jessyink effect specification among the children x = subelement.get('{https://launchpad.net/jessyink}' + effect) if x is not None: if x == 'order': # Found the order attribute, store it current_effect_order.append(subelement.text) # Store all effects order # Set up a dictionary mapping from old numbering to new numbering current_effect_order = sorted(set(current_effect_order),key=int) # Sort the list numerically ascending z = 10 for item in current_effect_order: # Create a dictionary that maps each existing effect order to a new order number new_effects_order[str(item)] = str(z) z += 10 # Loop through the XML tree again to renumber based on the dictionary mapping for element in root.iter(tag=etree.Element): # Find jessyink elements (contains the effect and some textboxes) effect = element.get('{https://launchpad.net/jessyink}element') # Get the effect type if effect is not None: if opt_verbose: print(element.get('id')); print(effect) for subelement in element.iter(tag=etree.Element): # Look for the jessyink effect among the children x = subelement.get('{https://launchpad.net/jessyink}' + effect) if x is not None: if x == 'order': # Set new value of node if opt_verbose: print('OLD %s: %s' % (x, subelement.text)) subelement.text = new_effects_order[subelement.text] if opt_verbose: print('NEW %s: %s' % (x, subelement.text)) # Write the svg file print('Writing ', filename) tree.write(filename) def usage(): usage = """ WARNING: This is proof of concept code. It will overwrite files supplied and may break anything! NAME jessy_renumber - Renumber jessyink effects order SYNOPSIS: jessy_renumber FILENAME DESCRIPTION: Renumber jessyink effects order. FILENAME is the path to the svg file containing jessyink effects. -h Help (print this message) -v Verbose """ print(usage) if __name__ == '__main__': # This is the main entry point to the code main()