bug #1171: output record to temp file /tmp/report.mdwn temporarily
[utils.git] / src / budget_sync / main.py
1 import os
2 import re
3 import sys
4 import json
5 from typing import Optional
6 from budget_sync.ordered_set import OrderedSet
7 from budget_sync.write_budget_csv import write_budget_csv
8 from bugzilla import Bugzilla
9 import logging
10 import argparse
11 from pathlib import Path
12 from budget_sync.util import all_bugs, tty_out
13 from budget_sync.config import Config, ConfigParseError
14 from budget_sync.budget_graph import BudgetGraph, PaymentSummary
15 from budget_sync.write_budget_markdown import (write_budget_markdown,
16 markdown_for_person)
17
18
19 def main():
20 parser = argparse.ArgumentParser(
21 description="Check for errors in "
22 "Libre-SOC's style of budget tracking in Bugzilla.")
23 parser.add_argument(
24 "-c", "--config", type=argparse.FileType('r'),
25 required=True, help="The path to the configuration TOML file",
26 dest="config", metavar="<path/to/budget-sync-config.toml>")
27 parser.add_argument(
28 "-o", "--output-dir", type=Path, default=None,
29 help="The path to the output directory, will be created if it "
30 "doesn't exist",
31 dest="output_dir", metavar="<path/to/output/dir>")
32 parser.add_argument('--subset',
33 help="write the output for this subset of bugs",
34 metavar="<bug-id>,<bug-id>,...")
35 parser.add_argument('--subset-person',
36 help="write the output for this person",
37 dest="person")
38 parser.add_argument('--username',
39 help="Log in with this Bugzilla username")
40 parser.add_argument('--password',
41 help="Log in with this Bugzilla password")
42 parser.add_argument('--comments', action='store_true',
43 help="Put JSON into comments")
44 args = parser.parse_args()
45 try:
46 with args.config as config_file:
47 config = Config.from_file(config_file)
48 except (IOError, ConfigParseError) as e:
49 logging.error("Failed to parse config file: %s", e)
50 return
51 logging.info("Using Bugzilla instance at %s", config.bugzilla_url)
52 f = open("/tmp/report.mdwn", "w")
53 print("```", file=f) # for using the output as markdown
54 bz = Bugzilla(config.bugzilla_url)
55 if args.username:
56 logging.debug("logging in...")
57 bz.interactive_login(args.username, args.password)
58 logging.debug("Connected to Bugzilla")
59 budget_graph = BudgetGraph(all_bugs(bz), config)
60 for error in budget_graph.get_errors():
61 logging.error("%s", error)
62 if args.person or args.subset:
63 if not args.person:
64 logging.fatal("must use --subset-person with --subset option")
65 sys.exit(1)
66 print_markdown_for_person(f, budget_graph, config,
67 args.person, args.subset)
68 return
69 if args.output_dir is not None:
70 write_budget_markdown(budget_graph, args.output_dir)
71 write_budget_csv(budget_graph, args.output_dir)
72 summarize_milestones(f, budget_graph)
73 print("```", file=f) # for using the output as markdown
74 json_milestones(budget_graph, args.comments, args.output_dir)
75
76
77 def print_markdown_for_person(f, budget_graph, config, person_str, subset_str):
78 person = config.all_names.get(person_str)
79 if person is None:
80 logging.fatal("--subset-person: unknown person: %s", person_str)
81 sys.exit(1)
82 nodes_subset = None
83 if subset_str:
84 nodes_subset = OrderedSet()
85 for bug_id in re.split(r"[\s,]+", subset_str):
86 try:
87 node = budget_graph.nodes[int(bug_id)]
88 except (ValueError, KeyError):
89 logging.fatal("--subset: unknown bug: %s", bug_id)
90 sys.exit(1)
91 nodes_subset.add(node)
92 print(markdown_for_person(budget_graph, person, nodes_subset), file=f)
93
94
95 def print_budget_then_children(f, indent, nodes, bug_id):
96 """recursive indented printout of budgets
97 """
98
99 bug = nodes[bug_id]
100 b_incl = str(bug.fixed_budget_including_subtasks)
101 b_excl = str(bug.fixed_budget_excluding_subtasks)
102 s_incl = str(bug.submitted_including_subtasks)
103 p_incl = str(bug.paid_including_subtasks)
104 if b_incl == s_incl and b_incl == p_incl:
105 descr = "(s+p)"
106 elif b_incl == s_incl:
107 descr = "(s) p %s" % p_incl
108 elif b_incl == p_incl:
109 descr = "(p) s %s" % s_incl
110 elif s_incl == p_incl:
111 descr = " s,p %s" % (p_incl)
112 else:
113 descr = "s %s p %s" % (s_incl, p_incl)
114 excl_desc = " "
115 if b_incl != b_excl:
116 excl_desc = "excltasks %6s" % b_excl
117 print("bug #%5d %s budget %6s %s %s" %
118 (bug.bug.id, ' | ' * indent,
119 b_incl,
120 excl_desc,
121 descr
122 ), file=f)
123 # print(repr(bug))
124
125 for child in bug.immediate_children:
126 if (str(child.budget_including_subtasks) == "0" and
127 str(child.budget_excluding_subtasks) == "0"):
128 continue
129 print_budget_then_children(f, indent+1, nodes, child.bug.id)
130
131
132 def summarize_milestones(f, budget_graph):
133 for milestone, payments in budget_graph.milestone_payments.items():
134 summary = PaymentSummary(payments)
135 print(f"{milestone.identifier}", file=f)
136 print(f"\t{summary.total} submitted: "
137 f"{summary.total_submitted} paid: {summary.total_paid}", file=f)
138 not_submitted = summary.get_not_submitted()
139 if not_submitted:
140 print("not submitted", not_submitted, file=f)
141
142 # and one to display people
143 for person in budget_graph.milestone_people[milestone]:
144 print("\t%-30s - %s" % (person.identifier, person.full_name),
145 file=f)
146 print(file=f)
147
148 # now do trees
149 for milestone, payments in budget_graph.milestone_payments.items():
150 print("%s %d" % (milestone.identifier, milestone.canonical_bug_id),
151 file=f)
152 print_budget_then_children(f, 0, budget_graph.nodes,
153 milestone.canonical_bug_id)
154 print(file=f)
155
156
157 def json_milestones(budget_graph: BudgetGraph, add_comments: bool,
158 output_dir: Path):
159 """reports milestones as json format
160 """
161 bug_comments_map = {}
162 if add_comments:
163 need_set = set()
164 bugzilla = None
165 for nodes in budget_graph.assigned_nodes_for_milestones.values():
166 for node in nodes:
167 need_set.add(node.bug.id)
168 bugzilla = node.bug.bugzilla
169 need_list = sorted(need_set)
170 total = len(need_list)
171 with tty_out() as term:
172 step = 100
173 i = 0
174 while i < total:
175 cur_need = need_list[i:i + step]
176 stop = i + len(cur_need)
177 print("loading comments %d:%d of %d" % (i, stop, total),
178 flush=True, file=term)
179 comments = bugzilla.get_comments(cur_need)['bugs']
180 if len(comments) < len(cur_need) and len(cur_need) > 1:
181 step = max(1, step // 2)
182 print("failed, trying smaller step of %" % step,
183 flush=True, file=term)
184 continue
185 bug_comments_map.update(comments)
186 i += len(cur_need)
187 for milestone, payments in budget_graph.milestone_payments.items():
188 summary = PaymentSummary(payments)
189 # and one to display people
190 ppl = []
191 for person in budget_graph.milestone_people[milestone]:
192 p = {'name': person.full_name, 'email': person.email}
193 ppl.append(p)
194
195 tasks = []
196 canonical = budget_graph.nodes[milestone.canonical_bug_id]
197 for child in canonical.immediate_children:
198 milestones = []
199 # include the task itself as a milestone
200 for st in list(child.children()) + [child]:
201 amount = st.fixed_budget_excluding_subtasks.int()
202 if amount == 0: # skip anything at zero
203 continue
204 # if "task itself" then put the milestone as "wrapup"
205 if st.bug == child.bug:
206 description = 'wrapup'
207 intro = []
208 else:
209 # otherwise create a description and get comment #0
210 description = "%d %s" % (st.bug.id, st.bug.summary)
211 # add parent and MoU top-level
212 parent_id = st.parent.bug.id
213 if parent_id != child.bug.id:
214 description += "\n(Sub-sub-task of %d)" % parent_id
215 task = {'description': description,
216 'amount': amount,
217 }
218 #mou_bug = st.closest_bug_in_mou
219 # if mou_bug is not None:
220 # task['mou_task'] = mou_bug.bug.id
221 milestones.append(task)
222 # create MoU task: get comment #0
223 intro = []
224 comment = "%s\n " % child.bug_url
225 if add_comments:
226 comment += "\n"
227 comments = bug_comments_map[str(child.bug.id)]['comments']
228 lines = comments[0]['text'].splitlines()
229 for i, line in enumerate(lines):
230 # look for a line with only 2 or more `-` as the
231 # standard way in markdown of having a "break" (<hl />)
232 # this truncates the comment so that the RFP database
233 # has only the "summary description" but the rest may
234 # be used for "TODO" lists
235 l = line.strip()
236 if len(l) >= 2 and l == "-" * len(l):
237 lines[i:] = []
238 break
239 comment += "\n".join(lines)
240 intro.append(comment)
241 # print (description, intro)
242 # sys.stdout.flush()
243 task = {'title': "%d %s" % (child.bug.id, child.bug.summary),
244 'intro': intro,
245 'amount': child.fixed_budget_including_subtasks.int(),
246 'url': "{{ %s }} " % child.bug_url,
247 'milestones': milestones
248 }
249 tasks.append(task)
250
251 d = {'participants': ppl,
252 'preamble': '',
253 'type': 'Group',
254 'url': canonical.bug_url,
255 'plan': {'intro': [''],
256 'tasks': tasks,
257 'rfp_secret': '',
258 }
259 }
260
261 output_file = output_dir / f"report.{milestone.identifier}.json"
262 output_file.write_text(json.dumps(d, indent=2), encoding="utf-8")
263
264
265 if __name__ == "__main__":
266 main()