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

25 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2024-04-30 09:42 +0000

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

2import logging 

3from pathlib import Path 

4from sys import stdin 

5 

6import typer 

7from jinja2 import Environment, FunctionLoader, select_autoescape 

8 

9from .util import ( 

10 existing_file_arg_config, 

11 file_arg_config, 

12 resolved_somesy_input, 

13 wrap_exceptions, 

14) 

15 

16logger = logging.getLogger("somesy") 

17app = typer.Typer() 

18 

19 

20@app.callback(invoke_without_command=True) 

21@wrap_exceptions 

22def fill( 

23 template_file: Path = typer.Option( 

24 None, 

25 "--template", 

26 "-t", 

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

28 **existing_file_arg_config, 

29 ), 

30 input_file: Path = typer.Option( 

31 None, 

32 "--input-file", 

33 "-i", 

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

35 **existing_file_arg_config, 

36 ), 

37 output_file: Path = typer.Option( 

38 None, 

39 "--output-file", 

40 "-o", 

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

42 **file_arg_config, 

43 ), 

44): 

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

46 somesy_input = resolved_somesy_input(input_file=input_file) 

47 

48 if template_file: 

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

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

51 template_str = f.read() 

52 else: 

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

54 template_str = stdin.read() 

55 

56 result = ( 

57 Environment( 

58 loader=FunctionLoader(lambda _: template_str), 

59 autoescape=select_autoescape(), 

60 ) 

61 .get_template("") 

62 .render(project=somesy_input.project) 

63 ) 

64 

65 if output_file: 

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

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

68 f.write(result) 

69 else: 

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

71 print(result)