Mercurial > hg > TextShaper
comparison textshaper/indent.py @ 24:0930c6884f8a
STUB: README.txt setup.py textshaper/indent.py
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sun, 23 Feb 2014 10:57:19 -0800 |
parents | 0d0db0d79bfd |
children | c23782a7b7ba |
comparison
equal
deleted
inserted
replaced
23:7ffe000f6f42 | 24:0930c6884f8a |
---|---|
2 | 2 |
3 """ | 3 """ |
4 indentation of text blocks | 4 indentation of text blocks |
5 """ | 5 """ |
6 | 6 |
7 import optparse | 7 import argparse |
8 import os | 8 import os |
9 import sys | 9 import sys |
10 | 10 |
11 def indent(text, indentation=4, space=' ', strict=False): | 11 def indent(text, indentation=4, space=' ', strict=False): |
12 """ | 12 """ |
40 retval.append(line[index:]) | 40 retval.append(line[index:]) |
41 | 41 |
42 return retval | 42 return retval |
43 | 43 |
44 | 44 |
45 def add_arguments(parser): | |
46 parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), | |
47 default=sys.stdin) | |
48 parser.add_argument('-o', '--output', dest='output', | |
49 help="output file or stdout if not given") | |
50 | |
45 def main(args=sys.argv[1:]): | 51 def main(args=sys.argv[1:]): |
46 # TODO : refactor to be more general and stuff | |
47 | 52 |
48 # parse command line | 53 # parse command line |
49 usage = '%prog [options] [file] [file2] [...]' | |
50 description = """indent files or stdin if no files given""" | 54 description = """indent files or stdin if no files given""" |
51 parser = optparse.OptionParser(usage=usage, description=__doc__) | 55 parser = argparse.Argument(description=__doc__) |
52 parser.add_option('-o', '--output', dest='output', | 56 add_arguments(parser) |
53 help="output file or stdout if not given") | 57 options = parser.parse_args(args) |
54 options, files = parser.parse_args(args) | |
55 | |
56 # input from files or stdin | |
57 if files: | |
58 missing = [not os.path.exists(filename) for filename in files] | |
59 if missing: | |
60 parser.error("File(s) not found: %s" % ', '.join(missing)) | |
61 def _files(): | |
62 for filename in files: | |
63 with open(f, 'r') as f: | |
64 yield f | |
65 else: | |
66 def _files(): | |
67 yield sys.stdin | |
68 | 58 |
69 # process input | 59 # process input |
70 for f in _files(): | 60 for f in _files(): |
71 print f | 61 |
62 # indent the text | |
63 indented = indent(f) | |
64 | |
65 # append to output | |
66 if options.output: | |
67 with open(options.output, 'a') as f: | |
68 f.write(indented) | |
69 else: | |
70 sys.stdout.write(indented) | |
72 | 71 |
73 if __name__ == '__main__': | 72 if __name__ == '__main__': |
74 main() | 73 main() |