citadel

My dotfiles, scripts and nix configs
git clone git://jb55.com/citadel
Log | Files | Refs | README | LICENSE

collapse (1466B)


      1 #!/usr/bin/env python
      2 
      3 import sys
      4 
      5 class col:
      6     RED = '\033[31m'
      7     GREEN = '\033[32m'
      8     YELLOW = '\033[33m'
      9     BLUE = '\033[34m'
     10     MAGENTA = '\033[35m'
     11     CYAN = '\033[36m'
     12     END = '\033[0m'
     13 
     14 
     15 COLORS = [
     16     col.MAGENTA,
     17     col.RED,
     18     col.GREEN,
     19     col.BLUE,
     20     col.YELLOW,
     21     col.CYAN
     22 ]
     23 
     24 
     25 def collapse_lines(ls, context, delim):
     26     for l in ls[:context]:
     27         sys.stdout.write(colorize_line(l, delim))
     28     print(f"{col.MAGENTA}> [..]{col.END}")
     29     for l in ls[-context:]:
     30         sys.stdout.write(colorize_line(l, delim))
     31 
     32 
     33 def colorize_line(line, delim):
     34     if line[0] != delim:
     35         return line
     36 
     37     i = 0
     38     s = "" + COLORS[i] + line[0]
     39     i += 1
     40 
     41     for c in line[1:]:
     42         if c == delim:
     43             s += col.END + COLORS[i] + delim
     44             i = (i+1) % len(COLORS)
     45         else:
     46             s += c
     47 
     48     s += col.END
     49     return s
     50 
     51 
     52 def process(delim):
     53     thresh = 10
     54     context = 5
     55     count = 0
     56     lines = []
     57 
     58     for line in sys.stdin:
     59         if line[0] == delim:
     60             count += 1
     61             lines.append(line)
     62         else:
     63             if count > thresh:
     64                 collapse_lines(lines, context, delim)
     65             else:
     66                 for l in lines:
     67                     sys.stdout.write(colorize_line(l, delim))
     68 
     69             count = 0
     70             lines = []
     71 
     72             sys.stdout.write(colorize_line(line, delim))
     73 
     74     if len(lines) > 0:
     75         collapse_lines(lines, context, delim)
     76 
     77 
     78 process(">")