Debian Codegraph @

beangrow/config.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Library coded to process the input configuration.
3 """
4
5 __copyright__ = "Copyright (C) 2020 Martin Blais"
6 __license__ = "GNU GPLv2"
7
8 from typing import List
9 import fnmatch
10 import re
11
12 from google.protobuf import text_format
13
14 from beangrow.config_pb2 import Config
15
16
17 # Basic type aliases.
18 Account = str
19
20
21 def is_glob(pattern):
22 return re.compile(r"[*?]").search(pattern)
23
24
25 def expand_globs(patterns: List[str], valid_set: List[str]) -> List[str]:
26 out_values = []
27 for pattern in patterns:
28 if is_glob(pattern):
29 out_values.extend(fnmatch.filter(valid_set, pattern))
30 else:
31 out_values.append(pattern)
32 return out_values
33
34
35 def read_config_from_string(config_string: str,
36 filter_reports: List[str],
37 accounts: List[Account]) -> Config:
38 """Read the configuration, perform globbing expansions, and whittle down the
39 list of reports and investments to the requested minimal."""
40
41 # Read the config from a string.
42 config = Config()
43 text_format.Merge(config_string, config)
44 reports = list(config.groups.group)
45
46 # Expand account names.
47 for investment in config.investments.investment:
48 assert not is_glob(investment.asset_account)
49 investment.dividend_accounts[:] = expand_globs(investment.dividend_accounts,
50 accounts)
51 investment.match_accounts[:] = expand_globs(investment.match_accounts, accounts)
52 investment.cash_accounts[:] = expand_globs(investment.cash_accounts, accounts)
53
54 # Expand investment names.
55 investment_names = [investment.asset_account
56 for investment in config.investments.investment]
57 for report in config.groups.group:
58 report.investment[:] = expand_globs(report.investment, investment_names)
59
60 # Filter down reports.
61 if filter_reports:
62 reports = [report
63 for report in config.groups.group
64 if any(fnmatch.fnmatch(report.name, pattern)
65 for pattern in filter_reports)]
66 del config.groups.group[:]
67 config.groups.group.extend(reports)
68
69 # Filter just the list of investments needed for the reports defined.
70 used_investments = set(inv
71 for report in config.groups.group
72 for inv in report.investment)
73 investments = [invest
74 for invest in config.investments.investment
75 if invest.asset_account in used_investments]
76 del config.investments.investment[:]
77 config.investments.investment.extend(investments)
78
79 return config
80
81
82 def read_config(config_filename: str,
83 filter_reports: List[str],
84 accounts: List[Account]) -> Config:
85 # Read the file.
86 with open(config_filename, "r") as infile:
87 config_string = infile.read()
88
89 return read_config_from_string(config_string, filter_reports, accounts)