File: nn.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 # Note: string slicing is a major source of inefficiencies in this script,
  27 # making it viable only for small inputs; it's not clear what the stdlib
  28 # offers to loop over sub-strings without copying data, which is really
  29 # needed in this case.
  30 #
  31 # In the end the code has become much uglier by using explicit index-pairs,
  32 # which are used/updated all over to avoid copying sub-strings. Standard
  33 # output seems already line-buffered by default, which means explicit
  34 # output-buffering is unlikely to bring any noticeable speed-ups.
  35 
  36 
  37 from io import TextIOWrapper
  38 from sys import argv, exit, stderr, stdin, stdout
  39 
  40 
  41 info = '''
  42 nn [options...] [filepaths/URIs...]
  43 
  44 Nice Numbers restyles all runs of 4+ digits by alternating ANSI-styles
  45 every 3-digit group, so long numbers become easier to read at a glance.
  46 
  47 All (optional) leading options start with either single or double-dash,
  48 and most of them change the style/color used. Some of the options are,
  49 shown in their single-dash form:
  50 
  51     -h          show this help message
  52     -help       show this help message
  53 
  54     -b          use a blue color
  55     -blue       use a blue color
  56     -bold       bold-style digits
  57     -g          use a green color
  58     -gray       use a gray color (default)
  59     -green      use a green color
  60     -hi         use a highlighting/inverse style
  61     -m          use a magenta color
  62     -magenta    use a magenta color
  63     -o          use an orange color
  64     -orange     use an orange color
  65     -p          use a purple color
  66     -purple     use a purple color
  67     -r          use a red color
  68     -red        use a red color
  69     -u          underline digits
  70     -underline  underline digits
  71 '''
  72 
  73 # handle standard help cmd-line options, quitting right away in that case
  74 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  75     print(info.strip(), file=stderr)
  76     exit(0)
  77 
  78 # names_aliases normalizes lookup keys for table names2styles
  79 names_aliases = {
  80     'b': 'blue',
  81     'g': 'green',
  82     'm': 'magenta',
  83     'o': 'orange',
  84     'p': 'purple',
  85     'r': 'red',
  86     'u': 'underline',
  87 
  88     'bb': 'bblue',
  89     'bg': 'bgreen',
  90     'bm': 'bmagenta',
  91     'bo': 'borange',
  92     'bp': 'bpurple',
  93     'br': 'bred',
  94     'bu': 'bunderline',
  95 
  96     'bb': 'bblue',
  97     'gb': 'bgreen',
  98     'mb': 'bmagenta',
  99     'ob': 'borange',
 100     'pb': 'bpurple',
 101     'rb': 'bred',
 102     'ub': 'bunderline',
 103 
 104     'hi': 'inverse',
 105     'inv': 'inverse',
 106     'mag': 'magenta',
 107 
 108     'flip': 'inverse',
 109     'swap': 'inverse',
 110 
 111     'reset': 'plain',
 112     'highlight': 'inverse',
 113     'hilite': 'inverse',
 114     'invert': 'inverse',
 115     'inverted': 'inverse',
 116     'swapped': 'inverse',
 117 
 118     'blueback': 'bblue',
 119     'grayback': 'bgray',
 120     'greenback': 'bgreen',
 121     'magback': 'bmagenta',
 122     'magentaback': 'bmagenta',
 123     'orangeback': 'borange',
 124     'purpleback': 'bpurple',
 125     'redback': 'bred',
 126 
 127     'bgblue': 'bblue',
 128     'bggray': 'bgray',
 129     'bggreen': 'bgreen',
 130     'bgmag': 'bmagenta',
 131     'bgmagenta': 'bmagenta',
 132     'bgorange': 'borange',
 133     'bgpurple': 'bpurple',
 134     'bgred': 'bred',
 135 
 136     'bluebg': 'bblue',
 137     'graybg': 'bgray',
 138     'greenbg': 'bgreen',
 139     'magbg': 'bmagenta',
 140     'magentabg': 'bmagenta',
 141     'orangebg': 'borange',
 142     'purplebg': 'bpurple',
 143     'redbg': 'bred',
 144 
 145     'backblue': 'bblue',
 146     'backgray': 'bgray',
 147     'backgreen': 'bgreen',
 148     'backmag': 'bmagenta',
 149     'backmagenta': 'bmagenta',
 150     'backorange': 'borange',
 151     'backpurple': 'bpurple',
 152     'backred': 'bred',
 153 }
 154 
 155 # names2styles matches color/style names to their ANSI-style strings
 156 names2styles = {
 157     'blue': '\x1b[38;5;26m',
 158     'bold': '\x1b[1m',
 159     'gray': '\x1b[38;5;248m',
 160     'green': '\x1b[38;5;29m',
 161     'inverse': '\x1b[7m',
 162     'magenta': '\x1b[38;5;165m',
 163     'orange': '\x1b[38;5;166m',
 164     'plain': '\x1b[0m',
 165     'purple': '\x1b[38;5;99m',
 166     'red': '\x1b[31m',
 167     'underline': '\x1b[4m',
 168 
 169     'bblue': '\x1b[48;5;26m\x1b[38;5;15m',
 170     'bgray': '\x1b[48;5;248m\x1b[38;5;15m',
 171     'bgreen': '\x1b[48;5;29m\x1b[38;5;15m',
 172     'bmagenta': '\x1b[48;5;165m\x1b[38;5;15m',
 173     'borange': '\x1b[48;5;166m\x1b[38;5;15m',
 174     'bpurple': '\x1b[48;5;99m\x1b[38;5;15m',
 175     'bred': '\x1b[41m\x1b[38;5;15m',
 176 }
 177 
 178 
 179 def restyle_line(w, line: str, style: str) -> None:
 180     '''Alternate styles for runs of digits in the string given'''
 181 
 182     start = 0
 183     end = len(line)
 184 
 185     if end > 1 and line[end - 2] == '\r' and line[end - 1] == '\n':
 186         end -= 2
 187     elif end > 0 and line[end - 1] == '\n':
 188         end -= 1
 189 
 190     while True:
 191         # see if line is over
 192         if start >= end:
 193             w.write('\n')
 194             return
 195 
 196         # find where the next run of digits starts; a negative index means
 197         # none were found
 198         i = -1
 199         for j in range(start, end):
 200             if line[j].isdigit():
 201                 i = j
 202                 break
 203 
 204         # check if rest of the line has no more digits
 205         if i < 0:
 206             w.write(line[start:end])
 207             w.write('\n')
 208             return
 209 
 210         # emit line up to right before the next run of digits starts
 211         w.write(line[start:i])
 212         start = i
 213 
 214         # find where/if the current run of digits ends; a negative index
 215         # means the run reaches the end of the line
 216         i = -1
 217         for j in range(start, end):
 218             if not line[j].isdigit():
 219                 i = j
 220                 break
 221 
 222         # check if rest of the line has only digits in it
 223         if i < 0:
 224             restyle_digits(w, line, start, end, style)
 225             w.write('\n')
 226             return
 227 
 228         # emit digits using alternate styling, and advance past them
 229         restyle_digits(w, line, start, i, style)
 230         start = i
 231 
 232 
 233 def restyle_digits(w, digits: str, start: int, end: int, style: str) -> None:
 234     '''Alternate styles on 3-item chunks from the string given'''
 235     diff = end - start
 236 
 237     # it's overall quicker to just emit short-enough digit-runs verbatim
 238     if diff < 4:
 239         w.write(digits[start:end])
 240         return
 241 
 242     # emit leading chunk of digits, which is the only one which
 243     # can have fewer than 3 items
 244     lead = diff % 3
 245     w.write(digits[start:start + lead])
 246 
 247     # the rest of the sub-string now has a multiple of 3 items left
 248     start += lead
 249 
 250     # start by styling the next digit-group only if there was a
 251     # non-empty leading group at the start of the full digit-run
 252     use_style = lead > 0
 253 
 254     # alternate styles until the string is over
 255     while start < end:
 256         # the digits left are always a multiple of 3
 257         stop = start + 3
 258 
 259         if use_style:
 260             w.write(style)
 261             w.write(digits[start:stop])
 262             w.write('\x1b[0m')
 263         else:
 264             w.write(digits[start:stop])
 265 
 266         # switch style and advance to the next 3-digit chunk
 267         use_style = not use_style
 268         start = stop
 269 
 270 
 271 def seems_url(s: str) -> bool:
 272     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
 273     return any(s.startswith(p) for p in protocols)
 274 
 275 
 276 def handle_lines(w, src, style: str) -> None:
 277     for line in src:
 278         restyle_line(w, line, style)
 279 
 280 
 281 args = argv[1:]
 282 # default (alternate) style is a light-gray color
 283 style = names2styles['gray']
 284 
 285 # handle leading style/color option, if present
 286 if len(args) > 0 and args[0].startswith('-'):
 287     s = args[0].lstrip('-')
 288     if s in names_aliases:
 289         s = names_aliases[s]
 290     if s in names2styles:
 291         style = names2styles[s]
 292         # skip leading arg, since it's clearly not a filepath
 293         args = args[1:]
 294 
 295 try:
 296     if args.count('-') > 1:
 297         msg = 'reading from `-` (standard input) more than once not allowed'
 298         raise ValueError(msg)
 299 
 300     if any(seems_url(e) for e in args):
 301         from urllib.request import urlopen
 302 
 303     # handle all named inputs given
 304     for path in args:
 305         if path == '-':
 306             handle_lines(stdout, stdin, style)
 307             continue
 308 
 309         if seems_url(path):
 310             with urlopen(path) as inp:
 311                 with TextIOWrapper(inp, encoding='utf-8') as txt:
 312                     handle_lines(stdout, txt, style)
 313             continue
 314 
 315         with open(path, encoding='utf-8') as inp:
 316             handle_lines(stdout, inp, style)
 317 
 318     if len(args) == 0:
 319         handle_lines(stdout, stdin, style)
 320 except BrokenPipeError:
 321     # quit quietly, instead of showing a confusing error message
 322     stderr.flush()
 323     stderr.close()
 324 except KeyboardInterrupt:
 325     # quit quietly, instead of showing a confusing error message
 326     exit(2)
 327 except Exception as e:
 328     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
 329     exit(1)