Last active
October 19, 2015 17:29
-
-
Save tueda/1e78d907130b0cd6c9b3 to your computer and use it in GitHub Desktop.
Check stedi-folds. (python>=2.6) #bin #python #form
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
#! /bin/sh | |
""":" | |
exec python "$0" ${1+"$@"} | |
""" | |
__doc__ = """Check stedi-folds.""" | |
import re | |
import sys | |
from collections import namedtuple | |
from optparse import OptionParser | |
if sys.version_info < (3, 0, 0): | |
from io import BytesIO as StringIO | |
else: | |
from io import StringIO | |
Fold = namedtuple('Fold', 'lineno, label') | |
class DummyIO(object): | |
def write(self, _): | |
pass | |
def __enter__(self): | |
return self | |
def __exit__(self, _type, _value, _traceback): | |
pass | |
def print_error(filename, lineno, message): | |
print('{0}:{1}: {2}'.format(filename, lineno, message)) | |
def print_error2(message): | |
print(message) | |
print_message = print_error2 | |
def check_file(filename, fixing): | |
fixed = False | |
folds = [] | |
lineno = 0 | |
with (StringIO() if fixing else DummyIO()) as fout: | |
with open(filename, 'rU') as fin: | |
for line in fin: | |
lineno += 1 | |
m = re.match(r'...#(\[|\])([^:]*):', line) | |
if m: | |
text = line.rstrip('\n') | |
label = m.group(2) | |
beginning = (line[4] == '[') | |
closed = text[-1] == ' ' | |
if beginning: | |
folds.append(Fold(lineno, label)) | |
else: | |
if not folds: | |
print_error( | |
filename, | |
lineno, | |
'unexpected end of fold' | |
) | |
print_error2(text) | |
fixing = False | |
elif folds[-1].label != label: | |
print_error( | |
filename, | |
lineno, | |
('unexpected end of fold ' | |
'("{0}" expected)').format(folds[-1].label) | |
) | |
print_error2(text) | |
fixing = False | |
else: | |
folds.pop() | |
if not closed: | |
print_error( | |
filename, | |
lineno, | |
'unclosed fold {0}'.format(label) | |
) | |
print_error2(text) | |
if fixing: | |
fout.write(text) | |
fout.write(' \n') | |
fixed = True | |
continue | |
fout.write(line) | |
if fixing and fixed: | |
with open(filename, 'w') as f: | |
f.write(fout.getvalue()) | |
print_message('"{0}" is fixed'.format(filename)) | |
def main(): | |
parser = OptionParser(usage='Usage: %prog [options] files..') | |
parser.add_option( | |
'-f', '--fix', action='store_true', dest='fix', default=False, | |
help='Close all folds' | |
) | |
(options, files) = parser.parse_args() | |
if not files: | |
parser.print_help() | |
else: | |
for f in files: | |
check_file(f, options.fix) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment