Coverage for src/somesy/cli/fill.py: 44%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-07-29 07:42 +0000

1"""Fill command of somesy.""" 

2 

3import logging 

4from pathlib import Path 

5from sys import stdin 

6 

7import typer 

8from jinja2 import Environment, FunctionLoader, select_autoescape 

9 

10from .util import ( 

11 existing_file_arg_config, 

12 file_arg_config, 

13 resolved_somesy_input, 

14 wrap_exceptions, 

15) 

16 

17logger = logging.getLogger("somesy") 

18app = typer.Typer() 

19 

20 

21@app.callback(invoke_without_command=True) 

22@wrap_exceptions 

23def fill( 

24 template_file: Path = typer.Option( 

25 None, 

26 "--template", 

27 "-t", 

28 help="Path to a Jinja2 template for somesy to fill (default: stdin).", 

29 **existing_file_arg_config, 

30 ), 

31 input_file: Path = typer.Option( 

32 None, 

33 "--input-file", 

34 "-i", 

35 help="Path of somesy input file (default: try to infer).", 

36 **existing_file_arg_config, 

37 ), 

38 output_file: Path = typer.Option( 

39 None, 

40 "--output-file", 

41 "-o", 

42 help="Path for target file (default: stdout).", 

43 **file_arg_config, 

44 ), 

45): 

46 """Fill a Jinja2 template with somesy project metadata (e.g. list authors in project docs).""" 

47 somesy_input = resolved_somesy_input(input_file=input_file) 

48 

49 if template_file: 

50 logger.debug(f"Reading Jinja2 template from '{template_file}'.") 

51 with open(template_file, "r") as f: 

52 template_str = f.read() 

53 else: 

54 logger.debug("Reading Jinja2 template from stdin.") 

55 template_str = stdin.read() 

56 

57 result = ( 

58 Environment( 

59 loader=FunctionLoader(lambda _: template_str), 

60 autoescape=select_autoescape(), 

61 ) 

62 .get_template("") 

63 .render(project=somesy_input.project) 

64 ) 

65 

66 if output_file: 

67 logger.debug(f"Writing result to '{output_file}'.") 

68 with open(output_file, "w") as f: 

69 f.write(result) 

70 else: 

71 logger.debug("Writing result to stdout.") 

72 print(result)