Coverage for sel_tools/diff_creation/report.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-04 21:22 +0000

1"""Git diff report.""" 

2 

3from dataclasses import dataclass 

4from pathlib import Path 

5 

6import pandas as pd 

7from pygments import highlight 

8from pygments.formatters import HtmlFormatter 

9from pygments.lexers.diff import DiffLexer 

10 

11 

12@dataclass 

13class Diff: 

14 """Git diff model.""" 

15 

16 hexsha: str 

17 author: str 

18 message: str 

19 patch: str 

20 

21 

22@dataclass 

23class DiffReport: 

24 """Git diff model.""" 

25 

26 def __init__(self, repo_path: Path, diffs: list[Diff]) -> None: 

27 self.repo_path = repo_path 

28 self.diffs = diffs 

29 

30 def generate_overview_table(self) -> pd.DataFrame: 

31 return pd.DataFrame( 

32 [ 

33 { 

34 "hexsha": diff.hexsha, 

35 "author": diff.author, 

36 "message": diff.message, 

37 } 

38 for diff in self.diffs 

39 ] 

40 ) 

41 

42 def write_diff_patches(self) -> None: 

43 for index, diff in enumerate(self.diffs): 

44 base_path = self.repo_path / f"{index}-{diff.hexsha}" 

45 base_path.with_suffix(".patch").write_text(diff.patch) 

46 base_path.with_suffix(".html").write_text(self.highlight_diff(diff.patch)) 

47 

48 @staticmethod 

49 def highlight_diff(patch: str) -> str: 

50 return str(highlight(patch, DiffLexer(), HtmlFormatter(full=True, style="manni"))) 

51 

52 

53def write_diff_reports(reports: list[DiffReport], report_base_name: str) -> None: 

54 """Write diff reports to disk.""" 

55 for report in reports: 

56 report.generate_overview_table().to_csv(report.repo_path.joinpath(report_base_name).with_suffix(".csv")) 

57 report.write_diff_patches()