diff --git a/pretty_c14n.py b/pretty_c14n.py new file mode 100755 index 0000000000000000000000000000000000000000..f986044980f777001bc723b7d59d4f216a473b6d --- /dev/null +++ b/pretty_c14n.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +import sys +from trans import pretty_c14n + +def error_and_exit(x): + print('ERROR: ', str(x), file=sys.stderr) + sys.exit(1) + +if len(sys.argv) < 3: + error_and_exit('too few arguments') +if sys.argv[1] == sys.argv[2]: + error_and_exit('"infile" and "outfile" must be different') + +infile = sys.argv[1] +outfile = sys.argv[2] + +try: + with open(infile, 'r') as f1: + xml = f1.read() + with open(outfile, 'w') as f2: + err, xml = pretty_c14n(xml) + if err: + error_and_exit(xml) + f2.write(xml) +except Exception as error: + error_and_exit(error) + +print('\nFile »' + infile + '« was successfully canonized to file »' + \ + outfile + '«\n') + +sys.exit(0) diff --git a/trans.py b/trans.py index 7b21703adad1f8a865e00a3549b2acc2bbc0792a..d2729add498e0775d528bba1314c07eaef5ca9ee 100644 --- a/trans.py +++ b/trans.py @@ -9,6 +9,20 @@ config = utils.config from pprint import pprint +def pretty_c14n(_xml): + xml = _xml + err = False + try: + xml = etree.canonicalize(xml, with_comments=True, strip_text=True) + # Bad side-effect of "prettify_xml": adds XML declaration again + xml = prettify_xml(xml, indent=2, debug=False) + xml = etree.canonicalize(xml, with_comments=True) + except Exception as error: + xml = str(error) + err = True + + return err, xml + def cert_to_xml(cert_doc): dcc_template = config['main_xml_template'] ###pprint(config) @@ -22,12 +36,12 @@ def cert_to_xml(cert_doc): cert_doc['DCC']['administrativeData']['dccSoftware'].append(s) try: xml = render_template(dcc_template, doc=cert_doc['DCC'], utils=utils) - xml = etree.canonicalize(xml, with_comments=True, strip_text=True) - # Bad side-effect: adds XML declaration again - xml = prettify_xml(xml, indent=2, debug=False) - xml = etree.canonicalize(xml, with_comments=True) + err, xml = pretty_c14n(xml) + if err: + xml = '<error>' + xml + '</error>\n' + except Exception as error: xml = '<error>' + str(error) + '</error>\n' - + return xml