1#************************************************************** 2# 3# Licensed to the Apache Software Foundation (ASF) under one 4# or more contributor license agreements. See the NOTICE file 5# distributed with this work for additional information 6# regarding copyright ownership. The ASF licenses this file 7# to you under the Apache License, Version 2.0 (the 8# "License"); you may not use this file except in compliance 9# with the License. You may obtain a copy of the License at 10# 11# http://www.apache.org/licenses/LICENSE-2.0 12# 13# Unless required by applicable law or agreed to in writing, 14# software distributed under the License is distributed on an 15# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16# KIND, either express or implied. See the License for the 17# specific language governing permissions and limitations 18# under the License. 19# 20#************************************************************** 21 22# usage: validate.py <outdir> <val.json> 23# Validates every package in <outdir> against ODF 1.2 as written, against ODF 1.3 and 1.4 with an office:version or 24# manifest:version of 1.2 or 1.3 rewritten to the target ("13", "14"; any other version stays and is reported), and against 25# ODF 1.2, 1.3 and 1.4 after removing foreign elements and attributes ("12x", "13x", "14x"; Part 1 2.2.2 B.1; manifest left 26# as written apart from the version). 27import sys, os, re, zipfile, subprocess, json, shutil, importlib.util 28 29D = os.path.dirname(os.path.abspath(__file__)) 30JING = ["java", "-jar", os.environ.get("ODFV_JING", "/Applications/XMLauthor/lib/jing.jar"), "-i"] 31SCH = {"12": (D + "/schema/OpenDocument-v1.2-os-schema.rng", D + "/schema/OpenDocument-v1.2-os-manifest-schema.rng"), 32 "13": (D + "/schema/OpenDocument-v1.3-schema.rng", D + "/schema/OpenDocument-v1.3-manifest-schema.rng"), 33 "14": (D + "/schema/OpenDocument-v1.4-schema.rng", D + "/schema/OpenDocument-v1.4-manifest-schema.rng")} 34SCH["12x"] = SCH["12"] 35SCH["13x"] = SCH["13"] 36SCH["14x"] = SCH["14"] 37VERSIONS = ("12", "14", "12x", "13", "13x", "14x") 38_spec = importlib.util.spec_from_file_location("foreign", D + "/foreign.py") 39foreign = importlib.util.module_from_spec(_spec) 40_spec.loader.exec_module(foreign) 41STREAMS = {"content.xml", "styles.xml", "meta.xml", "settings.xml"} 42# ODF 1.2 Part 1 2.2.1 B.4: a content.xml rooted at MathML is validated against MathML, not ODF 43ERR = re.compile(r"^(.*?):(\d+):(\d+): (error|fatal|warning): (.*)$") 44 45 46def root_is_mathml(text): 47 body = re.sub(r'<\?xml[^>]*\?>|<!DOCTYPE[^>]*>|<!--.*?-->', '', text[:4000], flags=re.S).lstrip() 48 return bool(re.match(r'<(?:[\w.-]+:)?math[\s>/]', body)) 49 50 51def main(): 52 outdir, valjson = sys.argv[1], sys.argv[2] 53 work = os.path.abspath(valjson[:-5] + ".xml") 54 if not work.startswith(os.path.join(D, "runs") + os.sep): 55 sys.exit("validate.py: <val.json> must live under " + os.path.join(D, "runs")) 56 shutil.rmtree(work, ignore_errors=True) 57 files = {v: ([], []) for v in VERSIONS} 58 mixed = {v: foreign.mixed_elements(SCH[v][0]) for v in ("12x", "13x", "14x")} 59 skipped, bad_zip = [], [] 60 pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith(".")) 61 for pkg in pkgs: 62 try: 63 z = zipfile.ZipFile(os.path.join(outdir, pkg)) 64 except Exception: 65 bad_zip.append(pkg); continue 66 for name in z.namelist(): 67 is_mani = name == "META-INF/manifest.xml" 68 if name.rsplit("/", 1)[-1] not in STREAMS and not is_mani: 69 continue 70 text = z.read(name).decode("utf-8") 71 if not is_mani and name.endswith("content.xml") and root_is_mathml(text): 72 skipped.append(pkg + "/" + name); continue 73 for v in VERSIONS: 74 t = text 75 if v in mixed and not is_mani: 76 t = foreign.strip_foreign(t, mixed[v]) 77 if v in ("13", "13x", "14", "14x"): 78 attr = "manifest:version" if is_mani else "office:version" 79 t = re.sub(attr + '="1\\.[23]"', attr + '="1.%s"' % v[1], t, count=1) 80 p = os.path.join(work, v, pkg, name) 81 os.makedirs(os.path.dirname(p), exist_ok=True) 82 open(p, "w", encoding="utf-8").write(t) 83 files[v][1 if is_mani else 0].append(p) 84 errors = {} 85 for v in VERSIONS: 86 errs = [] 87 for schema, fl in ((SCH[v][0], files[v][0]), (SCH[v][1], files[v][1])): 88 while fl: 89 batch = fl[:400] 90 r = subprocess.run(JING + [schema] + batch, capture_output=True, text=True) 91 fl = fl[400:] 92 for line in (r.stdout + r.stderr).splitlines(): 93 m = ERR.match(line) 94 if m: 95 errs.append([os.path.relpath(m.group(1), os.path.join(work, v)), int(m.group(2)), int(m.group(3)), m.group(5)]) 96 # a fatal error stops jing: resume with the files after the one that caused it 97 if m.group(4) == "fatal" and m.group(1) in batch: 98 fl = batch[batch.index(m.group(1)) + 1:] + fl 99 elif line.strip(): 100 errs.append(["?", 0, 0, line.strip()]) 101 errors[v] = errs 102 json.dump({"packages": pkgs, "bad_zip": bad_zip, "mathml_skipped": skipped, 103 "nfiles": len(files["12"][0]) + len(files["12"][1]), "errors": errors}, open(valjson, "w")) 104 for v in VERSIONS: 105 print(f"ODF {v[0]}.{v[1]}{' extended, foreign content removed' if v.endswith('x') else ''}: {len(errors[v])} errors in {len({e[0].split('/')[0] for e in errors[v]})} of {len(pkgs)} packages") 106 print(f"files validated: {len(files['12'][0]) + len(files['12'][1])}, MathML skipped: {len(skipped)}, bad zips: {bad_zip}") 107 unparsed = [e for v in errors for e in errors[v] if e[0] == "?"] 108 if unparsed: 109 print("UNPARSED jing output:", *[e[3] for e in unparsed[:5]], sep="\n ") 110 111 112main() 113