Created
February 26, 2023 11:12
-
-
Save sangimed/259c158f60ff876740d2129581717748 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import random | |
import string | |
def generate_random_string(length=10, prefix=""): | |
"""Générer une chaîne de caractères aléatoire de longueur donnée avec un préfixe optionnel.""" | |
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=length)) | |
return f"{prefix}{random_string}" | |
def update_env(env_file, vars_file): | |
# Lecture des variable depuis le fichier vars_file et écriture dans vars_dict | |
vars_dict = {} | |
with open(vars_file, "r") as f: | |
for line in f: | |
# On ignore les commentaires et les sauts de lignes | |
if line.startswith("#") or line.strip() == "" : | |
continue | |
if "=" in line: | |
var_name, var_value = line.strip().split("=") | |
vars_dict[var_name] = var_value | |
# Read the variables from the .env file | |
env_dict = {} | |
with open(env_file, "r") as f: | |
for line in f: | |
""" | |
Si la ligne sagit d'un saut de ligne ou d'un commentaire, alors créer une clé unique du dict prefixé avec respectivement blank_ ou comment_ | |
dans le but de contourner l'unicité des clés toute en ayant la possibilité d'identifier la ligne pour pouvoir l'insérer à nouveau dans le fichier. | |
""" | |
# Commentaire | |
if line.startswith("#"): | |
env_dict[generate_random_string(10, "comment_")] = line | |
continue | |
# Saut de ligne | |
if line.strip() == "": | |
env_dict[generate_random_string(10, "blank_")] = '\n' | |
continue | |
# Variable | |
if "=" in line: | |
var_name, var_value = line.strip().split("=") | |
env_dict[var_name] = line | |
# Ajout/MàJ des variables dans env_dict | |
for var_name, var_value in vars_dict.items(): | |
if var_name in env_dict: | |
env_dict[var_name] = f"{var_name}={var_value}\n" | |
else: | |
env_dict[var_name] = f"\n{var_name}={var_value}" | |
# Réecrire le fichier .env avec le contenu de env_dict | |
with open(env_file, "w") as f: | |
for line in env_dict.values(): | |
f.write(line) | |
return len(vars_dict) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Script qui permet de mettre à jours les variable d'un fichier .env depuis un fichier *.txt qui a la même structure.") | |
parser.add_argument("env_file", type=str, help="Chemin vers le fichier .env file") | |
parser.add_argument("vars_file", type=str, help="Chemin vers le fichier txt") | |
args = parser.parse_args() | |
vars_dict_length = update_env(args.env_file, args.vars_file) | |
print(f"{args.env_file} updated with variables from {args.vars_file} : {vars_dict_length}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment