Coverage for src / answers / __init__.py: 100%

38 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-11-21 16:36 +0000

1import copy 

2import json 

3import sys 

4 

5import yaml 

6 

7from .. import constants as c 

8from .. import jinja, utils 

9from . import schema 

10 

11 

12def load(filepath): 

13 """ 

14 Load the yaml `filepath` file, modify the data if needed to have the strict 

15 minimum required to run other commands. 

16 

17 Returns data dict 

18 """ 

19 if not filepath: 

20 return None 

21 

22 try: 

23 with open(filepath, encoding="UTF-8") as fd: 

24 data = yaml.safe_load(fd) 

25 except Exception as err: 

26 sys.exit(f"error: failed to open '{filepath}': {err}") 

27 

28 if data is None: 

29 data = {} 

30 data = {"answers": data.get("answers")} 

31 

32 return data 

33 

34 

35def validate(data): 

36 """ 

37 Validate the data against a schema. Returns the normalized data, or throws an exception. 

38 """ 

39 

40 yaml_schema = yaml.safe_load(schema.SCHEMA) 

41 validator = schema.LocalValidator(yaml_schema) 

42 

43 if data is None: 

44 data = {} 

45 else: 

46 

47 if not validator.validate(data): 

48 locations = str(json.dumps(validator.errors, indent=2)) 

49 raise SystemExit(f"error: YAML answer file schema validation error. Location:\n{locations}") from None 

50 

51 return validator.normalized(data) 

52 

53 

54def process(data, env, ctx): 

55 if data is None: 

56 return ctx 

57 

58 answers = data.get("answers", {}) 

59 if answers is None: 

60 return ctx 

61 

62 for k, v in answers.items(): 

63 v = jinja.evaluate(v, env, ctx) 

64 ctx = jinja.ctx_add(ctx, k, v) 

65 return ctx