cli.py 2.13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
import logging
import os
import sys
import argparse
from typing import Dict
from datetime import datetime

from preproc.preprocessor import PreProcessor, PreProcessorError

_LOG = logging.getLogger("preprocessor")

# adapted from http://stackoverflow.com/a/8527629
class LogLevelChoices(argparse.Action):
    CHOICES = ["error", "warn", "info", "debug"]
    def __call__(self, parser, namespace, value, option_string=None):
        if value:
            if value not in self.CHOICES:
                message = ("invalid choice: {0!r} (choose from {1})"
                           .format(value,
                                   ', '.join([repr(action)
                                              for action in self.CHOICES])))

                raise argparse.ArgumentError(self, message)
            setattr(namespace, self.dest, value)

def run():
    parser = argparse.ArgumentParser(description="MiniJava preprocessor", add_help=True)
    parser.add_argument("src_file", metavar="FILE", help="File to pre process")
    if os.getenv("MJ_IMPORT_DIR", None) is None:
        parser.add_argument("import_base_dir",
                            metavar="MJ_IMPORT_DIR",
                            help="Base directory for imports. "
                                 "Can be omitted by assigning the environment variable MJ_IMPORT_DIR.")
    parser.add_argument("dst_file", metavar="DEST", help="Destination file, '-' if it should be printed on std out.")

    parser.add_argument("--log_level", action=LogLevelChoices, default="warn", const="log_level",
                        help="Logging level (error, warn, info or debug)")
    args = vars(parser.parse_args())

    if os.getenv("MJ_IMPORT_DIR", None) is not None:
            args["import_base_dir"] = os.getenv("MJ_IMPORT_DIR")

    LOG_LEVELS = {
        "info": logging.INFO,
        "error": logging.ERROR,
        "warn": logging.WARN,
        "debug": logging.DEBUG
    }

    logging.basicConfig(level=LOG_LEVELS[args["log_level"]])

    try:
        PreProcessor(args["src_file"], args["import_base_dir"], args["dst_file"]).preprocess()
    except PreProcessorError as err:
        _LOG.error(str(err))
        return 1