diff options
author | Patrice Clement <monsieurp@gentoo.org> | 2017-04-24 00:50:30 +0200 |
---|---|---|
committer | Patrice Clement <monsieurp@gentoo.org> | 2017-07-04 00:04:20 +0200 |
commit | 3f1bc87f8eb40560689ae8ff3dbf190ed3be8c23 (patch) | |
tree | 7e043582358420b49cdd44517ca550d645fb9f75 | |
parent | fix a typo (diff) | |
download | javatoolkit-3f1bc87f8eb40560689ae8ff3dbf190ed3be8c23.tar.gz javatoolkit-3f1bc87f8eb40560689ae8ff3dbf190ed3be8c23.tar.bz2 javatoolkit-3f1bc87f8eb40560689ae8ff3dbf190ed3be8c23.zip |
port to python 3
Closes: https://github.com/gentoo/javatoolkit/pull/1
-rwxr-xr-x | src/py/build-xml-rewrite | 79 | ||||
-rwxr-xr-x | src/py/buildparser | 12 | ||||
-rwxr-xr-x | src/py/class-version-verify.py | 30 | ||||
-rwxr-xr-x | src/py/eclipse-build.py | 4 | ||||
-rwxr-xr-x | src/py/findclass | 32 | ||||
-rwxr-xr-x | src/py/jarjarclean | 51 | ||||
-rw-r--r-- | src/py/javatoolkit/classpath.py | 26 | ||||
-rw-r--r-- | src/py/javatoolkit/cvv.py | 19 | ||||
-rw-r--r-- | src/py/javatoolkit/java/properties.py | 8 | ||||
-rw-r--r-- | src/py/javatoolkit/maven/MavenPom.py | 13 | ||||
-rw-r--r-- | src/py/javatoolkit/output.py | 9 | ||||
-rw-r--r-- | src/py/javatoolkit/parser/__init__.py | 10 | ||||
-rw-r--r-- | src/py/javatoolkit/parser/buildproperties.py | 4 | ||||
-rw-r--r-- | src/py/javatoolkit/parser/manifest.py | 6 | ||||
-rw-r--r-- | src/py/javatoolkit/parser/parser.py | 2 | ||||
-rw-r--r-- | src/py/javatoolkit/parser/tree.py | 8 | ||||
-rw-r--r-- | src/py/javatoolkit/xml/DomRewriter.py | 9 | ||||
-rw-r--r-- | src/py/javatoolkit/xml/SaxRewriter.py | 48 | ||||
-rw-r--r-- | src/py/javatoolkit/xml/__init__.py | 2 | ||||
-rwxr-xr-x | src/py/maven-helper.py | 30 | ||||
-rwxr-xr-x | src/py/xml-rewrite-2.py | 244 | ||||
-rwxr-xr-x | src/py/xml-rewrite-3.py | 22 | ||||
-rwxr-xr-x | src/py/xml-rewrite.py | 31 |
23 files changed, 328 insertions, 371 deletions
diff --git a/src/py/build-xml-rewrite b/src/py/build-xml-rewrite index a762e16..229de89 100755 --- a/src/py/build-xml-rewrite +++ b/src/py/build-xml-rewrite @@ -1,47 +1,50 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import sys import xml.etree.cElementTree as et from optparse import OptionParser -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('-e', '--encoding', dest="encoding") -(options, args) = parser.parse_args() +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('-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 = [] + if options.change: + for c in options.change: + changes.append((c[0].split(),c[1], c[2])) -gcp = options.gcp -gcp_str = '${gentoo.classpath}' -gcp_sub = et.Element('classpath', path=gcp_str) + gcp = options.gcp + gcp_str = '${gentoo.classpath}' + gcp_sub = et.Element('classpath', path=gcp_str) -for file in args: - tree = et.ElementTree(file=file) - if gcp or options.encoding: - for javac in tree.getiterator('javac'): - if gcp: - javac.attrib['classpath'] = gcp_str - if options.encoding: - javac.attrib['encoding'] = options.encoding - for javadoc in tree.getiterator('javadoc'): - if gcp: - javadoc.attrib['classpath'] = gcp_str - if options.encoding: - 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 junit in tree.getiterator('junit'): - if gcp: - junit.append(gcp_sub) - junit.attrib['haltonfailure'] = 'true' + for file in args: + tree = et.ElementTree(file=file) + if gcp or options.encoding: + for javac in tree.getiterator('javac'): + if gcp: + javac.attrib['classpath'] = gcp_str + if options.encoding: + javac.attrib['encoding'] = options.encoding + for javadoc in tree.getiterator('javadoc'): + if gcp: + javadoc.attrib['classpath'] = gcp_str + if options.encoding: + 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 junit in tree.getiterator('junit'): + if gcp: + junit.append(gcp_sub) + junit.attrib['haltonfailure'] = 'true' - f = open(file, 'w') - tree.write(f) - f.close() + with open(file, 'w') as f: + tree.write(f) + +if __name__ == '__main__': + main() diff --git a/src/py/buildparser b/src/py/buildparser index f388fcd..a7e656d 100755 --- a/src/py/buildparser +++ b/src/py/buildparser @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Copyright(c) 2006, 2008 James Le Cuirot <chewi@aura-online.co.uk> # Copyright(c) 2005, Karl Trygve Kalleberg <karltk@gentoo.org> @@ -25,7 +25,6 @@ __description__ = "A parser for build.properties and JAR manifest files." def parse_args(): - usage = 'buildparser [options] [node name] [replacement] <filename>' about = __productname__ + " : " + __description__ + "\n" + \ "Version : " + __version__ + "\n" \ @@ -60,7 +59,6 @@ def parse_args(): return opt, args def main(): - opt, args = parse_args() f = open(args[-1]) @@ -111,18 +109,18 @@ def main(): if n != None: if opt.wrap: - print p.wrapped_value(n) + print(p.wrapped_value(n)) else: - print n.value + print(n.value) else: for x in t.node_names(): - print x + print(x) if __name__ == '__main__': try: main() except KeyboardInterrupt: - print "Interrupted by user, aborting." + print("Interrupted by user, aborting.") #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 dbfb7d5..fb62ad5 100755 --- a/src/py/class-version-verify.py +++ b/src/py/class-version-verify.py @@ -1,22 +1,20 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Copyright(c) 2005, Thomas Matthijs <axxo@gentoo.org> # Copyright(c) 2005, Gentoo Foundation # # Licensed under the GNU General Public License, v2 # -# $Header: /var/cvsroot/gentoo-src/javatoolkit/src/bsfix/class-version-verify.py,v 1.2 2005/07/19 10:35:18 axxo Exp $ +# $Id$ import os,sys from optparse import OptionParser, make_option from javatoolkit.cvv import * -if __name__ == '__main__': - +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"), @@ -26,17 +24,17 @@ if __name__ == '__main__': (options, args) = parser.parse_args() if not options.version: - print "-t is mandatory" + print("-t is mandatory") sys.exit(2) options.version = int(options.version.split(".")[-1]) - + cvv = cvv(options.version) for arg in args: if os.path.isfile(arg): cvv.do_file(arg) - + if options.deep and os.path.isdir(arg): for root, dirs, files in os.walk(arg): for filename in files: @@ -45,22 +43,22 @@ if __name__ == '__main__': if options.file_only: lst = set([set[1] for set in cvv.bad]) for i in lst: - print i + print(i) else: - if options.verbose: for set in cvv.good: - print "Good: %s %s %s" % set - + print("Good: %s %s %s" % set) + if not options.silent: 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("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))) if len(cvv.bad) > 0: sys.exit(1) else: sys.exit(0) -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap +if __name__ == '__main__': + main() diff --git a/src/py/eclipse-build.py b/src/py/eclipse-build.py index b660f95..2f41b3a 100755 --- a/src/py/eclipse-build.py +++ b/src/py/eclipse-build.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2008 Gentoo Foundation @@ -17,6 +17,7 @@ from javatoolkit.java.properties import PropertiesParser __version__ = "$Revision: 1 $"[11:-2] + if __name__ == '__main__': usage = "Eclipse Ant Build File writer " + __version__ + "\n" usage += "Copyright 2008 Gentoo Foundation\n" @@ -24,7 +25,6 @@ if __name__ == '__main__': usage += "Please contact the Gentoo Java Team <java@gentoo.org> with problems.\n" 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' ), diff --git a/src/py/findclass b/src/py/findclass index 15802c9..0581acc 100755 --- a/src/py/findclass +++ b/src/py/findclass @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Copyright (c) Karl Trygve Kalleberg <karltk@gentoo.org> # Copyright (c) Fabio Lessa <flessa@gmail.com> @@ -15,16 +15,17 @@ import re import sys import glob from optparse import OptionParser -from commands import getstatusoutput +from subprocess import getstatusoutput from java_config.jc_util import find_exec, collect_packages + __author__ = "Karl Trygve Kalleberg <karltk@gentoo.org> and Fabio Lessa <flessa@gmail.com>" __version__ = "0.1.0" __productname__ = "findclass" __description__ = "Gentoo Java Class Query Tool" -def parse_args(): +def parse_args(): usage = 'findclass [options] class.or.package.Name' about = __productname__ + " : " + __description__ + "\n" + \ "Authors : " + __author__ + \ @@ -40,39 +41,36 @@ def parse_args(): return opt, files + def main(): - opt, files = parse_args() jarcmd = find_exec('jar') - + 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, - print jar + if opt.verbose: print("Found in %s" % pkg, end=' ') + print(jar) -def get_all_packages(): +def get_all_packages(): pkg = glob.glob('/usr/share/*/package.env') pkg = [os.path.basename(os.path.dirname(i)) for i in pkg] - + classpath = glob.glob('/usr/share/*/classpath.env') classpath = [os.path.basename(os.path.dirname(i)) for i in classpath] - + dir = glob.glob('/usr/share/java/packages/*') dir = [os.path.basename(i) for i in dir] - + pkg.extend(classpath) pkg.extend(dir) return pkg @@ -82,4 +80,4 @@ if __name__ == '__main__': try: main() except KeyboardInterrupt: - print "Interrupted by user, aborting." + print("Interrupted by user, aborting.") diff --git a/src/py/jarjarclean b/src/py/jarjarclean index 517f0be..3effaec 100755 --- a/src/py/jarjarclean +++ b/src/py/jarjarclean @@ -1,42 +1,45 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Copyright 2008 James Le Cuirot <chewi@aura-online.co.uk> # Copyright 2008 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # -# $Header: $ +# $Id$ + import sys import xml.etree.cElementTree as et + args = sys.argv[1:] if len(args) == 0: - args = [ 'build.xml' ] + args = ['build.xml'] -for file in args: - tree = et.ElementTree(file=file) - tags = [] - for elem in tree.getiterator(): - for child in list(elem): - if child.tag == 'taskdef' and child.get('classname') == 'com.tonicsystems.jarjar.JarJarTask': - tags.append(child.get('name')) - elem.remove(child) +def main(): + for file in args: + tree = et.ElementTree(file=file) + tags = [] - for tag in tags: - for jarjar in tree.getiterator(tag): - if jarjar.get('destfile') or jarjar.get('jarfile'): - jarjar.tag = 'jar' + for elem in tree.getiterator(): + for child in list(elem): + if child.tag == 'taskdef' and child.get('classname') == 'com.tonicsystems.jarjar.JarJarTask': + tags.append(child.get('name')) + elem.remove(child) - if jarjar.get('verbose'): - del jarjar.attrib['verbose'] + for tag in tags: + for jarjar in tree.getiterator(tag): + if jarjar.get('destfile') or jarjar.get('jarfile'): + jarjar.tag = 'jar' + if jarjar.get('verbose'): + del jarjar.attrib['verbose'] + for child in list(jarjar): + if child.tag == 'keep' or child.tag == 'rule' or child.tag == 'zipfileset': + jarjar.remove(child) - for child in list(jarjar): - if child.tag == 'keep' or child.tag == 'rule' or child.tag == 'zipfileset': - jarjar.remove(child) + with open(file, 'w') as f: + tree.write(f) - f = open(file, 'w') - tree.write(f) - f.close() -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap +if __name__ == '__main__': + main() diff --git a/src/py/javatoolkit/classpath.py b/src/py/javatoolkit/classpath.py index 18c6857..fb801f2 100644 --- a/src/py/javatoolkit/classpath.py +++ b/src/py/javatoolkit/classpath.py @@ -2,67 +2,53 @@ # Copyright(c) 2004, Gentoo Foundation # # Licensed under the GNU General Public License, v2 -# -# $Header: /var/cvsroot/gentoo-src/javatoolkit/src/javatoolkit/classpath.py,v 1.4 2004/11/08 20:06:06 karltk Exp $ + class ClasspathIter: """An iterator for the Classpath class, below.""" - def __init__(self, classpath): self._classpath = classpath self._index = 0 - - def next(self): + + def __next__(self): self._index += 1 if self._index >= len(self._classpath.classpath): raise StopIteration return self._classpath.classpath[self._index] - + class Classpath: """A classpath object provides a collection interface to the elements of a : separated path list. """ - def __init__(self, classpath_string = None): if classpath_string != None: cs = classpath_string.strip().strip("\"") self.classpath = cs.split(":") else: self.classpath = [] - - + def __iter__(self): """Returns iterator. Elements of the original classpath string are considered split by ':'.""" - return ClasspathIter(self) - def __len__(self): """Returns length (number of elements) in this classpath.""" - return len(self.classpath) - def __getitem__(self, i): """Returns i'th element.""" - return self.classpath[i] - def __setitem__(self, i, val): """Sets i'th element.""" - self.classpath[i] = val - def __str__(self): """Constructs a suitable string representation of the classpath.""" - return ":".join(self.classpath) - def append(self, element): """Appends an path to the classpath.""" - self.classpath.append(element) + # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap: diff --git a/src/py/javatoolkit/cvv.py b/src/py/javatoolkit/cvv.py index 72375d3..c72cfcc 100644 --- a/src/py/javatoolkit/cvv.py +++ b/src/py/javatoolkit/cvv.py @@ -3,10 +3,12 @@ # Distributed under the terms of the GNU General Public License v2 # $Header: $ -import os,sys +import os +import sys from struct import unpack from zipfile import ZipFile + class cvv: def __init__(self, target): self.target = target @@ -22,26 +24,21 @@ class cvv: def do_class(self,filename): classFile = file(filename,"rb") classFile.seek(4) - temp = classFile.read(4) - #(version,) = unpack('>i',temp) (version,) = unpack('>xxh',temp) - version-=44 - + version -= 44 self.add(version, None, filename) - + def do_jar(self, filename): zipfile = ZipFile(filename, 'r') - + for file in zipfile.namelist(): if file.endswith('class'): classFile = zipfile.read(file) - (version,) = unpack('>h',classFile[6:8]) - version-=44 - + version -= 44 self.add(version, filename, file) - + def do_file(self, filename): if not os.path.islink(filename): if filename.endswith(".class"): diff --git a/src/py/javatoolkit/java/properties.py b/src/py/javatoolkit/java/properties.py index adf7a79..7796d15 100644 --- a/src/py/javatoolkit/java/properties.py +++ b/src/py/javatoolkit/java/properties.py @@ -1,9 +1,8 @@ # Copyright 2008 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 -# $Header: $ - import os + class PropertiesParser: """ Parse eclipse projects build.properties file. @@ -25,7 +24,6 @@ class PropertiesParser: while line != '': line = line.strip('\n') line = line.strip() - #print 'line="'+line+'"' if line.isspace() or line == '' or line.startswith('#'): line = stream.readline() continue @@ -35,14 +33,10 @@ class PropertiesParser: name = name.strip() value = line[index+1:] - #print 'name="'+name+'"; value="'+value+'"' - while line.endswith('\\'): - #stream.next() line = stream.readline() line = line.strip('\n') line = line.strip() - #print 'line="'+line+'"' if line.isspace() or line == '' or line.startswith('#'): line = stream.readline() break diff --git a/src/py/javatoolkit/maven/MavenPom.py b/src/py/javatoolkit/maven/MavenPom.py index 5de57b9..5bb01af 100644 --- a/src/py/javatoolkit/maven/MavenPom.py +++ b/src/py/javatoolkit/maven/MavenPom.py @@ -17,7 +17,7 @@ # 08/05/2007 initial version import sys -import StringIO +import io # either a very simplified representation of a maven pom # or a fully xml rewritten pom @@ -29,7 +29,7 @@ class MavenPom: self.name = '' self.is_child = "false" self.dependencies = [] - self.buffer = StringIO.StringIO() + self.buffer = io.StringIO() self.__write = self.buffer.write self.mydoc = None self.cli_options = cli_options @@ -164,20 +164,19 @@ class MavenPom: plugins_nodes = ( xmldoc.getElementsByTagName("plugins") or [] ) # no plugins node if len(plugins_nodes) < 1 : - plugins_node = self.create_element(xmldoc,"plugins") + plugins_node = self.create_element(xmldoc,"plugins") plugins_nodes.append(plugins_node) - for plugins_node in plugins_nodes: # add our generated plugin node plugins_node.appendChild(plugin_node) # no build node build_nodes = ( xmldoc.getElementsByTagName("build") or [] ) - if len(build_nodes) < 1 : - build_node = self.create_element(xmldoc,"build") + if len(build_nodes) < 1 : + build_node = self.create_element(xmldoc,"build") build_nodes.append(build_node) # add build node to project_node - project_nodes = ( xmldoc.getElementsByTagName("project") or [] ) + project_nodes = ( xmldoc.getElementsByTagName("project") or [] ) for project_node in project_nodes: project_node.appendChild(build_node) diff --git a/src/py/javatoolkit/output.py b/src/py/javatoolkit/output.py index 6f7680d..2af324a 100644 --- a/src/py/javatoolkit/output.py +++ b/src/py/javatoolkit/output.py @@ -2,24 +2,25 @@ # Copyright(c) 2004, Gentoo Foundation # # Licensed under the GNU General Public License, v2 -# -# $Header: /var/cvsroot/gentoo-src/javatoolkit/src/javatoolkit/output.py,v 1.1 2004/11/08 19:21:52 karltk Exp $ +# FIXME: Use gentoolkit stuff instead import sys -# FIXME: Use gentoolkit stuff instead def eerror(s): sys.stderr.write("!!! " + s + "\n") + def ewarn(s): sys.stdout.write("* " + s + "\n") + def einfo(s): sys.stdout.write("* " + s + "\n") + def die(err, s): eerror(s) sys.exit(err) - + # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap: diff --git a/src/py/javatoolkit/parser/__init__.py b/src/py/javatoolkit/parser/__init__.py index 55f6e54..f9cc2e5 100644 --- a/src/py/javatoolkit/parser/__init__.py +++ b/src/py/javatoolkit/parser/__init__.py @@ -1,14 +1,12 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # # Copyright(c) 2004, Karl Trygve Kalleberg <karltk@gentoo.org> # Copyright(c) 2004, Gentoo Foundation # # Licensed under the GNU General Public License, v2 -# -# $Header: $ -from helpers import * -import buildproperties +from .helpers import * +from . import buildproperties if __name__ == "__main__": - print "This is not an executable module" + print("This is not an executable module") diff --git a/src/py/javatoolkit/parser/buildproperties.py b/src/py/javatoolkit/parser/buildproperties.py index e3672e5..a09614d 100644 --- a/src/py/javatoolkit/parser/buildproperties.py +++ b/src/py/javatoolkit/parser/buildproperties.py @@ -6,8 +6,8 @@ # # $Header: $ -from tree import * -import parser +from .tree import * +from . import parser class BuildPropertiesParser(parser.Parser): diff --git a/src/py/javatoolkit/parser/manifest.py b/src/py/javatoolkit/parser/manifest.py index 09acf4c..b5a1701 100644 --- a/src/py/javatoolkit/parser/manifest.py +++ b/src/py/javatoolkit/parser/manifest.py @@ -4,8 +4,8 @@ # # $Header: $ -from tree import * -import parser +from .tree import * +from . import parser class ManifestParser(parser.Parser): @@ -54,7 +54,7 @@ class ManifestParser(parser.Parser): def output(self, ous, tree): tree.output(ous, "", ": ", "", ",", " ") - + def wrapped_value(self, node): return node.output_value(",") diff --git a/src/py/javatoolkit/parser/parser.py b/src/py/javatoolkit/parser/parser.py index 01e1171..3393fef 100644 --- a/src/py/javatoolkit/parser/parser.py +++ b/src/py/javatoolkit/parser/parser.py @@ -1,8 +1,6 @@ # Copyright(c) 2006, James Le Cuirot <chewi@aura-online.co.uk> # # Licensed under the GNU General Public License, v2 -# -# $Header: $ class Parser: def parse(self, ins): diff --git a/src/py/javatoolkit/parser/tree.py b/src/py/javatoolkit/parser/tree.py index ca361c9..6a07b45 100644 --- a/src/py/javatoolkit/parser/tree.py +++ b/src/py/javatoolkit/parser/tree.py @@ -3,25 +3,25 @@ # Copyright(c) 2004, Gentoo Foundation # # Licensed under the GNU General Public License, v2 -# -# $Header: $ - import sys + class ParseError: def __init__(self, error): self.error = error + class NodeIter: def __init__(self, node): self._node = node self._index = 0 - def next(self): + def __next__(self): self._index += 1 if self._index >= len(self._node._kids): raise StopIteration return self._node._kids[self._index] + class Node: def __init__(self, name = None, value = None): self.name = name diff --git a/src/py/javatoolkit/xml/DomRewriter.py b/src/py/javatoolkit/xml/DomRewriter.py index 4be78a1..7cd5a2f 100644 --- a/src/py/javatoolkit/xml/DomRewriter.py +++ b/src/py/javatoolkit/xml/DomRewriter.py @@ -1,14 +1,8 @@ # -*- coding: UTF-8 -*- - # Copyright 2004-2008 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 -# $Header: $ from xml.dom import NotFoundErr -#import os -#import sys -#import StringIO -#import xml.sax.saxutils import quoteattr,escape class DomRewriter: """ @@ -16,7 +10,6 @@ class DomRewriter: 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 = None, attributes = None , values=None, index=None): self.modifyElems = modifyElems self.attributes = attributes @@ -50,7 +43,7 @@ class DomRewriter: def add_gentoo_classpath(self,document,**kwargs): - if not kwargs.has_key('classpath') or not kwargs['classpath']: + if 'classpath' not in kwargs or not kwargs['classpath']: return cp = document.createElement("classpath") diff --git a/src/py/javatoolkit/xml/SaxRewriter.py b/src/py/javatoolkit/xml/SaxRewriter.py index 3e75d99..07528c9 100644 --- a/src/py/javatoolkit/xml/SaxRewriter.py +++ b/src/py/javatoolkit/xml/SaxRewriter.py @@ -6,7 +6,7 @@ import os import sys -import StringIO +import io from xml.sax.saxutils import XMLGenerator from xml.sax.saxutils import quoteattr @@ -17,33 +17,33 @@ class SaxRewriter(XMLGenerator): and is only marginally slower than expat as it is just a tight layer over it """ def __init__(self, **kwds): - self.elems = kwds.has_key('elems') and kwds['elems'] or [] - self.attributes = kwds.has_key('attributes') and kwds['attributes'] or [] - self.values = kwds.has_key('values') and kwds['values'] or [] - self.sourceElems = kwds.has_key('sourceElems') and kwds['sourceElems'] or [] - self.sourceAttributes = kwds.has_key('sourceAttributes') and kwds['sourceAttributes'] or [] - self.sourceValues = kwds.has_key('sourceValues') and kwds['sourceValues'] or [] - self.targetElems = kwds.has_key('targetElems') and kwds['targetElems'] or [] - self.targetAttributes = kwds.has_key('targetAttributes') and kwds['targetAttributes'] or [] - self.targetValues = kwds.has_key('targetValues') and kwds['targetValues'] or [] + self.elems = 'elems' in kwds and kwds['elems'] or [] + self.attributes = 'attributes' in kwds and kwds['attributes'] or [] + self.values = 'values' in kwds and kwds['values'] or [] + self.sourceElems = 'sourceElems' in kwds and kwds['sourceElems'] or [] + self.sourceAttributes = 'sourceAttributes' in kwds and kwds['sourceAttributes'] or [] + self.sourceValues = 'sourceValues' in kwds and kwds['sourceValues'] or [] + self.targetElems = 'targetElems' in kwds and kwds['targetElems'] or [] + self.targetAttributes = 'targetAttributes' in kwds and kwds['targetAttributes'] or [] + self.targetValues = 'targetValues' in kwds and kwds['targetValues'] or [] - self.deleteElems = kwds.has_key('deleteElems') and kwds['deleteElems'] or [] - self.deleteAttributes = kwds.has_key('deleteAttributes') and kwds['deleteAttributes'] or [] + self.deleteElems = 'deleteElems' in kwds and kwds['deleteElems'] or [] + self.deleteAttributes = 'deleteAttributes' in kwds and kwds['deleteAttributes'] or [] - self.src_dirs = kwds.has_key('src_dirs') and kwds['src_dirs'] or [] - self.output_dir = kwds.has_key('output_dir') and kwds['output_dir'] or None + self.src_dirs = 'src_dirs' in kwds and kwds['src_dirs'] or [] + self.output_dir = 'output_dir' in kwds and kwds['output_dir'] or None - self.buffer = StringIO.StringIO() + self.buffer = io.StringIO() XMLGenerator.__init__(self, self.buffer, 'UTF-8') def add_gentoo_javadoc(self, name, attrs): - self.p(u'<%s ' % name) - for a,v in attrs.items(): + self.p('<%s ' % name) + for a,v in list(attrs.items()): self.write_attr(a,v) - self.p(u'>') + self.p('>') if name == "project": javadoc_str = """ @@ -69,20 +69,20 @@ class SaxRewriter(XMLGenerator): </target> """ - self.p(u'%s' % javadoc_str) + self.p('%s' % javadoc_str) # write as they are or delete if wanted attributes first # next, add / update def modify_elements(self, name, attrs): - self.p(u'<%s ' % name) + self.p('<%s ' % name) match = ( name in self.elems ) matchSource = ( name in self.sourceElems ) matchTarget = ( name in self.targetElems ) matchDelete = ( name in self.deleteElems ) - for a,v in attrs.items(): + for a,v in list(attrs.items()): if not ( (match and a in self.attributes) or (matchSource and a in self.sourceAttributes) @@ -103,7 +103,7 @@ class SaxRewriter(XMLGenerator): for i, attr in enumerate(self.attributes): self.write_attr(attr, self.values[i]) - self.p(u'>') + self.p('>') def char_data(self, data): @@ -121,13 +121,13 @@ class SaxRewriter(XMLGenerator): def write_attr(self,a,v): - self.p(u'%s=%s ' % (a,quoteattr(v, {u'©':'©'}))) + self.p('%s=%s ' % (a,quoteattr(v, {'©':'©'}))) def process(self, in_stream, callback): self.startElement = callback from xml.sax import parseString parseString(in_stream, self) - self.p(u'\n') + self.p('\n') # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap: diff --git a/src/py/javatoolkit/xml/__init__.py b/src/py/javatoolkit/xml/__init__.py index 8d36aa9..f7f2910 100644 --- a/src/py/javatoolkit/xml/__init__.py +++ b/src/py/javatoolkit/xml/__init__.py @@ -4,4 +4,4 @@ # Licensed under the GNU General Public License, v2 if __name__ == "__main__": - print "This is not an executable module" + print("This is not an executable module") diff --git a/src/py/maven-helper.py b/src/py/maven-helper.py index e5a8876..108abae 100755 --- a/src/py/maven-helper.py +++ b/src/py/maven-helper.py @@ -19,14 +19,16 @@ import sys -import StringIO +import io from optparse import OptionParser, make_option from javatoolkit.maven.MavenPom import MavenPom + __version__ = "$Revision: 1.1 $"[11:-2] -if __name__ == '__main__': +def main() + usage = "XML MAVEN POM MODULE " + __version__ + "\n" usage += "Copyright 2004,2006,2007 Gentoo Foundation\n" usage += "Distributed under the terms of the GNU General Public Lincense v2\n" @@ -44,7 +46,7 @@ if __name__ == '__main__': def error(message): - print "ERROR: " + message + print("ERROR: " + message) sys.exit(1) @@ -54,7 +56,6 @@ if __name__ == '__main__': pom.parse(stream, pom.rewrite) elif options.p_ischild or options.p_group or options.p_dep or options.p_artifact or options.p_version: pom.parse(stream, pom.getDescription) - return pom @@ -78,21 +79,15 @@ if __name__ == '__main__': f.write(pom.read()) f.close() else: - print "%s" % pom.read() - + print("%s" % pom.read()) os.chdir(cwd) - else: # process stdin pom = doAction(sys.stdin.read(),options) - print pom.read() - + 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."), @@ -111,8 +106,8 @@ if __name__ == '__main__': # Invalid Arguments Must be smited! if not options.p_ischild and not options.p_rewrite and not options.p_dep and not options.p_version and not options.p_artifact and not options.p_group: - print usage - print + print(usage) + print() error("No action was specified.") if options.files: @@ -125,14 +120,11 @@ if __name__ == '__main__': if options.p_source: if len(options.p_source) != 1: error("Please specify one and only one source.") - if options.p_source[0] not in valid_sources: error("Source %s is not valid" % options.p_source[0]) - if options.p_target: if len(options.p_target) != 1: error("Please specify one and only one target.") - if options.p_target[0] not in valid_sources: error("Target %s is not valid" % options.p_target[0]) @@ -143,11 +135,11 @@ if __name__ == '__main__': start.append(options.classpath[0]) for item in options.classpath[1:]: start[0] += ":%s" % (item) - options.classpath = start # End Invalid Arguments Check # main loop run() -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap +if __name__ == '__main__': + main() diff --git a/src/py/xml-rewrite-2.py b/src/py/xml-rewrite-2.py index a143ee3..2755bb6 100755 --- a/src/py/xml-rewrite-2.py +++ b/src/py/xml-rewrite-2.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # vim: set ai ts=8 sts=0 sw=8 tw=0 noexpandtab: @@ -19,15 +19,16 @@ # December 23, 2004 - Initial Write # December 24, 2004 - Added usage information -import sys -import StringIO +import sys +import io from xml.sax.saxutils import quoteattr,escape - from optparse import OptionParser, make_option + __version__ = "$Revision: 1.7 $"[11:-2] + def add_gentoo_classpath(document): matches = document.getElementsByTagName("classpath") gcp = document.createElement("location") @@ -95,11 +96,10 @@ class DomRewriter: stream.write(self.document.toxml()) class StreamRewriterBase: - def __init__(self, elems, attributes, values, index, sourceElems = [], sourceAttributes = [], sourceValues = [], targetElems = [], targetAttributes = [], targetValues = [] ): - self.buffer = StringIO.StringIO() + self.buffer = io.StringIO() self.__write = self.buffer.write self.elems = elems or [] self.attributes = attributes or [] @@ -120,10 +120,10 @@ class StreamRewriterBase: self.buffer.truncate(0) def write_attr(self,a,v): - self.p(u'%s=%s ' % (a,quoteattr(v, {u'©':'©'}))) + self.p('%s=%s ' % (a,quoteattr(v, {'©':'©'}))) def start_element(self, name, attrs): - self.p(u'<%s ' % name) + self.p('<%s ' % name) match = ( name in self.elems ) matchSource = ( name in self.sourceElems ) @@ -149,7 +149,7 @@ class StreamRewriterBase: for i, attr in enumerate(self.attributes): self.write_attr(attr, self.values[i]) - self.p(u'>') + self.p('>') class ExpatRewriter(StreamRewriterBase): """ @@ -164,13 +164,13 @@ class ExpatRewriter(StreamRewriterBase): parser.EndElementHandler = self.end_element parser.CharacterDataHandler = self.char_data parser.ParseFile(in_stream) - self.p(u'\n') + self.p('\n') def start_element(self, name, attrs): - StreamRewriterBase(self, name, attrs.iteritems()) + StreamRewriterBase(self, name, iter(attrs.items())) def end_element(self,name): - self.p(u'</%s>' % name) + self.p('</%s>' % name) def char_data(self,data): self.p(escape(data)) @@ -192,130 +192,120 @@ class SaxRewriter(XMLGenerator, StreamRewriterBase): def process(self, in_stream): from xml.sax import parse parse(in_stream, self) - self.p(u'\n') + self.p('\n') def startElement(self, name, attrs): - self.start_element(name, attrs.items()) - -if __name__ == '__main__': - usage = "XML Rewrite Python Module Version " + __version__ + "\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 <java@gentoo.org> with problems.\n" - usage += "\n" - usage += "Usage:\n" - usage += " xml-rewrite.py [-f file] --delete [-g] -e tag [-e tag] -a attribute [-a attribute] [-i index]\n" - usage += " xml-rewrite.py [-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 += " xml-rewrite.py [-f file] -g\n" - usage += "\n" - usage += "If the -f parameter is not utilized, the script will read and\n" - 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) - + 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 += "Distributed under the terms of the GNU General Public Lincense v2\n" + usage += "Please contact the Gentoo Java Team <java@gentoo.org> with problems.\n" + usage += "\n" + usage += "Usage:\n" + usage += " xml-rewrite.py [-f file] --delete [-g] -e tag [-e tag] -a attribute [-a attribute] [-i index]\n" + usage += " xml-rewrite.py [-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 += " xml-rewrite.py [-f file] -g\n" + usage += "\n" + usage += "If the -f parameter is not utilized, the script will read and\n" + 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) # 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.") - ] - - parser = OptionParser(usage, options_list) - (options, args) = parser.parse_args() - - + 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.") + ] + + parser = OptionParser(usage, options_list) + (options, args) = parser.parse_args() # 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.") - - 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.") + if not options.doAdd and not options.doDelete and not options.gentoo_classpath: + 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 - 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 - - 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() - + 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: - if options.gentoo_classpath: - rewriter.process(sys.stdin,add_gentoo_classpath) - else: - rewriter.process(sys.stdin) + 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() + + else: + if options.gentoo_classpath: + rewriter.process(sys.stdin,add_gentoo_classpath) + else: + rewriter.process(sys.stdin) + rewriter.write(sys.stdout) - rewriter.write(sys.stdout) +if __name__ == '__main__': + main() diff --git a/src/py/xml-rewrite-3.py b/src/py/xml-rewrite-3.py index 096db76..605e927 100755 --- a/src/py/xml-rewrite-3.py +++ b/src/py/xml-rewrite-3.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2004-2008 Gentoo Foundation @@ -23,16 +23,18 @@ # December 23, 2004 - Initial Write # December 24, 2004 - Added usage information + import os import sys -import StringIO +import io from optparse import OptionParser, make_option from javatoolkit.xml.DomRewriter import DomRewriter from javatoolkit.xml.SaxRewriter import SaxRewriter + __version__ = "$Revision: 1.7 $"[11:-2] -if __name__ == '__main__': +def main(): usage = "XML Rewrite Python Module Version " + __version__ + "\n" usage += "Copyright 2004,2006,2007 Gentoo Foundation\n" usage += "Distributed under the terms of the GNU General Public Lincense v2\n" @@ -61,7 +63,7 @@ if __name__ == '__main__': usage += "parameters will break the script.\n" def error(message): - print "ERROR: " + message + print("ERROR: " + message) sys.exit(1) @@ -72,7 +74,7 @@ if __name__ == '__main__': else: rewriter.process(in_stream, **kwargs) - out = StringIO.StringIO() + out = io.StringIO() rewriter.write(out) return out.getvalue() @@ -157,8 +159,8 @@ if __name__ == '__main__': # Invalid Arguments Must be smited! if not options.doAdd and not options.doDelete and not options.gentoo_classpath and not options.doJavadoc and not options.doMaven: - print usage - print + print(usage) + print() error("No action was specified.") if options.doAdd: @@ -204,7 +206,7 @@ if __name__ == '__main__': # main loop if options.files: for file in options.files: - print "Rewriting %s" % file + 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() @@ -225,4 +227,6 @@ if __name__ == '__main__': outxml = processActions(options, sys.stdin) sys.stdout.write(outxml) -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap + +if __name__ == '__main__': + main() diff --git a/src/py/xml-rewrite.py b/src/py/xml-rewrite.py index 624fd77..7e1dbc4 100755 --- a/src/py/xml-rewrite.py +++ b/src/py/xml-rewrite.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2004 Gentoo Foundation @@ -14,17 +14,19 @@ # December 23, 2004 - Initial Write # December 24, 2004 - Added usage information + import sys from xml.dom.minidom import parse - from optparse import OptionParser, make_option from xml.dom import NotFoundErr + __version__ = "$Revision: 1.6 $"[11:-2] + class IOWrapper: def __init__(self, object): - self.stream = object + self.stream = object def stream(self): return self.stream @@ -37,6 +39,7 @@ class IOWrapper: file.write(data.encode('utf-8')) file.close() + class Rewriter: def __init__(self, stream): self.stream = stream @@ -46,7 +49,7 @@ class Rewriter: matches = self.document.getElementsByTagName(elementTag) if matches: if index == None: - for match in matches: + for match in matches: match.setAttribute(attribute, value) else: matches[index].setAttribute(attribute, value) @@ -70,7 +73,7 @@ class Rewriter: self.stream.write(self.document.toxml()) -if __name__ == '__main__': +def main(): usage = "XML Rewrite Python Module Version " + __version__ + "\n" usage += "Copyright 2004 Gentoo Foundation\n" usage += "Distributed under the terms of the GNU General Public Lincense v2\n" @@ -86,14 +89,14 @@ if __name__ == '__main__': def error(message): - print "ERROR: " + message + print("ERROR: " + message) sys.exit(1) # if len(sys.argv) == 1: # usage(True) - options_list = [ + 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."), @@ -106,11 +109,10 @@ if __name__ == '__main__': parser = OptionParser(usage, options_list) (options, args) = parser.parse_args() - # Invalid Arguments Must be smited! if not options.doAdd and not options.doDelete: - print usage - print + print(usage) + print() error("No action was specified.") if options.doAdd and options.doDelete: @@ -123,20 +125,23 @@ if __name__ == '__main__': error("You must specify values for the attributes to be modified.") # End Invalid Arguments Check - if options.file: source = options.file else: source = sys.stdin rewriter = Rewriter(IOWrapper(source)) - + if options.doDelete: for element in options.elements: rewriter.deleteAttribute(element, options.attribute, options.index) - + if options.doAdd: for element in options.elements: rewriter.modifyAttribute(element, options.attribute, options.value, options.index) rewriter.write() + + +if __name__ == '__main__': + main() |