summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/scripts/baseline_diff.py
blob: ccbb271381ac365f0e0b252d4c5708a547bcd350 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env python3
"""Compare a fresh test run with the baseline recorded before a same-stack uplift.

    python3 baseline_diff.py <BASELINE.md> --junit DIR_OR_FILE [--junit ...] [--json] [--max-list N]

BASELINE.md (analysis/<system>/BASELINE.md) records how the tests behaved on the OLD version. This
script reads it and the fresh results, and reports what changed. Nothing is judged by a model.

Baseline, any of these (the most detailed one found is used):
  a per-test table      | Test | Result |      one row per test, PASS / FAIL / ERROR / SKIP
  a per-module table    | Module | Pass | Fail | Error | Skip |     (the first column may be a module,
                        project or test class; column names are matched, their order does not matter)
  a totals table        | Executed | 946 |, | Passed | 945 |, | Failed | 1 | ...
  a line                target-only: <why the old version could not run here>   (nothing to compare)

Fresh results: JUnit-style XML (Maven surefire, Gradle, pytest --junitxml, Ant, jest-junit ...) or
Visual Studio .trx files. Give a file or a folder; a folder is searched for result files, links are
never followed, and a file that declares a DTD or entity is refused. A test id is
"<classname>#<name>"; a repeated id in one file gets a "~N" suffix in document order (the first
stays plain); the module's own absolute path in a parameterized name is replaced by <MODULE>.

Reported: regressions (passed before, fails now), new failures (a test the baseline never listed),
tests that still fail as they did, tests that now pass, tests that were skipped and now run, tests
that no longer run, missing modules, skipped growth and a drop in executed tests. When test names
drifted inside a class but its counts did not get worse, that is counted as renamed, not missing.

Exit 0 when nothing regressed and something ran; 1 on any regression or new failure, or when no test
executed; 2 for input that cannot be used. Standard library only.
"""
import argparse
import json
import os
import re
import sys
from xml.parsers import expat

BAD = ("FAIL", "ERROR")
MAX_FILE, MAX_FILES, MAX_CASES, MAX_DEPTH, KEEP = 200 << 20, 20000, 2000000, 60, 200
SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv"}
STATUS = {"pass": "PASS", "passed": "PASS", "ok": "PASS", "success": "PASS", "green": "PASS", "fail": "FAIL", "failed": "FAIL", "failure": "FAIL",
          "red": "FAIL", "error": "ERROR", "errors": "ERROR", "errored": "ERROR", "skip": "SKIP", "skipped": "SKIP", "ignored": "SKIP",
          "pending": "SKIP", "disabled": "SKIP"}
COLUMNS = (("pass", r"pass|passed|passing|ok|successes?"), ("fail", r"fail|failed|failing|failures?"), ("error", r"errors?|errored"),
           ("skip", r"skip|skipped|ignored|pending|disabled"))
TOTALS = {"executed": "executed", "test cases": "cases", "passed": "pass", "pass": "pass", "failed": "fail", "failures": "fail", "errors": "error",
          "skipped": "skip", "ignored": "skip"}


