-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindent
executable file
·48 lines (41 loc) · 1.31 KB
/
indent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python3
import sys
import os
import tempfile
import click
def get_terminal_size(fallback=(80, 24)):
for i in range(0, 3):
try:
columns, rows = os.get_terminal_size(i)
except OSError:
continue
break
else:
columns, rows = fallback
return columns, rows
@click.command()
@click.argument('input', required=False, type=click.File('r'))
@click.argument('output', required=False, type=click.File('w'))
@click.option('-tmp', 'tmp', help='pipe to tmp file', is_flag=True)
def cli(input, output, tmp):
"""Simple, pipeable tool for indenting text"""
columns, _ = get_terminal_size()
source = input.readlines() if input else list(sys.stdin)
max_line = len(sorted(source, key=len, reverse=True)[0])
indent_size = int((columns - max_line) / 2)
format_ = '{}{{}}\n'.format(indent_size * ' ')
if tmp:
filename = tempfile.mktemp()
with open(filename, 'w') as f:
f.write(''.join(format_.format(l.strip('\n')) for l in source))
f.write(str(columns))
sys.stdout.write(filename)
return
for line in source:
text = format_.format(line.strip())
if output:
output.write(text)
else:
sys.stdout.write(text)
if __name__ == "__main__":
cli()