webis.py 4.61 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#!/usr/bin/env python3

import sys
import os
import argparse
import json

import loader

from log import *
from lib import *
from system import *


def get_modules(config):
    """
    read all modules from moduls_directory
    :return list of modules
    """
    lInfo("read all available moduls in " + config["moduls_directory"])
    modules = {}
    for directory in os.listdir(config["moduls_directory"]):
        if os.path.isdir(config["moduls_directory"] + directory) and directory not in config["ignored_dirs"]:
            modules[directory] = config["moduls_directory"] + directory
    return modules


def check_allowed_shebang(scriptpath, allowed_scripts):
    """
    check for given script if it is allowed
    :return true if scriptpath has a valid shebang
    """
    shebang = get_shebang(scriptpath)
    for interpreter in allowed_scripts:
        if interpreter in shebang:
            return True
    return False


def get_submodules(config, modulepath):
    """
    get all submodules based on modulepath
    :return list of submodules
    """
    submodules = {}
    for script in os.listdir(modulepath):
        scriptpath = modulepath + "/" + script
        if os.path.isfile(scriptpath):
            if check_allowed_shebang(scriptpath, config["allowed_scripts"]):
                # store scriptname without extension as shortcut
                submodules[script.rsplit(".", 1)[0]] = scriptpath

    return submodules


def get_submodule_description(modulepath):
    """
    extract submodul description based on modulepath
    :return description
    """
    f = open(modulepath)
    lines = f.readlines()
    f.close()
    if len(lines) < 1 or lines[1][0] != "#":
        return ""
    return lines[1][1:].replace("\n", "").strip()


def handle_script(submodul, scriptfile, params=[]):
    """
    run extracted submodul based on scriptpath with all given params as parameter
    :return exit code of submodul
    """
    lInfo("start script")
    lDbg("run: " + submodul + ", path: " + scriptfile)
Steve Goering's avatar
Steve Goering committed
76 77 78

    """
    with this call, stdin and stdout is not simulatnious visible
79
    output = shell_call([scriptfile] + params)
Steve Goering's avatar
Steve Goering committed
80 81 82 83 84
    lInfo("output: \n" + output)"""

    lInfo("output:")
    os.system(" ".join([scriptfile] + params))
    lInfo("done")
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    # todo "return code"
    return 0


def main(args):
    lInfo("read config")
    # read config file
    try:
        config = json.loads(read_file(os.path.dirname(os.path.realpath(__file__)) + "/config.json"))
    except Exception as e:
        lError("configuration file 'config.json' is corupt (not json conform).")
        return 1

    # config check
    if not os.path.isdir(config["moduls_directory"]):
        config["moduls_directory"] = os.path.dirname(os.path.realpath(__file__)) + "/" + config["moduls_directory"]
        if not os.path.isdir(config["moduls_directory"]):
            lError("moduls_directory " + config["moduls_directory"] + " is not a valid directory, check config.json")
            return 1

    modules = get_modules(config)

    parser = argparse.ArgumentParser(description='supercmd -- meta cmd controller', epilog="Steve Göring 2015")
    parser.add_argument('modul', type=str, choices=list(modules.keys()), help='modulname')
    parser.add_argument('submodul', type=str, help='submodul')
    parser.add_argument('parameter', type=str, nargs='*', help='parameters for submodul command')

    argsdict = vars(parser.parse_args(sys.argv[1:3]))  # using sys.arv[..] is necessary because of unknown arguments in the parameters for submoduls

    # set parameters
    argsdict["parameter"] = sys.argv[3:]

    lInfo("available moduls: " + str(len(modules)))

    if argsdict["modul"] not in modules:
        lError("selected modul " + argsdict["modul"] + " is not available, " + str(list(modules.keys())))
        return 1
    lInfo("selected modul: " + argsdict["modul"])

    submodules = get_submodules(config, modules[argsdict["modul"]])
    if argsdict["submodul"] == "help":
        lHelp("submodules of " + argsdict["modul"])
Steve Goering's avatar
Steve Goering committed
127 128
        max_size = len(max(submodules.keys(), key=len))
        format_str = "{:<" + str(max_size) + "}"
129
        for sub in sorted(submodules.keys()):
Steve Goering's avatar
Steve Goering committed
130
            lHelp("    " + format_str.format(sub) + " : " + get_submodule_description(submodules[sub]))
131 132 133 134 135 136 137 138 139 140 141 142
        return 0

    if argsdict["submodul"] not in submodules:
        lError("selected submodul " + argsdict["submodul"] + " is not available use help, " + str(list(submodules.keys())))
        return 1

    lInfo("selected submodul: " + argsdict["submodul"])
    return handle_script(argsdict["submodul"], submodules[argsdict["submodul"]], argsdict["parameter"])


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))