| 1 | #!/usr/bin/env python3 |
| 2 | """Normalize go test -json output for gotestfmt. |
| 3 | |
| 4 | Ensures every JSON object has a non-empty Package field so |
| 5 | GoTestTools/gotestfmt does not panic when encountering top-level output |
| 6 | (lines such as module download notices or toolchain diagnostics). |
| 7 | If a line is not valid JSON, wrap it in a minimal JSON object so the |
| 8 | parser downstream still receives structured input. |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import json |
| 14 | import sys |
| 15 | |
| 16 | _DEFAULT_PACKAGE = "__go_test__" |
| 17 | |
| 18 | |
| 19 | def _emit(obj: dict[str, object]) -> None: |
| 20 | sys.stdout.write(json.dumps(obj, ensure_ascii=True)) |
| 21 | sys.stdout.write("\n") |
| 22 | |
| 23 | |
| 24 | def main() -> int: |
| 25 | for raw in sys.stdin: |
| 26 | line = raw.rstrip("\n") |
| 27 | if not line: |
| 28 | # Preserve empty lines as synthetic output events. |
| 29 | _emit({"Action": "output", "Package": _DEFAULT_PACKAGE, "Output": "\n"}) |
| 30 | continue |
| 31 | |
| 32 | try: |
| 33 | data = json.loads(line) |
| 34 | except json.JSONDecodeError: |
| 35 | # Wrap unexpected non-JSON text so downstream tooling keeps working. |
| 36 | _emit({"Action": "output", "Package": _DEFAULT_PACKAGE, "Output": line + "\n"}) |
| 37 | continue |
| 38 | |
| 39 | if not data.get("Package"): |
| 40 | data["Package"] = _DEFAULT_PACKAGE |
| 41 | |
| 42 | _emit(data) |
| 43 | |
| 44 | return 0 |
| 45 | |
| 46 | |
| 47 | if __name__ == "__main__": |
| 48 | sys.exit(main()) |