def clean(value, limit=200):
    text = " ".join(re.sub(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]", " ", str(value if value is not None else "")).split())
    return text if len(text) <= limit else text[:limit - 1] + "…"


class InputError(Exception):
    pass


# ---------------------------------------------------------------- the baseline
def cell(text):
    text = text.replace("\\|", "|").strip()
    if len(text) > 4 and text.startswith("**") and text.endswith("**"):
        text = text[2:-2].strip()
    if len(text) >= 2 and text.startswith("`") and text.endswith("`"):
        text = text[1:-1]
    return text


def split_row(line):
    s = line.strip()
    s = s[1:] if s.startswith("|") else s
    s = s[:-1] if s.endswith("|") and not s.endswith("\\|") else s
    return [cell(c) for c in re.split(r"(?<!\\)\|", s[:20000])]


def join_cut_rows(lines):
    """A test name that contains a newline cuts its table row in two; put the row back together (at most 3 extra lines)."""
    out, i = [], 0
    while i < len(lines):
        line, extra = lines[i], 0
        while (line.lstrip().startswith("|") and not line.rstrip().endswith("|") and extra < 3 and i + 1 < len(lines)
               and lines[i + 1].strip() and not lines[i + 1].lstrip().startswith(("|", "#"))):
            i += 1
            extra += 1
            line += "\n" + lines[i]
        out.append(line)
        i += 1
    return out


def md_tables(text):
    """(nearest heading, header cells, [row cells]) for every pipe table."""
    lines, heading = join_cut_rows(text.split("\n")), ""
    i = 0
    while i < len(lines):
        h = re.match(r"#{1,6}[ \t]+(.*)", lines[i][:2000])
        heading = h.group(1) if h else heading
        if "|" in lines[i] and i + 1 < len(lines) and re.fullmatch(r"\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*", lines[i + 1][:5000]):
            rows, j = [], i + 2
            while j < len(lines) and "|" in lines[j] and lines[j].strip():
                rows.append(split_row(lines[j]))
                j += 1
            yield heading, split_row(lines[i]), rows
            i = j
        else:
            i += 1


def to_int(text):
    t = text.strip().replace(",", "")
    if t in ("", "-", "\u2013", "\u2014"):
        return 0
    return int(t) if re.fullmatch(r"\d{1,12}", t) else None


def parse_baseline(text):
    """-> {targetOnly, why, modules {name: counts}, tests {id: status}, totals {name: n}}."""
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    m = re.search(r"(?im)^\W*target-only:[ \t]*(.*)$", text)
    out = {"targetOnly": bool(m), "why": clean(m.group(1), 300) if m else "", "modules": {}, "tests": {}, "totals": {}, "flaky": [], "approved": {}}
    for heading, header, rows in md_tables(text):
        low = [h.lower() for h in header]
        if re.search(r"(?i)flak", heading):                    # tests the baseline itself says flip on the same version
            out["flaky"] += [clean(r[0], 400) for r in rows if r and r[0]]
            continue
        if re.search(r"(?i)approved", heading):                # differences a person accepted: | Test | Reason |
            for r in rows:
                if r and r[0]:
                    out["approved"].setdefault(clean(r[0], 400), clean(r[1] if len(r) > 1 else "", 300))
            continue
        cols = {key: next((i for i, h in enumerate(low) if re.fullmatch(rx, h)), None) for key, rx in COLUMNS}
        result = next((i for i, h in enumerate(low) if re.fullmatch(r"result|status|outcome|verdict", h)), None)
        if cols["pass"] is not None and any(cols[k] is not None for k in ("fail", "error", "skip")):
            for row in rows:
                name, nums = row[0] if row else "", {k: to_int(row[i]) if i is not None and i < len(row) else 0 for k, i in cols.items()}
                if name and not re.fullmatch(r"(?i)totals?|all|sum", name) and None not in nums.values():
                    out["modules"][name[:300]] = nums
        elif result is not None:
            name_col = next((i for i, h in enumerate(low) if re.fullmatch(r"tests?|test name|test id|id|name|cases?|test case", h)), 0)
            for row in rows:
                status = STATUS.get(row[result].lower()) if result < len(row) else None
                if status and name_col < len(row) and row[name_col] and result != name_col:
                    out["tests"][row[name_col][:400]] = status
        elif len(header) >= 2:
            for row in rows:
                label, n = (row[0].lower() if row else ""), to_int(row[1]) if len(row) > 1 else None
                if label in TOTALS and n is not None:
                    out["totals"][TOTALS[label]] = n
    if not (out["modules"] or out["tests"] or out["totals"]):
        counts = {}
        for word, key in (("pass(?:ed|ing)", "pass"), ("fail(?:ed|ing|ures?)", "fail"), ("skipped", "skip"), ("errors?", "error")):
            hit = re.search(r"(?i)(\d{1,9})\s+(?:tests?\s+|cases?\s+)?" + word, text)
            if hit:
                counts[key] = int(hit.group(1))
        out["totals"] = counts
    return out


def tally(statuses):
    c = {"pass": 0, "fail": 0, "error": 0, "skip": 0}
    for s in statuses:
        c[s.lower()] += 1
    c["executed"] = c["pass"] + c["fail"] + c["error"]
    return c


def baseline_counts(base):
    """(counts, where they came from)."""
    if base["tests"]:
        return tally(base["tests"].values()), "per-test table"
    if base["modules"]:
        c = {k: sum(v[k] for v in base["modules"].values()) for k in ("pass", "fail", "error", "skip")}
        c["executed"] = c["pass"] + c["fail"] + c["error"]
        return c, "per-module table"
    t = base["totals"]
    if t:
        c = {k: t.get(k, 0) for k in ("pass", "fail", "error", "skip")}
        c["executed"] = t["executed"] if "executed" in t else c["pass"] + c["fail"] + c["error"]
        return c, "totals"
    return None, "nothing"


# ---------------------------------------------------------------- the fresh results
def refuse(*_):
    raise ValueError("it declares a DTD or an entity, which test results never do")


def parse_results(path):
    """[(classname, name, status, skip message given, suite name)] from one JUnit or TRX file. Raises ValueError."""
    cases, suites, cur, depth = [], [], [], [0]
    trx = {"Passed": "PASS", "Failed": "FAIL", "Error": "ERROR", "Timeout": "ERROR", "Aborted": "ERROR"}

    def start(tag, attrs):
        depth[0] += 1
        if depth[0] > MAX_DEPTH:
            raise ValueError("the XML is nested more than %d levels deep" % MAX_DEPTH)
        if tag == "testsuite":
            suites.append(attrs.get("name", "")[:300])
        elif tag == "testcase":
            if len(cases) >= MAX_CASES:
                raise ValueError("more than %d test cases" % MAX_CASES)
            flag = (attrs.get("status") or attrs.get("result") or "").lower()
            cur[:] = [(attrs.get("classname") or (suites[-1] if suites else ""))[:300], attrs.get("name", "")[:400],
                      "SKIP" if flag in ("skipped", "ignored", "notrun", "notexecuted", "disabled") else "PASS", False]
        elif cur and tag in ("failure", "error", "skipped"):
            if tag == "skipped":
                cur[3] = bool(attrs.get("message", "").strip())
            new = {"failure": "FAIL", "error": "ERROR", "skipped": "SKIP"}[tag]
            if cur[2] == "PASS" or (cur[2] == "SKIP" and new != "SKIP"):
                cur[2] = new
        elif tag == "UnitTestResult":
            name = attrs.get("testName", "")[:400]
            head, sep, tail = name.partition("(")
            klass, dot, method = head.rpartition(".")
            outcome = attrs.get("outcome", "")
            cases.append((klass[:300] if dot else "", (method + sep + tail) if dot else name, trx.get(outcome, "SKIP"), False, ""))

    def end(tag):
        depth[0] -= 1
        if tag == "testcase" and cur:
            cases.append((cur[0], cur[1], cur[2], cur[3], suites[-1] if suites else ""))
            cur.clear()
        elif tag == "testsuite" and suites:
            suites.pop()

    parser = expat.ParserCreate()
    parser.StartDoctypeDeclHandler = refuse
    parser.EntityDeclHandler = refuse
    parser.StartElementHandler = start
    parser.EndElementHandler = end
    try:
        with open(path, "rb") as fh:
            parser.ParseFile(fh)
    except expat.ExpatError as err:
        raise ValueError("the XML is not well formed (%s)" % expat.ErrorString(err.code))
    return cases


def result_files(paths):
    """([files], [problems]) from files and folders. Links are never followed."""
    found, problems = [], []
    for p in paths:
        if os.path.isfile(p) and not os.path.islink(p):
            found.append(p)
        elif os.path.isdir(p) and not os.path.islink(p):
            for base, dirs, names in os.walk(p):
                dirs[:] = [d for d in sorted(dirs) if d not in SKIP_DIRS and not os.path.islink(os.path.join(base, d))]
                for n in sorted(names):
                    full = os.path.join(base, n)
                    if os.path.islink(full) or not n.lower().endswith((".xml", ".trx")):
                        continue
                    try:
                        with open(full, "rb") as fh:
                            head = fh.read(4096)
                    except OSError:
                        continue
                    if b"<testsuite" in head or b"<TestRun" in head:
                        found.append(full)
                if len(found) > MAX_FILES:
                    problems.append("More than %d result files were found; the rest were not read." % MAX_FILES)
                    return found[:MAX_FILES], problems
        else:
            problems.append("%s is not a file or folder that can be read." % clean(p, 120))
    return found, problems


def module_label(path):
    """The module folder a Maven or Gradle report belongs to (its parent of target/ or build/), or ''."""
    parts = os.path.abspath(path).split(os.sep)
    for i in range(len(parts) - 2, 1, -1):
        if parts[i] in ("target", "build") and parts[i + 1] in ("surefire-reports", "failsafe-reports", "test-results"):
            return os.sep.join(parts[:i]) or os.sep
    return ""


def read_results(paths):
    """-> {tests {id: status}, skipReasons {id: bool}, classes, modules, suites, files, unreadable [str], problems [str], oldest, newest}."""
    files, problems = result_files(paths)
    out = {"tests": {}, "skipReasons": {}, "classes": {}, "modules": {}, "suites": {}, "files": 0, "unreadable": [], "problems": problems, "oldest": None, "newest": None}
    for path in files:
        label = clean(os.path.basename(path), 100)
        try:
            if os.path.getsize(path) > MAX_FILE:
                raise ValueError("the file is larger than %d MB" % (MAX_FILE >> 20))
            cases = parse_results(path)
        except (OSError, ValueError) as err:
            out["unreadable"].append("%s: %s" % (label, clean(err, 120)))
            continue
        root = module_label(path)
        roots = sorted({root, os.path.realpath(root), root[len("/private"):] if root.startswith("/private/") else root} - {os.sep}, key=len, reverse=True) if root else []
        seen, mtime = {}, os.path.getmtime(path)
        out["files"] += 1
        out["oldest"] = mtime if out["oldest"] is None else min(out["oldest"], mtime)
        out["newest"] = mtime if out["newest"] is None else max(out["newest"], mtime)
        for klass, name, status, has_reason, suite in cases:
            for r in roots:
                name = name.replace(r, "<MODULE>")
            name = re.sub(r"(test)\d+(\.tmp)", r"\1<N>\2", name)
            base = "%s#%s" % (klass, name) if klass else name
            n = seen.get(base, 0)
            seen[base] = n + 1
            tid = base if n == 0 else "%s~%d" % (base, n)
            out["tests"][tid] = status
            out["skipReasons"][tid] = has_reason
            for key, store in ((klass, out["classes"]), (root and os.path.basename(root), out["modules"]), (suite, out["suites"])):
                if key:
                    store.setdefault(key, []).append(status)
    for store in ("classes", "modules", "suites"):
        out[store] = {k: tally(v) for k, v in out[store].items()}
    return out


# ---------------------------------------------------------------- the comparison
def keep(items):
    return items[:KEEP]


def compare(base, fresh):
    """-> the report dict (see the module docstring)."""
    counts_b, source = baseline_counts(base)
    counts_f = tally(fresh["tests"].values())
    rep = {"baseline": {"targetOnly": base["targetOnly"], "why": base["why"], "source": source, "counts": counts_b},
           "fresh": {"files": fresh["files"], "counts": counts_f, "unreadable": fresh["unreadable"][:20], "unreadableCount": len(fresh["unreadable"]),
                     "oldest": fresh["oldest"], "newest": fresh["newest"]},
           "regressions": [], "flaky": [], "newFailures": [], "stillFailing": [], "fixed": [], "newlySkipped": [], "missing": [], "renamed": 0,
           "missingModules": [], "moduleDiffs": [], "executedDrop": None, "skippedGrowth": None, "problems": list(fresh["problems"])}
    bt, ft, flaky = base["tests"], fresh["tests"], set(base.get("flaky", []))
    if bt:
        missing = [t for t in bt if t not in ft]
        added = [t for t in ft if t not in bt]
        for t, b in bt.items():
            f = ft.get(t)
            if f is None:
                continue
            if b == "PASS" and f in BAD:
                (rep["flaky"] if t in flaky else rep["regressions"]).append({"id": t, "before": b, "now": f})
            elif b in BAD and f in BAD:
                rep["stillFailing"].append(t)
            elif b in BAD and f == "PASS":
                rep["fixed"].append(t)
            elif b == "PASS" and f == "SKIP":
                rep["newlySkipped"].append(t)
            elif b == "SKIP" and f in BAD:
                rep["newFailures"].append(t)
        by_class = {}
        for t in missing:
            by_class.setdefault(t.split("#", 1)[0], [[], []])[0].append(t)
        for t in added:
            by_class.setdefault(t.split("#", 1)[0], [[], []])[1].append(t)
        drifting = {k for k, (gone, new) in by_class.items() if gone and new}
        grouped_b, grouped_f = {}, {}
        for src, dst in ((bt, grouped_b), (ft, grouped_f)):
            for t, v in src.items():
                if t.split("#", 1)[0] in drifting:
                    dst.setdefault(t.split("#", 1)[0], []).append(v)
        for klass, (gone, new) in by_class.items():
            b_counts, f_counts = tally(grouped_b.get(klass, [])), tally(grouped_f.get(klass, []))
            if gone and new and f_counts["executed"] >= b_counts["executed"] and f_counts["fail"] + f_counts["error"] <= b_counts["fail"] + b_counts["error"]:
                rep["renamed"] += len(gone)
            else:
                rep["missing"] += gone
                rep["newFailures"] += [t for t in new if ft[t] in BAD]
    for name, b in base["modules"].items():
        f = fresh["classes"].get(name) or fresh["modules"].get(name) or fresh["suites"].get(name)
        if f is None:
            rep["missingModules"].append(name)
            continue
        problems = []
        if f["executed"] < b["pass"] + b["fail"] + b["error"]:
            problems.append("%d test(s) executed, %d before" % (f["executed"], b["pass"] + b["fail"] + b["error"]))
        if f["skip"] > b["skip"]:
            problems.append("%d skipped, %d before" % (f["skip"], b["skip"]))
        if not bt and f["fail"] + f["error"] > b["fail"] + b["error"]:
            rep["regressions"].append({"id": name + " (all its tests)", "before": "%d failing" % (b["fail"] + b["error"]), "now": "%d failing" % (f["fail"] + f["error"])})
        if problems:
            rep["moduleDiffs"].append({"module": name, "problems": problems})
    if counts_b:
        if counts_f["executed"] < counts_b["executed"]:
            rep["executedDrop"] = {"before": counts_b["executed"], "now": counts_f["executed"]}
        if counts_f["skip"] > counts_b["skip"]:
            rep["skippedGrowth"] = {"before": counts_b["skip"], "now": counts_f["skip"]}
    rep["approved"] = []
    for key, label in (("regressions", "passed before, fails now"), ("newFailures", "not in the baseline, fails now")):
        kept = []
        for item in rep[key]:
            tid = item["id"] if isinstance(item, dict) else item
            if tid in base.get("approved", {}):
                rep["approved"].append({"id": tid, "reason": base["approved"][tid], "was": label})
            else:
                kept.append(item)
        rep[key] = kept
    for key in ("regressions", "flaky", "newFailures", "stillFailing", "fixed", "newlySkipped", "missing", "missingModules", "moduleDiffs", "approved"):
        rep[key + "Count"], rep[key] = len(rep[key]), keep(rep[key])
    rep["ok"] = counts_f["executed"] > 0 and not rep["regressionsCount"] and not rep["newFailuresCount"]
    return rep


def render(rep, limit=10):
    b, f = rep["baseline"]["counts"], rep["fresh"]["counts"]
    show = lambda c: "%d executed (%d pass, %d fail, %d error, %d skip)" % (c["executed"], c["pass"], c["fail"], c["error"], c["skip"])  # noqa: E731
    lines = ["baseline (%s): %s" % (rep["baseline"]["source"], show(b) if b else "nothing readable"),
             "this run (%d result file(s)): %s" % (rep["fresh"]["files"], show(f))]
    if rep["baseline"]["targetOnly"]:
        lines.append("BASELINE.md says target-only (%s): there is no old-version result to compare with." % (rep["baseline"]["why"] or "no reason given"))

    def block(title, key, fmt=lambda x: clean(x, 160)):
        if rep[key + "Count"]:
            lines.append("%s: %d" % (title, rep[key + "Count"]))
            lines.extend("  " + fmt(x) for x in rep[key][:limit])
            if rep[key + "Count"] > limit:
                lines.append("  ... and %d more (use --json)" % (rep[key + "Count"] - limit))
        else:
            lines.append("%s: 0" % title)
    block("regressions (passed before, fail now)", "regressions", lambda x: "%s: %s -> %s" % (clean(x["id"], 140), x["before"], x["now"]))
    block("differences a person approved in BASELINE.md (not counted)", "approved", lambda x: "%s: %s (%s)" % (clean(x["id"], 120), x["was"], clean(x["reason"], 100)))
    block("flaky flips the baseline lists (not counted)", "flaky", lambda x: "%s: %s -> %s" % (clean(x["id"], 140), x["before"], x["now"]))
    block("new failures (not in the baseline)", "newFailures")
    block("still failing, as in the baseline", "stillFailing")
    block("now passing (failed before)", "fixed")
    block("skipped now that ran before", "newlySkipped")
    block("baseline tests that did not run", "missing")
    block("modules missing from this run", "missingModules")
    block("modules with fewer tests or more skips", "moduleDiffs", lambda x: "%s: %s" % (clean(x["module"], 100), "; ".join(x["problems"])))
    if rep["renamed"]:
        lines.append("renamed: %d test name(s) changed but their class did not get worse" % rep["renamed"])
    if rep["executedDrop"]:
        lines.append("executed tests dropped from %(before)d to %(now)d" % rep["executedDrop"])
    if rep["skippedGrowth"]:
        lines.append("skipped tests grew from %(before)d to %(now)d" % rep["skippedGrowth"])
    lines += ["%d result file(s) could not be read: %s" % (rep["fresh"]["unreadableCount"], "; ".join(rep["fresh"]["unreadable"][:3])) if rep["fresh"]["unreadableCount"] else "all result files were read"]
    lines += rep["problems"]
    lines.append("OK: nothing regressed and %d test(s) executed" % f["executed"] if rep["ok"] else "NOT OK: %s" % (
        "no test executed" if not f["executed"] else "%d regression(s), %d new failure(s)" % (rep["regressionsCount"], rep["newFailuresCount"])))
    return "\n".join(lines)


def run(baseline_path, paths):
    """-> the report. Raises InputError for a baseline or results that cannot be used."""
    if os.path.islink(baseline_path):
        raise InputError("%s is a symbolic link" % baseline_path)
    try:
        with open(baseline_path, "rb") as fh:
            text = fh.read(16 << 20).decode("utf-8", "replace")
    except OSError as err:
        raise InputError("cannot read %s: %s" % (baseline_path, err.__class__.__name__))
    base = parse_baseline(text)
    if not (base["targetOnly"] or base["modules"] or base["tests"] or base["totals"]):
        raise InputError("%s has no per-test table, per-module table, totals or target-only line that can be read" % baseline_path)
    return compare(base, read_results(paths))


def main(argv=None):
    ap = argparse.ArgumentParser(description="Compare a fresh test run with BASELINE.md.")
    ap.add_argument("baseline", help="analysis/<system>/BASELINE.md")
    ap.add_argument("--junit", "--trx", action="append", default=[], metavar="PATH", help="a results file or a folder to search (repeat for several)")
    ap.add_argument("--json", action="store_true", help="print the full report as JSON")
    ap.add_argument("--max-list", type=int, default=10, help="how many entries to print per list (default 10)")
    args = ap.parse_args(argv)
    if not args.junit:
        print("baseline_diff.py: give at least one --junit file or folder", file=sys.stderr)
        return 2
    try:
        rep = run(args.baseline, args.junit)
    except InputError as err:
        print("baseline_diff.py: %s" % err, file=sys.stderr)
        return 2
    print(json.dumps(rep, indent=1, ensure_ascii=True) if args.json else render(rep, max(1, args.max_list)))
    return 0 if rep["ok"] else 1


if __name__ == "__main__":
    sys.exit(main())