"""Convert Git porcelain-v2 -z bytes to JSON without splitting path whitespace. No Git commands, file writes, or network calls are performed by this converter. """ import base64 import json import sys MAX_BYTES = 1024 * 1024 def path_value(raw): if not raw: raise ValueError("empty_path") try: display = raw.decode("utf-8", errors="strict") except UnicodeDecodeError: display = None return {"bytes_base64": base64.b64encode(raw).decode("ascii"), "utf8": display} def parse_status(raw): if len(raw) > MAX_BYTES: raise ValueError("input_too_large") if raw and not raw.endswith(b"\0"): raise ValueError("missing_final_nul") chunks = raw.split(b"\0")[:-1] if raw else [] records, headers, index = [], 0, 0 layouts = { b"1": (8, ["xy", "submodule", "head_mode", "index_mode", "worktree_mode", "head_oid", "index_oid"]), b"2": (9, ["xy", "submodule", "head_mode", "index_mode", "worktree_mode", "head_oid", "index_oid", "score"]), b"u": (10, ["xy", "submodule", "stage1_mode", "stage2_mode", "stage3_mode", "worktree_mode", "stage1_oid", "stage2_oid", "stage3_oid"]), } while index < len(chunks): record = chunks[index] index += 1 if record.startswith(b"# "): headers += 1 continue if record.startswith((b"? ", b"! ")): records.append({"kind": "untracked" if record[:1] == b"?" else "ignored", "path": path_value(record[2:])}) continue tag = record[:1] if tag not in layouts or record[1:2] != b" ": raise ValueError("unknown_record_type") count, fields = layouts[tag] parts = record.split(b" ", count) if len(parts) != count + 1 or any(not value for value in parts[1:count]): raise ValueError("truncated_record") try: metadata = dict(zip(fields, [value.decode("ascii") for value in parts[1:count]])) except UnicodeDecodeError as error: raise ValueError("non_ascii_metadata") from error item = {"kind": {b"1": "ordinary", b"2": "rename_or_copy", b"u": "unmerged"}[tag], **metadata, "path": path_value(parts[count])} if tag == b"2": if index >= len(chunks): raise ValueError("missing_original_path") item["original_path"] = path_value(chunks[index]) index += 1 records.append(item) return {"ok": True, "format": "git-porcelain-v2-z", "records": records, "ignored_headers": headers} def main(): raw = sys.stdin.buffer.read(MAX_BYTES + 1) try: result = parse_status(raw) except ValueError as error: print(json.dumps({"ok": False, "error": str(error)})) return 1 print(json.dumps(result, ensure_ascii=True)) return 0 if __name__ == "__main__": raise SystemExit(main())