* [gentoo-commits] proj/javatoolkit:master commit in: src/javatoolkit/scripts/, src/javatoolkit/xml/, /
@ 2025-02-15 10:18 Arthur Zamarin
0 siblings, 0 replies; only message in thread
From: Arthur Zamarin @ 2025-02-15 10:18 UTC (permalink / raw
To: gentoo-commits
commit: 033b3fd64b9bc06e83029ef10bd10a8b0df207a6
Author: Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
AuthorDate: Sat Feb 15 10:11:18 2025 +0000
Commit: Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
CommitDate: Sat Feb 15 10:12:03 2025 +0000
URL: https://gitweb.gentoo.org/proj/javatoolkit.git/commit/?id=033b3fd6
remove xml-rewrite scripts
Closes: https://bugs.gentoo.org/942810
Signed-off-by: Arthur Zamarin <arthurzam <AT> gentoo.org>
pyproject.toml | 4 -
src/javatoolkit/scripts/build_xml_rewrite.py | 63 -----
src/javatoolkit/scripts/xml_rewrite.py | 159 -----------
src/javatoolkit/scripts/xml_rewrite_2.py | 396 ---------------------------
src/javatoolkit/scripts/xml_rewrite_3.py | 340 -----------------------
src/javatoolkit/xml/DomRewriter.py | 76 -----
src/javatoolkit/xml/SaxRewriter.py | 133 ---------
src/javatoolkit/xml/__init__.py | 7 -
src/javatoolkit/xml/sax.py | 44 ---
9 files changed, 1222 deletions(-)
diff --git a/pyproject.toml b/pyproject.toml
index bc4612f..7da5990 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -25,13 +25,9 @@ Source = "https://gitweb.gentoo.org/proj/javatoolkit.git/"
[project.scripts]
"maven-helper.py" = "javatoolkit.scripts.maven_helper:main"
-"xml-rewrite-3.py" = "javatoolkit.scripts.xml_rewrite_3:main"
findclass = "javatoolkit.scripts.findclass:main"
-"xml-rewrite.py" = "javatoolkit.scripts.xml_rewrite:main"
-"xml-rewrite-2.py" = "javatoolkit.scripts.xml_rewrite_2:main"
buildparser = "javatoolkit.scripts.buildparser:main"
"class-version-verify.py" = "javatoolkit.scripts.class_version_verify:main"
-build-xml-rewrite = "javatoolkit.scripts.build_xml_rewrite:main"
jarjarclean = "javatoolkit.scripts.jarjarclean:main"
"eclipse-build.py" = "javatoolkit.scripts.eclipse_build:main"
diff --git a/src/javatoolkit/scripts/build_xml_rewrite.py b/src/javatoolkit/scripts/build_xml_rewrite.py
deleted file mode 100755
index 7fe8abc..0000000
--- a/src/javatoolkit/scripts/build_xml_rewrite.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python3
-
-import sys, os
-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('-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]))
-
- gcp = options.gcp
- gcp_str = '${gentoo.classpath}'
- gcp_sub = et.Element('classpath', path=gcp_str)
-
- for file in args:
- if os.path.getsize(file) == 0 : continue
- tree = et.ElementTree(file=file)
- if gcp or options.encoding:
- for javac in tree.iter('javac'):
- if gcp:
- javac.attrib['classpath'] = gcp_str
- if options.encoding:
- javac.attrib['encoding'] = options.encoding
- for javadoc in tree.iter('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.iter(elem):
- e.attrib[attr] = value
- for junit in tree.iter('junit'):
- if gcp:
- junit.append(gcp_sub)
- junit.attrib['haltonfailure'] = 'true'
-
- with open(file, 'wb') as f:
- tree.write(f)
-
-
-if __name__ == '__main__':
- main()
diff --git a/src/javatoolkit/scripts/xml_rewrite.py b/src/javatoolkit/scripts/xml_rewrite.py
deleted file mode 100755
index bb9141c..0000000
--- a/src/javatoolkit/scripts/xml_rewrite.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2004 Gentoo Foundation
-# Distributed under the terms of the GNU General Public Licence v2
-
-
-import sys
-from xml.dom.minidom import parse
-from optparse import OptionParser, make_option
-from xml.dom import NotFoundErr
-
-
-class IOWrapper:
- def __init__(self, object):
- self.stream = object
-
- def stream(self):
- return self.stream
-
- def write(self, data):
- if self.stream == sys.stdin:
- sys.stdout.write(data.encode('utf-8'))
- else:
- file = open(self.stream, 'w')
- file.write(data.encode('utf-8'))
- file.close()
-
-
-class Rewriter:
- def __init__(self, stream):
- self.stream = stream
- self.document = parse(stream.stream)
-
- def modifyAttribute(self, elementTag, attribute, value, index=None):
- matches = self.document.getElementsByTagName(elementTag)
- if matches:
- if index is None:
- for match in matches:
- match.setAttribute(attribute, value)
- else:
- matches[index].setAttribute(attribute, value)
-
- def deleteAttribute(self, elementTag, attribute, index=None):
- matches = self.document.getElementsByTagName(elementTag)
- if matches:
- if index is None:
- for match in matches:
- try:
- match.removeAttribute(attribute)
- except NotFoundErr:
- continue
- else:
- try:
- matches[index].removeAttribute(attribute)
- except NotFoundErr:
- return
-
- def write(self):
- self.stream.write(self.document.toxml())
-
-
-def main():
- 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 <java@gentoo.org> with problems.\n"
- usage += "\n"
- usage += "Usage:\n"
- usage += " xml-rewrite.py [-f] --delete -e tag [-e tag] -a attribute [-i index]\n"
- usage += " xml-rewrite.py [-f] --change -e tag [-e tag] -a attribute -v value [-i index]\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)
-
- 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.")
- ]
-
- 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()
- error("No action was specified.")
-
- if options.doAdd and options.doDelete:
- error("Unable to perform multiple actions simultaneously.")
-
- if not options.elements or not options.attribute:
- error("At least one element and attribute must be specified.")
-
- if options.doAdd and not options.value:
- 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()
diff --git a/src/javatoolkit/scripts/xml_rewrite_2.py b/src/javatoolkit/scripts/xml_rewrite_2.py
deleted file mode 100755
index b953675..0000000
--- a/src/javatoolkit/scripts/xml_rewrite_2.py
+++ /dev/null
@@ -1,396 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2004-2020 Gentoo Authors
-# Distributed under the terms of the GNU General Public License v2
-
-
-import io
-import sys
-
-from optparse import OptionParser, make_option
-
-import xml.sax.handler
-from xml.sax.saxutils import XMLGenerator, escape, quoteattr
-
-from ..xml import sax
-
-
-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)
-
-
-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 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
- self.attributes = attributes
- self.values = values
- self.sourceElems = sourceElems
- self.sourceAttributes = sourceAttributes
- self.sourceValues = sourceValues
- self.targetElems = targetElems
- self.targetAttributes = targetAttributes
- self.targetValues = targetValues
-
- def p(self, str):
- self.__write(str)
-
- 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()
-
- parser.StartElementHandler = self.start_element
- parser.EndElementHandler = self.end_element
- parser.CharacterDataHandler = self.char_data
- parser.ParseFile(in_stream)
- self.p('\n')
-
- def start_element(self, name, attrs):
- StreamRewriterBase(self, name, iter(attrs.items()))
-
- def end_element(self, name):
- self.p('</%s>' % name)
-
- def char_data(self, data):
- self.p(escape(data))
-
-
-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=[]):
- if not sourceElems:
- sourceElems = []
- if not sourceAttributes:
- sourceAttributes = []
- if not sourceValues:
- sourceValues = []
- if not targetElems:
- targetElems = []
- if not targetAttributes:
- targetAttributes = []
- if not targetValues:
- targetValues = []
- if not index:
- index = 0
- 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):
- sax.parse(in_stream, content_handler=self, features={xml.sax.handler.feature_external_ges: 1})
- self.p('\n')
-
- def startElement(self, name, attrs):
- self.start_element(name, list(attrs.items()))
-
-
-def main():
- usage = """Copyright 2004, 2006, 2007, 2017 Gentoo Foundation
-Distributed under the terms of the GNU General Public Licence v2
-
-Reach out to the Gentoo Java Team <java@gentoo.org> for questions/problems.
-
-Usage:
- xml-rewrite-2.py [-f file] --delete [-g] -e tag [-e tag] -a attribute [-a attribute] [-i index]
- xml-rewrite-2.py [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value]
- xml-rewrite-2.py [-f file] -g
-
-Additional parameters:
- [--source-element tag] [--source-attribute attribute --source-value value]
- [--target-element tag] [--target-attribute attribute --target-value value] [-i index]
-
-If the -f parameter is not used, the script will read and
-write to stdin and stdout respectively. The use of quotes on
-parameters will break the script."""
-
- def error(message):
- print("ERROR: " + message)
- sys.exit(1)
-
- 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.")
-
- # 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))
-
- with open(os.path.basename(file), 'r') as f:
- if options.gentoo_classpath:
- rewriter.process(f, add_gentoo_classpath)
- else:
- rewriter.process(f)
-
- os.chdir(cwd)
-
- # Then write it back out to the file
- with open(file, 'w') as f:
- rewriter.write(f)
-
- else:
- if options.gentoo_classpath:
- rewriter.process(sys.stdin, add_gentoo_classpath)
- else:
- rewriter.process(sys.stdin)
- rewriter.write(sys.stdout)
-
-
-if __name__ == '__main__':
- main()
diff --git a/src/javatoolkit/scripts/xml_rewrite_3.py b/src/javatoolkit/scripts/xml_rewrite_3.py
deleted file mode 100755
index 61a06fd..0000000
--- a/src/javatoolkit/scripts/xml_rewrite_3.py
+++ /dev/null
@@ -1,340 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2004-2008 Gentoo Foundation
-# Distributed under the terms of the GNU General Public Licence v2
-
-
-import os
-import sys
-import io
-from optparse import OptionParser, make_option
-from ..xml.DomRewriter import DomRewriter
-from ..xml.SaxRewriter import SaxRewriter
-
-
-def main():
- usage = """Copyright 2004, 2006, 2007, 2017 Gentoo Foundation
-Distributed under the terms of the GNU General Public Licence v2
-
-Reach out to the Gentoo Java Team <java@gentoo.org> for questions/problems.
-
-Usage:
- xml-rewrite-3.py [-f file] --delete [-g] -n tag [-n tag] -m attribute [-m attribute] [-i index]
- xml-rewrite-3.py [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value]
- xml-rewrite-3.py [-f file] --javadoc --source-directory dir [--source-directory dir2] --output-directory dir3
- xml-rewrite-3.py [-f file] --maven-cleaning
- xml-rewrite-3.py [-f file] -g
-
-Additional parameters:
- [--source-element tag] [--source-attribute attribute --source-value value]
- [--target-element tag] [--target-attribute attribute --target-value value] [-i index]
-
-Multiple actions can be done simultaneously.
-
-If the -f parameter is not used, the script will read and
-write to stdin and stdout respectively. The use of quotes on
-parameters will break the script."""
-
- def error(message):
- print("ERROR: " + message)
- sys.exit(1)
-
- # instream is a string
- def doRewrite(rewriter, in_stream, callback=None, **kwargs):
- if callback:
- rewriter.process(in_stream, callback, **kwargs)
- else:
- rewriter.process(in_stream, **kwargs)
-
- out = io.StringIO()
- rewriter.write(out)
- return out.getvalue()
-
- def processActions(options, f):
- out_stream = f.read()
- 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)
-
- 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)
-
- 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.
- if options.index:
- 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
- )
- out_stream = doRewrite(
- rewriter, out_stream, rewriter.modify_elements)
-
- if options.doMaven:
- if options.mavenMultiProjectsDirs:
- for elem in options.mavenMultiProjectsDirs:
- newcp += ":" + elem
-
- rewriter = DomRewriter()
- 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)
-
- 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)")
- ]
-
- 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 and not options.doJavadoc and not options.doMaven:
- print(usage)
- print()
- error("No action was specified.")
-
- 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.")
-
- 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 options.doJavadoc:
- if len(options.src_dirs or []) < 1:
- error("You must specify as least one src directory.")
-
- for dir in options.src_dirs:
- if not os.path.isdir(dir):
- error("You must specify existing directory for src output")
-
- if len(options.javadoc_dir or []) != 1:
- error("You must specify one and only one javadoc output directory.")
-
- if not os.path.isdir(options.javadoc_dir[0]):
- error("You must specify an existing directory for javadoc output")
-
- if options.doDelete:
- 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.")
- # 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
- 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")
- outxml = processActions(options, f)
- os.chdir(cwd)
- f.close()
- # Then write it back to the file
- f = open(file, "w")
- f.write(outxml)
- f.close()
-
- else:
- outxml = processActions(options, sys.stdin)
- sys.stdout.write(outxml)
-
-
-if __name__ == '__main__':
- main()
diff --git a/src/javatoolkit/xml/DomRewriter.py b/src/javatoolkit/xml/DomRewriter.py
deleted file mode 100644
index d1200b6..0000000
--- a/src/javatoolkit/xml/DomRewriter.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# -*- coding: UTF-8 -*-
-# Copyright 2004-2008 Gentoo Foundation
-# Distributed under the terms of the GNU General Public License v2
-
-from xml.dom import NotFoundErr
-
-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.
- """
- def __init__(self, modifyElems = None, attributes = None , values=None, index=None):
- self.modifyElems = modifyElems
- self.attributes = attributes
- self.values = values
- self.index = index
-
-
- def delete_elements(self, document, **kwargs):
- if not self.modifyElems:
- return
-
- tomodify = []
- for tag in self.modifyElems:
- matches = document.getElementsByTagName(tag)
- if matches:
- if self.index == None:
- for match in matches:
- tomodify.append(match)
- else:
- tomodify.append(matches[self.index])
-
- for elem in tomodify:
- 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 add_gentoo_classpath(self,document,**kwargs):
- if 'classpath' not in kwargs or not kwargs['classpath']:
- return
-
- cp = document.createElement("classpath")
- cp.setAttribute("path", kwargs['classpath'])
- last_parent = None
-
- # Add our classpath element to every node already containing a classpath element.
- for match in document.getElementsByTagName("classpath"):
- if last_parent != match.parentNode:
- match.parentNode.appendChild(cp.cloneNode(True))
- last_parent = match.parentNode
-
- # Add our classpath element to every javac node we missed earlier.
- for match in document.getElementsByTagName("javac") + document.getElementsByTagName("xjavac"):
- if not match.getElementsByTagName("classpath"):
- match.appendChild(cp.cloneNode(True))
-
-
- def process(self,in_stream,callback=None,*args,**kwargs):
- from xml.dom import minidom
- self.document = minidom.parseString(in_stream);
-
- if callback:
- callback(self.document,*args,**kwargs)
-
-
- def write(self,stream):
- stream.write(self.document.toxml('utf-8').decode('utf-8'))
-
-# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/src/javatoolkit/xml/SaxRewriter.py b/src/javatoolkit/xml/SaxRewriter.py
deleted file mode 100644
index 96d8345..0000000
--- a/src/javatoolkit/xml/SaxRewriter.py
+++ /dev/null
@@ -1,133 +0,0 @@
-# -*- coding: UTF-8 -*-
-# Copyright 2004-2020 Gentoo Authors
-# Distributed under the terms of the GNU General Public License v2
-
-import io
-import os
-import sys
-
-import xml.sax.handler
-from xml.sax.saxutils import XMLGenerator
-from xml.sax.saxutils import quoteattr
-
-from . import sax
-
-class SaxRewriter(XMLGenerator):
- """
- 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, **kwds):
- 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 = 'deleteElems' in kwds and kwds['deleteElems'] or []
- self.deleteAttributes = 'deleteAttributes' in kwds and kwds['deleteAttributes'] or []
-
- 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 = io.StringIO()
-
- XMLGenerator.__init__(self, self.buffer, 'UTF-8')
-
-
- def add_gentoo_javadoc(self, name, attrs):
- self.p('<%s ' % name)
- for a,v in list(attrs.items()):
- self.write_attr(a,v)
-
- self.p('>')
-
- if name == "project":
- javadoc_str = """
- <target name=\"gentoojavadoc\" >
- <mkdir dir=\"""" + self.output_dir + """\" />
- <javadoc
- destdir=\"""" + self.output_dir + """\"
- author="true"
- version="true"
- use="true"
- windowtitle="javadoc">
- """
-
- for src_dir in self.src_dirs:
- javadoc_str += """
- <fileset dir=\"""" + src_dir + """\" defaultexcludes="yes">
- <include name="**/*.java"/>
- </fileset>
- """
-
- javadoc_str += """
- </javadoc>
- </target>
- """
-
- 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('<%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 list(attrs.items()):
- if not (
- (match and a in self.attributes)
- or (matchSource and a in self.sourceAttributes)
- or (matchTarget and a in self.targetAttributes)
- or (matchDelete and a in self.deleteAttributes)
- ):
- 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 char_data(self, data):
- self.p(escape(data))
-
-
- def write(self, out_stream):
- value = self.buffer.getvalue()
- out_stream.write(value)
- self.buffer.truncate(0)
-
-
- def p(self,str):
- self.buffer.write(str)
-
-
- def write_attr(self,a,v):
- self.p('%s=%s ' % (a,quoteattr(v, {'©':'©'})))
-
-
- def process(self, in_stream, callback):
- self.startElement = callback
- sax.parse_string(in_stream.encode('UTF8'), content_handler=self, features={xml.sax.handler.feature_external_ges: 1})
- self.p('\n')
-
-# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap:
diff --git a/src/javatoolkit/xml/__init__.py b/src/javatoolkit/xml/__init__.py
deleted file mode 100644
index f7f2910..0000000
--- a/src/javatoolkit/xml/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright(c) 2007, Gentoo Foundation
-# Licensed under the GNU General Public License, v2
-
-if __name__ == "__main__":
- print("This is not an executable module")
diff --git a/src/javatoolkit/xml/sax.py b/src/javatoolkit/xml/sax.py
deleted file mode 100644
index d3d2a4c..0000000
--- a/src/javatoolkit/xml/sax.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright 2020 Gentoo Authors
-# Distributed under the terms of the GNU General Public License v2
-
-import io
-import xml.sax
-import xml.sax.xmlreader
-
-def _make_parser(*, content_handler=None, dtd_handler=None, entity_resolver=None, error_handler=None, locale=None, features=None, properties=None):
- parser = xml.sax.make_parser()
-
- if content_handler is not None:
- parser.setContentHandler(content_handler)
- if dtd_handler is not None:
- parser.setDTDHandler(dtd_handler)
- if entity_resolver is not None:
- parser.setEntityResolver(entity_resolver)
- if error_handler is not None:
- parser.setErrorHandler(error_handler)
- if locale is not None:
- parser.setLocale(locale)
- if features is not None:
- for feature, value in features.items():
- parser.setFeature(feature, value)
- if properties is not None:
- for property, value in properties.items():
- parser.setProperty(property, value)
-
- return parser
-
-def parse(source, *, content_handler=None, dtd_handler=None, entity_resolver=None, error_handler=None, locale=None, features=None, properties=None):
- parser = _make_parser(content_handler=content_handler, dtd_handler=dtd_handler, entity_resolver=entity_resolver, error_handler=error_handler, locale=locale, features=features, properties=properties)
-
- parser.parse(source)
-
-def parse_string(string, *, content_handler=None, dtd_handler=None, entity_resolver=None, error_handler=None, locale=None, features=None, properties=None):
- parser = _make_parser(content_handler=content_handler, dtd_handler=dtd_handler, entity_resolver=entity_resolver, error_handler=error_handler, locale=locale, features=features, properties=properties)
-
- inputsource = xml.sax.xmlreader.InputSource()
- if isinstance(string, str):
- inputsource.setCharacterStream(io.StringIO(string))
- else:
- inputsource.setByteStream(io.BytesIO(string))
-
- parser.parse(inputsource)
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2025-02-15 10:18 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-02-15 10:18 [gentoo-commits] proj/javatoolkit:master commit in: src/javatoolkit/scripts/, src/javatoolkit/xml/, / Arthur Zamarin
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox