File: j2.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2024 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the “Software”), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # j2 [filepath/URI...]
  27 #
  28 # Json-2 reformats valid JSON input into indented multi-line JSON output,
  29 # using 2 spaces for each indentation level.
  30 
  31 
  32 from json import load, dump
  33 from sys import argv, exit, stderr, stdin, stdout
  34 from urllib.request import urlopen
  35 
  36 
  37 # info is the help message shown when asked to
  38 info = '''
  39 j2 [filepath/URI...]
  40 
  41 Json-2 reformats valid JSON input into indented multi-line JSON output,
  42 using 2 spaces for each indentation level.
  43 '''.strip()
  44 
  45 # handle standard help cmd-line options, quitting right away in that case
  46 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  47     print(info, file=stderr)
  48     exit(0)
  49 
  50 
  51 def json2(w, src) -> None:
  52     dump(load(src), w, indent=2, allow_nan=False, separators=(', ', ': '))
  53     w.write('\n')
  54 
  55 
  56 def seems_url(s: str) -> bool:
  57     for prot in ('https://', 'http://', 'file://', 'ftp://', 'data:'):
  58         if s.startswith(prot):
  59             return True
  60     return False
  61 
  62 
  63 try:
  64     stdout.reconfigure(newline='\n', encoding='utf-8')
  65 
  66     if len(argv) < 2:
  67         json2(stdout, stdin.buffer)
  68     elif len(argv) == 2:
  69         name = argv[1]
  70         if name == '-':
  71             json2(stdout, stdin.buffer)
  72         elif seems_url(name):
  73             with urlopen(name) as inp:
  74                 json2(stdout, inp)
  75         else:
  76             with open(name, 'rb') as inp:
  77                 json2(stdout, inp)
  78     else:
  79         raise ValueError('multiple inputs not allowed')
  80 except (BrokenPipeError, KeyboardInterrupt):
  81     # quit quietly, instead of showing a confusing error message
  82     stderr.flush()
  83     stderr.close()
  84 except Exception as e:
  85     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
  86     exit(1)