Coverage for ghtc/utils.py: 0%

49 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2024-10-08 10:59 +0000

1from typing import List, Optional 

2import os 

3import jinja2 

4from git import Repo, Tag, Commit 

5import re 

6 

7CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) 

8 

9 

10class TagNotFound(Exception): 

11 pass 

12 

13 

14def get_tags(repo: Repo, tag_regex: str) -> List[Tag]: 

15 compiled_pattern = re.compile(tag_regex) 

16 res = [] 

17 for tag in repo.tags: 

18 if re.match(compiled_pattern, tag.name): 

19 res.append(tag) 

20 return sorted(res, key=lambda x: x.object.authored_date) 

21 

22 

23def get_first_commit(repo: Repo) -> Commit: 

24 return list(repo.iter_commits(max_parents=0))[0] 

25 

26 

27def get_commits_between(repo: Repo, rev1: str = "", rev2: str = "") -> List[Commit]: 

28 kwargs = {} 

29 first_commit = None 

30 if rev1 is None or rev1 == "": 

31 tmp_tags = get_tags(repo, "^ghtc_changelog_start") 

32 if len(tmp_tags) >= 1: 

33 tag1_name = tmp_tags[-1] 

34 else: 

35 first_commit = get_first_commit(repo) 

36 tag1_name = first_commit.hexsha 

37 else: 

38 tag1_name = rev1 

39 tag2_name = "HEAD" if rev2 is None or rev2 == "" else rev2 

40 kwargs["rev"] = f"{tag1_name}..{tag2_name}" 

41 tmp = list(repo.iter_commits(**kwargs)) 

42 if first_commit is None: 

43 return tmp 

44 # we also include first commit in list 

45 return [first_commit] + tmp 

46 

47 

48def render_template(context, template_file: str = "") -> str: 

49 if template_file is not None and template_file != "": 

50 template_to_read = template_file 

51 else: 

52 template_to_read = f"{CURRENT_DIR}/CHANGELOG.md" 

53 with open(template_to_read, "r") as f: 

54 content = f.read() 

55 template = jinja2.Template(content) 

56 return template.render(context) 

57 

58 

59def get_reverted_commit(commit: Commit) -> Optional[str]: 

60 for tmp in commit.message.splitlines(): 

61 line = tmp.strip() 

62 if line.startswith("This reverts commit "): 

63 sha = line.replace("This reverts commit ", "").split(".")[0] 

64 if len(sha) >= 40: 

65 return sha 

66 return None