diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 44d8bb5..0000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.temp -__pycache__ diff --git a/README.md b/README.md deleted file mode 100644 index 8cc2cb7..0000000 --- a/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# Reshade2Basalt -This python3 scripts will convert Reshade .ini presets to vkBasalt .conf files, changing shader settings directly in .fx files. - -# Dependencies -- Python >= 3.4 -- vkBasalt - -# Usage -After downloading it, you are ready to start using, with ```python3 run.py [--args] ``` command. - -# Options - -Because method of handle arguments, all arguments must to be passed with python types (True/False, "str", etc). These are the types that script will use: - - - -| Type | Description | Example | -|------|-----------------------------------------------------------|------------------------| -| bool | A True or False argument | --arg=True | -| str | A phrase/word wrapped in quotes | --arg="Str1,Str2..." -| path | A complete path to file or folder, looking at system root | --arg="/home/user/dir" | - -Arguments syntax are the following ```--arg=value```, and can contain various arguments. Bellow, you will find the complete arguments list. - -| Option | Description | Required | Default | Type | -|-----------------------|-----------------------------------------------------------|----------|----------------------------------------------|------| -| --help | Show help menu | No | False | bool | -| --verbose | Show some extra debug messages. Use when reporting issues | No | False | bool | -| --shaders-repo, --fxr | Set a different one reshade-shaders git repository | No | "https://github.com/crosire/reshade-shaders" | str | -| --shaders-branch, --fxb | Shaders repository branch | No | master | str | -| --preset, --p | Path to reshade .ini file. | No | $PWD/preset.ini | path | -| --ignore-shaders, --fxi | Shaders that are preset in preset, but that you want to ignore. Util when vkBasalt can't handle correctly the shader. Pass without spaces, divided by a comma. | No | "" | str | -| --output-dir | Path to save shaders after setting them up. Default is current directory (note that if you want to change shaders folder path, you must to change it on generate vkBasalt.conf too) | No | $PWD/output/ | path | - -# Contributions -All contributions to source are welcome, just create a pull request in this repo and i will verify as soon possible. - -If you can try different presets (for now, only part of reshade default shaders are noticable 100% working in vkBasalt) in looking for issues, you would already help me a lot. Please report any issue with default shaders in Issues section of this repo. - -And if you're a Linux gamer entusiast and want to helpe-me and encourage to do more linux games utilities, buy me a coffe! You can enter in contact to me to receive a payment link to donate how much you want and can to give-me. - -# Project status - -This is a Beta 1.0.0 version, with obviously various bugs to map and fix, and improvements to do. Updates by author will only occur in weekends, so you can enter here each sunday night to check for status - -Below, a list of updates that you can do, or wait for me: - -* Test various presets to map bugs, and register then in issues. -* A better documentation -* A argument that allow user to include custom shaders in .temp dir -* A better argument handler -* Special treatment to shaders that contains a .fxh file included (e.g. SMAA/FXAA, that is current not supported) -* A install script to make it available globally -* A argument that allow user to automatically creates a .sh/.desktop for some game/application already with vkBasalt configuration variables in command. -* A argument that allow user to live test presets (with vkcube) before write shaders/settings in output_dir -* .sh to run script with arguments directly as a shell script - -# Authors -* Emmy Gomes | | +55 (11) 9537-8163. diff --git a/converter.py b/converter.py deleted file mode 100644 index 62e2e35..0000000 --- a/converter.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -import sys -import os -import re - -class Converter: - def __init__(self): - self.pwd = os.getcwd() + "/" - - def get_config_update(self, shader, config, new_val): - # Add a identifier to isolate config from rest of file - config_regex = r"(.+) {}?(.+)".format(config) - config_start = re.sub(config_regex, r'|||||||\1 {}\2'.format(config), shader, count=1) - config_end = "|||||||" + re.sub(r"> =(.+)", r"> =\1|||||||", config_start.split("|||||||")[1], count=1) - - # Get old config and new config string - old_config = config_end.split('|||||||')[1] - new_config = re.sub(r"\> \= (.+)", " > = {};".format(new_val) , old_config, count=1) - - return { - "old": old_config, - "new": new_config - } - - def update_file(self, filename, shader, configs, verbose = False): - if verbose: - print("\nOperation: Converting file {}".format(filename)) - - for config in configs: - if config == '': - continue - - # Get param name and new value - param = config.split("=")[0] - value = config.split("=")[1] - - if verbose: - print("\n--------------------------------------------------------------------------------------------------------------------------------") - print("Param: " + param) - print("Value: {}\n".format(value)) - - # Get and treat setting replaces - replaces = self.get_config_update(shader, param, value) - replaces["new"] = self.treat_update_values_conversion(replaces["old"], replaces["new"]) - - if verbose: - print("Replace: " + replaces["old"] + "\n") - print("With: " + replaces["new"]) - print("--------------------------------------------------------------------------------------------------------------------------------") - - # Replace config in shader - shader = shader.replace(replaces["old"], replaces["new"]) - - return shader - - def treat_update_values_conversion(self, old, new): - # Treatments conditions - bool_cond = old.find("> = false") != -1 or old.find("> = true") - float_cond = old.find("float3(") != -1 or old.find("float2(") != -1 or old.find("float4(") != -1 - - # Treats booleans - if bool_cond: - new = new.replace("> = 0;", "> = false;") - new = new.replace("> = 1;", "> = true;") - - # Treats float - if float_cond: - value = new.split("> = ")[1].replace(";", "") - funcType = "" - - # Prevent errors with float type (2, 3 or 4 values) - if old.find("float2(") != -1: - funcType = "2" - elif old.find("float3(") != -1: - funcType = "3" - elif old.find("float4(") != -1: - funcType = "4" - - new = new.replace(value, "float{}({});".format(funcType, value)) - - return new - -converter = Converter() diff --git a/files.py b/files.py deleted file mode 100644 index 9759f4f..0000000 --- a/files.py +++ /dev/null @@ -1,203 +0,0 @@ -# -*- coding: utf-8 -*- -from shell import shell -import shutil -import sys -import os - -class Files: - def __init__(self): - self.pwd = os.getcwd() + "/" - self.ini_path = self.pwd + "preset.ini" - self.shaders_path = self.pwd + ".temp/shaders/Shaders/" - - self.replace_shaders_rules = { - "BloomAndLensFlares.fx": "Bloom.fx" - } - - self.exclude_shaders_rules = [ - "Tint.fx", - "" - ] - - - def add_excludes(self, extra_excludes = False): - if extra_excludes != False: - extra_excludes = extra_excludes.split(",") - - for extra in extra_excludes: - if extra.find(".fx") == -1: - extra = extra + ".fx" - - self.exclude_shaders_rules.append(extra) - pass - pass - pass - - def init_temp_dirs(self, use_cache = False): - # Verifies if temp dir exists, and remove it case exists - if os.path.exists("{}.temp".format(self.pwd)): - try: - if use_cache: - shutil.rmtree("{}.temp/output".format(self.pwd)) - else: - shutil.rmtree("{}.temp".format(self.pwd)) - except: - print("Error when trying to delete old temporary dir") - sys.exit() - - # Create temporary directories - try: - if use_cache == False: - os.mkdir(".temp") - os.mkdir(".temp/shaders/") - - os.mkdir(".temp/output/") - os.mkdir(".temp/output/shaders") - except: - print("Error when trying to create temporary directories.") - sys.exit() - - def get_preset_ini(self, path = False): - # Verifies if preset file is a custom one or default - if path == False: - path = self.ini_path - - # Verifies if preset exists - if not os.path.exists(path): - print("Cannot found preset file. Informed path: {}".format(path)) - sys.exit() - - file_contents = open(path, "r").read() - settings = { - "effects": [], - "configurations": {} - } - - # Get used effects - effects = file_contents.split("Techniques=")[1].split("TechniqueSorting=")[0].replace(" ", "").replace("\n", "").split(",") - - # Get effects names - for effect in effects: - if effect.find(".fx") == -1: - effect = effect + ".fx" - - # Treat replace rule for shader name, if was - if effect in self.replace_shaders_rules: - effect = self.replace_shaders_rules[effect] - - # Exclude shader if it is not supported - if effect in self.exclude_shaders_rules: - continue - - settings["effects"].append(effect) - - # Get effects settings - for effect in settings['effects']: - try: - effect_key = "[{}]\n".format(effect) - effect_settings = file_contents.split(effect_key)[1].split("\n\n")[0].split("\n") - - settings["configurations"][effect] = effect_settings - except: - print("Shader {} not found, add it to extra shaders or ignore this file".format(effect)) - sys.exit() - - return settings - - def get_shader_content(self, shader): - # Verifies if shader exists - if not os.path.exists(self.shaders_path + shader): - print("Shader file {} not exists".format(self.shader)) - sys.exit() - - content = open(self.shaders_path + shader, "r").read() - - return content - - def write_new_temp_shader(self, file_content, filename): - try: - new_file = open("{}.temp/output/shaders/{}".format(self.pwd, filename), "w") - new_file.write(file_content) - new_file.close() - except: - print("Error when trying to write new shader file in temp folder. Filename: " + filename) - sys.exit() - - def copy_reshade_core_to_temp(self): - try: - current_path = [ - self.pwd + ".temp/shaders/Shaders/ReShade.fxh", - self.pwd + ".temp/shaders/Shaders/ReShadeUI.fxh" - ] - new_path = [ - self.pwd + ".temp/output/shaders/ReShade.fxh", - self.pwd + ".temp/output/shaders/ReShadeUI.fxh" - ] - - shutil.copyfile(current_path[0], new_path[0]) - shutil.copyfile(current_path[1], new_path[1]) - except: - print("Error when trying to copy Reshade Core file to temporary output folder.") - sys.exit() - - def copy_reshade_textures_to_temp(self): - try: - current_path = self.pwd + ".temp/shaders/Textures/" - new_path = self.pwd + ".temp/output/textures/" - - shutil.copytree(current_path, new_path) - except: - print("Error when trying to copy Reshade Textures to temporary output folder.") - sys.exit() - - def create_conf(self, effects, output_dir = False): - # Verifies if user want to use default output dir - if output_dir == False: - output_dir = self.pwd + "output" - - # Verifies if output dir exists, and han - if os.path.exists(output_dir): - create_dir = input("Output directory already exists. Want to overwrite it? [S/n]: ") - - if create_dir == "n" or create_dir == "N": - print("Exiting the program") - sys.exit() - else: - os.system("cd {} && rm -rf * && rm -rf .*".format(output_dir)) - else: - os.system("mkdir {}".format(output_dir)) - - if output_dir[-1] != "/": - output_dir = output_dir + "/" - - # Variables - textures_path = output_dir + "textures/" - shaders_path = output_dir + "shaders/" - used_effects_str = "effects = " - effects_path_str = "" - - # Loop effects to build file - for effect in effects: - name = effect.lower().replace(".fx", "") - - used_effects_str += "{}:".format(name) - effects_path_str += "{} = {}{}\n ".format(name, shaders_path, effect) - - file_content = """ - reshadeTexturePath = {} - reshadeIncludePath = {} - - {} - - {} - """.format(textures_path, shaders_path, effects_path_str, used_effects_str[:-1]).replace(" ", "") - - # Write config file - conf_file = open(self.pwd + ".temp/output/vkBasalt.conf", "w") - conf_file.write(file_content) - conf_file.close() - - return output_dir - - -files = Files() diff --git a/messages.py b/messages.py deleted file mode 100644 index 7bfe5c4..0000000 --- a/messages.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- - -version = "v1.0.0" - -help_str = """ -Reshade2Basalt. - -{} -Author: Emmy Gomes -Email: aou-emmy@outlook.com -Issues: https://github.com/eemmy/Reshade2Basalt/issues - -To donate, please contact +55 11 95837-8163 on Whatsapp, or send-me a email. - - -Syntax: python3 run.py [--argument=value] - -Types: -bool True/False (uppercase). -int 0,1,2... -float 0.4,0.5,0.6... -path Absolute path to files or folders -str Phrase or word wrapped in quotes (ex: \"Shaders, Textures, etc...\") - - -Options: - ---help=bool Show this menu instead running script. ---verbose=bool Add a high debug output. Recommended to report issues. -[--shaders-repo, --fxr]=str Git clone string to shaders repository (default is Reshade Shaders in packages section). -[--shaders-branch, --fxb]=str Shaders repository branch (default is master). -[--preset, --p]=path Path to reshade .ini file. If not specified, the script will assume that the file is in the current directory, as preset.ini -[--ignore-shaders, --fxi]=str Inform which preset using shaders you want to ignore. This is util with complex shaders that vkBasalt can't handle correctly. Pass without spaces, divided by a comma. ---use-cached-shaders=bool Inform to script does not re-download shaders from remote git repository if it already exists. ---include-shaders-dir=path Inform a path to folder with custom shaders that you want to include in script job. This shaders will replace remote shaders. ---output-dir=path Path to save shaders after setting them up. Default is current directory (note that if you want to change shaders folder path, you must to change it on generate vkBasalt.conf too) - - -Packages: - -List of packages that work with this script, that the conversion result might be useful, or that inspired or were used to build this script. - -Reshade by Crosire: https://reshade.me, https://github.com/crosire/reshade -reshade-shaders by Crosire: https://github.com/crosire/reshade-shaders -vkBasalt by DadSchoorse: https://github.com/DadSchoorse/vkBasalt - -""".format(version) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..00dcf02 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +GitPython +click diff --git a/run.py b/run.py index 1c1bc8e..e698c50 100644 --- a/run.py +++ b/run.py @@ -1,52 +1,216 @@ # -*- coding: utf-8 -*- -from files import files -from converter import converter -from shell import shell -from messages import * +import click +import configparser +from git import Repo +import logging +import os +from os.path import join as path_join +import re +import shutil import sys +import tempfile -# Arguments variations -repo = ["shaders-repo", "fxr"] -branch = ["shaders-branch", "fxb"] -preset = ["preset", "p"] -exclude_shaders = ["ignore-shaders", "fxi"] -verbose = ["verbose"] -include_shaders = ["include-shaders-dir"] -cache = ["use-cached-shaders"] -output_dir = ["output-dir"] +# TODO: Improve options help +# TODO: Remove constant "shaders" folder and put it as argument -# Get script arguments -shell.get_args(sys.argv) +# Use click (https://click.palletsprojects.com) to create a nice CLI +@click.command() +@click.option("--preset", "-p", default="preset.ini", show_default=True, + help="Name of the preset .ini file to convert.") +@click.option("--output-dir", "-o", "output", default="output/") +@click.option("--shaders-repo", "-r", "repos", multiple=True, + default=["https://github.com/crosire/reshade-shaders.git"], show_default=True) +@click.option("--shaders-branch-prompt", "-b", "branch", + default=False, help="Ask to use different branches than master") +@click.option("--ignore-shaders", "-i", "ignored_shaders", multiple=True, type=str, + help="Shader to ignore. Repeatable option.") +@click.option("--use-cached-shaders", "-c", "use_cache", default=True, + help="Clear the shaders directory first") +@click.option("--verbose", "-v", "verbosity", count=True) # Verbosity level unused for now, equivalent to boolean +def run(preset, output, repos, branch, ignored_shaders, use_cache, verbosity): + logging.basicConfig(level=max(10, 40-verbosity*10)) + if os.path.exists(output): + create_dir = input("Output directory already exists. Want to overwrite it? [y/N]: ") + if create_dir.lower().strip() != "y": + logging.warning("Exiting the program") + sys.exit() + os.makedirs(output, exist_ok=True) -# Verifies if user want's to see help menu -if (shell.get_arg("help")): - print(help_str) - sys.exit() + if not (use_cache and os.path.exists(".cache")): + if os.path.exists(".cache"): + confirm = input("Going to delete .cache! Continue? [y/N]") + if confirm.lower != "y": + sys.exit(1) + shutil.rmtree(".cache", ignore_errors=True) + os.makedirs(".cache", exist_ok=True) -# Add exclude rules -files.add_excludes(shell.get_arg(exclude_shaders)) + for repo in repos: + cur_branch = "master" + if branch: + cur_branch = input(f"Branch to use for {repo} ? [master]") or "master" + init_shaders(repo, cur_branch) -# Init temp dirs and download shaders -files.init_temp_dirs(shell.get_arg(cache)) -shell.download_shaders(shell.get_arg(repo), shell.get_arg(branch), shell.get_arg(cache)) + # Create output folder structure + out_shaders = path_join(output, "shaders/") + out_textures = path_join(output, "textures/") + os.makedirs(out_shaders, exist_ok=True) + os.makedirs(out_textures, exist_ok=True) -# Get ini configurations -settings = files.get_preset_ini(shell.get_arg(preset)) + settings = get_preset_ini(preset, ignored_shaders) + for shader, config in settings["configurations"].items(): + shader_path = path_join(".cache/Shaders", shader) + try: + with open(shader_path, "r") as f: + old_shader_file = f.read() + except FileNotFoundError as e: + if "_" not in shader: + raise + logging.warning(f"{shader_path} not found, trying to find a subfolder...") + new_path = path_join(".cache/Shaders", shader.split("_")[0], shader) + with open(new_path, "r") as f: + old_shader_file = f.read() + logging.info(f"Converting shader {shader_path}") + new_shader_file = update_file(old_shader_file, config, verbosity) + with open(path_join(output, "shaders/", shader), "w") as f: + f.write(new_shader_file) -# Loop settings to convert files -debug = shell.get_arg(verbose) -for shader in settings["configurations"]: - old_shader_file = files.get_shader_content(shader) - new_shader_file = converter.update_file(shader, old_shader_file, settings["configurations"][shader], debug) + shutil.copy(".cache/Shaders/ReShade.fxh", out_shaders) + shutil.copy(".cache/Shaders/ReShadeUI.fxh", out_shaders) + shutil.copytree(".cache/Textures", out_textures, dirs_exist_ok=True) + create_conf(settings["effects"], output) - files.write_new_temp_shader(new_shader_file, shader) -# Get reshade core to shaders path, and copy textures folder to prevent errors -files.copy_reshade_core_to_temp() -files.copy_reshade_textures_to_temp() +def init_shaders(repo, branch): + with tempfile.TemporaryDirectory() as tmpdir: + repo_dir = path_join(tmpdir) + logging.info(f"Cloning repo {repo}") + Repo.clone_from(repo, to_path=repo_dir, multi_options=[f"--branch={branch}"]) + shaders_path = path_join(repo_dir, "Shaders/") + textures_path = path_join(repo_dir, "Textures/") -# Create vkBasalt.conf file -output_dir_path = files.create_conf(settings["effects"], shell.get_arg(output_dir)) + if os.path.exists(shaders_path): + shutil.copytree(shaders_path, ".cache/Shaders", dirs_exist_ok=True) + if os.path.exists(textures_path): + shutil.copytree(textures_path, ".cache/Textures", dirs_exist_ok=True) -# Move converted files to output dir -shell.move_temp_to_output(output_dir_path) + +def get_preset_ini(path, ignored_shaders): + replace_shaders_rules = {"BloomAndLensFlares.fx": "Bloom.fx", "ADOF.fx": "DOF.fx", + "ContrastAdaptiveSharpen.fx": "CAS.fx"} + exclude_rules = {"Tint.fx"} + for ignored in ignored_shaders: + if not ignored.endswith(".fx"): + ignored += ".fx" + exclude_rules.add(ignored) + + # Verifies if preset exists + if not os.path.exists(path): + logging.error("Cannot find preset file. Informed path: {}".format(path)) + sys.exit() + + # Read the content of the .ini file through configparser + with open(path, "r") as f: + contents = f.read() + config = configparser.ConfigParser() + config.optionxform = str # Required to have case-sensitive keys + try: + config.read_string(path, source=path) + except configparser.MissingSectionHeaderError: + logging.warning("Invalid .ini, trying to add a [default] category") + config.read_string("[root]\n"+contents, source=path) + + # TODO: This is partly redundant with configparser's structure, it could be done better + settings = { + "effects": [], + "configurations": {} + } + + # Get effects names + for effect in {i.strip().split("@")[-1] for i in config["root"]["TechniqueSorting"].split(",")}: + if not effect.endswith(".fx"): # Is this needed (or even working as intended)? + effect += ".fx" + + # Replace shader if a rule says so + if effect in replace_shaders_rules: + effect = replace_shaders_rules[effect] + + # Exclude shader if a rule says so + if effect in exclude_rules: + continue + + settings["effects"].append(effect) + + for effect in settings['effects']: + try: + settings["configurations"][effect] = dict(config[effect]) + except KeyError: + logging.error(f"Shader {effect} not found, check config file (including filename-case), " + "that the shader exist, or add it to the ignored shaders") + sys.exit() + return settings + + +def create_conf(effects, output_dir): + # Variables + textures_path = path_join(output_dir, "textures/") + shaders_path = path_join(output_dir, "shaders/") + used_effects_str = "effects = " + effects_path_str = "" + + # Loop effects to build file + for effect in effects: + if effect.lower().endswith(".fx"): + name = effect[:-3] + else: + name = effect + used_effects_str += f"{name}:" + effects_path_str += f"{name} = {shaders_path}{effect}\n" + + file_content = "\n".join([ + f"reshadeTexturePath = {textures_path}", + f"reshadeIncludePath = {shaders_path}" + f"\n\n{effects_path_str}", + f"\n{used_effects_str[:-1]}" + ]) + + # Write config file + with open(path_join(output_dir, "vkBasalt.conf"), "w") as f: + f.write(file_content) + return output_dir + + +def update_file(shader: str, configs: dict, verbose=0): + for param, value in configs.items(): + if verbose: + logging.debug(f"Param: {param}\nValue: {value}") + + pattern = r"".join([ + "(^\[[:alnum:]]*\[[:blank:]]*)", # "uniform" keyword or similar, group 1 + "(\[[:alnum:]]*)", # variable type (bool, float, float2, etc), group 2 + "(\[[:blank:]]*{param}\[[:blank:]]*", # name of the current parameter, group 3 until value assignment + "<.*?>", # content block between brackets + "\[[:blank:]]*=\[[:blank:]])(.*?);$" # value assignment (e.g. " = 1.00;"), with value captured as group 4 + ]) # Brackets have to be escaped (e.g. \[[:alnum:]]) to prevent a FutureWarning, + # pycharm warns about invalid sequence because their regex handler probably still follows old norms + + # This custom function is passed to re.sub. This could have been done through a re.search followed by re.sub, + # but would have implied running the regex twice, which is unnecessary. Instead we hijack the substitution + # function to process and inject the new value. + def transform_value(matchobj): + """Process a config block to inject a new value inside without breaking everything""" + value_type = matchobj.group(2) + if value_type == "bool": + new_value = "true" if int(value) == 1 else "false" + elif re.search(r"float.+", value_type): # floatX value type + new_value = f"{value_type}({value})" # value is a str containing multiple values (and not a tuple) + else: + new_value = value + # FIXME: This return object is really ugly, there has to be a better way + return "".join([matchobj.group(1), matchobj.group(2), matchobj.group(3), new_value, ";"]) + + shader = re.sub(pattern, transform_value, shader) + return shader + + +if __name__ == "__main__": + run() diff --git a/shell.py b/shell.py deleted file mode 100644 index 1f0d654..0000000 --- a/shell.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -import sys -import os - -# Handle shell operations, like shade repositories management. -class Shell: - def __init__(self): - self.shaders_repo = "https://github.com/crosire/reshade-shaders.git" - self.shaders_branch = "master" - self.shaders_package = "crosire/reshade-shaders" - - self.pwd = os.getcwd() + "/" - - self.args = {} - - def download_shaders(self, repo = False, branch = False, use_cached = False): - # Verifies if user want's to use cached shaders - if use_cached: - if os.path.exists(self.pwd + ".temp/shaders/Shaders"): - return - else: - print("Can't find cached shaders. Downloading from remote.\n") - - # Verifies if branch/repo are a custom one or the defaults - if repo == False: - repo = self.shaders_repo - if branch == False: - branch = self.shaders_branch - - # Download shaders repo - try: - os.system("git clone {} {}.temp/shaders/".format(repo, self.pwd)) - os.system("cd {}.temp/shaders && git checkout {}".format(self.pwd, branch)) - except: - print("Error when trying to download git-repository {} from {}:{}".format(self.shaders_package, repo, branch)) - sys.exit() - - def get_args(self, args): - args_dict = {} - args.pop(0) - - # Add arguments to dict - for arg in args: - # Verifies if argument is invalid - if arg.find("--") == -1 or arg.find("=") == -1: - if "invalid" not in args_dict: - args_dict["invalid"] = [ arg ] - else: - args_dict["invalid"].append(arg) - else: - key_val = arg.split("=") - args_dict[key_val[0].replace("--", "")] = key_val[1] - - # Validates arguments - self.validate_args(args_dict) - - self.args = args_dict - - def validate_args(self, args): - if not "invalid" in args: - return True - - for invalid_arg in args["invalid"]: - print("Invalid argument {}".format(invalid_arg)) - - print("\nPlease consult supported arguments and arguments syntax.") - sys.exit() - - def get_arg(self, name): - if isinstance(name, list): - for n in name: - if n in self.args: - return self.args[n] - - return False - else: - if not name in self.args: - return False - else: - return self.args[name] - - def move_temp_to_output(self, path): - try: - os.system("mv {}.temp/output/* {}".format(self.pwd, path)) - except: - print("Error when trying to move temporary output folder to final destination.") - sys.exit() - -shell = Shell()