webis.py 4.83 KB
Newer Older
1
#!/usr/bin/env python3
Steve Goering's avatar
Steve Goering committed
2 3
"""
    Webis command
4

Steve Goering's avatar
Steve Goering committed
5 6 7 8 9
    Copyright 2015-today

    Project WEBIS
    Author: Steve Göring
"""
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 76 77 78 79 80 81 82
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
83 84

    lInfo("output:")
85
    cmd = " ".join([scriptfile] + params)
86 87 88

    # make script executable
    os.system("chmod +x {}".format(scriptfile))
89 90 91 92 93 94 95 96
    return_value = os.system(cmd)

    if return_value == 0:
        lInfo("done")
    else:
        lError("something was wrong with your call: " + cmd)

    return return_value
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116


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)

117
    parser = argparse.ArgumentParser(description='supercmd -- meta cmd controller', epilog="Steve Göring 2015", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
118
    parser.add_argument('modul', type=str, choices=list(modules.keys()), help='modulname')
119
    parser.add_argument('submodul', type=str, nargs='?', default="help", help='submodul')
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    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
137 138
        max_size = len(max(submodules.keys(), key=len))
        format_str = "{:<" + str(max_size) + "}"
139
        for sub in sorted(submodules.keys()):
Steve Goering's avatar
Steve Goering committed
140
            lHelp("    " + format_str.format(sub) + " : " + get_submodule_description(submodules[sub]))
141 142 143 144 145 146 147 148 149 150 151 152
        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:]))