webis.py 5.78 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
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
    """
Steve Goering's avatar
Steve Goering committed
68 69 70
    if not os.path.isfile(modulepath):
        return os.path.basename(modulepath)

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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
86 87

    lInfo("output:")
88
    cmd = " ".join([scriptfile] + params)
89 90 91

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

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

    return return_value
100 101


Steve Goering's avatar
Steve Goering committed
102 103 104 105 106 107 108 109
def get_keys_startswith(dictionary, searchkey):
    """
    extract keys that have a prefix match
    """
    needed_keys = [x for x in dictionary.keys() if x.startswith(searchkey)]
    return needed_keys


Steve Goering's avatar
Steve Goering committed
110
def get_random_msg():
Steve Goering's avatar
fix  
Steve Goering committed
111 112 113 114 115
    cmd = "wget -qO - http://www.asciiartfarts.com/random.cgi | sed -n '/<pre>/,/<\/pre>/p' | sed -n '/<table*/,/<\/table>/p' | sed '1d' | sed '$d'"
    import subprocess
    output = subprocess.check_output(cmd, shell=True).decode("ascii")
    from html import unescape
    return unescape(output)
Steve Goering's avatar
Steve Goering committed
116 117


118 119
def main(args):
    lInfo("read config")
Steve Goering's avatar
fix  
Steve Goering committed
120
    lInfo("\n" + get_random_msg())
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    # 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)

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

Steve Goering's avatar
Steve Goering committed
142 143 144 145
    if len(args) > 0 and len(get_keys_startswith(modules, args[0])) == 1:
        args[0] = get_keys_startswith(modules, args[0])[0]

    argsdict = vars(parser.parse_args(args[0:2]))  # using args[..] is necessary because of unknown arguments in the parameters for submoduls
146 147

    # set parameters
Steve Goering's avatar
Steve Goering committed
148
    argsdict["parameter"] = args[2:]
149 150 151 152 153 154 155 156 157

    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"]])
Steve Goering's avatar
Steve Goering committed
158 159 160 161 162
    submodules["help"] = "integrated help"

    if len(get_keys_startswith(submodules, argsdict["submodul"])) == 1:
        argsdict["submodul"] = get_keys_startswith(submodules, argsdict["submodul"])[0]

163 164
    if argsdict["submodul"] == "help":
        lHelp("submodules of " + argsdict["modul"])
Steve Goering's avatar
Steve Goering committed
165 166
        max_size = len(max(submodules.keys(), key=len))
        format_str = "{:<" + str(max_size) + "}"
167
        for sub in sorted(submodules.keys()):
Steve Goering's avatar
Steve Goering committed
168
            lHelp("    " + format_str.format(sub) + " : " + get_submodule_description(submodules[sub]))
169 170 171 172 173 174 175 176 177 178 179 180
        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:]))