Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-10-13 08:15:23

0001 #!/usr/bin/env python3
0002 import argparse
0003 import json
0004 import pathlib
0005 import sys
0006 
0007 
0008 def format_one(path: pathlib.Path, indent: int, sort_keys: bool) -> int:
0009     """
0010     Returns:
0011       0 if unchanged,
0012       1 if rewritten,
0013       2 if invalid JSON
0014     """
0015     try:
0016         raw = path.read_text(encoding="utf-8")
0017     except Exception as e:
0018         print(f"[format-json] Could not read {path}: {e}", file=sys.stderr)
0019         return 2
0020 
0021     try:
0022         data = json.loads(raw)
0023     except json.JSONDecodeError as e:
0024         print(f"[format-json] Invalid JSON in {path}: {e}", file=sys.stderr)
0025         return 2
0026 
0027     # Use separators to avoid trailing spaces after commas/colons.
0028     formatted = (
0029         json.dumps(
0030             data,
0031             indent=indent,
0032             ensure_ascii=False,
0033             sort_keys=sort_keys,
0034         )
0035         + "\n"
0036     )  # ensure single trailing newline
0037 
0038     if formatted != raw:
0039         try:
0040             path.write_text(formatted, encoding="utf-8")
0041         except Exception as e:
0042             print(f"[format-json] Could not write {path}: {e}", file=sys.stderr)
0043             return 2
0044         print(f"[format-json] Rewrote {path}")
0045         return 1
0046 
0047     return 0
0048 
0049 
0050 def main() -> int:
0051     parser = argparse.ArgumentParser(description="Format JSON files in-place.")
0052     parser.add_argument(
0053         "--indent", type=int, default=2, help="Indent width (default: 2)"
0054     )
0055     parser.add_argument(
0056         "--sort-keys",
0057         action="store_true",
0058         help="Sort object keys for stable ordering (off by default)",
0059     )
0060     parser.add_argument("files", nargs="+")
0061 
0062     args = parser.parse_args()
0063 
0064     status_max = 0
0065     for f in args.files:
0066         p = pathlib.Path(f)
0067         # Skip non-files (pre-commit can pass deleted paths)
0068         if not p.is_file():
0069             continue
0070         rc = format_one(p, indent=args.indent, sort_keys=args.sort_keys)
0071         status_max = max(status_max, rc)
0072 
0073     # Return 0 if all good (even if files were rewritten).
0074     # Return 2 if any invalid JSON encountered to block the commit.
0075     return 0 if status_max < 2 else 2
0076 
0077 
0078 if __name__ == "__main__":
0079     sys.exit(main())