Coverage for hledger_lots/commodity_tag.py: 34%

32 statements  

« prev     ^ index     » next       coverage.py v7.2.3, created at 2023-05-04 22:41 -0300

1import re 

2from typing import List, Tuple, TypedDict 

3 

4 

5class CommodityTag(TypedDict): 

6 commodity: str 

7 value: str 

8 

9 

10def get_commodity_name(commodity_directive: str): 

11 commodity = re.sub(r"(\d[,\d.]*\d)|( )|\'|\"", "", commodity_directive) 

12 return commodity 

13 

14 

15def get_comment_tag_value(comment: str, tag: str) -> str: 

16 search = re.search(f"{tag}:\\s?(\\S+)", comment) 

17 if search and len(search.groups()) == 1: 

18 return search.group(1) 

19 else: 

20 return "" 

21 

22 

23class CommodityDirective: 

24 def __init__(self, files: Tuple[str, ...]): 

25 self.files = files 

26 self.rows = self.get_commodities_rows() 

27 

28 def get_commodities_rows(self) -> List[str]: 

29 rows = [] 

30 for file in self.files: 

31 with open(file, "r") as f: 

32 for row in f: 

33 if row.startswith("commodity"): 

34 rows.append(row) 

35 return rows 

36 

37 def get_commodity_tag(self, tag: str): 

38 regex = re.compile(r"commodity (.+)(;.+)") 

39 searches = (regex.search(row) for row in self.rows) 

40 commented_search = ( 

41 search for search in searches if search and len(search.groups()) == 2 

42 ) 

43 commodities = ( 

44 CommodityTag( 

45 commodity=get_commodity_name(comment.group(1)), 

46 value=get_comment_tag_value(comment.group(2), tag), 

47 ) 

48 for comment in commented_search 

49 ) 

50 commodities = [ 

51 commodity for commodity in commodities if "" not in commodity.values() 

52 ] 

53 

54 return commodities