git @ Cat's Eye Technologies Cleandown / master src / cleandown / main.py
master

Tree @master (Download .tar.gz)

main.py @masterraw · history · blame

# Copyright (c) 2024 Chris Pressey, Cat's Eye Technologies.
#
# SPDX-License-Identifier: LicenseRef-MIT-X-Cleandown

from argparse import ArgumentParser
import codecs
import logging
import sys

from marko import Parser

from .renderer import CleanMarkdownRenderer


def rewrite_file(in_filename, out_filename):
    with codecs.open(in_filename, 'r', encoding="utf-8") as f:
        content = f.read()

    parser = Parser()
    document = parser.parse(content)

    renderer = CleanMarkdownRenderer()
    result = renderer.render(document)

    if out_filename is None:
        sys.stdout.write(result)
    else:
        with codecs.open(out_filename, 'w', encoding="utf-8") as f:
            f.write(result)


def initialize_logging(level):
    root = logging.getLogger()
    root.setLevel(level)

    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(level)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)

    root.addHandler(handler)


def main(args):
    argparser = ArgumentParser()
    argparser.add_argument('filenames', metavar='FILENAME', type=str, nargs='+',
        help='Names of Markdown files to pretty-print'
    )
    argparser.add_argument('--debug', action='store_true',
        help='If given, display debugging information'
    )
    argparser.add_argument('-i', '--in-place', action='store_true',
        help='If given, rewrite Markdown files in place instead of creating new files'
    )
    argparser.add_argument('-e', '--output-extension', type=str, default=None,
        help='If given, add to each input filename to form output filename to write to '
             '(e.g. ".out.md")'
    )
    argparser.add_argument('--version', action='version', version="%(prog)s 0.1")

    options = argparser.parse_args(sys.argv[1:])

    initialize_logging(logging.DEBUG if options.debug else logging.INFO)

    for in_filename in options.filenames:
        out_filename = None
        if options.in_place:
            out_filename = in_filename
        elif options.output_extension:
            out_filename = in_filename + '.out.md'
        rewrite_file(in_filename, out_filename)


def sys_main():
    return main(sys.argv[1:])


if __name__ == "__main__":
    sys_main()