Last active
August 29, 2015 14:09
-
-
Save jdp/aa05b4f40d516e16b0e7 to your computer and use it in GitHub Desktop.
Write gophermap files easily and naturally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import argparse | |
import sys | |
import textwrap | |
try: | |
from cStringIO import StringIO | |
except ImportError: | |
from StringIO import StringIO | |
def process(infile, outfile, width, delimiter): | |
wrapper = textwrap.TextWrapper(width=width) | |
buf = StringIO() | |
def flush(): | |
if buf.tell() > 0: | |
section = "\n".join(wrapper.wrap(buf.getvalue())) | |
outfile.write(section + "\n") | |
buf.truncate(0) | |
for line in infile: | |
if delimiter in line: | |
flush() | |
outfile.write(line.replace(delimiter, "\t")) | |
elif not line.strip(): | |
flush() | |
outfile.write("\n") | |
else: | |
buf.write(line) | |
def main(): | |
parser = argparse.ArgumentParser(description="Format a gophermap file.") | |
parser.add_argument( | |
'infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin) | |
parser.add_argument( | |
'-o', '--outfile', nargs='?', type=argparse.FileType('w'), | |
default=sys.stdout) | |
parser.add_argument('-w', '--width', action='store', type=int, default=67) | |
parser.add_argument('-d', '--delimiter', action='store', type=str, default="\t") | |
args = parser.parse_args() | |
process(args.infile, args.outfile, args.width, args.delimiter) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment