Commit 5fcaeae1e904cd253a5ac6fa0edca7185b7f174f

Authored by Quillot Mathias
1 parent 7213a20609
Exists in master

New way to set environment variable using core.env module. Need to define now how to store envs.

Showing 2 changed files with 98 additions and 15 deletions Inline Diff

File was created 1 import json
2
3 """
4 This module aims to manage environement variables local to the application.
5 These variables are persitent and located in a json file.
6 """
7
8 class Env(object):
9 """Initialize with an persistent file (json)
10
11 You can access to environment variables using the brackets operators.
12 You can also check with the 'in' operator if a key is present among
13 the variables.
14
15 example code:
16 ```
17 env = Env("myfile.json")
18
19 if "MyVariable" in env:
20 print(env["MyVariable"])
21 else:
22 env["MyVariable"] = "New value"
23 ```
24
25 """
26 def __init__(self, file: str):
27 self.__variables = {}
28 self.file = file
29 self.load()
30
31 @property
32 def variables(self):
33 return self.__variables
34
35 @property
36 def file(self):
37 return self.__file
38
39 @file.setter
40 def file(self, file):
41 self.__file = file
42
43
44 def set(self, key: str, value: str):
45 """Modify an environment variable
46
47 Args:
48 key (str): [description]
49 value ([type]): [description]
50 """
51 self.__variables[str]
52 self.save()
53
54
55 def get(self, key: str) -> str:
56 """Get an environment variable.
57
58 Args:
59 key (str): [description]
60
61 Returns:
62 [str]: [description]
63 """
64 return self.variables[key]
65
66 def __getitem__(self, key):
67 print(key)
68 return self.variables[key]
69
70 def __setitem__(self, key, value):
71 self.variables[key] = value
72
73 def __delitem__(self, key):
74 del self.variables[key]
75
76 def __contains__(self, key):
77 return key in self.variables
78
79 def load(self):
80 """Load the variables from the json file.
81 """
82 with open(self.file, "r") as f:
83 self.__variables = json.load(f)
84
85
86 def save(self):
87 """Save the variables into the json file.
88 """
89 with open(self.file, "w") as f:
90 json.dump(self.variables, f)
91
1 import argparse 1 import argparse
2 import os 2 import os
3 from utils import SubCommandRunner 3 from utils import SubCommandRunner
4 #from decouple import Config, RepositoryEnv 4 #from decouple import Config, RepositoryEnv
5 import decouple 5 import decouple
6 import json 6 import json
7 import core.env
7 8
8
9 # TODO: 9 # TODO:
10 # Load automatically if exists the persistency file 10 # Load automatically if exists the persistency file
11 # Create a class that is a sigleton with configuration variables 11 # Create a class that is a sigleton with configuration variables
12 12
13 VOLIA_ENV_VAR="VOLIA_EXPERIMENT" 13 VOLIA_ENV_VAR="VOLIA_EXPERIMENT"
14 14
15 15
16 def init(): 16 def init():
17 """ 17 """
18 Initialize volia 18 Initialize volia
19 """ 19 """
20 20
21 directory = VOLIA_HOME 21 directory = VOLIA_HOME
22 22
23 if not os.path.isdir(directory): 23 if not os.path.isdir(directory):
24 os.mkdir(directory) 24 os.mkdir(directory)
25 25
26 #config = decouple.AutoConfig(search_path=directory) 26 #config = decouple.AutoConfig(search_path=directory)
27 #config = Config(RepositoryEnv(directory)) 27 #config = Config(RepositoryEnv(directory))
28 28
29 persistency_file = os.path.join(directory, "persistency.json") 29 persistency_file = os.path.join(directory, "persistency.json")
30 env_file = os.path.join(directory, ".env") 30 env_file = os.path.join(directory, ".env")
31 31
32 with open(env_file, "w") as f: 32 with open(env_file, "w") as f:
33 f.write(f"VOLIA_PERSISTENCY=\"{persistency_file}\"") 33 f.write(f"VOLIA_PERSISTENCY=\"{persistency_file}\"")
34 #exit(1) 34 #exit(1)
35 basic_persistency = { 35 basic_persistency = {
36 "current_experiment": None 36 "current_experiment": None
37 } 37 }
38 38
39 with open(persistency_file, "w") as f: 39 with open(persistency_file, "w") as f:
40 json.dump(basic_persistency, f, indent=4) 40 json.dump(basic_persistency, f, indent=4)
41 41
42 42
43 43
44 def create(): 44 def create():
45 pass 45 pass
46 46
47 def show(): 47 def show():
48 print("Volia env var : " + VOLIA_ENV_VAR) 48 print("Volia env var : " + VOLIA_ENV_VAR)
49 print("Value : " + str(os.getenv(VOLIA_ENV_VAR))) 49 print("Value : " + str(os.getenv(VOLIA_ENV_VAR)))
50 config = decouple.AutoConfig(search_path="") 50 config = decouple.AutoConfig(search_path="")
51 pass 51 pass
52 52
53 def activate(): 53 def activate():
54 pass 54 pass
55 55
56 def deactivate(): 56 def deactivate():
57 #pycrosskit.envariables.SysEnv.set_var(VOLIA_ENV_VAR, "UNE VARIABLE") 57 #pycrosskit.envariables.SysEnv.set_var(VOLIA_ENV_VAR, "UNE VARIABLE")
58 print("VARIABLE: " + pycrosskit.envariables.SysEnv.get_var(VOLIA_ENV_VAR, delete=True)) 58 print("VARIABLE: " + pycrosskit.envariables.SysEnv.get_var(VOLIA_ENV_VAR, delete=True))
59 print("Desactivation") 59 print("Desactivation")
60 print("New var : " + os.getenv(VOLIA_ENV_VAR)) 60 print("New var : " + os.getenv(VOLIA_ENV_VAR))
61 pass 61 pass
62 62
63 def remove(): 63 def remove():
64 pass 64 pass
65 65
66 66
67 if __name__ == '__main__': 67 if __name__ == '__main__':
68 68
69 # Load VOLIA_HOME env var 69 # Load VOLIA_HOME env var
70 VOLIA_HOME = os.getenv("VOLIA_HOME") 70 VOLIA_HOME = os.getenv("VOLIA_HOME")
71 71
72 if VOLIA_HOME is None: 72 if VOLIA_HOME is None:
73 raise Exception("VOLIA_HOME is not defined. Please, define where you want to initialize VOLIA_HOME.\nWe suggest to set this variable to following value: /home/[your name]/.volia.") 73 raise Exception("VOLIA_HOME is not defined. Please, define where you want to initialize VOLIA_HOME.\nWe suggest to set this variable to following value: /home/[your name]/.volia.")
74 74
75 # Load environment file if exists 75 # Load environment file if exists
76 # TODO: Pas besoin de INIT finalement. 76 # TODO: Pas besoin de INIT finalement.
77 CONFIG = None 77 CONFIG = None
78 PERSISTENCY_DATA = None 78 PERSISTENCY_DATA = None
79 env_file = os.path.join(VOLIA_HOME, ".env") 79 env_file = os.path.join(VOLIA_HOME, ".env")
80 if os.path.isfile(env_file):
81 # Load le fichier
82 CONFIG = decouple.AutoConfig(search_path=VOLIA_HOME)
83 # Then loading the persistency file
84 persistency_file = os.path.join(VOLIA_HOME, "persistency.json")
85 80
86 with open(persistency_file, "r") as f: 81 if not os.path.isfile(env_file):
87 PERSISTENCY_DATA = json.load(f)
88
89 else:
90 # Volia not initialized.
91 print("VOLIA is not initialized. Initializing.") 82 print("VOLIA is not initialized. Initializing.")
92 init() 83 init()
93 pass
94 84
95 print("Config: ", CONFIG) 85 # Load le fichier
96 print("PERSISTENCY_DATA: ", PERSISTENCY_DATA) 86 CONFIG = decouple.AutoConfig(search_path=VOLIA_HOME)
87 # Then loading the persistency file
88 persistency_file = os.path.join(VOLIA_HOME, "persistency.json")
89 PERSISTENCY_DATA = core.env.Env(persistency_file)
97 90
98 91 # PARSER
99 parser = argparse.ArgumentParser(description="...") 92 parser = argparse.ArgumentParser(description="...")
100 subparsers = parser.add_subparsers(title="actions") 93 subparsers = parser.add_subparsers(title="actions")
101 94
102 # init : initialize the volia environment tool 95 # init : initialize the volia environment tool
103 parser_init = subparsers.add_parser("init", help="init volia environment") 96 parser_init = subparsers.add_parser("init", help="init volia environment")
104 parser_init.set_defaults(which="init") 97 parser_init.set_defaults(which="init")
105 98
106 # create a new env 99 # create a new env
107 parser_create = subparsers.add_parser("create", help="create an experimental environment") 100 parser_create = subparsers.add_parser("create", help="create an experimental environment")
108 parser_create.set_defaults(which="create") 101 parser_create.set_defaults(which="create")
109 102
110 # activate env 103 # activate env
111 parser_activate = subparsers.add_parser("activate", help="activate an experimental environment") 104 parser_activate = subparsers.add_parser("activate", help="activate an experimental environment")
112 parser_activate.set_defaults(which="activate") 105 parser_activate.set_defaults(which="activate")
113 ''' 106 '''
114 Pour activater, il suffit d'ajouter la variable d'environnement. 107 Pour activater, il suffit d'ajouter la variable d'environnement.
115 ''' 108 '''
116 # deactivate env 109 # deactivate env
117 parser_deactivate = subparsers.add_parser("deactivate", help="deactivate an experimental environment") 110 parser_deactivate = subparsers.add_parser("deactivate", help="deactivate an experimental environment")
118 parser_deactivate.set_defaults(which="deactivate") 111 parser_deactivate.set_defaults(which="deactivate")
119 ''' 112 '''
120 Pour désactiver il suffit d'enlever la variable d'environnement. 113 Pour désactiver il suffit d'enlever la variable d'environnement.
121 ''' 114 '''
122 115
123 # remove env 116 # remove env
124 parser_remove = subparsers.add_parser("remove", help="remove an experimental environment") 117 parser_remove = subparsers.add_parser("remove", help="remove an experimental environment")
125 parser_remove.set_defaults(which="remove") 118 parser_remove.set_defaults(which="remove")
126 119
127 # show env 120 # show env
128 parser_show = subparsers.add_parser("show", help="show the list of experimental environment") 121 parser_show = subparsers.add_parser("show", help="show the list of experimental environment")
129 parser_show.set_defaults(which="show") 122 parser_show.set_defaults(which="show")
130 123
131 # Parse 124 # Parse
132 args = parser.parse_args() 125 args = parser.parse_args()
133 126
134 # Run commands 127 # Run commands
135 runner = SubCommandRunner({ 128 runner = SubCommandRunner({
136 "create": create, 129 "create": create,
137 "activate": activate, 130 "activate": activate,
138 "deactivate": deactivate, 131 "deactivate": deactivate,
139 "remove": remove, 132 "remove": remove,
140 "show" : show, 133 "show" : show,
141 "init" : init 134 "init" : init