From a5af39e2e0c3f00226be6a3ca4bacabf6ea39118 Mon Sep 17 00:00:00 2001 From: Patrice Clement Date: Tue, 8 Aug 2017 01:32:12 +0200 Subject: autopep8 format --- src/py/build-xml-rewrite | 28 ++- src/py/buildparser | 23 +- src/py/class-version-verify.py | 52 +++- src/py/eclipse-build.py | 88 +++++-- src/py/findclass | 13 +- src/py/jarjarclean | 3 +- src/py/maven-helper.py | 90 +++++-- src/py/xml-rewrite-2.py | 542 ++++++++++++++++++++++++----------------- src/py/xml-rewrite-3.py | 273 ++++++++++++++++----- src/py/xml-rewrite.py | 59 +++-- 10 files changed, 785 insertions(+), 386 deletions(-) diff --git a/src/py/build-xml-rewrite b/src/py/build-xml-rewrite index 229de89..5a67145 100755 --- a/src/py/build-xml-rewrite +++ b/src/py/build-xml-rewrite @@ -4,17 +4,28 @@ import sys import xml.etree.cElementTree as et from optparse import OptionParser + def main(): parser = OptionParser() - parser.add_option('-c', '--changeattributes', dest='change', action="append", nargs=3) - parser.add_option('-g', '--gentooclasspath', dest="gcp", action="store_true", default=False) + parser.add_option( + '-c', + '--changeattributes', + dest='change', + action="append", + nargs=3) + parser.add_option( + '-g', + '--gentooclasspath', + dest="gcp", + action="store_true", + default=False) parser.add_option('-e', '--encoding', dest="encoding") (options, args) = parser.parse_args() changes = [] if options.change: for c in options.change: - changes.append((c[0].split(),c[1], c[2])) + changes.append((c[0].split(), c[1], c[2])) gcp = options.gcp gcp_str = '${gentoo.classpath}' @@ -26,8 +37,8 @@ def main(): for javac in tree.getiterator('javac'): if gcp: javac.attrib['classpath'] = gcp_str - if options.encoding: - javac.attrib['encoding'] = options.encoding + if options.encoding: + javac.attrib['encoding'] = options.encoding for javadoc in tree.getiterator('javadoc'): if gcp: javadoc.attrib['classpath'] = gcp_str @@ -35,9 +46,9 @@ def main(): javadoc.attrib['encoding'] = options.encoding for c in changes: elems, attr, value = c - for elem in elems: - for e in tree.getiterator(elem): - e.attrib[attr] = value + for elem in elems: + for e in tree.getiterator(elem): + e.attrib[attr] = value for junit in tree.getiterator('junit'): if gcp: junit.append(gcp_sub) @@ -46,5 +57,6 @@ def main(): with open(file, 'w') as f: tree.write(f) + if __name__ == '__main__': main() diff --git a/src/py/buildparser b/src/py/buildparser index 7af980d..3007d9b 100755 --- a/src/py/buildparser +++ b/src/py/buildparser @@ -16,7 +16,8 @@ from javatoolkit.parser.buildproperties import BuildPropertiesParser from javatoolkit.parser.manifest import ManifestParser from javatoolkit.parser.tree import Node, ParseError -__author__ = ["James Le Cuirot ", "Karl Trygve Kalleberg "] +__author__ = ["James Le Cuirot ", + "Karl Trygve Kalleberg "] __version__ = "0.3.0" __productname__ = "buildparser" __description__ = "A parser for build.properties and JAR manifest files." @@ -34,14 +35,14 @@ def parse_args(): parser = OptionParser(usage, version=about) parser.add_option('-t', '--type', action='store', type='choice', - dest='type', choices=['manifest', 'buildprops'], - help='Type of file to parse: manifest or buildprops') + dest='type', choices=['manifest', 'buildprops'], + help='Type of file to parse: manifest or buildprops') parser.add_option('-i', '--in-place', action='store_true', dest='in_place', - help='Edit file in place when replacing') + help='Edit file in place when replacing') parser.add_option('-w', '--wrap', action='store_true', dest='wrap', - help='Wrap when returning singular values') + help='Wrap when returning singular values') opt, args = parser.parse_args() @@ -56,6 +57,7 @@ def parse_args(): return opt, args + def main(): opt, args = parse_args() @@ -78,7 +80,9 @@ def main(): p = BuildPropertiesParser() else: - sys.exit(__productname__ + ": error: Unknown file type. Specify using the -t option.") + sys.exit( + __productname__ + + ": error: Unknown file type. Specify using the -t option.") t = p.parse(f) f.close() @@ -89,7 +93,7 @@ def main(): if len(args) > 2: n = t.find_node(args[0]) - if n != None: + if n is not None: n.value = args[1] else: t.add_kid(Node(args[0], args[1])) @@ -105,7 +109,7 @@ def main(): elif len(args) > 1: n = t.find_node(args[0]) - if n != None: + if n is not None: if opt.wrap: print(p.wrapped_value(n)) else: @@ -115,10 +119,11 @@ def main(): for x in t.node_names(): print(x) + if __name__ == '__main__': try: main() except KeyboardInterrupt: print("Interrupted by user, aborting.") -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap +# set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap diff --git a/src/py/class-version-verify.py b/src/py/class-version-verify.py index fb62ad5..b46d99c 100755 --- a/src/py/class-version-verify.py +++ b/src/py/class-version-verify.py @@ -7,20 +7,53 @@ # # $Id$ -import os,sys +import os +import sys from optparse import OptionParser, make_option from javatoolkit.cvv import * + def main(): options_list = [ - make_option ("-r", "--recurse", action="store_true", dest="deep", default=False, help="go into dirs"), - make_option ("-t", "--target", type="string", dest="version", help="target version that is valid"), - make_option ("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print version of every calss"), - make_option ("-s", "--silent", action="store_true", dest="silent", default=False, help="No output"), - make_option ("-f", "--file-only", action="store_true", dest="file_only", default=False, help="Only output the files"), + make_option( + "-r", + "--recurse", + action="store_true", + dest="deep", + default=False, + help="go into dirs"), + make_option( + "-t", + "--target", + type="string", + dest="version", + help="target version that is valid"), + make_option( + "-v", + "--verbose", + action="store_true", + dest="verbose", + default=False, + help="Print version of every calss"), + make_option( + "-s", + "--silent", + action="store_true", + dest="silent", + default=False, + help="No output"), + make_option( + "-f", + "--file-only", + action="store_true", + dest="file_only", + default=False, + help="Only output the files"), ] - parser = OptionParser("%prog -t version [-r] [-v] [-s] ", options_list) + parser = OptionParser( + "%prog -t version [-r] [-v] [-s] ", + options_list) (options, args) = parser.parse_args() if not options.version: @@ -53,12 +86,15 @@ def main(): for set in cvv.bad: print("Bad: %s %s %s" % set) - print("CVV: %s\nChecked: %i Good: %i Bad: %i" % (options.version, len(cvv.good)+len(cvv.bad) , len(cvv.good), len(cvv.bad))) + print("CVV: %s\nChecked: %i Good: %i Bad: %i" % + (options.version, len(cvv.good) + + len(cvv.bad), len(cvv.good), len(cvv.bad))) if len(cvv.bad) > 0: sys.exit(1) else: sys.exit(0) + if __name__ == '__main__': main() diff --git a/src/py/eclipse-build.py b/src/py/eclipse-build.py index ab65307..3baa23f 100755 --- a/src/py/eclipse-build.py +++ b/src/py/eclipse-build.py @@ -23,32 +23,57 @@ if __name__ == '__main__': usage += "\nJust wait till I finish this." option_list = [ - make_option ( '-p', '--project', action='store', dest='project', help='Project Name' ), - make_option ( '-i', '--include', action='append', dest='includes', help='Files to include in jar' ), - make_option ( '-s', '--src', action='append', dest='source', help='Directories containing src to build' ), - make_option ( '-m', '--manifest', action='store', dest='manifest', help='Manifest File' ), - make_option ( '-f', '--file', action='store', dest='file', help='Eclipse build.properties file to parse.' ), - make_option ( '-o', '--output', action='store', dest='output', help='Output build.xml to this file' ) + make_option( + '-p', + '--project', + action='store', + dest='project', + help='Project Name'), + make_option( + '-i', + '--include', + action='append', + dest='includes', + help='Files to include in jar'), + make_option('-s', '--src', action='append', dest='source', + help='Directories containing src to build'), + make_option( + '-m', + '--manifest', + action='store', + dest='manifest', + help='Manifest File'), + make_option('-f', '--file', action='store', dest='file', + help='Eclipse build.properties file to parse.'), + make_option( + '-o', + '--output', + action='store', + dest='output', + help='Output build.xml to this file') ] - parser = OptionParser( usage, option_list ) + parser = OptionParser(usage, option_list) (options, args) = parser.parse_args() - #check parser options here. + # check parser options here. if options.file: - properties = PropertiesParser( options.file ) + properties = PropertiesParser(options.file) #dom = parse( options.file ) #classpathentries = dom.getElementsByTagName('classpathentry') - #for entry in classpathentries: + # for entry in classpathentries: # if entry.attributes['kind'] and entry.attributes['kind'].nodeValue == 'src': # print entry.attributes['path'].nodeValue # if entry.attributes['path']: # src_dirs.append( entry.attributes['path'].nodeValue ) - with open( options.output, 'w' ) as output: + with open(options.output, 'w') as output: output.write('\n') - output.write('\n') + output.write( + '\n') output.write('\n') output.write('\n') output.write('\n\n') @@ -58,46 +83,55 @@ if __name__ == '__main__': try: if properties.config['source..']: for dir in properties.config['source..']: - output.write('\n') + output.write( + '\n') if properties.config['bin.includes']: for item in properties.config['bin.includes']: if item != '.': if item.endswith('/'): item = item.rstrip('/') - output.write('\n') + output.write( + '\n') else: - output.write('\n') + output.write( + '\n') finally: output.write('\n') if options.includes: for file in options.includes: - output.write('') + output.write('') output.write('\n') - output.write('\n\n\t\n\n\n') + output.write( + '\n\n\t\n\n\n') output.write('\n') - output.write('\n') + output.write( + '\n') try: if properties.config['source..']: for dir in properties.config['source..']: - output.write('\t\n') + output.write('\t\n') finally: output.write('\n') output.write('\n\n') output.write('\n') output.write('\n') + output.write('\nmanifest="' + parser.manifest + '">\n') else: output.write('>\n') output.write('\n') output.write('\n') output.write('\n') - #output.write('') - #output.write('') - #output.write('') - #output.write('') - #output.write('') - #output.write('') - #output.write('') + # output.write('') + # output.write('') + # output.write('') + # output.write('') + # output.write('') + # output.write('') + # output.write('') # vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap : diff --git a/src/py/findclass b/src/py/findclass index 0581acc..98575e6 100755 --- a/src/py/findclass +++ b/src/py/findclass @@ -47,17 +47,20 @@ def main(): jarcmd = find_exec('jar') - javapaths = [ f.replace('.', '/') for f in files ] - matchers = [ re.compile(p) for p in javapaths ] + javapaths = [f.replace('.', '/') for f in files] + matchers = [re.compile(p) for p in javapaths] for pkg in get_all_packages(): - if opt.verbose: print("Searching package %s" % pkg) + if opt.verbose: + print("Searching package %s" % pkg) for jar in collect_packages(pkg).split(':'): - if opt.verbose: print("Searching jar %s" % jar) + if opt.verbose: + print("Searching jar %s" % jar) status, out = getstatusoutput("%s tvf %s" % (jarcmd, jar)) for m in matchers: if m.search(out): - if opt.verbose: print("Found in %s" % pkg, end=' ') + if opt.verbose: + print("Found in %s" % pkg, end=' ') print(jar) diff --git a/src/py/jarjarclean b/src/py/jarjarclean index 3effaec..2b95969 100755 --- a/src/py/jarjarclean +++ b/src/py/jarjarclean @@ -23,7 +23,8 @@ def main(): for elem in tree.getiterator(): for child in list(elem): - if child.tag == 'taskdef' and child.get('classname') == 'com.tonicsystems.jarjar.JarJarTask': + if child.tag == 'taskdef' and child.get( + 'classname') == 'com.tonicsystems.jarjar.JarJarTask': tags.append(child.get('name')) elem.remove(child) diff --git a/src/py/maven-helper.py b/src/py/maven-helper.py index 9aa41cc..cf924f6 100755 --- a/src/py/maven-helper.py +++ b/src/py/maven-helper.py @@ -40,13 +40,11 @@ def main(): usage += "write to stdin and stdout respectively. The use of quotes on\n" usage += "parameters will break the script.\n" - def error(message): print("ERROR: " + message) sys.exit(1) - - def doAction(stream,options): + def doAction(stream, options): pom = MavenPom(options) if options.p_rewrite: pom.parse(stream, pom.rewrite) @@ -54,7 +52,6 @@ def main(): pom.parse(stream, pom.getDescription) return pom - def run(): if options.files: import os @@ -62,16 +59,16 @@ def main(): # First parse the file into memory cwd = os.getcwd() dirname = os.path.dirname(file) - if dirname != '': # for file comes out as '' + if dirname != '': # for file comes out as '' os.chdir(os.path.dirname(file)) - f = open(os.path.basename(file),"r") + f = open(os.path.basename(file), "r") fs = f.read() f.close() # parse file and return approtiate pom object - pom = doAction(fs,options) + pom = doAction(fs, options) if options.p_rewrite: - f = open(os.path.basename(file),"w") + f = open(os.path.basename(file), "w") f.write(pom.read()) f.close() else: @@ -79,22 +76,72 @@ def main(): os.chdir(cwd) else: # process stdin - pom = doAction(sys.stdin.read(),options) + pom = doAction(sys.stdin.read(), options) print(pom.read()) ############### MAIN ############### options_list = [ - make_option ("-a", "--artifact", action="store_true", dest="p_artifact", help="get artifact name."), - make_option ("-c", "--classpath", action="append", dest="classpath", help="set classpath to use with maven."), - make_option ("-s", "--source", action="append", dest="p_source", help="Java source version."), - make_option ("-t", "--target", action="append", dest="p_target", help="Java target version."), - make_option ("-d", "--depependencies" , action="store_true", dest="p_dep", help="get dependencies infos"), - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"), - make_option ("-g", "--group" , action="store_true", dest="p_group", help="get artifact group."), - make_option ("-r", "--rewrite", action="store_true", dest="p_rewrite", help="rewrite poms to use our classpath"), - make_option ("-p", "--ischild", action="store_true", dest="p_ischild", help="return true if this is a child pom"), - make_option ("-v", "--version" , action="store_true", dest="p_version", help="get artifact version."), + make_option( + "-a", + "--artifact", + action="store_true", + dest="p_artifact", + help="get artifact name."), + make_option( + "-c", + "--classpath", + action="append", + dest="classpath", + help="set classpath to use with maven."), + make_option( + "-s", + "--source", + action="append", + dest="p_source", + help="Java source version."), + make_option( + "-t", + "--target", + action="append", + dest="p_target", + help="Java target version."), + make_option( + "-d", + "--depependencies", + action="store_true", + dest="p_dep", + help="get dependencies infos"), + make_option( + "-f", + "--file", + action="append", + dest="files", + help="Transform files instead of operating on stdout and stdin"), + make_option( + "-g", + "--group", + action="store_true", + dest="p_group", + help="get artifact group."), + make_option( + "-r", + "--rewrite", + action="store_true", + dest="p_rewrite", + help="rewrite poms to use our classpath"), + make_option( + "-p", + "--ischild", + action="store_true", + dest="p_ischild", + help="return true if this is a child pom"), + make_option( + "-v", + "--version", + action="store_true", + dest="p_version", + help="get artifact version."), ] parser = OptionParser(usage, options_list) @@ -111,7 +158,7 @@ def main(): error("Please specify only one pom at a time.") if options.p_rewrite: - valid_sources = ["1.4","1.5"] + valid_sources = ["1.4", "1.5"] for source in valid_sources: if options.p_source: if len(options.p_source) != 1: @@ -127,7 +174,7 @@ def main(): # join any classpathes if any if options.classpath: if len(options.classpath) > 1: - start =[] + start = [] start.append(options.classpath[0]) for item in options.classpath[1:]: start[0] += ":%s" % (item) @@ -137,5 +184,6 @@ def main(): # main loop run() + if __name__ == '__main__': main() diff --git a/src/py/xml-rewrite-2.py b/src/py/xml-rewrite-2.py index 5c8aa6b..46b4bfd 100755 --- a/src/py/xml-rewrite-2.py +++ b/src/py/xml-rewrite-2.py @@ -22,181 +22,189 @@ import sys import io -from xml.sax.saxutils import quoteattr,escape +from xml.sax.saxutils import quoteattr, escape from optparse import OptionParser, make_option def add_gentoo_classpath(document): - matches = document.getElementsByTagName("classpath") - gcp = document.createElement("location") - gcp.setAttribute("path","${gentoo.classpath}") - - handled_refs = set() - for match in matches: - if match.hasAttribute("refid"): - refid = match.getAttribute("refid") - for ref in document.getElementsByTagName("path"): - id = ref.getAttribute("id") - if id not in handled_refs and id == refid: - gcp = document.createElement("pathelement") - gcp.setAttribute("path","${gentoo.classpath}") - ref.appendChild(gcp) - handled_refs.add(id) - else: - match.appendChild(gcp) + matches = document.getElementsByTagName("classpath") + gcp = document.createElement("location") + gcp.setAttribute("path", "${gentoo.classpath}") + + handled_refs = set() + for match in matches: + if match.hasAttribute("refid"): + refid = match.getAttribute("refid") + for ref in document.getElementsByTagName("path"): + id = ref.getAttribute("id") + if id not in handled_refs and id == refid: + gcp = document.createElement("pathelement") + gcp.setAttribute("path", "${gentoo.classpath}") + ref.appendChild(gcp) + handled_refs.add(id) + else: + match.appendChild(gcp) + class DomRewriter: - """ - The old DOM rewriter is still around for index based stuff. It can - be used for all the complex stuff but portage needed features should - be in StreamRewriterBase subclasses as they are much faster. - """ - from xml.dom import NotFoundErr - - def __init__(self, modifyElems, attributes, values=None, index=None): - self.modify = modifyElems - self.attributes = attributes - self.values = values - self.index = index - - def change_elem(self, elem): - for i,attr in enumerate(self.attributes): - if self.values: - elem.setAttribute(attr, self.values[i]) - else: - try: - elem.removeAttribute(attr) - except DomRewriter.NotFoundErr: - continue - - def process(self,in_stream,callback=None): - from xml.dom.minidom import parse - - self.document = parse(in_stream); - - if callback: - callback(self.document) - - if not self.modify: - return - - for tag in self.modify: - matches = self.document.getElementsByTagName(tag) - if matches: - if self.index == None: - for match in matches: - self.change_elem(match) - else: - self.change_elem(matches[self.index]) - - def write(self,stream): - stream.write(self.document.toxml()) + """ + The old DOM rewriter is still around for index based stuff. It can + be used for all the complex stuff but portage needed features should + be in StreamRewriterBase subclasses as they are much faster. + """ + from xml.dom import NotFoundErr + + def __init__(self, modifyElems, attributes, values=None, index=None): + self.modify = modifyElems + self.attributes = attributes + self.values = values + self.index = index + + def change_elem(self, elem): + for i, attr in enumerate(self.attributes): + if self.values: + elem.setAttribute(attr, self.values[i]) + else: + try: + elem.removeAttribute(attr) + except DomRewriter.NotFoundErr: + continue + + def process(self, in_stream, callback=None): + from xml.dom.minidom import parse + + self.document = parse(in_stream) + + if callback: + callback(self.document) + + if not self.modify: + return + + for tag in self.modify: + matches = self.document.getElementsByTagName(tag) + if matches: + if self.index is None: + for match in matches: + self.change_elem(match) + else: + self.change_elem(matches[self.index]) + + def write(self, stream): + stream.write(self.document.toxml()) + class StreamRewriterBase: - def __init__(self, elems, attributes, values, index, - sourceElems = [], sourceAttributes = [], sourceValues = [], - targetElems = [], targetAttributes = [], targetValues = [] ): - self.buffer = io.StringIO() - self.__write = self.buffer.write - self.elems = elems or [] - self.attributes = attributes or [] - self.values = values or [] - self.sourceElems = sourceElems or [] - self.sourceAttributes = sourceAttributes or [] - self.sourceValues = sourceValues or [] - self.targetElems = targetElems or [] - self.targetAttributes = targetAttributes or [] - self.targetValues = targetValues or [] - - def p(self,str): - self.__write(str.encode('utf8')) - - def write(self, out_stream): - value = self.buffer.getvalue() - out_stream.write(value) - self.buffer.truncate(0) - - def write_attr(self,a,v): - self.p('%s=%s ' % (a,quoteattr(v, {'©':'©'}))) - - def start_element(self, name, attrs): - self.p('<%s ' % name) - - match = ( name in self.elems ) - matchSource = ( name in self.sourceElems ) - matchTarget = ( name in self.targetElems ) - - for a,v in attrs: - if not ( - (match and a in self.attributes) - or (matchSource and a in self.sourceAttributes) - or (matchTarget and a in self.targetAttributes) - ): - self.write_attr(a,v) - - if matchSource: - for i, attr in enumerate(self.sourceAttributes): - self.write_attr(attr, self.sourceValues[i]) - - if matchTarget: - for i, attr in enumerate(self.targetAttributes): - self.write_attr(attr, self.targetValues[i]) - - if match: - for i, attr in enumerate(self.attributes): - self.write_attr(attr, self.values[i]) - - self.p('>') + def __init__(self, elems, attributes, values, index, + sourceElems=[], sourceAttributes=[], sourceValues=[], + targetElems=[], targetAttributes=[], targetValues=[]): + self.buffer = io.StringIO() + self.__write = self.buffer.write + self.elems = elems or [] + self.attributes = attributes or [] + self.values = values or [] + self.sourceElems = sourceElems or [] + self.sourceAttributes = sourceAttributes or [] + self.sourceValues = sourceValues or [] + self.targetElems = targetElems or [] + self.targetAttributes = targetAttributes or [] + self.targetValues = targetValues or [] + + def p(self, str): + self.__write(str.encode('utf8')) + + def write(self, out_stream): + value = self.buffer.getvalue() + out_stream.write(value) + self.buffer.truncate(0) + + def write_attr(self, a, v): + self.p('%s=%s ' % (a, quoteattr(v, {'©': '©'}))) + + def start_element(self, name, attrs): + self.p('<%s ' % name) + + match = (name in self.elems) + matchSource = (name in self.sourceElems) + matchTarget = (name in self.targetElems) + + for a, v in attrs: + if not ( + (match and a in self.attributes) + or (matchSource and a in self.sourceAttributes) + or (matchTarget and a in self.targetAttributes) + ): + self.write_attr(a, v) + + if matchSource: + for i, attr in enumerate(self.sourceAttributes): + self.write_attr(attr, self.sourceValues[i]) + + if matchTarget: + for i, attr in enumerate(self.targetAttributes): + self.write_attr(attr, self.targetValues[i]) + + if match: + for i, attr in enumerate(self.attributes): + self.write_attr(attr, self.values[i]) + + self.p('>') + class ExpatRewriter(StreamRewriterBase): - """ - The only problem with this Expat based implementation is that it does not - handle entities doctypes etc properly so for example dev-java/skinlf fails. - """ - def process(self, in_stream): - from xml.parsers.expat import ParserCreate - parser = ParserCreate() + """ + The only problem with this Expat based implementation is that it does not + handle entities doctypes etc properly so for example dev-java/skinlf fails. + """ - parser.StartElementHandler = self.start_element - parser.EndElementHandler = self.end_element - parser.CharacterDataHandler = self.char_data - parser.ParseFile(in_stream) - self.p('\n') + def process(self, in_stream): + from xml.parsers.expat import ParserCreate + parser = ParserCreate() - def start_element(self, name, attrs): - StreamRewriterBase(self, name, iter(attrs.items())) + parser.StartElementHandler = self.start_element + parser.EndElementHandler = self.end_element + parser.CharacterDataHandler = self.char_data + parser.ParseFile(in_stream) + self.p('\n') - def end_element(self,name): - self.p('' % name) + def start_element(self, name, attrs): + StreamRewriterBase(self, name, iter(attrs.items())) + + def end_element(self, name): + self.p('' % name) + + def char_data(self, data): + self.p(escape(data)) - def char_data(self,data): - self.p(escape(data)) from xml.sax.saxutils import XMLGenerator + + class SaxRewriter(XMLGenerator, StreamRewriterBase): - """ - Using Sax gives us the support for writing back doctypes and all easily - and is only marginally slower than expat as it is just a tight layer over it - """ - def __init__(self, elems, attributes, values, index, - sourceElems = [], sourceAttributes = [], sourceValues = [], - targetElems = [], targetAttributes = [], targetValues = []): - StreamRewriterBase.__init__(self, elems, attributes, values, index, - sourceElems, sourceAttributes, sourceValues, - targetElems, targetAttributes, targetValues) - XMLGenerator.__init__(self, self.buffer, 'UTF-8') - - def process(self, in_stream): - from xml.sax import parse - parse(in_stream, self) - self.p('\n') - - def startElement(self, name, attrs): - self.start_element(name, list(attrs.items())) + """ + Using Sax gives us the support for writing back doctypes and all easily + and is only marginally slower than expat as it is just a tight layer over it + """ + + def __init__(self, elems, attributes, values, index, + sourceElems=[], sourceAttributes=[], sourceValues=[], + targetElems=[], targetAttributes=[], targetValues=[]): + StreamRewriterBase.__init__(self, elems, attributes, values, index, + sourceElems, sourceAttributes, sourceValues, + targetElems, targetAttributes, targetValues) + XMLGenerator.__init__(self, self.buffer, 'UTF-8') + + def process(self, in_stream): + from xml.sax import parse + parse(in_stream, self) + self.p('\n') + + def startElement(self, name, attrs): + self.start_element(name, list(attrs.items())) + def main(): - usage = "XML Rewrite Python Module Version " + __version__ + "\n" - usage += "Copyright 2004,2006,2007 Gentoo Foundation\n" + usage = "Copyright 2004,2006,2007 Gentoo Foundation\n" usage += "Distributed under the terms of the GNU General Public Lincense v2\n" usage += "Please contact the Gentoo Java Team with problems.\n" usage += "\n" @@ -213,95 +221,177 @@ def main(): usage += "parameters will break the script.\n" def error(message): - print("ERROR: " + message) - sys.exit(1) + print("ERROR: " + message) + sys.exit(1) # if len(sys.argv) == 1: # usage(True) options_list = [ - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"), - make_option ("-g", "--gentoo-classpath", action="store_true", dest="gentoo_classpath", help="Rewrite build.xml to use gentoo.classpath where applicable."), - make_option ("-c", "--change", action="store_true", dest="doAdd", default=False, help="Change the value of an attribute. If it does not exist, it will be created."), - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."), - make_option ("-e", "--element", action="append", dest="elements", help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), - make_option ("-a", "--attribute", action="append", dest="attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"), - make_option ("-v", "--value", action="append", dest="values", help="Value to set the attribute to."), - make_option ("-r", "--source-element", action="append", dest="source_elements", help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."), - make_option ("-t","--source-attribute", action="append", dest="source_attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"), - make_option ("-y", "--source-value", action="append", dest="source_values", help="Value to set the attribute to. (sourceonly)"), - make_option ("-j", "--target-element", action="append", dest="target_elements", help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."), - make_option ("-k", "--target-attribute", action="append", dest="target_attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"), - make_option ("-l", "--target-value", action="append", dest="target_values", help="Value to set the attribute to (targeronly)."), - make_option ("-i", "--index", type="int", dest="index", help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero.") + make_option( + "-f", + "--file", + action="append", + dest="files", + help="Transform files instead of operating on stdout and stdin"), + make_option( + "-g", + "--gentoo-classpath", + action="store_true", + dest="gentoo_classpath", + help="Rewrite build.xml to use gentoo.classpath where applicable."), + make_option( + "-c", + "--change", + action="store_true", + dest="doAdd", + default=False, + help="Change the value of an attribute. If it does not exist, it will be created."), + make_option( + "-d", + "--delete", + action="store_true", + dest="doDelete", + default=False, + help="Delete an attribute from matching elements."), + make_option( + "-e", + "--element", + action="append", + dest="elements", + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), + make_option( + "-a", + "--attribute", + action="append", + dest="attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"), + make_option( + "-v", + "--value", + action="append", + dest="values", + help="Value to set the attribute to."), + make_option( + "-r", + "--source-element", + action="append", + dest="source_elements", + help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."), + make_option( + "-t", + "--source-attribute", + action="append", + dest="source_attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"), + make_option( + "-y", + "--source-value", + action="append", + dest="source_values", + help="Value to set the attribute to. (sourceonly)"), + make_option( + "-j", + "--target-element", + action="append", + dest="target_elements", + help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."), + make_option( + "-k", + "--target-attribute", + action="append", + dest="target_attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"), + make_option( + "-l", + "--target-value", + action="append", + dest="target_values", + help="Value to set the attribute to (targeronly)."), + make_option( + "-i", + "--index", + type="int", + dest="index", + help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero.") ] parser = OptionParser(usage, options_list) (options, args) = parser.parse_args() - # Invalid Arguments Must be smited! + # Invalid Arguments Must be smited! if not options.doAdd and not options.doDelete and not options.gentoo_classpath: - print(usage) - print() - error("No action was specified.") + print(usage) + print() + error("No action was specified.") if not options.gentoo_classpath: - if options.doAdd and options.doDelete: - error("Unable to perform multiple actions simultaneously.") - if not options.elements and not options.target_elements and not options.source_elements: - error("At least one element (global, source only or target only) and attribute must be specified.") - for elem in ( options.source_attributes or [] ): - if elem in ( options.attributes or [] ): - error("You can't set an attribute in global and source scope at the same time") - for elem in ( options.target_attributes or [] ): - if elem in ( options.attributes or [] ): - error("You can't set an attribute in global and target scope at the same time") - if options.doAdd and (len(options.values or []) != len(options.attributes or []) - or len(options.source_values or [] ) != len(options.source_attributes or []) - or len(options.target_values or [] ) != len(options.target_attributes or [])): - error("You must give attribute(s)/value(s) for every element you are changing.") - - # End Invalid Arguments Check + if options.doAdd and options.doDelete: + error("Unable to perform multiple actions simultaneously.") + if not options.elements and not options.target_elements and not options.source_elements: + error( + "At least one element (global, source only or target only) and attribute must be specified.") + for elem in (options.source_attributes or []): + if elem in (options.attributes or []): + error( + "You can't set an attribute in global and source scope at the same time") + for elem in (options.target_attributes or []): + if elem in (options.attributes or []): + error( + "You can't set an attribute in global and target scope at the same time") + if options.doAdd and (len(options.values or []) != len(options.attributes or []) + or len(options.source_values or []) != len(options.source_attributes or []) + or len(options.target_values or []) != len(options.target_attributes or [])): + error( + "You must give attribute(s)/value(s) for every element you are changing.") + + # End Invalid Arguments Check def get_rewriter(options): - if options.index or options.doDelete or options.gentoo_classpath: - # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter - # and let the DomRewriter do these. Also keeps the index option compatible for sure. - rewriter = DomRewriter(options.elements, options.attributes, options.values, options.index) - else: - rewriter = SaxRewriter(options.elements, options.attributes, options.values, options.index, - options.source_elements, options.source_attributes, options.source_values, - options.target_elements, options.target_attributes, options.target_values) - return rewriter + if options.index or options.doDelete or options.gentoo_classpath: + # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter + # and let the DomRewriter do these. Also keeps the index option + # compatible for sure. + rewriter = DomRewriter( + options.elements, + options.attributes, + options.values, + options.index) + else: + rewriter = SaxRewriter(options.elements, options.attributes, options.values, options.index, + options.source_elements, options.source_attributes, options.source_values, + options.target_elements, options.target_attributes, options.target_values) + return rewriter rewriter = get_rewriter(options) if options.files: - import os - for file in options.files: - print("Rewriting %s" % file) - # First parse the file into memory - # Tricks with cwd are needed for relative includes of other xml files to build.xml files - cwd = os.getcwd() - dirname = os.path.dirname(file) - if dirname != '': # for file = build.xml comes out as '' - os.chdir(os.path.dirname(file)) - f = open(os.path.basename(file),"r") - if options.gentoo_classpath: - rewriter.process(f,add_gentoo_classpath) - else: - rewriter.process(f) - os.chdir(cwd) - f.close() - # Then write it back to the file - f = open(file, "w") - rewriter.write(f) - f.close() + import os + for file in options.files: + print("Rewriting %s" % file) + # First parse the file into memory + # Tricks with cwd are needed for relative includes of other xml + # files to build.xml files + cwd = os.getcwd() + dirname = os.path.dirname(file) + if dirname != '': # for file = build.xml comes out as '' + os.chdir(os.path.dirname(file)) + f = open(os.path.basename(file), "r") + if options.gentoo_classpath: + rewriter.process(f, add_gentoo_classpath) + else: + rewriter.process(f) + os.chdir(cwd) + f.close() + # Then write it back to the file + f = open(file, "w") + rewriter.write(f) + f.close() else: - if options.gentoo_classpath: - rewriter.process(sys.stdin,add_gentoo_classpath) - else: - rewriter.process(sys.stdin) - rewriter.write(sys.stdout) + if options.gentoo_classpath: + rewriter.process(sys.stdin, add_gentoo_classpath) + else: + rewriter.process(sys.stdin) + rewriter.write(sys.stdout) if __name__ == '__main__': diff --git a/src/py/xml-rewrite-3.py b/src/py/xml-rewrite-3.py index 549443b..82255c9 100755 --- a/src/py/xml-rewrite-3.py +++ b/src/py/xml-rewrite-3.py @@ -39,12 +39,15 @@ def main(): usage += "Please contact the Gentoo Java Team with problems.\n" usage += "\n" usage += "Usage:\n" - usage += " " + sys.argv[0] + " [-f file] --delete [-g] -n tag [-n tag] -m attribute [-m attribute] [-i index]\n" - usage += " " + sys.argv[0] + " [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value] \\\n" + usage += " " + \ + sys.argv[0] + " [-f file] --delete [-g] -n tag [-n tag] -m attribute [-m attribute] [-i index]\n" + usage += " " + \ + sys.argv[0] + " [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value] \\\n" usage += " [--source-element tag] [--source-attribute attribute --source-value value] \\\n" usage += " [--target-element tag] [--target-attribute attribute --target-value value] [-i index]\n" usage += "Or:\n" - usage += " " + sys.argv[0] + " [-f file] --javadoc --source-directory dir [--source-directory dir2] --output-directory dir3 \n" + usage += " " + \ + sys.argv[0] + " [-f file] --javadoc --source-directory dir [--source-directory dir2] --output-directory dir3 \n" usage += "Or:\n" usage += " " + sys.argv[0] + " [-f file] -g\n" usage += "\n" @@ -64,7 +67,6 @@ def main(): print("ERROR: " + message) sys.exit(1) - # instream is a string def doRewrite(rewriter, in_stream, callback=None, **kwargs): if callback: @@ -76,81 +78,213 @@ def main(): rewriter.write(out) return out.getvalue() - def processActions(options, f): out_stream = f.read() - newcp="${gentoo.classpath}" + newcp = "${gentoo.classpath}" if options.gentoo_classpath: - rewriter = DomRewriter(options.elements, options.attributes, options.values, options.index) - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_classpath,classpath = newcp) + rewriter = DomRewriter( + options.elements, + options.attributes, + options.values, + options.index) + out_stream = doRewrite( + rewriter, + out_stream, + rewriter.add_gentoo_classpath, + classpath=newcp) if options.doJavadoc: - rewriter = SaxRewriter(src_dirs = options.src_dirs, output_dir = options.javadoc_dir[0]) - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_javadoc) + rewriter = SaxRewriter( + src_dirs=options.src_dirs, + output_dir=options.javadoc_dir[0]) + out_stream = doRewrite( + rewriter, out_stream, rewriter.add_gentoo_javadoc) if options.doAdd or options.doDelete: # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter - # and let the DomRewriter do these. Also keeps the index option compatible for sure. + # and let the DomRewriter do these. Also keeps the index option + # compatible for sure. if options.index: - rewriter = DomRewriter(options.delete_elements, options.delete_attributes, options.values, options.index) - out_stream = doRewrite(rewriter, out_stream, rewriter.delete_elements) + rewriter = DomRewriter( + options.delete_elements, + options.delete_attributes, + options.values, + options.index) + out_stream = doRewrite( + rewriter, out_stream, rewriter.delete_elements) else: rewriter = SaxRewriter( - elems = options.elements, - attributes = options.attributes, - values = options.values, - sourceElems = options.source_elements, - sourceAttributes = options.source_attributes, - sourceValues = options.source_values, - targetElems = options.target_elements, - targetAttributes = options.target_attributes, - targetValues = options.target_values, - deleteElems = options.delete_elements, - deleteAttributes = options.delete_attributes + elems=options.elements, + attributes=options.attributes, + values=options.values, + sourceElems=options.source_elements, + sourceAttributes=options.source_attributes, + sourceValues=options.source_values, + targetElems=options.target_elements, + targetAttributes=options.target_attributes, + targetValues=options.target_values, + deleteElems=options.delete_elements, + deleteAttributes=options.delete_attributes ) - out_stream = doRewrite(rewriter, out_stream, rewriter.modify_elements) + out_stream = doRewrite( + rewriter, out_stream, rewriter.modify_elements) if options.doMaven: if options.mavenMultiProjectsDirs: for elem in options.mavenMultiProjectsDirs: - newcp+=":"+elem + newcp += ":" + elem rewriter = DomRewriter() - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_classpath, classpath = newcp) + out_stream = doRewrite( + rewriter, + out_stream, + rewriter.add_gentoo_classpath, + classpath=newcp) deleteElems = [] deleteAttributes = [] deleteElems.append("target") deleteAttributes.append("depends") - rewriter = SaxRewriter( deleteElems = deleteElems, deleteAttributes = deleteAttributes) - out_stream = doRewrite(rewriter, out_stream, rewriter.modify_elements) + rewriter = SaxRewriter( + deleteElems=deleteElems, + deleteAttributes=deleteAttributes) + out_stream = doRewrite( + rewriter, out_stream, rewriter.modify_elements) return out_stream - options_list = [ - make_option ("-a", "--attribute", action="append", dest="attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"), - make_option ("-b", "--target-element", action="append", dest="target_elements", help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."), - make_option ("-c", "--change", action="store_true", dest="doAdd", default=False, help="Change the value of an attribute. If it does not exist, it will be created."), - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."), - make_option ("-e", "--element", action="append", dest="elements", help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"), - make_option ("-g", "--gentoo-classpath", action="store_true", dest="gentoo_classpath", help="Rewrite build.xml to use gentoo.classpath where applicable."), - make_option ("-i", "--index", type="int", dest="index", help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero."), - make_option ("-j", "--javadoc", action="store_true", dest="doJavadoc", default=False, help="add a basic javadoc target. Sources must be placed in ${WORKDIR}/javadoc_src."), - make_option ("-k", "--target-attribute", action="append", dest="target_attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"), - make_option ("-l", "--target-value", action="append", dest="target_values", help="Value to set the attribute to (targeronly)."), - make_option ("-m", "--delete-attribute", action="append", dest="delete_attributes", help="Attribute of the matching elements to delete. These can be chained for multiple value-attribute pairs"), - make_option ("-n", "--delete-element", action="append", dest="delete_elements", help="Tag of the element of which the attributes to be deleted. These can be chained for multiple elements."), - make_option ("-o", "--output-directory", action="append", dest="javadoc_dir", help="javadoc output directory. Must be an existing directory"), - make_option ("-p", "--source-directory", action="append", dest="src_dirs", help="source directory for javadoc generation. Must be an existing directory"), - make_option ("-q", "--maven-cleaning", action="store_true", dest="doMaven", default=False, help="Turns on maven generated build.xml cleanup rewriting."), - make_option ("-r", "--source-element", action="append", dest="source_elements", help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."), - make_option ("-s", "--multi-project-dirs", action="append", dest="mavenMultiProjectsDirs", help="Dirs in classpath notation"), - - make_option ("-t", "--source-attribute", action="append", dest="source_attributes", help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"), - make_option ("-v", "--value", action="append", dest="values", help="Value to set the attribute to."), - make_option ("-y", "--source-value", action="append", dest="source_values", help="Value to set the attribute to. (sourceonly)") + make_option( + "-a", + "--attribute", + action="append", + dest="attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"), + make_option( + "-b", + "--target-element", + action="append", + dest="target_elements", + help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."), + make_option( + "-c", + "--change", + action="store_true", + dest="doAdd", + default=False, + help="Change the value of an attribute. If it does not exist, it will be created."), + make_option( + "-d", + "--delete", + action="store_true", + dest="doDelete", + default=False, + help="Delete an attribute from matching elements."), + make_option( + "-e", + "--element", + action="append", + dest="elements", + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), + make_option( + "-f", + "--file", + action="append", + dest="files", + help="Transform files instead of operating on stdout and stdin"), + make_option( + "-g", + "--gentoo-classpath", + action="store_true", + dest="gentoo_classpath", + help="Rewrite build.xml to use gentoo.classpath where applicable."), + make_option( + "-i", + "--index", + type="int", + dest="index", + help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero."), + make_option( + "-j", + "--javadoc", + action="store_true", + dest="doJavadoc", + default=False, + help="add a basic javadoc target. Sources must be placed in ${WORKDIR}/javadoc_src."), + make_option( + "-k", + "--target-attribute", + action="append", + dest="target_attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"), + make_option( + "-l", + "--target-value", + action="append", + dest="target_values", + help="Value to set the attribute to (targeronly)."), + make_option( + "-m", + "--delete-attribute", + action="append", + dest="delete_attributes", + help="Attribute of the matching elements to delete. These can be chained for multiple value-attribute pairs"), + make_option( + "-n", + "--delete-element", + action="append", + dest="delete_elements", + help="Tag of the element of which the attributes to be deleted. These can be chained for multiple elements."), + make_option( + "-o", + "--output-directory", + action="append", + dest="javadoc_dir", + help="javadoc output directory. Must be an existing directory"), + make_option( + "-p", + "--source-directory", + action="append", + dest="src_dirs", + help="source directory for javadoc generation. Must be an existing directory"), + make_option( + "-q", + "--maven-cleaning", + action="store_true", + dest="doMaven", + default=False, + help="Turns on maven generated build.xml cleanup rewriting."), + make_option( + "-r", + "--source-element", + action="append", + dest="source_elements", + help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."), + make_option( + "-s", + "--multi-project-dirs", + action="append", + dest="mavenMultiProjectsDirs", + help="Dirs in classpath notation"), + + make_option( + "-t", + "--source-attribute", + action="append", + dest="source_attributes", + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"), + make_option( + "-v", + "--value", + action="append", + dest="values", + help="Value to set the attribute to."), + make_option( + "-y", + "--source-value", + action="append", + dest="source_values", + help="Value to set the attribute to. (sourceonly)") ] parser = OptionParser(usage, options_list) (options, args) = parser.parse_args() @@ -163,20 +297,24 @@ def main(): if options.doAdd: if not options.elements and not options.target_elements and not options.source_elements: - error("At least one element (global, source only or target only) and attribute must be specified.") + error( + "At least one element (global, source only or target only) and attribute must be specified.") - for elem in ( options.source_attributes or [] ): - if elem in ( options.attributes or [] ): - error("You can't set an attribute in global and source scope at the same time") + for elem in (options.source_attributes or []): + if elem in (options.attributes or []): + error( + "You can't set an attribute in global and source scope at the same time") - for elem in ( options.target_attributes or [] ): - if elem in ( options.attributes or [] ): - error("You can't set an attribute in global and target scope at the same time") + for elem in (options.target_attributes or []): + if elem in (options.attributes or []): + error( + "You can't set an attribute in global and target scope at the same time") if options.doAdd and (len(options.values or []) != len(options.attributes or []) - or len(options.source_values or [] ) != len(options.source_attributes or []) - or len(options.target_values or [] ) != len(options.target_attributes or [])): - error("You must give attribute(s)/value(s) for every element you are changing.") + or len(options.source_values or []) != len(options.source_attributes or []) + or len(options.target_values or []) != len(options.target_attributes or [])): + error( + "You must give attribute(s)/value(s) for every element you are changing.") if options.doJavadoc: if len(options.src_dirs or []) < 1: @@ -196,20 +334,21 @@ def main(): if not options.delete_elements: error("At least one element to delete must be specified.") - if options.doDelete and ( len(options.attributes or []) < 0): - error("You must give attribute(s) to delete for every element you are changing.") + if options.doDelete and (len(options.attributes or []) < 0): + error( + "You must give attribute(s) to delete for every element you are changing.") # End Invalid Arguments Check - # main loop if options.files: for file in options.files: print("Rewriting %s" % file) # First parse the file into memory - # Tricks with cwd are needed for relative includes of other xml files to build.xml files + # Tricks with cwd are needed for relative includes of other xml + # files to build.xml files cwd = os.getcwd() dirname = os.path.dirname(file) - if dirname != '': # for file = build.xml comes out as '' + if dirname != '': # for file = build.xml comes out as '' os.chdir(os.path.dirname(file)) f = open(os.path.basename(file), "r") diff --git a/src/py/xml-rewrite.py b/src/py/xml-rewrite.py index 6bf8ea2..b164b6e 100755 --- a/src/py/xml-rewrite.py +++ b/src/py/xml-rewrite.py @@ -40,12 +40,12 @@ class IOWrapper: class Rewriter: def __init__(self, stream): self.stream = stream - self.document = parse(stream.stream); + self.document = parse(stream.stream) def modifyAttribute(self, elementTag, attribute, value, index=None): matches = self.document.getElementsByTagName(elementTag) if matches: - if index == None: + if index is None: for match in matches: match.setAttribute(attribute, value) else: @@ -54,7 +54,7 @@ class Rewriter: def deleteAttribute(self, elementTag, attribute, index=None): matches = self.document.getElementsByTagName(elementTag) if matches: - if index == None: + if index is None: for match in matches: try: match.removeAttribute(attribute) @@ -71,8 +71,7 @@ class Rewriter: def main(): - usage = "XML Rewrite Python Module Version " + __version__ + "\n" - usage += "Copyright 2004 Gentoo Foundation\n" + usage = "Copyright 2004 Gentoo Foundation\n" usage += "Distributed under the terms of the GNU General Public Lincense v2\n" usage += "Please contact the Gentoo Java Herd with problems.\n" usage += "\n" @@ -84,7 +83,6 @@ def main(): usage += "write to stdin and stdout respectively. The use of quotes on\n" usage += "parameters will break the script.\n" - def error(message): print("ERROR: " + message) sys.exit(1) @@ -94,13 +92,42 @@ def main(): # usage(True) options_list = [ - make_option ("-f", "--file", type="string", dest="file", help="Read input from file instead of stdin"), - make_option ("-c", "--change", action="store_true", dest="doAdd", default=False, help="Change the value of an attribute. If it does not exist, it will be created."), - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."), - make_option ("-e", "--element", action="append", dest="elements", help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), - make_option ("-a", "--attribute", type="string", dest="attribute", help="Attribute of the matching elements to change."), - make_option ("-v", "--value", type="string", dest="value", help="Value to set the attribute to."), - make_option ("-i", "--index", type="int", dest="index", help="Index of the match. If none is specified, the changes will be applied to all matches within the document.") + make_option("-f", "--file", type="string", dest="file", + help="Read input from file instead of stdin"), + make_option( + "-c", + "--change", + action="store_true", + dest="doAdd", + default=False, + help="Change the value of an attribute. If it does not exist, it will be created."), + make_option( + "-d", + "--delete", + action="store_true", + dest="doDelete", + default=False, + help="Delete an attribute from matching elements."), + make_option( + "-e", + "--element", + action="append", + dest="elements", + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."), + make_option( + "-a", + "--attribute", + type="string", + dest="attribute", + help="Attribute of the matching elements to change."), + make_option("-v", "--value", type="string", dest="value", + help="Value to set the attribute to."), + make_option( + "-i", + "--index", + type="int", + dest="index", + help="Index of the match. If none is specified, the changes will be applied to all matches within the document.") ] parser = OptionParser(usage, options_list) @@ -135,7 +162,11 @@ def main(): if options.doAdd: for element in options.elements: - rewriter.modifyAttribute(element, options.attribute, options.value, options.index) + rewriter.modifyAttribute( + element, + options.attribute, + options.value, + options.index) rewriter.write() -- cgit v1.2.3-65-gdbad