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 from json import load, dump
  27 from sys import argv, exit, stderr, stdin, stdout
  28 
  29 
  30 info = '''
  31 j2 [filepath/URI...]
  32 
  33 Json-2 reformats valid JSON input into indented multi-line JSON output,
  34 using 2 spaces for each indentation level.
  35 '''
  36 
  37 # handle standard help cmd-line options, quitting right away in that case
  38 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  39     print(info.strip(), file=stderr)
  40     exit(0)
  41 
  42 
  43 def json2(w, src) -> None:
  44     dump(load(src), w, indent=2, allow_nan=False, separators=(', ', ': '))
  45     w.write('\n')
  46 
  47 
  48 def seems_url(s: str) -> bool:
  49     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
  50     return any(s.startswith(p) for p in protocols)
  51 
  52 
  53 try:
  54     if len(argv) < 2:
  55         json2(stdout, stdin.buffer)
  56     elif len(argv) == 2:
  57         name = argv[1]
  58         if name == '-':
  59             json2(stdout, stdin.buffer)
  60         elif seems_url(name):
  61             from urllib.request import urlopen
  62             with urlopen(name) as inp:
  63                 json2(stdout, inp)
  64         else:
  65             with open(name, mode='rb') as inp:
  66                 json2(stdout, inp)
  67     else:
  68         raise ValueError('multiple inputs not allowed')
  69 except BrokenPipeError:
  70     # quit quietly, instead of showing a confusing error message
  71     stderr.close()
  72 except KeyboardInterrupt:
  73     exit(2)
  74 except Exception as e:
  75     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
  76     exit(1)