Gentoo Archives: gentoo-commits

From: Patrice Clement <monsieurp@g.o>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/javatoolkit:master commit in: src/py/
Date: Mon, 07 Aug 2017 23:48:41
Message-Id: 1502148895.a5af39e2e0c3f00226be6a3ca4bacabf6ea39118.monsieurp@gentoo
1 commit: a5af39e2e0c3f00226be6a3ca4bacabf6ea39118
2 Author: Patrice Clement <monsieurp <AT> gentoo <DOT> org>
3 AuthorDate: Mon Aug 7 23:32:12 2017 +0000
4 Commit: Patrice Clement <monsieurp <AT> gentoo <DOT> org>
5 CommitDate: Mon Aug 7 23:34:55 2017 +0000
6 URL: https://gitweb.gentoo.org/proj/javatoolkit.git/commit/?id=a5af39e2
7
8 autopep8 format
9
10 src/py/build-xml-rewrite | 28 ++-
11 src/py/buildparser | 23 +-
12 src/py/class-version-verify.py | 52 +++-
13 src/py/eclipse-build.py | 88 +++++--
14 src/py/findclass | 13 +-
15 src/py/jarjarclean | 3 +-
16 src/py/maven-helper.py | 90 +++++--
17 src/py/xml-rewrite-2.py | 542 ++++++++++++++++++++++++-----------------
18 src/py/xml-rewrite-3.py | 273 ++++++++++++++++-----
19 src/py/xml-rewrite.py | 59 +++--
20 10 files changed, 785 insertions(+), 386 deletions(-)
21
22 diff --git a/src/py/build-xml-rewrite b/src/py/build-xml-rewrite
23 index 229de89..5a67145 100755
24 --- a/src/py/build-xml-rewrite
25 +++ b/src/py/build-xml-rewrite
26 @@ -4,17 +4,28 @@ import sys
27 import xml.etree.cElementTree as et
28 from optparse import OptionParser
29
30 +
31 def main():
32 parser = OptionParser()
33 - parser.add_option('-c', '--changeattributes', dest='change', action="append", nargs=3)
34 - parser.add_option('-g', '--gentooclasspath', dest="gcp", action="store_true", default=False)
35 + parser.add_option(
36 + '-c',
37 + '--changeattributes',
38 + dest='change',
39 + action="append",
40 + nargs=3)
41 + parser.add_option(
42 + '-g',
43 + '--gentooclasspath',
44 + dest="gcp",
45 + action="store_true",
46 + default=False)
47 parser.add_option('-e', '--encoding', dest="encoding")
48 (options, args) = parser.parse_args()
49
50 changes = []
51 if options.change:
52 for c in options.change:
53 - changes.append((c[0].split(),c[1], c[2]))
54 + changes.append((c[0].split(), c[1], c[2]))
55
56 gcp = options.gcp
57 gcp_str = '${gentoo.classpath}'
58 @@ -26,8 +37,8 @@ def main():
59 for javac in tree.getiterator('javac'):
60 if gcp:
61 javac.attrib['classpath'] = gcp_str
62 - if options.encoding:
63 - javac.attrib['encoding'] = options.encoding
64 + if options.encoding:
65 + javac.attrib['encoding'] = options.encoding
66 for javadoc in tree.getiterator('javadoc'):
67 if gcp:
68 javadoc.attrib['classpath'] = gcp_str
69 @@ -35,9 +46,9 @@ def main():
70 javadoc.attrib['encoding'] = options.encoding
71 for c in changes:
72 elems, attr, value = c
73 - for elem in elems:
74 - for e in tree.getiterator(elem):
75 - e.attrib[attr] = value
76 + for elem in elems:
77 + for e in tree.getiterator(elem):
78 + e.attrib[attr] = value
79 for junit in tree.getiterator('junit'):
80 if gcp:
81 junit.append(gcp_sub)
82 @@ -46,5 +57,6 @@ def main():
83 with open(file, 'w') as f:
84 tree.write(f)
85
86 +
87 if __name__ == '__main__':
88 main()
89
90 diff --git a/src/py/buildparser b/src/py/buildparser
91 index 7af980d..3007d9b 100755
92 --- a/src/py/buildparser
93 +++ b/src/py/buildparser
94 @@ -16,7 +16,8 @@ from javatoolkit.parser.buildproperties import BuildPropertiesParser
95 from javatoolkit.parser.manifest import ManifestParser
96 from javatoolkit.parser.tree import Node, ParseError
97
98 -__author__ = ["James Le Cuirot <chewi@××××××××××××××.uk>", "Karl Trygve Kalleberg <karltk@g.o>"]
99 +__author__ = ["James Le Cuirot <chewi@××××××××××××××.uk>",
100 + "Karl Trygve Kalleberg <karltk@g.o>"]
101 __version__ = "0.3.0"
102 __productname__ = "buildparser"
103 __description__ = "A parser for build.properties and JAR manifest files."
104 @@ -34,14 +35,14 @@ def parse_args():
105 parser = OptionParser(usage, version=about)
106
107 parser.add_option('-t', '--type', action='store', type='choice',
108 - dest='type', choices=['manifest', 'buildprops'],
109 - help='Type of file to parse: manifest or buildprops')
110 + dest='type', choices=['manifest', 'buildprops'],
111 + help='Type of file to parse: manifest or buildprops')
112
113 parser.add_option('-i', '--in-place', action='store_true', dest='in_place',
114 - help='Edit file in place when replacing')
115 + help='Edit file in place when replacing')
116
117 parser.add_option('-w', '--wrap', action='store_true', dest='wrap',
118 - help='Wrap when returning singular values')
119 + help='Wrap when returning singular values')
120
121 opt, args = parser.parse_args()
122
123 @@ -56,6 +57,7 @@ def parse_args():
124
125 return opt, args
126
127 +
128 def main():
129 opt, args = parse_args()
130
131 @@ -78,7 +80,9 @@ def main():
132 p = BuildPropertiesParser()
133
134 else:
135 - sys.exit(__productname__ + ": error: Unknown file type. Specify using the -t option.")
136 + sys.exit(
137 + __productname__ +
138 + ": error: Unknown file type. Specify using the -t option.")
139
140 t = p.parse(f)
141 f.close()
142 @@ -89,7 +93,7 @@ def main():
143 if len(args) > 2:
144 n = t.find_node(args[0])
145
146 - if n != None:
147 + if n is not None:
148 n.value = args[1]
149 else:
150 t.add_kid(Node(args[0], args[1]))
151 @@ -105,7 +109,7 @@ def main():
152 elif len(args) > 1:
153 n = t.find_node(args[0])
154
155 - if n != None:
156 + if n is not None:
157 if opt.wrap:
158 print(p.wrapped_value(n))
159 else:
160 @@ -115,10 +119,11 @@ def main():
161 for x in t.node_names():
162 print(x)
163
164 +
165 if __name__ == '__main__':
166 try:
167 main()
168 except KeyboardInterrupt:
169 print("Interrupted by user, aborting.")
170
171 -#set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
172 +# set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
173
174 diff --git a/src/py/class-version-verify.py b/src/py/class-version-verify.py
175 index fb62ad5..b46d99c 100755
176 --- a/src/py/class-version-verify.py
177 +++ b/src/py/class-version-verify.py
178 @@ -7,20 +7,53 @@
179 #
180 # $Id$
181
182 -import os,sys
183 +import os
184 +import sys
185 from optparse import OptionParser, make_option
186 from javatoolkit.cvv import *
187
188 +
189 def main():
190 options_list = [
191 - make_option ("-r", "--recurse", action="store_true", dest="deep", default=False, help="go into dirs"),
192 - make_option ("-t", "--target", type="string", dest="version", help="target version that is valid"),
193 - make_option ("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print version of every calss"),
194 - make_option ("-s", "--silent", action="store_true", dest="silent", default=False, help="No output"),
195 - make_option ("-f", "--file-only", action="store_true", dest="file_only", default=False, help="Only output the files"),
196 + make_option(
197 + "-r",
198 + "--recurse",
199 + action="store_true",
200 + dest="deep",
201 + default=False,
202 + help="go into dirs"),
203 + make_option(
204 + "-t",
205 + "--target",
206 + type="string",
207 + dest="version",
208 + help="target version that is valid"),
209 + make_option(
210 + "-v",
211 + "--verbose",
212 + action="store_true",
213 + dest="verbose",
214 + default=False,
215 + help="Print version of every calss"),
216 + make_option(
217 + "-s",
218 + "--silent",
219 + action="store_true",
220 + dest="silent",
221 + default=False,
222 + help="No output"),
223 + make_option(
224 + "-f",
225 + "--file-only",
226 + action="store_true",
227 + dest="file_only",
228 + default=False,
229 + help="Only output the files"),
230 ]
231
232 - parser = OptionParser("%prog -t version [-r] [-v] [-s] <class/jar files or dir>", options_list)
233 + parser = OptionParser(
234 + "%prog -t version [-r] [-v] [-s] <class/jar files or dir>",
235 + options_list)
236 (options, args) = parser.parse_args()
237
238 if not options.version:
239 @@ -53,12 +86,15 @@ def main():
240 for set in cvv.bad:
241 print("Bad: %s %s %s" % set)
242
243 - print("CVV: %s\nChecked: %i Good: %i Bad: %i" % (options.version, len(cvv.good)+len(cvv.bad) , len(cvv.good), len(cvv.bad)))
244 + print("CVV: %s\nChecked: %i Good: %i Bad: %i" %
245 + (options.version, len(cvv.good) +
246 + len(cvv.bad), len(cvv.good), len(cvv.bad)))
247
248 if len(cvv.bad) > 0:
249 sys.exit(1)
250 else:
251 sys.exit(0)
252
253 +
254 if __name__ == '__main__':
255 main()
256
257 diff --git a/src/py/eclipse-build.py b/src/py/eclipse-build.py
258 index ab65307..3baa23f 100755
259 --- a/src/py/eclipse-build.py
260 +++ b/src/py/eclipse-build.py
261 @@ -23,32 +23,57 @@ if __name__ == '__main__':
262 usage += "\nJust wait till I finish this."
263
264 option_list = [
265 - make_option ( '-p', '--project', action='store', dest='project', help='Project Name' ),
266 - make_option ( '-i', '--include', action='append', dest='includes', help='Files to include in jar' ),
267 - make_option ( '-s', '--src', action='append', dest='source', help='Directories containing src to build' ),
268 - make_option ( '-m', '--manifest', action='store', dest='manifest', help='Manifest File' ),
269 - make_option ( '-f', '--file', action='store', dest='file', help='Eclipse build.properties file to parse.' ),
270 - make_option ( '-o', '--output', action='store', dest='output', help='Output build.xml to this file' )
271 + make_option(
272 + '-p',
273 + '--project',
274 + action='store',
275 + dest='project',
276 + help='Project Name'),
277 + make_option(
278 + '-i',
279 + '--include',
280 + action='append',
281 + dest='includes',
282 + help='Files to include in jar'),
283 + make_option('-s', '--src', action='append', dest='source',
284 + help='Directories containing src to build'),
285 + make_option(
286 + '-m',
287 + '--manifest',
288 + action='store',
289 + dest='manifest',
290 + help='Manifest File'),
291 + make_option('-f', '--file', action='store', dest='file',
292 + help='Eclipse build.properties file to parse.'),
293 + make_option(
294 + '-o',
295 + '--output',
296 + action='store',
297 + dest='output',
298 + help='Output build.xml to this file')
299 ]
300
301 - parser = OptionParser( usage, option_list )
302 + parser = OptionParser(usage, option_list)
303 (options, args) = parser.parse_args()
304 - #check parser options here.
305 + # check parser options here.
306
307 if options.file:
308 - properties = PropertiesParser( options.file )
309 + properties = PropertiesParser(options.file)
310 #dom = parse( options.file )
311 #classpathentries = dom.getElementsByTagName('classpathentry')
312
313 - #for entry in classpathentries:
314 + # for entry in classpathentries:
315 # if entry.attributes['kind'] and entry.attributes['kind'].nodeValue == 'src':
316 # print entry.attributes['path'].nodeValue
317 # if entry.attributes['path']:
318 # src_dirs.append( entry.attributes['path'].nodeValue )
319
320 - with open( options.output, 'w' ) as output:
321 + with open(options.output, 'w') as output:
322 output.write('<?xml version="1.0" encoding="UTF-8" ?>\n')
323 - output.write('<project basedir="." default="jar" name="'+options.project+'">\n')
324 + output.write(
325 + '<project basedir="." default="jar" name="' +
326 + options.project +
327 + '">\n')
328 output.write('<property name="target" value="1.4"/>\n')
329 output.write('<property name="source" value="1.4"/>\n')
330 output.write('<property name="gentoo.classpath" value="" />\n\n')
331 @@ -58,46 +83,55 @@ if __name__ == '__main__':
332 try:
333 if properties.config['source..']:
334 for dir in properties.config['source..']:
335 - output.write('<fileset dir="'+dir+'" excludes="**/*.java, **/*.launch" />\n')
336 + output.write(
337 + '<fileset dir="' +
338 + dir +
339 + '" excludes="**/*.java, **/*.launch" />\n')
340 if properties.config['bin.includes']:
341 for item in properties.config['bin.includes']:
342 if item != '.':
343 if item.endswith('/'):
344 item = item.rstrip('/')
345 - output.write('<fileset dir="." includes="'+item+'/**" excludes="**/*.java, **/*.launch" />\n')
346 + output.write(
347 + '<fileset dir="." includes="' +
348 + item +
349 + '/**" excludes="**/*.java, **/*.launch" />\n')
350 else:
351 - output.write('<fileset file="'+item+'" />\n')
352 + output.write(
353 + '<fileset file="' + item + '" />\n')
354 finally:
355 output.write('</copy>\n')
356 if options.includes:
357 for file in options.includes:
358 - output.write('<copy file="'+file+'" todir="bin"/>')
359 + output.write('<copy file="' + file + '" todir="bin"/>')
360 output.write('</target>\n')
361 - output.write('\n<target name="clean">\n\t<delete dir="bin"/>\n</target>\n\n')
362 + output.write(
363 + '\n<target name="clean">\n\t<delete dir="bin"/>\n</target>\n\n')
364 output.write('<target depends="init" name="compile">\n')
365 - output.write('<javac destdir="bin" source="${source}" target="${target}" classpath="${gentoo.classpath}">\n')
366 + output.write(
367 + '<javac destdir="bin" source="${source}" target="${target}" classpath="${gentoo.classpath}">\n')
368 try:
369 if properties.config['source..']:
370 for dir in properties.config['source..']:
371 - output.write('\t<src path="'+dir+'" />\n')
372 + output.write('\t<src path="' + dir + '" />\n')
373 finally:
374 output.write('</javac>\n')
375 output.write('</target>\n\n')
376 output.write('<target depends="compile" name="jar" >\n')
377 output.write('<jar file="${ant.project.name}.jar" basedir="bin"')
378 if options.manifest:
379 - output.write('\nmanifest="'+parser.manifest+'">\n')
380 + output.write('\nmanifest="' + parser.manifest + '">\n')
381 else:
382 output.write('>\n')
383 output.write('</jar>\n')
384 output.write('</target>\n')
385 output.write('</project>\n')
386 - #output.write('')
387 - #output.write('')
388 - #output.write('')
389 - #output.write('')
390 - #output.write('')
391 - #output.write('')
392 - #output.write('')
393 + # output.write('')
394 + # output.write('')
395 + # output.write('')
396 + # output.write('')
397 + # output.write('')
398 + # output.write('')
399 + # output.write('')
400
401 # vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap :
402
403 diff --git a/src/py/findclass b/src/py/findclass
404 index 0581acc..98575e6 100755
405 --- a/src/py/findclass
406 +++ b/src/py/findclass
407 @@ -47,17 +47,20 @@ def main():
408
409 jarcmd = find_exec('jar')
410
411 - javapaths = [ f.replace('.', '/') for f in files ]
412 - matchers = [ re.compile(p) for p in javapaths ]
413 + javapaths = [f.replace('.', '/') for f in files]
414 + matchers = [re.compile(p) for p in javapaths]
415
416 for pkg in get_all_packages():
417 - if opt.verbose: print("Searching package %s" % pkg)
418 + if opt.verbose:
419 + print("Searching package %s" % pkg)
420 for jar in collect_packages(pkg).split(':'):
421 - if opt.verbose: print("Searching jar %s" % jar)
422 + if opt.verbose:
423 + print("Searching jar %s" % jar)
424 status, out = getstatusoutput("%s tvf %s" % (jarcmd, jar))
425 for m in matchers:
426 if m.search(out):
427 - if opt.verbose: print("Found in %s" % pkg, end=' ')
428 + if opt.verbose:
429 + print("Found in %s" % pkg, end=' ')
430 print(jar)
431
432
433
434 diff --git a/src/py/jarjarclean b/src/py/jarjarclean
435 index 3effaec..2b95969 100755
436 --- a/src/py/jarjarclean
437 +++ b/src/py/jarjarclean
438 @@ -23,7 +23,8 @@ def main():
439
440 for elem in tree.getiterator():
441 for child in list(elem):
442 - if child.tag == 'taskdef' and child.get('classname') == 'com.tonicsystems.jarjar.JarJarTask':
443 + if child.tag == 'taskdef' and child.get(
444 + 'classname') == 'com.tonicsystems.jarjar.JarJarTask':
445 tags.append(child.get('name'))
446 elem.remove(child)
447
448
449 diff --git a/src/py/maven-helper.py b/src/py/maven-helper.py
450 index 9aa41cc..cf924f6 100755
451 --- a/src/py/maven-helper.py
452 +++ b/src/py/maven-helper.py
453 @@ -40,13 +40,11 @@ def main():
454 usage += "write to stdin and stdout respectively. The use of quotes on\n"
455 usage += "parameters will break the script.\n"
456
457 -
458 def error(message):
459 print("ERROR: " + message)
460 sys.exit(1)
461
462 -
463 - def doAction(stream,options):
464 + def doAction(stream, options):
465 pom = MavenPom(options)
466 if options.p_rewrite:
467 pom.parse(stream, pom.rewrite)
468 @@ -54,7 +52,6 @@ def main():
469 pom.parse(stream, pom.getDescription)
470 return pom
471
472 -
473 def run():
474 if options.files:
475 import os
476 @@ -62,16 +59,16 @@ def main():
477 # First parse the file into memory
478 cwd = os.getcwd()
479 dirname = os.path.dirname(file)
480 - if dirname != '': # for file comes out as ''
481 + if dirname != '': # for file comes out as ''
482 os.chdir(os.path.dirname(file))
483
484 - f = open(os.path.basename(file),"r")
485 + f = open(os.path.basename(file), "r")
486 fs = f.read()
487 f.close()
488 # parse file and return approtiate pom object
489 - pom = doAction(fs,options)
490 + pom = doAction(fs, options)
491 if options.p_rewrite:
492 - f = open(os.path.basename(file),"w")
493 + f = open(os.path.basename(file), "w")
494 f.write(pom.read())
495 f.close()
496 else:
497 @@ -79,22 +76,72 @@ def main():
498 os.chdir(cwd)
499 else:
500 # process stdin
501 - pom = doAction(sys.stdin.read(),options)
502 + pom = doAction(sys.stdin.read(), options)
503 print(pom.read())
504
505
506 ############### MAIN ###############
507 options_list = [
508 - make_option ("-a", "--artifact", action="store_true", dest="p_artifact", help="get artifact name."),
509 - make_option ("-c", "--classpath", action="append", dest="classpath", help="set classpath to use with maven."),
510 - make_option ("-s", "--source", action="append", dest="p_source", help="Java source version."),
511 - make_option ("-t", "--target", action="append", dest="p_target", help="Java target version."),
512 - make_option ("-d", "--depependencies" , action="store_true", dest="p_dep", help="get dependencies infos"),
513 - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"),
514 - make_option ("-g", "--group" , action="store_true", dest="p_group", help="get artifact group."),
515 - make_option ("-r", "--rewrite", action="store_true", dest="p_rewrite", help="rewrite poms to use our classpath"),
516 - make_option ("-p", "--ischild", action="store_true", dest="p_ischild", help="return true if this is a child pom"),
517 - make_option ("-v", "--version" , action="store_true", dest="p_version", help="get artifact version."),
518 + make_option(
519 + "-a",
520 + "--artifact",
521 + action="store_true",
522 + dest="p_artifact",
523 + help="get artifact name."),
524 + make_option(
525 + "-c",
526 + "--classpath",
527 + action="append",
528 + dest="classpath",
529 + help="set classpath to use with maven."),
530 + make_option(
531 + "-s",
532 + "--source",
533 + action="append",
534 + dest="p_source",
535 + help="Java source version."),
536 + make_option(
537 + "-t",
538 + "--target",
539 + action="append",
540 + dest="p_target",
541 + help="Java target version."),
542 + make_option(
543 + "-d",
544 + "--depependencies",
545 + action="store_true",
546 + dest="p_dep",
547 + help="get dependencies infos"),
548 + make_option(
549 + "-f",
550 + "--file",
551 + action="append",
552 + dest="files",
553 + help="Transform files instead of operating on stdout and stdin"),
554 + make_option(
555 + "-g",
556 + "--group",
557 + action="store_true",
558 + dest="p_group",
559 + help="get artifact group."),
560 + make_option(
561 + "-r",
562 + "--rewrite",
563 + action="store_true",
564 + dest="p_rewrite",
565 + help="rewrite poms to use our classpath"),
566 + make_option(
567 + "-p",
568 + "--ischild",
569 + action="store_true",
570 + dest="p_ischild",
571 + help="return true if this is a child pom"),
572 + make_option(
573 + "-v",
574 + "--version",
575 + action="store_true",
576 + dest="p_version",
577 + help="get artifact version."),
578 ]
579
580 parser = OptionParser(usage, options_list)
581 @@ -111,7 +158,7 @@ def main():
582 error("Please specify only one pom at a time.")
583
584 if options.p_rewrite:
585 - valid_sources = ["1.4","1.5"]
586 + valid_sources = ["1.4", "1.5"]
587 for source in valid_sources:
588 if options.p_source:
589 if len(options.p_source) != 1:
590 @@ -127,7 +174,7 @@ def main():
591 # join any classpathes if any
592 if options.classpath:
593 if len(options.classpath) > 1:
594 - start =[]
595 + start = []
596 start.append(options.classpath[0])
597 for item in options.classpath[1:]:
598 start[0] += ":%s" % (item)
599 @@ -137,5 +184,6 @@ def main():
600 # main loop
601 run()
602
603 +
604 if __name__ == '__main__':
605 main()
606
607 diff --git a/src/py/xml-rewrite-2.py b/src/py/xml-rewrite-2.py
608 index 5c8aa6b..46b4bfd 100755
609 --- a/src/py/xml-rewrite-2.py
610 +++ b/src/py/xml-rewrite-2.py
611 @@ -22,181 +22,189 @@
612
613 import sys
614 import io
615 -from xml.sax.saxutils import quoteattr,escape
616 +from xml.sax.saxutils import quoteattr, escape
617 from optparse import OptionParser, make_option
618
619
620 def add_gentoo_classpath(document):
621 - matches = document.getElementsByTagName("classpath")
622 - gcp = document.createElement("location")
623 - gcp.setAttribute("path","${gentoo.classpath}")
624 -
625 - handled_refs = set()
626 - for match in matches:
627 - if match.hasAttribute("refid"):
628 - refid = match.getAttribute("refid")
629 - for ref in document.getElementsByTagName("path"):
630 - id = ref.getAttribute("id")
631 - if id not in handled_refs and id == refid:
632 - gcp = document.createElement("pathelement")
633 - gcp.setAttribute("path","${gentoo.classpath}")
634 - ref.appendChild(gcp)
635 - handled_refs.add(id)
636 - else:
637 - match.appendChild(gcp)
638 + matches = document.getElementsByTagName("classpath")
639 + gcp = document.createElement("location")
640 + gcp.setAttribute("path", "${gentoo.classpath}")
641 +
642 + handled_refs = set()
643 + for match in matches:
644 + if match.hasAttribute("refid"):
645 + refid = match.getAttribute("refid")
646 + for ref in document.getElementsByTagName("path"):
647 + id = ref.getAttribute("id")
648 + if id not in handled_refs and id == refid:
649 + gcp = document.createElement("pathelement")
650 + gcp.setAttribute("path", "${gentoo.classpath}")
651 + ref.appendChild(gcp)
652 + handled_refs.add(id)
653 + else:
654 + match.appendChild(gcp)
655 +
656
657 class DomRewriter:
658 - """
659 - The old DOM rewriter is still around for index based stuff. It can
660 - be used for all the complex stuff but portage needed features should
661 - be in StreamRewriterBase subclasses as they are much faster.
662 - """
663 - from xml.dom import NotFoundErr
664 -
665 - def __init__(self, modifyElems, attributes, values=None, index=None):
666 - self.modify = modifyElems
667 - self.attributes = attributes
668 - self.values = values
669 - self.index = index
670 -
671 - def change_elem(self, elem):
672 - for i,attr in enumerate(self.attributes):
673 - if self.values:
674 - elem.setAttribute(attr, self.values[i])
675 - else:
676 - try:
677 - elem.removeAttribute(attr)
678 - except DomRewriter.NotFoundErr:
679 - continue
680 -
681 - def process(self,in_stream,callback=None):
682 - from xml.dom.minidom import parse
683 -
684 - self.document = parse(in_stream);
685 -
686 - if callback:
687 - callback(self.document)
688 -
689 - if not self.modify:
690 - return
691 -
692 - for tag in self.modify:
693 - matches = self.document.getElementsByTagName(tag)
694 - if matches:
695 - if self.index == None:
696 - for match in matches:
697 - self.change_elem(match)
698 - else:
699 - self.change_elem(matches[self.index])
700 -
701 - def write(self,stream):
702 - stream.write(self.document.toxml())
703 + """
704 + The old DOM rewriter is still around for index based stuff. It can
705 + be used for all the complex stuff but portage needed features should
706 + be in StreamRewriterBase subclasses as they are much faster.
707 + """
708 + from xml.dom import NotFoundErr
709 +
710 + def __init__(self, modifyElems, attributes, values=None, index=None):
711 + self.modify = modifyElems
712 + self.attributes = attributes
713 + self.values = values
714 + self.index = index
715 +
716 + def change_elem(self, elem):
717 + for i, attr in enumerate(self.attributes):
718 + if self.values:
719 + elem.setAttribute(attr, self.values[i])
720 + else:
721 + try:
722 + elem.removeAttribute(attr)
723 + except DomRewriter.NotFoundErr:
724 + continue
725 +
726 + def process(self, in_stream, callback=None):
727 + from xml.dom.minidom import parse
728 +
729 + self.document = parse(in_stream)
730 +
731 + if callback:
732 + callback(self.document)
733 +
734 + if not self.modify:
735 + return
736 +
737 + for tag in self.modify:
738 + matches = self.document.getElementsByTagName(tag)
739 + if matches:
740 + if self.index is None:
741 + for match in matches:
742 + self.change_elem(match)
743 + else:
744 + self.change_elem(matches[self.index])
745 +
746 + def write(self, stream):
747 + stream.write(self.document.toxml())
748 +
749
750 class StreamRewriterBase:
751 - def __init__(self, elems, attributes, values, index,
752 - sourceElems = [], sourceAttributes = [], sourceValues = [],
753 - targetElems = [], targetAttributes = [], targetValues = [] ):
754 - self.buffer = io.StringIO()
755 - self.__write = self.buffer.write
756 - self.elems = elems or []
757 - self.attributes = attributes or []
758 - self.values = values or []
759 - self.sourceElems = sourceElems or []
760 - self.sourceAttributes = sourceAttributes or []
761 - self.sourceValues = sourceValues or []
762 - self.targetElems = targetElems or []
763 - self.targetAttributes = targetAttributes or []
764 - self.targetValues = targetValues or []
765 -
766 - def p(self,str):
767 - self.__write(str.encode('utf8'))
768 -
769 - def write(self, out_stream):
770 - value = self.buffer.getvalue()
771 - out_stream.write(value)
772 - self.buffer.truncate(0)
773 -
774 - def write_attr(self,a,v):
775 - self.p('%s=%s ' % (a,quoteattr(v, {'©':'&#169;'})))
776 -
777 - def start_element(self, name, attrs):
778 - self.p('<%s ' % name)
779 -
780 - match = ( name in self.elems )
781 - matchSource = ( name in self.sourceElems )
782 - matchTarget = ( name in self.targetElems )
783 -
784 - for a,v in attrs:
785 - if not (
786 - (match and a in self.attributes)
787 - or (matchSource and a in self.sourceAttributes)
788 - or (matchTarget and a in self.targetAttributes)
789 - ):
790 - self.write_attr(a,v)
791 -
792 - if matchSource:
793 - for i, attr in enumerate(self.sourceAttributes):
794 - self.write_attr(attr, self.sourceValues[i])
795 -
796 - if matchTarget:
797 - for i, attr in enumerate(self.targetAttributes):
798 - self.write_attr(attr, self.targetValues[i])
799 -
800 - if match:
801 - for i, attr in enumerate(self.attributes):
802 - self.write_attr(attr, self.values[i])
803 -
804 - self.p('>')
805 + def __init__(self, elems, attributes, values, index,
806 + sourceElems=[], sourceAttributes=[], sourceValues=[],
807 + targetElems=[], targetAttributes=[], targetValues=[]):
808 + self.buffer = io.StringIO()
809 + self.__write = self.buffer.write
810 + self.elems = elems or []
811 + self.attributes = attributes or []
812 + self.values = values or []
813 + self.sourceElems = sourceElems or []
814 + self.sourceAttributes = sourceAttributes or []
815 + self.sourceValues = sourceValues or []
816 + self.targetElems = targetElems or []
817 + self.targetAttributes = targetAttributes or []
818 + self.targetValues = targetValues or []
819 +
820 + def p(self, str):
821 + self.__write(str.encode('utf8'))
822 +
823 + def write(self, out_stream):
824 + value = self.buffer.getvalue()
825 + out_stream.write(value)
826 + self.buffer.truncate(0)
827 +
828 + def write_attr(self, a, v):
829 + self.p('%s=%s ' % (a, quoteattr(v, {'©': '&#169;'})))
830 +
831 + def start_element(self, name, attrs):
832 + self.p('<%s ' % name)
833 +
834 + match = (name in self.elems)
835 + matchSource = (name in self.sourceElems)
836 + matchTarget = (name in self.targetElems)
837 +
838 + for a, v in attrs:
839 + if not (
840 + (match and a in self.attributes)
841 + or (matchSource and a in self.sourceAttributes)
842 + or (matchTarget and a in self.targetAttributes)
843 + ):
844 + self.write_attr(a, v)
845 +
846 + if matchSource:
847 + for i, attr in enumerate(self.sourceAttributes):
848 + self.write_attr(attr, self.sourceValues[i])
849 +
850 + if matchTarget:
851 + for i, attr in enumerate(self.targetAttributes):
852 + self.write_attr(attr, self.targetValues[i])
853 +
854 + if match:
855 + for i, attr in enumerate(self.attributes):
856 + self.write_attr(attr, self.values[i])
857 +
858 + self.p('>')
859 +
860
861 class ExpatRewriter(StreamRewriterBase):
862 - """
863 - The only problem with this Expat based implementation is that it does not
864 - handle entities doctypes etc properly so for example dev-java/skinlf fails.
865 - """
866 - def process(self, in_stream):
867 - from xml.parsers.expat import ParserCreate
868 - parser = ParserCreate()
869 + """
870 + The only problem with this Expat based implementation is that it does not
871 + handle entities doctypes etc properly so for example dev-java/skinlf fails.
872 + """
873
874 - parser.StartElementHandler = self.start_element
875 - parser.EndElementHandler = self.end_element
876 - parser.CharacterDataHandler = self.char_data
877 - parser.ParseFile(in_stream)
878 - self.p('\n')
879 + def process(self, in_stream):
880 + from xml.parsers.expat import ParserCreate
881 + parser = ParserCreate()
882
883 - def start_element(self, name, attrs):
884 - StreamRewriterBase(self, name, iter(attrs.items()))
885 + parser.StartElementHandler = self.start_element
886 + parser.EndElementHandler = self.end_element
887 + parser.CharacterDataHandler = self.char_data
888 + parser.ParseFile(in_stream)
889 + self.p('\n')
890
891 - def end_element(self,name):
892 - self.p('</%s>' % name)
893 + def start_element(self, name, attrs):
894 + StreamRewriterBase(self, name, iter(attrs.items()))
895 +
896 + def end_element(self, name):
897 + self.p('</%s>' % name)
898 +
899 + def char_data(self, data):
900 + self.p(escape(data))
901
902 - def char_data(self,data):
903 - self.p(escape(data))
904
905 from xml.sax.saxutils import XMLGenerator
906 +
907 +
908 class SaxRewriter(XMLGenerator, StreamRewriterBase):
909 - """
910 - Using Sax gives us the support for writing back doctypes and all easily
911 - and is only marginally slower than expat as it is just a tight layer over it
912 - """
913 - def __init__(self, elems, attributes, values, index,
914 - sourceElems = [], sourceAttributes = [], sourceValues = [],
915 - targetElems = [], targetAttributes = [], targetValues = []):
916 - StreamRewriterBase.__init__(self, elems, attributes, values, index,
917 - sourceElems, sourceAttributes, sourceValues,
918 - targetElems, targetAttributes, targetValues)
919 - XMLGenerator.__init__(self, self.buffer, 'UTF-8')
920 -
921 - def process(self, in_stream):
922 - from xml.sax import parse
923 - parse(in_stream, self)
924 - self.p('\n')
925 -
926 - def startElement(self, name, attrs):
927 - self.start_element(name, list(attrs.items()))
928 + """
929 + Using Sax gives us the support for writing back doctypes and all easily
930 + and is only marginally slower than expat as it is just a tight layer over it
931 + """
932 +
933 + def __init__(self, elems, attributes, values, index,
934 + sourceElems=[], sourceAttributes=[], sourceValues=[],
935 + targetElems=[], targetAttributes=[], targetValues=[]):
936 + StreamRewriterBase.__init__(self, elems, attributes, values, index,
937 + sourceElems, sourceAttributes, sourceValues,
938 + targetElems, targetAttributes, targetValues)
939 + XMLGenerator.__init__(self, self.buffer, 'UTF-8')
940 +
941 + def process(self, in_stream):
942 + from xml.sax import parse
943 + parse(in_stream, self)
944 + self.p('\n')
945 +
946 + def startElement(self, name, attrs):
947 + self.start_element(name, list(attrs.items()))
948 +
949
950 def main():
951 - usage = "XML Rewrite Python Module Version " + __version__ + "\n"
952 - usage += "Copyright 2004,2006,2007 Gentoo Foundation\n"
953 + usage = "Copyright 2004,2006,2007 Gentoo Foundation\n"
954 usage += "Distributed under the terms of the GNU General Public Lincense v2\n"
955 usage += "Please contact the Gentoo Java Team <java@g.o> with problems.\n"
956 usage += "\n"
957 @@ -213,95 +221,177 @@ def main():
958 usage += "parameters will break the script.\n"
959
960 def error(message):
961 - print("ERROR: " + message)
962 - sys.exit(1)
963 + print("ERROR: " + message)
964 + sys.exit(1)
965
966 # if len(sys.argv) == 1:
967 # usage(True)
968 options_list = [
969 - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"),
970 - make_option ("-g", "--gentoo-classpath", action="store_true", dest="gentoo_classpath", help="Rewrite build.xml to use gentoo.classpath where applicable."),
971 - 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."),
972 - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."),
973 - 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."),
974 - 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"),
975 - make_option ("-v", "--value", action="append", dest="values", help="Value to set the attribute to."),
976 - 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."),
977 - 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)"),
978 - make_option ("-y", "--source-value", action="append", dest="source_values", help="Value to set the attribute to. (sourceonly)"),
979 - 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."),
980 - 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)"),
981 - make_option ("-l", "--target-value", action="append", dest="target_values", help="Value to set the attribute to (targeronly)."),
982 - 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.")
983 + make_option(
984 + "-f",
985 + "--file",
986 + action="append",
987 + dest="files",
988 + help="Transform files instead of operating on stdout and stdin"),
989 + make_option(
990 + "-g",
991 + "--gentoo-classpath",
992 + action="store_true",
993 + dest="gentoo_classpath",
994 + help="Rewrite build.xml to use gentoo.classpath where applicable."),
995 + make_option(
996 + "-c",
997 + "--change",
998 + action="store_true",
999 + dest="doAdd",
1000 + default=False,
1001 + help="Change the value of an attribute. If it does not exist, it will be created."),
1002 + make_option(
1003 + "-d",
1004 + "--delete",
1005 + action="store_true",
1006 + dest="doDelete",
1007 + default=False,
1008 + help="Delete an attribute from matching elements."),
1009 + make_option(
1010 + "-e",
1011 + "--element",
1012 + action="append",
1013 + dest="elements",
1014 + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."),
1015 + make_option(
1016 + "-a",
1017 + "--attribute",
1018 + action="append",
1019 + dest="attributes",
1020 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"),
1021 + make_option(
1022 + "-v",
1023 + "--value",
1024 + action="append",
1025 + dest="values",
1026 + help="Value to set the attribute to."),
1027 + make_option(
1028 + "-r",
1029 + "--source-element",
1030 + action="append",
1031 + dest="source_elements",
1032 + help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."),
1033 + make_option(
1034 + "-t",
1035 + "--source-attribute",
1036 + action="append",
1037 + dest="source_attributes",
1038 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"),
1039 + make_option(
1040 + "-y",
1041 + "--source-value",
1042 + action="append",
1043 + dest="source_values",
1044 + help="Value to set the attribute to. (sourceonly)"),
1045 + make_option(
1046 + "-j",
1047 + "--target-element",
1048 + action="append",
1049 + dest="target_elements",
1050 + help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."),
1051 + make_option(
1052 + "-k",
1053 + "--target-attribute",
1054 + action="append",
1055 + dest="target_attributes",
1056 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"),
1057 + make_option(
1058 + "-l",
1059 + "--target-value",
1060 + action="append",
1061 + dest="target_values",
1062 + help="Value to set the attribute to (targeronly)."),
1063 + make_option(
1064 + "-i",
1065 + "--index",
1066 + type="int",
1067 + dest="index",
1068 + help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero.")
1069 ]
1070
1071 parser = OptionParser(usage, options_list)
1072 (options, args) = parser.parse_args()
1073 - # Invalid Arguments Must be smited!
1074 + # Invalid Arguments Must be smited!
1075 if not options.doAdd and not options.doDelete and not options.gentoo_classpath:
1076 - print(usage)
1077 - print()
1078 - error("No action was specified.")
1079 + print(usage)
1080 + print()
1081 + error("No action was specified.")
1082
1083 if not options.gentoo_classpath:
1084 - if options.doAdd and options.doDelete:
1085 - error("Unable to perform multiple actions simultaneously.")
1086 - if not options.elements and not options.target_elements and not options.source_elements:
1087 - error("At least one element (global, source only or target only) and attribute must be specified.")
1088 - for elem in ( options.source_attributes or [] ):
1089 - if elem in ( options.attributes or [] ):
1090 - error("You can't set an attribute in global and source scope at the same time")
1091 - for elem in ( options.target_attributes or [] ):
1092 - if elem in ( options.attributes or [] ):
1093 - error("You can't set an attribute in global and target scope at the same time")
1094 - if options.doAdd and (len(options.values or []) != len(options.attributes or [])
1095 - or len(options.source_values or [] ) != len(options.source_attributes or [])
1096 - or len(options.target_values or [] ) != len(options.target_attributes or [])):
1097 - error("You must give attribute(s)/value(s) for every element you are changing.")
1098 -
1099 - # End Invalid Arguments Check
1100 + if options.doAdd and options.doDelete:
1101 + error("Unable to perform multiple actions simultaneously.")
1102 + if not options.elements and not options.target_elements and not options.source_elements:
1103 + error(
1104 + "At least one element (global, source only or target only) and attribute must be specified.")
1105 + for elem in (options.source_attributes or []):
1106 + if elem in (options.attributes or []):
1107 + error(
1108 + "You can't set an attribute in global and source scope at the same time")
1109 + for elem in (options.target_attributes or []):
1110 + if elem in (options.attributes or []):
1111 + error(
1112 + "You can't set an attribute in global and target scope at the same time")
1113 + if options.doAdd and (len(options.values or []) != len(options.attributes or [])
1114 + or len(options.source_values or []) != len(options.source_attributes or [])
1115 + or len(options.target_values or []) != len(options.target_attributes or [])):
1116 + error(
1117 + "You must give attribute(s)/value(s) for every element you are changing.")
1118 +
1119 + # End Invalid Arguments Check
1120
1121 def get_rewriter(options):
1122 - if options.index or options.doDelete or options.gentoo_classpath:
1123 - # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter
1124 - # and let the DomRewriter do these. Also keeps the index option compatible for sure.
1125 - rewriter = DomRewriter(options.elements, options.attributes, options.values, options.index)
1126 - else:
1127 - rewriter = SaxRewriter(options.elements, options.attributes, options.values, options.index,
1128 - options.source_elements, options.source_attributes, options.source_values,
1129 - options.target_elements, options.target_attributes, options.target_values)
1130 - return rewriter
1131 + if options.index or options.doDelete or options.gentoo_classpath:
1132 + # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter
1133 + # and let the DomRewriter do these. Also keeps the index option
1134 + # compatible for sure.
1135 + rewriter = DomRewriter(
1136 + options.elements,
1137 + options.attributes,
1138 + options.values,
1139 + options.index)
1140 + else:
1141 + rewriter = SaxRewriter(options.elements, options.attributes, options.values, options.index,
1142 + options.source_elements, options.source_attributes, options.source_values,
1143 + options.target_elements, options.target_attributes, options.target_values)
1144 + return rewriter
1145
1146 rewriter = get_rewriter(options)
1147
1148 if options.files:
1149 - import os
1150 - for file in options.files:
1151 - print("Rewriting %s" % file)
1152 - # First parse the file into memory
1153 - # Tricks with cwd are needed for relative includes of other xml files to build.xml files
1154 - cwd = os.getcwd()
1155 - dirname = os.path.dirname(file)
1156 - if dirname != '': # for file = build.xml comes out as ''
1157 - os.chdir(os.path.dirname(file))
1158 - f = open(os.path.basename(file),"r")
1159 - if options.gentoo_classpath:
1160 - rewriter.process(f,add_gentoo_classpath)
1161 - else:
1162 - rewriter.process(f)
1163 - os.chdir(cwd)
1164 - f.close()
1165 - # Then write it back to the file
1166 - f = open(file, "w")
1167 - rewriter.write(f)
1168 - f.close()
1169 + import os
1170 + for file in options.files:
1171 + print("Rewriting %s" % file)
1172 + # First parse the file into memory
1173 + # Tricks with cwd are needed for relative includes of other xml
1174 + # files to build.xml files
1175 + cwd = os.getcwd()
1176 + dirname = os.path.dirname(file)
1177 + if dirname != '': # for file = build.xml comes out as ''
1178 + os.chdir(os.path.dirname(file))
1179 + f = open(os.path.basename(file), "r")
1180 + if options.gentoo_classpath:
1181 + rewriter.process(f, add_gentoo_classpath)
1182 + else:
1183 + rewriter.process(f)
1184 + os.chdir(cwd)
1185 + f.close()
1186 + # Then write it back to the file
1187 + f = open(file, "w")
1188 + rewriter.write(f)
1189 + f.close()
1190
1191 else:
1192 - if options.gentoo_classpath:
1193 - rewriter.process(sys.stdin,add_gentoo_classpath)
1194 - else:
1195 - rewriter.process(sys.stdin)
1196 - rewriter.write(sys.stdout)
1197 + if options.gentoo_classpath:
1198 + rewriter.process(sys.stdin, add_gentoo_classpath)
1199 + else:
1200 + rewriter.process(sys.stdin)
1201 + rewriter.write(sys.stdout)
1202
1203
1204 if __name__ == '__main__':
1205
1206 diff --git a/src/py/xml-rewrite-3.py b/src/py/xml-rewrite-3.py
1207 index 549443b..82255c9 100755
1208 --- a/src/py/xml-rewrite-3.py
1209 +++ b/src/py/xml-rewrite-3.py
1210 @@ -39,12 +39,15 @@ def main():
1211 usage += "Please contact the Gentoo Java Team <java@g.o> with problems.\n"
1212 usage += "\n"
1213 usage += "Usage:\n"
1214 - usage += " " + sys.argv[0] + " [-f file] --delete [-g] -n tag [-n tag] -m attribute [-m attribute] [-i index]\n"
1215 - usage += " " + sys.argv[0] + " [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value] \\\n"
1216 + usage += " " + \
1217 + sys.argv[0] + " [-f file] --delete [-g] -n tag [-n tag] -m attribute [-m attribute] [-i index]\n"
1218 + usage += " " + \
1219 + sys.argv[0] + " [-f file] --change [-g] -e tag [-e tag] -a attribute -v value [-a attribute -v value] \\\n"
1220 usage += " [--source-element tag] [--source-attribute attribute --source-value value] \\\n"
1221 usage += " [--target-element tag] [--target-attribute attribute --target-value value] [-i index]\n"
1222 usage += "Or:\n"
1223 - usage += " " + sys.argv[0] + " [-f file] --javadoc --source-directory dir [--source-directory dir2] --output-directory dir3 \n"
1224 + usage += " " + \
1225 + sys.argv[0] + " [-f file] --javadoc --source-directory dir [--source-directory dir2] --output-directory dir3 \n"
1226 usage += "Or:\n"
1227 usage += " " + sys.argv[0] + " [-f file] -g\n"
1228 usage += "\n"
1229 @@ -64,7 +67,6 @@ def main():
1230 print("ERROR: " + message)
1231 sys.exit(1)
1232
1233 -
1234 # instream is a string
1235 def doRewrite(rewriter, in_stream, callback=None, **kwargs):
1236 if callback:
1237 @@ -76,81 +78,213 @@ def main():
1238 rewriter.write(out)
1239 return out.getvalue()
1240
1241 -
1242 def processActions(options, f):
1243 out_stream = f.read()
1244 - newcp="${gentoo.classpath}"
1245 + newcp = "${gentoo.classpath}"
1246 if options.gentoo_classpath:
1247 - rewriter = DomRewriter(options.elements, options.attributes, options.values, options.index)
1248 - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_classpath,classpath = newcp)
1249 + rewriter = DomRewriter(
1250 + options.elements,
1251 + options.attributes,
1252 + options.values,
1253 + options.index)
1254 + out_stream = doRewrite(
1255 + rewriter,
1256 + out_stream,
1257 + rewriter.add_gentoo_classpath,
1258 + classpath=newcp)
1259
1260 if options.doJavadoc:
1261 - rewriter = SaxRewriter(src_dirs = options.src_dirs, output_dir = options.javadoc_dir[0])
1262 - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_javadoc)
1263 + rewriter = SaxRewriter(
1264 + src_dirs=options.src_dirs,
1265 + output_dir=options.javadoc_dir[0])
1266 + out_stream = doRewrite(
1267 + rewriter, out_stream, rewriter.add_gentoo_javadoc)
1268
1269 if options.doAdd or options.doDelete:
1270 # java-ant-2.eclass does not use these options so we can optimize the ExpatWriter
1271 - # and let the DomRewriter do these. Also keeps the index option compatible for sure.
1272 + # and let the DomRewriter do these. Also keeps the index option
1273 + # compatible for sure.
1274 if options.index:
1275 - rewriter = DomRewriter(options.delete_elements, options.delete_attributes, options.values, options.index)
1276 - out_stream = doRewrite(rewriter, out_stream, rewriter.delete_elements)
1277 + rewriter = DomRewriter(
1278 + options.delete_elements,
1279 + options.delete_attributes,
1280 + options.values,
1281 + options.index)
1282 + out_stream = doRewrite(
1283 + rewriter, out_stream, rewriter.delete_elements)
1284 else:
1285 rewriter = SaxRewriter(
1286 - elems = options.elements,
1287 - attributes = options.attributes,
1288 - values = options.values,
1289 - sourceElems = options.source_elements,
1290 - sourceAttributes = options.source_attributes,
1291 - sourceValues = options.source_values,
1292 - targetElems = options.target_elements,
1293 - targetAttributes = options.target_attributes,
1294 - targetValues = options.target_values,
1295 - deleteElems = options.delete_elements,
1296 - deleteAttributes = options.delete_attributes
1297 + elems=options.elements,
1298 + attributes=options.attributes,
1299 + values=options.values,
1300 + sourceElems=options.source_elements,
1301 + sourceAttributes=options.source_attributes,
1302 + sourceValues=options.source_values,
1303 + targetElems=options.target_elements,
1304 + targetAttributes=options.target_attributes,
1305 + targetValues=options.target_values,
1306 + deleteElems=options.delete_elements,
1307 + deleteAttributes=options.delete_attributes
1308 )
1309 - out_stream = doRewrite(rewriter, out_stream, rewriter.modify_elements)
1310 + out_stream = doRewrite(
1311 + rewriter, out_stream, rewriter.modify_elements)
1312
1313 if options.doMaven:
1314 if options.mavenMultiProjectsDirs:
1315 for elem in options.mavenMultiProjectsDirs:
1316 - newcp+=":"+elem
1317 + newcp += ":" + elem
1318
1319 rewriter = DomRewriter()
1320 - out_stream = doRewrite(rewriter, out_stream, rewriter.add_gentoo_classpath, classpath = newcp)
1321 + out_stream = doRewrite(
1322 + rewriter,
1323 + out_stream,
1324 + rewriter.add_gentoo_classpath,
1325 + classpath=newcp)
1326
1327 deleteElems = []
1328 deleteAttributes = []
1329 deleteElems.append("target")
1330 deleteAttributes.append("depends")
1331 - rewriter = SaxRewriter( deleteElems = deleteElems, deleteAttributes = deleteAttributes)
1332 - out_stream = doRewrite(rewriter, out_stream, rewriter.modify_elements)
1333 + rewriter = SaxRewriter(
1334 + deleteElems=deleteElems,
1335 + deleteAttributes=deleteAttributes)
1336 + out_stream = doRewrite(
1337 + rewriter, out_stream, rewriter.modify_elements)
1338
1339 return out_stream
1340
1341 -
1342 options_list = [
1343 - 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"),
1344 - 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."),
1345 - 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."),
1346 - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."),
1347 - 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."),
1348 - make_option ("-f", "--file", action="append", dest="files", help="Transform files instead of operating on stdout and stdin"),
1349 - make_option ("-g", "--gentoo-classpath", action="store_true", dest="gentoo_classpath", help="Rewrite build.xml to use gentoo.classpath where applicable."),
1350 - 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."),
1351 - 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."),
1352 - 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)"),
1353 - make_option ("-l", "--target-value", action="append", dest="target_values", help="Value to set the attribute to (targeronly)."),
1354 - 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"),
1355 - 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."),
1356 - make_option ("-o", "--output-directory", action="append", dest="javadoc_dir", help="javadoc output directory. Must be an existing directory"),
1357 - make_option ("-p", "--source-directory", action="append", dest="src_dirs", help="source directory for javadoc generation. Must be an existing directory"),
1358 - make_option ("-q", "--maven-cleaning", action="store_true", dest="doMaven", default=False, help="Turns on maven generated build.xml cleanup rewriting."),
1359 - 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."),
1360 - make_option ("-s", "--multi-project-dirs", action="append", dest="mavenMultiProjectsDirs", help="Dirs in classpath notation"),
1361 -
1362 - 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)"),
1363 - make_option ("-v", "--value", action="append", dest="values", help="Value to set the attribute to."),
1364 - make_option ("-y", "--source-value", action="append", dest="source_values", help="Value to set the attribute to. (sourceonly)")
1365 + make_option(
1366 + "-a",
1367 + "--attribute",
1368 + action="append",
1369 + dest="attributes",
1370 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs"),
1371 + make_option(
1372 + "-b",
1373 + "--target-element",
1374 + action="append",
1375 + dest="target_elements",
1376 + help="Tag of the element of which the attributes to be changed just in target scope. These can be chained for multiple elements."),
1377 + make_option(
1378 + "-c",
1379 + "--change",
1380 + action="store_true",
1381 + dest="doAdd",
1382 + default=False,
1383 + help="Change the value of an attribute. If it does not exist, it will be created."),
1384 + make_option(
1385 + "-d",
1386 + "--delete",
1387 + action="store_true",
1388 + dest="doDelete",
1389 + default=False,
1390 + help="Delete an attribute from matching elements."),
1391 + make_option(
1392 + "-e",
1393 + "--element",
1394 + action="append",
1395 + dest="elements",
1396 + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."),
1397 + make_option(
1398 + "-f",
1399 + "--file",
1400 + action="append",
1401 + dest="files",
1402 + help="Transform files instead of operating on stdout and stdin"),
1403 + make_option(
1404 + "-g",
1405 + "--gentoo-classpath",
1406 + action="store_true",
1407 + dest="gentoo_classpath",
1408 + help="Rewrite build.xml to use gentoo.classpath where applicable."),
1409 + make_option(
1410 + "-i",
1411 + "--index",
1412 + type="int",
1413 + dest="index",
1414 + help="Index of the match. If none is specified, the changes will be applied to all matches within the document. Starts from zero."),
1415 + make_option(
1416 + "-j",
1417 + "--javadoc",
1418 + action="store_true",
1419 + dest="doJavadoc",
1420 + default=False,
1421 + help="add a basic javadoc target. Sources must be placed in ${WORKDIR}/javadoc_src."),
1422 + make_option(
1423 + "-k",
1424 + "--target-attribute",
1425 + action="append",
1426 + dest="target_attributes",
1427 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for targetonly)"),
1428 + make_option(
1429 + "-l",
1430 + "--target-value",
1431 + action="append",
1432 + dest="target_values",
1433 + help="Value to set the attribute to (targeronly)."),
1434 + make_option(
1435 + "-m",
1436 + "--delete-attribute",
1437 + action="append",
1438 + dest="delete_attributes",
1439 + help="Attribute of the matching elements to delete. These can be chained for multiple value-attribute pairs"),
1440 + make_option(
1441 + "-n",
1442 + "--delete-element",
1443 + action="append",
1444 + dest="delete_elements",
1445 + help="Tag of the element of which the attributes to be deleted. These can be chained for multiple elements."),
1446 + make_option(
1447 + "-o",
1448 + "--output-directory",
1449 + action="append",
1450 + dest="javadoc_dir",
1451 + help="javadoc output directory. Must be an existing directory"),
1452 + make_option(
1453 + "-p",
1454 + "--source-directory",
1455 + action="append",
1456 + dest="src_dirs",
1457 + help="source directory for javadoc generation. Must be an existing directory"),
1458 + make_option(
1459 + "-q",
1460 + "--maven-cleaning",
1461 + action="store_true",
1462 + dest="doMaven",
1463 + default=False,
1464 + help="Turns on maven generated build.xml cleanup rewriting."),
1465 + make_option(
1466 + "-r",
1467 + "--source-element",
1468 + action="append",
1469 + dest="source_elements",
1470 + help="Tag of the element of which the attributes to be changed just in source scope. These can be chained for multiple elements."),
1471 + make_option(
1472 + "-s",
1473 + "--multi-project-dirs",
1474 + action="append",
1475 + dest="mavenMultiProjectsDirs",
1476 + help="Dirs in classpath notation"),
1477 +
1478 + make_option(
1479 + "-t",
1480 + "--source-attribute",
1481 + action="append",
1482 + dest="source_attributes",
1483 + help="Attribute of the matching elements to change. These can be chained for multiple value-attribute pairs (for source only)"),
1484 + make_option(
1485 + "-v",
1486 + "--value",
1487 + action="append",
1488 + dest="values",
1489 + help="Value to set the attribute to."),
1490 + make_option(
1491 + "-y",
1492 + "--source-value",
1493 + action="append",
1494 + dest="source_values",
1495 + help="Value to set the attribute to. (sourceonly)")
1496 ]
1497 parser = OptionParser(usage, options_list)
1498 (options, args) = parser.parse_args()
1499 @@ -163,20 +297,24 @@ def main():
1500
1501 if options.doAdd:
1502 if not options.elements and not options.target_elements and not options.source_elements:
1503 - error("At least one element (global, source only or target only) and attribute must be specified.")
1504 + error(
1505 + "At least one element (global, source only or target only) and attribute must be specified.")
1506
1507 - for elem in ( options.source_attributes or [] ):
1508 - if elem in ( options.attributes or [] ):
1509 - error("You can't set an attribute in global and source scope at the same time")
1510 + for elem in (options.source_attributes or []):
1511 + if elem in (options.attributes or []):
1512 + error(
1513 + "You can't set an attribute in global and source scope at the same time")
1514
1515 - for elem in ( options.target_attributes or [] ):
1516 - if elem in ( options.attributes or [] ):
1517 - error("You can't set an attribute in global and target scope at the same time")
1518 + for elem in (options.target_attributes or []):
1519 + if elem in (options.attributes or []):
1520 + error(
1521 + "You can't set an attribute in global and target scope at the same time")
1522
1523 if options.doAdd and (len(options.values or []) != len(options.attributes or [])
1524 - or len(options.source_values or [] ) != len(options.source_attributes or [])
1525 - or len(options.target_values or [] ) != len(options.target_attributes or [])):
1526 - error("You must give attribute(s)/value(s) for every element you are changing.")
1527 + or len(options.source_values or []) != len(options.source_attributes or [])
1528 + or len(options.target_values or []) != len(options.target_attributes or [])):
1529 + error(
1530 + "You must give attribute(s)/value(s) for every element you are changing.")
1531
1532 if options.doJavadoc:
1533 if len(options.src_dirs or []) < 1:
1534 @@ -196,20 +334,21 @@ def main():
1535 if not options.delete_elements:
1536 error("At least one element to delete must be specified.")
1537
1538 - if options.doDelete and ( len(options.attributes or []) < 0):
1539 - error("You must give attribute(s) to delete for every element you are changing.")
1540 + if options.doDelete and (len(options.attributes or []) < 0):
1541 + error(
1542 + "You must give attribute(s) to delete for every element you are changing.")
1543 # End Invalid Arguments Check
1544
1545 -
1546 # main loop
1547 if options.files:
1548 for file in options.files:
1549 print("Rewriting %s" % file)
1550 # First parse the file into memory
1551 - # Tricks with cwd are needed for relative includes of other xml files to build.xml files
1552 + # Tricks with cwd are needed for relative includes of other xml
1553 + # files to build.xml files
1554 cwd = os.getcwd()
1555 dirname = os.path.dirname(file)
1556 - if dirname != '': # for file = build.xml comes out as ''
1557 + if dirname != '': # for file = build.xml comes out as ''
1558 os.chdir(os.path.dirname(file))
1559
1560 f = open(os.path.basename(file), "r")
1561
1562 diff --git a/src/py/xml-rewrite.py b/src/py/xml-rewrite.py
1563 index 6bf8ea2..b164b6e 100755
1564 --- a/src/py/xml-rewrite.py
1565 +++ b/src/py/xml-rewrite.py
1566 @@ -40,12 +40,12 @@ class IOWrapper:
1567 class Rewriter:
1568 def __init__(self, stream):
1569 self.stream = stream
1570 - self.document = parse(stream.stream);
1571 + self.document = parse(stream.stream)
1572
1573 def modifyAttribute(self, elementTag, attribute, value, index=None):
1574 matches = self.document.getElementsByTagName(elementTag)
1575 if matches:
1576 - if index == None:
1577 + if index is None:
1578 for match in matches:
1579 match.setAttribute(attribute, value)
1580 else:
1581 @@ -54,7 +54,7 @@ class Rewriter:
1582 def deleteAttribute(self, elementTag, attribute, index=None):
1583 matches = self.document.getElementsByTagName(elementTag)
1584 if matches:
1585 - if index == None:
1586 + if index is None:
1587 for match in matches:
1588 try:
1589 match.removeAttribute(attribute)
1590 @@ -71,8 +71,7 @@ class Rewriter:
1591
1592
1593 def main():
1594 - usage = "XML Rewrite Python Module Version " + __version__ + "\n"
1595 - usage += "Copyright 2004 Gentoo Foundation\n"
1596 + usage = "Copyright 2004 Gentoo Foundation\n"
1597 usage += "Distributed under the terms of the GNU General Public Lincense v2\n"
1598 usage += "Please contact the Gentoo Java Herd <java@g.o> with problems.\n"
1599 usage += "\n"
1600 @@ -84,7 +83,6 @@ def main():
1601 usage += "write to stdin and stdout respectively. The use of quotes on\n"
1602 usage += "parameters will break the script.\n"
1603
1604 -
1605 def error(message):
1606 print("ERROR: " + message)
1607 sys.exit(1)
1608 @@ -94,13 +92,42 @@ def main():
1609 # usage(True)
1610
1611 options_list = [
1612 - make_option ("-f", "--file", type="string", dest="file", help="Read input from file instead of stdin"),
1613 - 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."),
1614 - make_option ("-d", "--delete", action="store_true", dest="doDelete", default=False, help="Delete an attribute from matching elements."),
1615 - 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."),
1616 - make_option ("-a", "--attribute", type="string", dest="attribute", help="Attribute of the matching elements to change."),
1617 - make_option ("-v", "--value", type="string", dest="value", help="Value to set the attribute to."),
1618 - 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.")
1619 + make_option("-f", "--file", type="string", dest="file",
1620 + help="Read input from file instead of stdin"),
1621 + make_option(
1622 + "-c",
1623 + "--change",
1624 + action="store_true",
1625 + dest="doAdd",
1626 + default=False,
1627 + help="Change the value of an attribute. If it does not exist, it will be created."),
1628 + make_option(
1629 + "-d",
1630 + "--delete",
1631 + action="store_true",
1632 + dest="doDelete",
1633 + default=False,
1634 + help="Delete an attribute from matching elements."),
1635 + make_option(
1636 + "-e",
1637 + "--element",
1638 + action="append",
1639 + dest="elements",
1640 + help="Tag of the element of which the attributes to be changed. These can be chained for multiple elements."),
1641 + make_option(
1642 + "-a",
1643 + "--attribute",
1644 + type="string",
1645 + dest="attribute",
1646 + help="Attribute of the matching elements to change."),
1647 + make_option("-v", "--value", type="string", dest="value",
1648 + help="Value to set the attribute to."),
1649 + make_option(
1650 + "-i",
1651 + "--index",
1652 + type="int",
1653 + dest="index",
1654 + help="Index of the match. If none is specified, the changes will be applied to all matches within the document.")
1655 ]
1656
1657 parser = OptionParser(usage, options_list)
1658 @@ -135,7 +162,11 @@ def main():
1659
1660 if options.doAdd:
1661 for element in options.elements:
1662 - rewriter.modifyAttribute(element, options.attribute, options.value, options.index)
1663 + rewriter.modifyAttribute(
1664 + element,
1665 + options.attribute,
1666 + options.value,
1667 + options.index)
1668
1669 rewriter.write()