xref: /trunk/test/odf-validate/validate.py (revision 0e16a31d78a652c56c5c0fc79c752f48b9048df9)
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 the version rewritten
24# ("13", "14"), and against ODF 1.2 and 1.3 after removing foreign elements and attributes ("12x", "13x"; Part 1 2.2.2 B.1;
25# manifest left as written apart from the version).
26import sys, os, re, zipfile, subprocess, json, shutil, importlib.util
27
28D = os.path.dirname(os.path.abspath(__file__))
29JING = ["java", "-jar", os.environ.get("ODFV_JING", "/Applications/XMLauthor/lib/jing.jar"), "-i"]
30SCH = {"12": (D + "/schema/OpenDocument-v1.2-os-schema.rng", D + "/schema/OpenDocument-v1.2-os-manifest-schema.rng"),
31       "13": (D + "/schema/OpenDocument-v1.3-schema.rng", D + "/schema/OpenDocument-v1.3-manifest-schema.rng"),
32       "14": (D + "/schema/OpenDocument-v1.4-schema.rng", D + "/schema/OpenDocument-v1.4-manifest-schema.rng")}
33SCH["12x"] = SCH["12"]
34SCH["13x"] = SCH["13"]
35VERSIONS = ("12", "14", "12x", "13", "13x")
36_spec = importlib.util.spec_from_file_location("foreign", D + "/foreign.py")
37foreign = importlib.util.module_from_spec(_spec)
38_spec.loader.exec_module(foreign)
39STREAMS = {"content.xml", "styles.xml", "meta.xml", "settings.xml"}
40# ODF 1.2 Part 1 2.2.1 B.4: a content.xml rooted at MathML is validated against MathML, not ODF
41ERR = re.compile(r"^(.*?):(\d+):(\d+): (error|fatal|warning): (.*)$")
42
43
44def root_is_mathml(text):
45    body = re.sub(r'<\?xml[^>]*\?>|<!DOCTYPE[^>]*>|<!--.*?-->', '', text[:4000], flags=re.S).lstrip()
46    return bool(re.match(r'<(?:[\w.-]+:)?math[\s>/]', body))
47
48
49def main():
50    outdir, valjson = sys.argv[1], sys.argv[2]
51    work = os.path.abspath(valjson[:-5] + ".xml")
52    if not work.startswith(os.path.join(D, "runs") + os.sep):
53        sys.exit("validate.py: <val.json> must live under " + os.path.join(D, "runs"))
54    shutil.rmtree(work, ignore_errors=True)
55    files = {v: ([], []) for v in VERSIONS}
56    mixed = {"12x": foreign.mixed_elements(SCH["12"][0]), "13x": foreign.mixed_elements(SCH["13"][0])}
57    skipped, bad_zip = [], []
58    pkgs = sorted(p for p in os.listdir(outdir) if not p.startswith("."))
59    for pkg in pkgs:
60        try:
61            z = zipfile.ZipFile(os.path.join(outdir, pkg))
62        except Exception:
63            bad_zip.append(pkg); continue
64        for name in z.namelist():
65            is_mani = name == "META-INF/manifest.xml"
66            if name.rsplit("/", 1)[-1] not in STREAMS and not is_mani:
67                continue
68            text = z.read(name).decode("utf-8")
69            if not is_mani and name.endswith("content.xml") and root_is_mathml(text):
70                skipped.append(pkg + "/" + name); continue
71            for v in VERSIONS:
72                t = text
73                if v in ("12x", "13x") and not is_mani:
74                    t = foreign.strip_foreign(t, mixed[v])
75                if v in ("13", "13x", "14"):
76                    attr = "manifest:version" if is_mani else "office:version"
77                    t = re.sub(attr + '="1.2"', attr + '="1.%s"' % v[1], t, count=1)
78                p = os.path.join(work, v, pkg, name)
79                os.makedirs(os.path.dirname(p), exist_ok=True)
80                open(p, "w", encoding="utf-8").write(t)
81                files[v][1 if is_mani else 0].append(p)
82    errors = {}
83    for v in VERSIONS:
84        errs = []
85        for schema, fl in ((SCH[v][0], files[v][0]), (SCH[v][1], files[v][1])):
86            while fl:
87                batch = fl[:400]
88                r = subprocess.run(JING + [schema] + batch, capture_output=True, text=True)
89                fl = fl[400:]
90                for line in (r.stdout + r.stderr).splitlines():
91                    m = ERR.match(line)
92                    if m:
93                        errs.append([os.path.relpath(m.group(1), os.path.join(work, v)), int(m.group(2)), int(m.group(3)), m.group(5)])
94                        # a fatal error stops jing: resume with the files after the one that caused it
95                        if m.group(4) == "fatal" and m.group(1) in batch:
96                            fl = batch[batch.index(m.group(1)) + 1:] + fl
97                    elif line.strip():
98                        errs.append(["?", 0, 0, line.strip()])
99        errors[v] = errs
100    json.dump({"packages": pkgs, "bad_zip": bad_zip, "mathml_skipped": skipped,
101               "nfiles": len(files["12"][0]) + len(files["12"][1]), "errors": errors}, open(valjson, "w"))
102    for v in VERSIONS:
103        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")
104    print(f"files validated: {len(files['12'][0]) + len(files['12'][1])}, MathML skipped: {len(skipped)}, bad zips: {bad_zip}")
105    unparsed = [e for v in errors for e in errors[v] if e[0] == "?"]
106    if unparsed:
107        print("UNPARSED jing output:", *[e[3] for e in unparsed[:5]], sep="\n  ")
108
109
110main()
111