1515
1616from pathlib import Path
1717from typing import List , Optional
18+ import schema
19+ from schema import Regex , Schema , SchemaError
1820
1921import yaml
2022from loguru import logger
@@ -56,11 +58,16 @@ def from_file(cls, path):
5658 with open (path , "r" ) as stream :
5759 try :
5860 raw_config = yaml .safe_load (stream )
59- config = dict (raw_config )
60- raw_steps = config ["steps" ]
61- metadata = config ["metadata" ]
61+ if validate_config (raw_config ):
62+ config = dict (raw_config )
63+ raw_steps = config ["steps" ]
64+ metadata = config ["metadata" ]
65+ else :
66+ logger .info ("Validation of config failed." )
67+ return None
6268 except yaml .YAMLError as exc :
6369 logger .info (exc )
70+ return None
6471
6572 if raw_steps .get ("unlock_bootloader" ) is not None :
6673 unlock_bootloader = [
@@ -92,8 +99,42 @@ def _load_config(device_code: str, config_path: Path) -> Optional[InstallerConfi
9299 try :
93100 config = InstallerConfig .from_file (path )
94101 logger .info (f"Loaded device config from { path } ." )
95- logger .info (f"Config metadata: { config .metadata } ." )
102+ if config :
103+ logger .info (f"Config metadata: { config .metadata } ." )
96104 return config
97105 except FileNotFoundError :
98106 logger .info (f"No device config found for { path } ." )
99107 return None
108+
109+
110+ def validate_config (config : str ) -> bool :
111+ """Validate the schema of the config."""
112+
113+ step_schema = {
114+ "title" : str ,
115+ "type" : Regex (r"text|confirm_button|call_button|call_button_with_input" ),
116+ "content" : str ,
117+ schema .Optional ("command" ): Regex (r"^adb\s|^fastboot\s|^heimdall\s" ),
118+ schema .Optional ("allow_skip" ): bool ,
119+ }
120+
121+ config_schema = Schema ({
122+ "metadata" : {
123+ "maintainer" : str ,
124+ "devicename" : str ,
125+ "devicecode" : str ,
126+ },
127+ "requirements" : schema .Or (None , []),
128+ "steps" : {
129+ "unlock_bootloader" : schema .Or (None , [step_schema ]),
130+ "flash_recovery" : [step_schema ],
131+ "install_os" : [step_schema ],
132+ }
133+ })
134+ try :
135+ config_schema .validate (config )
136+ logger .info ("Config is valid." )
137+ return True
138+ except SchemaError as se :
139+ logger .info (f"Config is invalid. Error { se } " )
140+ return False
0 commit comments