From 742ff730e7bb0011acf961632c9775804b9c47f2 Mon Sep 17 00:00:00 2001 From: Nicolas KAROLAK <nicolas@karolak.fr> Date: Tue, 29 Jan 2019 17:30:03 +0100 Subject: [PATCH] add new utils to write option in conf.sh | refs #27883 --- utils.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/utils.py b/utils.py index d4c4afad..6f9faebc 100644 --- a/utils.py +++ b/utils.py @@ -5,6 +5,7 @@ from collections import OrderedDict import os from pathlib import Path +import re import subprocess import sys from typing import Any @@ -210,6 +211,44 @@ def get_conf(name: str, default: str = None) -> str: return conf.get(name, default) +def set_conf(key: str, value: str, override: bool = False) -> bool: + """Write the given configuration option in `conf.sh`. + + :param key: Option name + :type key: str + :param value: Option value + :type value: str + :param override: Wether to override the option if it already exists, defaults to False + :param override: bool, optional + :return: True if the option have changed, False otherwise + :rtype: bool + """ + + state = False + + # open conf.sh file + conf_fh = open(Path(__file__, CONF_PATH).resolve(), "w") + # get its content + conf = conf_fh.read() + + # check if option already exists + regex = re.compile(r"^" + key.upper() + "=(.*)$", flags=re.M) + match = regex.search(conf) + if match and override: + conf = regex.sub("{}='{}'".format(key.upper(), str(value)), conf) + state = True + else: + # add option + conf = conf + "\n{}='{}'\n".format(key.upper(), str(value)) + state = True + + # write file + conf_fh.write(conf) + conf_fh.close() + + return state + + def run_commands(cmds: list): """Run a serie of successive commands. -- GitLab