jw-python/scripts/trim-src.py

82 lines
2.7 KiB
Python
Raw Normal View History

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from abc import abstractmethod
import magic
import os.path
import re
import jwutils
from jwutils.log import *
class TrimSourceCmd(jwutils.Cmd):
def __init__(self, name, help):
super(TrimSourceCmd, self).__init__(name, help=help)
@abstractmethod
def _run(self, args, mime, path, contents):
raise Exception("_run() method not implemented")
def add_parser(self, parsers):
p = super(TrimSourceCmd, self).add_parser(parsers)
p.add_argument("input", help="input files", nargs='+')
return p
def run(self, args):
ms = magic.open(magic.NONE)
ms.load()
for path in args.input:
with open(path, 'r+') as infile:
contents = infile.read()
name = os.path.basename(path)
ext = os.path.splitext(path)[1]
# TODO: support other types in this block
mime = magic.detect_from_content(contents).mime_type
if mime in [ 'text/plain', 'application/x-empty' ]:
if name != 'Makefile' and ext != '.mk':
raise Exception("unsupported file type of", path)
mime = 'text/x-makefile'
out = self._run(args, mime, path, contents)
infile.seek(0)
infile.write(out)
class CmdBeautify(TrimSourceCmd):
def __init__(self):
super(CmdBeautify, self).__init__("beautify", help="Beautify source code files")
def add_parser(self, parsers):
p = super(CmdBeautify, self).add_parser(parsers)
p.add_argument('--indent-assignments', help='indent equal sign by this amount', nargs='?', default=30)
return p
def _processTextXMakefile(self, args, mime, path, contents):
# -- assignments
r = ''
indent = args.indent_assignments
for line in contents.splitlines(True):
m = re.match(r'^ *([a-zA-Z_][a-zA-Z0-9_]*)\s*([?+:]*)(=)\s*(.*)', line)
if m is None:
r += line
continue
r += misc.pad(m.group(1) + ' ', indent - len(m.group(2))) + m.group(2) + m.group(3) + ' ' + m.group(4) + '\n'
# -- trailing white space
contents = r
r = ''
for line in contents.splitlines(False):
r += line.rstrip() + '\n'
return r
def _run(self, args, mime, path, contents):
slog(NOTICE, "formatting", path, "of type", mime)
method = getattr(self, '_process' + ''.join(s.capitalize() for s in re.split('[/-]', mime)))
if method is None:
raise Exception("unsupported file type", mime, "of", path)
return method(args, mime, path, contents)
jwutils.run_sub_commands('trim source code')