Coverage for muuntaa/writer.py: 100.00%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-07-21 12:16:47 +00:00

1import json 

2import logging 

3import pathlib 

4 

5from muuntaa import CSAF_FILE_SUFFIX, ENCODING, Pathlike, ScopedMessages, WriterOptions 

6 

7 

8def write_csaf(csaf_dict: dict[str, object], file_path: Pathlike, options: WriterOptions = None) -> ScopedMessages: 

9 """Write the CSAF data from python dict into a CSAF JSON file creating path as needed.""" 

10 if options is None: 

11 options = {'ensure_ascii': False, 'indent': 2} 

12 scoped_messages: ScopedMessages = [] 

13 path = pathlib.Path(file_path).expanduser().resolve() 

14 base_dir = path.parent 

15 try: 

16 if not base_dir.is_dir(): 

17 path.mkdir(parents=True, exist_ok=True) 

18 scoped_messages.append((logging.INFO, f'Created output folder {base_dir}.')) 

19 if path.is_file(): 

20 scoped_messages.append((logging.WARNING, f'Output {path} already exists. Overwriting it.')) 

21 if path.suffixes[-1] != CSAF_FILE_SUFFIX: 

22 scoped_messages.append( 

23 (logging.WARNING, f'Given output file {path} does not contain valid {CSAF_FILE_SUFFIX} suffix.') 

24 ) 

25 with open(path, 'wt', encoding=ENCODING) as handle: 

26 json.dump(csaf_dict, handle, **options) # type: ignore 

27 scoped_messages.append((logging.INFO, f'Successfully wrote {path}.')) 

28 

29 except Exception as err: # noqa 

30 scoped_messages.append((logging.CRITICAL, f'Writing output file {path} failed. {err}')) 

31 

32 return scoped_messages