#!/usr/bin/env python ''' Reduce leading whitespace on lines in python code to a minimal number of tabs. Input and output tabstops separately adjustable. ''' from __future__ import print_function import sys def usage(retval): '''Output a usage message''' sys.stderr.write('Usage: %s -i input_tab_width -o output_tab_width\n' % sys.argv[0]) sys.exit(retval) class Options(object): # pylint: disable=R0903 # R0903: We don't need a lot of public methods '''A simple option parser''' def __init__(self, argv): self.input_tab_width = 8 self.output_tab_width = 8 while argv[1:]: if argv[1] == '-i': self.input_tab_width = int(argv[2]) del argv[1] elif argv[1] == '-o': self.output_tab_width = int(argv[2]) del argv[1] else: sys.stderr.write('unknown option: '+argv[1]+'\n') usage(1) del argv[1] def main(): '''Main function''' options = Options(sys.argv) while True: line = sys.stdin.readline() if not line: break whitespace_prefix_width = 0 ind = 0 len_line = len(line) while ind < len_line: #for ind in xrange(0, len(line)): if line[ind] == ' ': whitespace_prefix_width = whitespace_prefix_width + 1 elif line[ind] == '\t': whitespace_prefix_width = ( (whitespace_prefix_width + options.input_tab_width) / \ options.input_tab_width) * \ options.input_tab_width else: break ind += 1 if ind == len(line): print() if ind < len(line): sys.stdout.write('\t' * (whitespace_prefix_width / options.output_tab_width) + \ ' ' * (whitespace_prefix_width % options.output_tab_width) + line[ind:]) else: print() main()