auto-optimize 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1267 @@
1
+ #!/usr/bin/env python3
2
+ """The unit-test PR's body, rendered from generated tables and one prose
3
+ file.
4
+
5
+ python3 tests_pr_body.py DIR --template > DIR/prose.md
6
+ python3 tests_pr_body.py DIR --title 'Add unit tests for pkg' --out DIR/body.md
7
+
8
+ DIR is the folder `tests_pr_tables.py` writes its tables into,
9
+ `$WORK/ship/pr-tests`; the prose file (`DIR/prose.md` unless `--prose` names
10
+ another) holds what no table can say, in fields that each start with a line
11
+ `=== <field>`. `--template` prints a prose skeleton with one `<<FILL: …>>` per
12
+ field the tables call for.
13
+
14
+ Every number, total, percentage and ranking in the body is computed here from
15
+ the tables; prose refers to a computed number only through a `{{token}}`. The
16
+ same tables and prose give the same body, byte for byte. The body opens with
17
+ the `opening` field followed by the sentences computed from the tables.
18
+ `--out` needs `--title`, which must
19
+ pass attribution.py's title rule and is written to `<out stem>.title`.
20
+
21
+ `#<bug issue>` is replaced by the number in `DIR/../issue-bugs/filed.json`
22
+ once the bug report is filed. When the bug report is not among the documents
23
+ chosen at step 5 (`after.ship_documents` in the search's config.json), that
24
+ issue will never exist: the prose may not hold `#<bug issue>`, and
25
+ `contradictions` names an issue number, a URL or a file in the repository
26
+ instead.
27
+
28
+ A section whose tables are absent is dropped, and stderr says which. Exit 1,
29
+ with every problem listed and nothing written, on a `<<FILL` placeholder, a
30
+ field a rendered section needs and the prose lacks, an unknown field or
31
+ token, tables that disagree with each other, or a title or body that
32
+ attribution.py or lint_text.py refuses.
33
+
34
+ The tables, the fields and the sections: references/pr-tests.md. Standard
35
+ library only, Python 3.9 or later.
36
+ """
37
+
38
+ import os
39
+ import re
40
+ import sys
41
+ import json
42
+ import argparse
43
+
44
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
45
+
46
+ import attribution
47
+ import publish
48
+
49
+
50
+ # Files outside the tests that a tests PR may change, to declare a test
51
+ # dependency: only the files that list dependencies, by base name.
52
+ DEPENDENCY_MANIFESTS = ('DESCRIPTION', 'requirements-dev.txt',
53
+ 'requirements-test.txt', 'test-requirements.txt', 'dev-requirements.txt')
54
+
55
+ BUG_ISSUE = attribution.PLACEHOLDERS[0]
56
+
57
+ # Field name: (takes an argument, what it holds, as --template explains it).
58
+ FIELDS = {
59
+ 'opening': (False, 'the first sentence of the body: what the suite tests, '
60
+ 'e.g. "This PR adds a pytest suite for `pkg` and its command-line '
61
+ 'programs." The renderer follows it with the number of tests and '
62
+ 'modules and the sentence that no source, build or workflow file '
63
+ 'changes'),
64
+ 'support': (False, 'optional: what the suite adds besides its test '
65
+ 'modules, ending the sentence "It holds N tests in M modules under '
66
+ '`dir/`, with …", e.g. "shared helpers in `helpers.py` and fixtures in '
67
+ '`conftest.py`". Delete the field if there is nothing'),
68
+ 'declares': (False, 'optional: the one change outside the test files, as '
69
+ 'the sentence "Its one change outside the tests is <this>.", for a '
70
+ 'test dependency declared in a dependency manifest (' +
71
+ ', '.join(DEPENDENCY_MANIFESTS) + '), e.g. "adding `withr`, which '
72
+ 'the test helpers use, to `Suggests` in `DESCRIPTION`". No other file '
73
+ 'outside the tests is allowed. Delete the field if there is nothing'),
74
+ 'driver': (True, 'optional: the repository\'s own test driver, named after '
75
+ 'it (`=== driver test/test.sh`), when the branch edits it so that the '
76
+ 'existing test command runs the new tests; the text is a clause after '
77
+ '"which", e.g. "also runs each `test-<tool>-<topic>.sh` file in a '
78
+ 'tool\'s directory, so the new files run under `make test`". Allowed '
79
+ 'only when config.json\'s after.tests_driver_edit is yes. Delete the '
80
+ 'field if there is nothing'),
81
+ 'docs': (False, 'what expected values are checked against, as it reads '
82
+ 'mid-sentence: "the MANUAL", "the documentation", "the docstrings"'),
83
+ 'running.commands': (False, 'the commands that build what the suite needs '
84
+ 'and run it, one per line, without a code fence'),
85
+ 'running.notes': (False, 'bullets: how long the suite takes and on how '
86
+ 'many cores, the minimum Python and every new dependency, the '
87
+ 'environment variables the suite reads, and each reason a test skips '
88
+ '(a missing optional dependency or tool, an operating system)'),
89
+ 'running.ci': (False, 'optional: whether the suite is added to the CI '
90
+ 'workflows, and the step that would run it. Delete the field if there '
91
+ 'is nothing to say'),
92
+ 'checked': (False, 'one paragraph, no list: the CI configurations the '
93
+ 'suite was run in before this PR (each workflow job\'s install and test '
94
+ 'commands, in each Python or compiler version), and that it passed in '
95
+ 'each, from step 1\'s record of those runs in $WORK/tests/work/. It is '
96
+ 'the last paragraph of *Running it*'),
97
+ 'derivation': (False, 'one sentence on what expected values are checked '
98
+ 'against, then bullets: how inputs are generated, which fields are '
99
+ 'computed before the program runs and from which documented rules. The '
100
+ 'renderer appends how many test functions pin the current output'),
101
+ 'module': (True, 'what this module\'s tests check, one clause of at most '
102
+ '25 words: it is a table cell'),
103
+ 'coverage.method': (False, 'bullets: the build and its coverage flags, the '
104
+ 'compiler; the coverage tool and its version; what counts as covered; '
105
+ 'how the existing tests were run'),
106
+ 'parts.tests': (False, 'why tests per part were not counted (no per-test '
107
+ 'coverage, and no test files written per part)'),
108
+ 'contradictions': (False, 'one paragraph, no list: how many behaviours '
109
+ 'contradict the documentation and are left untested, and where they '
110
+ 'are listed: the bug report (#<bug issue>, until it is filed) when it '
111
+ 'is among the documents chosen at step 5, otherwise an issue number, a '
112
+ 'URL or a file in the repository in backticks; or the single word '
113
+ 'none'),
114
+ 'contradictions.marked': (False, 'where the suite records each case it '
115
+ 'leaves untested, as it is true of this suite: one paragraph of whole '
116
+ 'sentences, which the renderer puts after "… is left untested, so that '
117
+ 'fixing it will not break the suite." and before the paragraph naming '
118
+ 'where the cases are listed. Where every affected test is marked: '
119
+ '"Each affected test says so in a docstring or comment." Where a '
120
+ 'document names the cases instead, name the document and count what it '
121
+ 'and the tests name. Delete the field when contradictions is none'),
122
+ 'platforms': (False, 'the platforms the suite ran on, and those CI covers '
123
+ 'that were not tried'),
124
+ }
125
+
126
+ TOKEN = re.compile(r'\{\{\s*([A-Za-z_]+)\s*\}\}')
127
+ FIELD = re.compile(r'^=== (\S+)(?:[ \t]+(.*?))?[ \t]*$')
128
+ LIST_ITEM = re.compile(r'^\s*([-*+]|\d+[.)])\s')
129
+ WORDS = ('no', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
130
+ 'nine')
131
+ # How many rows the rankings show.
132
+ GAINS_SHOWN = 5
133
+ UNREACHED_SHOWN = 3
134
+ GAPS_SHOWN = 6
135
+ NAMES_SHOWN = 10
136
+ # The longest a module's table cell may be.
137
+ MODULE_WORDS = 25
138
+ # Where `contradictions` says its cases are listed: the bug report, or another
139
+ # issue or page; without the bug report, a file in the repository also does.
140
+ REPORT_LINK = re.compile(r'#<bug issue>|#\d+|https?://')
141
+ OTHER_LINK = re.compile(r'#\d+|https?://')
142
+ CODE_SPAN = re.compile(r'`([^`\s]+)`')
143
+
144
+
145
+ # Formatting ------------------------------------------------------------------
146
+
147
+ def count(n):
148
+ """Words below ten, digits with thousands separators from ten."""
149
+
150
+ return WORDS[n] if 0 <= n < len(WORDS) else '{:,}'.format(n)
151
+
152
+
153
+ def plural(n, word, many=None):
154
+ return '{} {}'.format(count(n), word if n == 1 else (many or word + 's'))
155
+
156
+
157
+ def lines_of(n):
158
+ return '{} {}'.format(digits(n), 'line' if n == 1 else 'lines')
159
+
160
+
161
+ def digits(n):
162
+ return '{:,}'.format(n)
163
+
164
+
165
+ def percent(part, whole):
166
+ return '{:.1f}%'.format(100.0 * part / whole) if whole else '–'
167
+
168
+
169
+ def capital(text):
170
+ return text[:1].upper() + text[1:]
171
+
172
+
173
+ def code(text):
174
+ return text if '`' in text else '`{}`'.format(text)
175
+
176
+
177
+ def pathlike(text):
178
+ """A part name shown in code type: a path, not a name the map gave."""
179
+
180
+ return code(text) if re.match(r'^[\w./+-]+$', text) and ('/' in text
181
+ or '.' in text) else text
182
+
183
+
184
+ def unwrap(text):
185
+ """Each paragraph and list item on one line: GitHub renders a line break
186
+ inside a PR's paragraph as a break. Code fences and table rows
187
+ are kept as they are."""
188
+
189
+ out, fenced = [], False
190
+
191
+ for line in text.split('\n'):
192
+ stripped = line.strip()
193
+
194
+ if stripped.startswith('```'):
195
+ fenced = not fenced
196
+ out.append(line.rstrip())
197
+ continue
198
+
199
+ if fenced:
200
+ out.append(line.rstrip())
201
+ continue
202
+
203
+ if not stripped:
204
+ if out and out[-1] != '':
205
+ out.append('')
206
+ continue
207
+
208
+ previous = out[-1].lstrip() if out else ''
209
+
210
+ if not out or not previous or stripped.startswith('|') \
211
+ or LIST_ITEM.match(line) or previous.startswith(('|', '```')):
212
+ out.append(line.rstrip())
213
+ else:
214
+ out[-1] = out[-1].rstrip() + ' ' + stripped
215
+
216
+ return '\n'.join(out).strip('\n')
217
+
218
+
219
+ def append_bullet(text, bullet):
220
+ """`bullet` as the last item of the list `text` ends with, or as a list
221
+ of its own after it."""
222
+
223
+ last = text.rstrip('\n').split('\n')[-1] if text.strip() else ''
224
+ return text.rstrip('\n') + ('\n' if LIST_ITEM.match(last) else '\n\n') \
225
+ + bullet
226
+
227
+
228
+ def one_paragraph(text):
229
+ """True when `text`, unwrapped, is one paragraph and not a list."""
230
+
231
+ text = text.strip()
232
+ return '\n' not in text and not LIST_ITEM.match(text)
233
+
234
+
235
+ # Reading ---------------------------------------------------------------------
236
+
237
+ class Problems(list):
238
+ def add(self, message):
239
+ if message not in self:
240
+ self.append(message)
241
+
242
+
243
+ def read_table(data, name, columns, problems):
244
+ """Rows of DATA/name as dicts (with `_line`), None when the file is
245
+ absent."""
246
+
247
+ path = os.path.join(data, name)
248
+
249
+ if not os.path.exists(path):
250
+ return None
251
+
252
+ try:
253
+ with open(path, encoding='utf-8') as infile:
254
+ lines = [line.rstrip('\r\n') for line in infile]
255
+ except OSError as error:
256
+ problems.add('could not read {}: {}'.format(path, error))
257
+ return []
258
+
259
+ numbered = [(number, line) for number, line in enumerate(lines, 1)
260
+ if line.strip()]
261
+
262
+ if not numbered:
263
+ problems.add('{} is empty: it needs its header line'.format(name))
264
+ return []
265
+
266
+ header = numbered[0][1].split('\t')
267
+ missing = [column for column in columns if column not in header]
268
+
269
+ if missing:
270
+ problems.add('{} has no {} column (its header: {})'.format(name,
271
+ ', '.join(missing), ', '.join(header)))
272
+ return []
273
+
274
+ rows = []
275
+
276
+ for number, line in numbered[1:]:
277
+ fields = line.split('\t')
278
+
279
+ if len(fields) != len(header):
280
+ problems.add('{} line {}: {} fields where the header has {}'.format(
281
+ name, number, len(fields), len(header)))
282
+ continue
283
+
284
+ row = dict(zip(header, fields))
285
+ row['_line'] = number
286
+ rows.append(row)
287
+
288
+ return rows
289
+
290
+
291
+ def whole(row, key, name, problems, empty=False):
292
+ """A cell as a non-negative int; None for an empty cell where allowed."""
293
+
294
+ value = row.get(key, '').strip()
295
+
296
+ if value == '' and empty:
297
+ return None
298
+
299
+ if not re.match(r'^\d+$', value):
300
+ problems.add('{} line {}: {} is {!r}, not a whole number'.format(name,
301
+ row['_line'], key, value))
302
+ return 0
303
+
304
+ return int(value)
305
+
306
+
307
+ def read_prose(path, problems, fields=None, plain=('running.commands',)):
308
+ """{(field, argument): text}, in file order. `fields` (default FIELDS)
309
+ names the fields the file may hold; `plain` names those that may hold
310
+ lines starting with `#`."""
311
+
312
+ known, kept = fields or FIELDS, {}
313
+
314
+ try:
315
+ with open(path, encoding='utf-8') as infile:
316
+ lines = infile.read().split('\n')
317
+ except OSError as error:
318
+ problems.add('could not read the prose file {}: {}. `--template` prints '
319
+ 'a skeleton'.format(path, error))
320
+ return {}
321
+
322
+ fields, current, name = kept, None, os.path.basename(path)
323
+
324
+ for number, line in enumerate(lines, 1):
325
+ found = FIELD.match(line)
326
+
327
+ if found:
328
+ field, argument = found.group(1), (found.group(2) or '').strip()
329
+ current = None
330
+
331
+ if field not in known:
332
+ problems.add('{} line {}: no field is called {!r} (the fields: {})'
333
+ .format(name, number, field, ', '.join(sorted(known))))
334
+ continue
335
+
336
+ if known[field][0] and not argument:
337
+ problems.add('{} line {}: "=== {}" needs what it describes after '
338
+ 'it'.format(name, number, field))
339
+ continue
340
+
341
+ if not known[field][0] and argument:
342
+ problems.add('{} line {}: "=== {}" takes nothing after it'.format(
343
+ name, number, field))
344
+ continue
345
+
346
+ key = (field, ' '.join(argument.split()))
347
+
348
+ if key in fields:
349
+ problems.add('{} line {}: "=== {}" appears twice'.format(name,
350
+ number, ' '.join(key).strip()))
351
+ continue
352
+
353
+ fields[key] = []
354
+ current = key
355
+ continue
356
+
357
+ if current is None:
358
+ if line.strip():
359
+ problems.add('{} line {}: text before the first "=== <field>" '
360
+ 'line'.format(name, number))
361
+ continue
362
+
363
+ fields[current].append(line.rstrip())
364
+
365
+ texts = {}
366
+
367
+ for key, body in fields.items():
368
+ text = '\n'.join(body).strip('\n')
369
+ label = ' '.join(key).strip()
370
+
371
+ if not text.strip():
372
+ problems.add('{}: "=== {}" is empty: fill it, or delete an optional '
373
+ 'field'.format(name, label))
374
+ continue
375
+
376
+ if '<<FILL' in text:
377
+ problems.add('{}: "=== {}" still holds a <<FILL placeholder'.format(
378
+ name, label))
379
+
380
+ fenced = False
381
+
382
+ for line in text.split('\n'):
383
+ if line.strip().startswith('```'):
384
+ fenced = not fenced
385
+ elif not fenced and key[0] not in plain \
386
+ and re.match(r'^#{1,6}\s', line):
387
+ problems.add('{}: "=== {}" holds a heading ({!r}); the renderer '
388
+ 'writes every heading'.format(name, label, line.strip()))
389
+
390
+ texts[key] = text
391
+
392
+ return texts
393
+
394
+
395
+ # The tables ------------------------------------------------------------------
396
+
397
+ def load(data, problems):
398
+ """Every table in DATA, checked against itself and the others."""
399
+
400
+ tables = {}
401
+ collection = read_table(data, 'collection.tsv', ['nodeid', 'pinned'],
402
+ problems)
403
+
404
+ if collection is None:
405
+ problems.add('{} has no collection.tsv: `tests_pr_tables.py collection` '
406
+ 'writes it, and every body needs it'.format(data))
407
+ collection = []
408
+
409
+ nodeids = [row['nodeid'] for row in collection]
410
+
411
+ if len(set(nodeids)) != len(nodeids):
412
+ problems.add('collection.tsv lists a node id twice')
413
+
414
+ modules = {}
415
+
416
+ for nodeid in nodeids:
417
+ module = publish.split_nodeid(nodeid)[0]
418
+ modules[module] = modules.get(module, 0) + 1
419
+
420
+ functions = sorted({publish.split_nodeid(n) for n in nodeids})
421
+ marks = {row['pinned'].strip() for row in collection}
422
+ pinned = None
423
+
424
+ if collection and marks <= {'yes', 'no'}:
425
+ pinned = len({publish.split_nodeid(row['nodeid']) for row in collection
426
+ if row['pinned'].strip() == 'yes'})
427
+ elif marks - {''}:
428
+ problems.add('collection.tsv: pinned is yes, no, or empty in every row')
429
+
430
+ tables['tests'] = len(nodeids)
431
+ tables['modules'] = modules
432
+ tables['functions'] = len(functions)
433
+ tables['pinned'] = pinned
434
+
435
+ files = read_table(data, 'files.tsv', ['status', 'path'], problems)
436
+ tables['files'] = None if files is None else [row['path'] for row in files]
437
+ tables['branch'] = None
438
+ branch = os.path.join(data, 'branch.json')
439
+
440
+ if os.path.exists(branch):
441
+ try:
442
+ with open(branch, encoding='utf-8') as handle:
443
+ tables['branch'] = json.load(handle)
444
+ except (OSError, ValueError) as error:
445
+ problems.add('could not read {}: {}'.format(branch, error))
446
+
447
+ coverage = read_table(data, 'coverage.tsv', ['file', 'part', 'excluded',
448
+ 'lines', 'existing', 'suite', 'both'], problems)
449
+ parts = read_table(data, 'parts.tsv', ['part', 'excluded', 'tests_before',
450
+ 'tests_after', 'counted'], problems)
451
+
452
+ if (coverage is None) != (parts is None):
453
+ problems.add('coverage.tsv and parts.tsv come together from '
454
+ '`tests_pr_tables.py coverage`; {} is missing'.format(
455
+ 'parts.tsv' if parts is None else 'coverage.tsv'))
456
+ coverage = parts = None
457
+
458
+ tables['coverage'] = coverage and load_coverage(coverage, parts, problems)
459
+
460
+ names = read_table(data, 'names.tsv', ['name', 'defined_in', 'tests'],
461
+ problems)
462
+
463
+ if names is not None:
464
+ for row in names:
465
+ row['tests'] = whole(row, 'tests', 'names.tsv', problems)
466
+
467
+ tables['names'] = names
468
+
469
+ return tables
470
+
471
+
472
+ def load_coverage(rows, parts, problems):
473
+ labels = [column[len('existing:'):] for column in rows[0] if column.startswith(
474
+ 'existing:')] if rows else []
475
+ files = []
476
+
477
+ for row in rows:
478
+ record = {'file': row['file'], 'part': row['part'],
479
+ 'excluded': row['excluded'].strip() == 'yes'}
480
+
481
+ for key in ('lines', 'existing', 'suite', 'both'):
482
+ record[key] = whole(row, key, 'coverage.tsv', problems)
483
+
484
+ record['labels'] = [whole(row, 'existing:' + label, 'coverage.tsv',
485
+ problems) for label in labels]
486
+ where = 'coverage.tsv line {} ({})'.format(row['_line'], row['file'])
487
+
488
+ if not (max(record['existing'], record['suite']) <= record['both']
489
+ <= min(record['lines'], record['existing'] + record['suite'])):
490
+ problems.add('{}: lines {}, existing {}, suite {} and both {} '
491
+ 'disagree: both is at least each of existing and suite, at most '
492
+ 'their sum and at most lines'.format(where, record['lines'],
493
+ record['existing'], record['suite'], record['both']))
494
+
495
+ if record['labels'] and not (max(record['labels']) <= record['existing']
496
+ <= sum(record['labels'])):
497
+ problems.add('{}: existing ({}) is not the union of its labels ({})'
498
+ .format(where, record['existing'], ', '.join(str(n)
499
+ for n in record['labels'])))
500
+
501
+ files.append(record)
502
+
503
+ if len({record['file'] for record in files}) != len(files):
504
+ problems.add('coverage.tsv lists a file twice')
505
+
506
+ counted_parts = {}
507
+
508
+ for record in files:
509
+ counted_parts.setdefault(record['part'], set()).add(record['excluded'])
510
+
511
+ for part, marks in sorted(counted_parts.items()):
512
+ if len(marks) > 1:
513
+ problems.add('coverage.tsv: part {} holds both excluded and counted '
514
+ 'files'.format(part))
515
+
516
+ table, total = {}, None
517
+
518
+ for row in parts:
519
+ record = {'part': row['part'], 'excluded': row['excluded'].strip() == 'yes',
520
+ 'before': whole(row, 'tests_before', 'parts.tsv', problems, True),
521
+ 'after': whole(row, 'tests_after', 'parts.tsv', problems, True),
522
+ 'counted': row['counted'].strip()}
523
+
524
+ if record['counted'] not in ('per-test', 'by-file', ''):
525
+ problems.add('parts.tsv line {}: counted is per-test, by-file or '
526
+ 'empty, not {!r}'.format(row['_line'], record['counted']))
527
+
528
+ if (record['before'] is None) != (record['after'] is None) or \
529
+ (record['before'] is not None and record['before'] > record['after']):
530
+ problems.add('parts.tsv line {} ({}): tests_before must be at most '
531
+ 'tests_after, and both given or both empty'.format(row['_line'],
532
+ row['part']))
533
+
534
+ if row['part'] == '(total)':
535
+ total = record
536
+ elif row['part'] in table:
537
+ problems.add('parts.tsv lists part {} twice'.format(row['part']))
538
+ else:
539
+ table[row['part']] = record
540
+
541
+ if set(table) != set(counted_parts):
542
+ problems.add('parts.tsv and coverage.tsv name different parts: only in '
543
+ 'parts.tsv {}; only in coverage.tsv {}'.format(sorted(set(table)
544
+ - set(counted_parts)) or 'none', sorted(set(counted_parts)
545
+ - set(table)) or 'none'))
546
+
547
+ if total is None:
548
+ problems.add('parts.tsv has no (total) row')
549
+ total = {'before': None, 'after': None, 'counted': ''}
550
+
551
+ for part, record in table.items():
552
+ if part in counted_parts and record['excluded'] != (True in
553
+ counted_parts[part]):
554
+ problems.add('parts.tsv and coverage.tsv disagree on whether part {} '
555
+ 'is excluded'.format(part))
556
+
557
+ counted = {record['counted'] for record in list(table.values()) + [total]
558
+ if not record.get('excluded')}
559
+
560
+ if len(counted) > 1:
561
+ problems.add('parts.tsv mixes ways of counting tests per part: {}'.format(
562
+ ', '.join(sorted(c or 'not counted' for c in counted))))
563
+
564
+ kept = [record for record in table.values() if not record['excluded']]
565
+
566
+ if total['before'] is not None and kept and all(record['before'] is not None
567
+ for record in kept):
568
+ if total['after'] < max(record['after'] for record in kept) or \
569
+ total['after'] > sum(record['after'] for record in kept):
570
+ problems.add('parts.tsv: the (total) row\'s tests_after ({}) is below '
571
+ 'a part\'s or above their sum'.format(total['after']))
572
+
573
+ return {'labels': labels, 'files': files, 'parts': table, 'total': total,
574
+ 'counted': counted.pop() if len(counted) == 1 else ''}
575
+
576
+
577
+ # Rendering -------------------------------------------------------------------
578
+
579
+ class Context:
580
+ def __init__(self, tables, prose, problems):
581
+ self.tables = tables
582
+ self.prose = prose
583
+ self.problems = problems
584
+ self.used = set()
585
+ self.allow_source = tables.get('allow_source') or []
586
+ self.bugs = tables.get('bugs', True)
587
+ self.tokens = self.make_tokens()
588
+
589
+ def make_tokens(self):
590
+ tables = self.tables
591
+ tokens = {'tests': digits(tables['tests']),
592
+ 'modules': count(len(tables['modules'])),
593
+ 'functions': digits(tables['functions'])}
594
+
595
+ if tables['pinned'] is not None:
596
+ tokens['pinned'] = digits(tables['pinned'])
597
+
598
+ return tokens
599
+
600
+ def substitute(self, key, text):
601
+ def replace(found):
602
+ name = found.group(1)
603
+
604
+ if name not in self.tokens:
605
+ self.problems.add('prose "=== {}": no table gives {{{{{}}}}} (the '
606
+ 'tokens here: {})'.format(' '.join(key).strip(), name,
607
+ ', '.join(sorted(self.tokens))))
608
+ return found.group(0)
609
+
610
+ return self.tokens[name]
611
+
612
+ return TOKEN.sub(replace, text)
613
+
614
+ def get(self, field, argument='', why=None, keep=False):
615
+ """The field's text, unwrapped, with its tokens substituted; None when
616
+ absent, and then a problem when `why` (the section that needs it) is
617
+ given."""
618
+
619
+ key = (field, argument)
620
+ self.used.add(key)
621
+ text = self.prose.get(key)
622
+
623
+ if text is None:
624
+ if why:
625
+ self.problems.add('the prose has no "=== {}", which {} needs'.format(
626
+ ' '.join(key).strip(), why))
627
+ return None
628
+
629
+ text = self.substitute(key, text)
630
+ return text if keep else unwrap(text)
631
+
632
+
633
+ def common_directory(modules):
634
+ directories = [os.path.dirname(module) for module in modules]
635
+
636
+ if not directories:
637
+ return ''
638
+
639
+ common = os.path.commonpath(directories) if all(directories) else ''
640
+ return common.replace('\\', '/')
641
+
642
+
643
+ def opening(ctx):
644
+ tables = ctx.tables
645
+ modules = tables['modules']
646
+ common = common_directory(modules)
647
+ first = (ctx.get('opening', why='the opening paragraph') or '').strip()
648
+ support = ctx.get('support')
649
+ declares = ctx.get('declares')
650
+ closing = 'It changes no source, build or workflow file.'
651
+
652
+ if first and not (first[0].isupper() or first[0] == '`'):
653
+ ctx.problems.add('prose "=== opening" is the first sentence of the body: '
654
+ 'start it with a capital letter ("This PR adds a pytest suite for '
655
+ '`pkg`.")')
656
+
657
+ if len(modules) == 1:
658
+ where = 'one module, `{}`'.format(next(iter(modules)))
659
+ else:
660
+ where = '{} modules{}'.format(count(len(modules)), ' under `{}/`'.format(
661
+ common) if common else '')
662
+
663
+ holds = 'It holds {} in {}{}.'.format(plural(tables['tests'], 'test'), where,
664
+ ', with ' + support.strip().rstrip('.') if support else '')
665
+
666
+ drivers = sorted(argument for field, argument in ctx.prose
667
+ if field == 'driver')
668
+ driver = drivers[0] if drivers else None
669
+ ctx.used.update(('driver', path) for path in drivers)
670
+
671
+ if len(drivers) > 1:
672
+ ctx.problems.add('prose: `driver` names {}; a tests PR may edit one test '
673
+ 'driver'.format(', '.join(drivers)))
674
+
675
+ if tables['files'] is not None:
676
+ if common:
677
+ outside = [path for path in tables['files']
678
+ if not path.startswith(common + '/')]
679
+
680
+ manifests = [path for path in outside
681
+ if os.path.basename(path) in DEPENDENCY_MANIFESTS]
682
+ driven = driver if driver in outside else None
683
+ others = [path for path in outside
684
+ if path not in manifests and path != driven]
685
+ edit = tables.get('driver_edit')
686
+
687
+ if driver and not driven:
688
+ ctx.problems.add('prose: `driver {}` names a file files.tsv does not '
689
+ 'show changed outside `{}/`: fix the path or delete the field'
690
+ .format(driver, common))
691
+
692
+ if driven and edit not in ('yes', True):
693
+ ctx.problems.add('files.tsv: the branch changes the test driver `{}`, '
694
+ 'and config.json\'s after.tests_driver_edit is {}: it is allowed '
695
+ 'only once the user says yes, recorded with `autoopt.py config '
696
+ '--set after.tests_driver_edit=yes --reason \'<their words>\'`'
697
+ .format(driven, 'absent' if edit is None else repr(edit)))
698
+
699
+ allowed = [path for path in others if path in ctx.allow_source]
700
+ others = [path for path in others if path not in allowed]
701
+ stale = [path for path in ctx.allow_source if path not in outside]
702
+ undeclared = [path for path in allowed
703
+ if path not in (declares or '')]
704
+
705
+ if stale:
706
+ ctx.problems.add('--allow-source names {}, which files.tsv does not '
707
+ 'show changed outside `{}/`: fix the path or drop the flag'
708
+ .format(', '.join(stale), common))
709
+
710
+ if undeclared:
711
+ ctx.problems.add('prose: --allow-source names {}, and `declares` does '
712
+ 'not mention {}: `declares` must name every file the user approved, '
713
+ 'in backticks'.format(', '.join(undeclared), 'it' if len(undeclared)
714
+ == 1 else 'them'))
715
+
716
+ if others or (manifests and not declares) or (allowed and not declares):
717
+ ctx.problems.add('files.tsv: the branch changes {} outside `{}/`, '
718
+ 'so the opening cannot say it changes no source, build or '
719
+ 'workflow file: {}{}'.format(plural(len(outside), 'file'), common,
720
+ ', '.join(outside[:10]),
721
+ '; a dependency manifest ({}) is allowed only with the '
722
+ '`declares` field, the repository\'s test driver only with '
723
+ '`=== driver <path>` and after.tests_driver_edit yes, and any other '
724
+ 'file only when the user approved it by name: `--allow-source PATH` '
725
+ 'plus `declares` naming it'.format(', '.join(DEPENDENCY_MANIFESTS))))
726
+ elif manifests or driven or allowed:
727
+ named = ['`{}`'.format(path) for path in manifests + allowed]
728
+
729
+ if allowed:
730
+ closing = 'It changes no workflow file.'
731
+ else:
732
+ closing = 'It changes no source or workflow file.'
733
+
734
+ if allowed:
735
+ closing += ' It changes {} outside the tests: {}.'.format(
736
+ publish.series(named), declares.strip().rstrip('.'))
737
+ elif manifests:
738
+ closing += ' Its one change outside the tests is {}.'.format(
739
+ declares.strip().rstrip('.'))
740
+
741
+ if driven:
742
+ closing += ' {} `{}`, the repository\'s test driver, which {}.'\
743
+ .format('It also changes' if manifests or allowed else 'Its one '
744
+ 'change outside the tests is to', driven, ctx.get('driver', driven)
745
+ .strip().rstrip('.'))
746
+
747
+ if declares and not manifests and not others and not allowed:
748
+ ctx.problems.add('prose: `declares` names a change outside the '
749
+ 'tests, and files.tsv shows no dependency manifest: delete the '
750
+ 'field')
751
+ else:
752
+ sys.stderr.write('tests_pr_body: the test modules share no directory, '
753
+ 'so files.tsv was not checked against the opening\'s claim\n')
754
+ else:
755
+ sys.stderr.write('tests_pr_body: no files.tsv, so the opening\'s claim '
756
+ 'that no source, build or workflow file changes was not checked\n')
757
+
758
+ return [' '.join(part for part in (first, holds, closing) if part)]
759
+
760
+
761
+ def module_name(module, common):
762
+ return module[len(common) + 1:] if common and module.startswith(common + '/') \
763
+ else module
764
+
765
+
766
+ def running(ctx):
767
+ commands = ctx.get('running.commands', why='*Running it*', keep=True) or ''
768
+ commands = '\n'.join(line for line in commands.strip('\n').split('\n')
769
+ if not line.strip().startswith('```'))
770
+ notes = ctx.get('running.notes', why='*Running it*') or ''
771
+ lines = ['## Running it', '', '```', commands, '```', '', notes]
772
+ ci = ctx.get('running.ci')
773
+
774
+ if ci:
775
+ lines += ['', ci]
776
+
777
+ # Where the suite was run before the PR, from step 1's record: always the
778
+ # section's last paragraph.
779
+ checked = (ctx.get('checked', why='*Running it*') or '').strip()
780
+
781
+ if checked and not one_paragraph(checked):
782
+ ctx.problems.add('prose "=== checked" must be one paragraph, not a list '
783
+ 'or several paragraphs: the CI configurations the suite was run in '
784
+ 'and that it passed in each')
785
+
786
+ return lines + ['', checked]
787
+
788
+
789
+ def derivation(ctx):
790
+ text = ctx.get('derivation', why='*How expected values are derived*') or ''
791
+ tables = ctx.tables
792
+ docs = ctx.get('docs') or 'the documentation'
793
+
794
+ if tables['pinned'] is None:
795
+ sys.stderr.write('tests_pr_body: collection.tsv has no pinned column '
796
+ '(collection without --root), so *How expected values are derived* '
797
+ 'does not count the test functions that pin the current output\n')
798
+ elif tables['pinned']:
799
+ text = append_bullet(text, '- **Where {} is silent:** {} of the {} test '
800
+ 'functions or methods pin the current output instead, and each says '
801
+ 'so in its documentation or a comment.'.format(docs,
802
+ digits(tables['pinned']), digits(tables['functions'])))
803
+ else:
804
+ text = append_bullet(text, '- **Pinned output:** none of the {} test '
805
+ 'functions or methods pins the current output.'.format(digits(
806
+ tables['functions'])))
807
+
808
+ return ['## How expected values are derived', '', text]
809
+
810
+
811
+ def covers(ctx):
812
+ modules = ctx.tables['modules']
813
+ common = common_directory(modules)
814
+ lines = ['## What it covers', '', '| Module | Tests | What it checks |',
815
+ '|---|---:|---|']
816
+
817
+ for module, n in sorted(modules.items(), key=lambda item: (-item[1],
818
+ item[0])):
819
+ text = ctx.get('module', module, why='the row of {} in *What it '
820
+ 'covers*'.format(module))
821
+
822
+ if text and '\n' in text:
823
+ ctx.problems.add('prose "=== module {}" is more than one paragraph: '
824
+ 'it is a table cell'.format(module))
825
+ elif text and len(text.split()) > MODULE_WORDS:
826
+ ctx.problems.add('prose "=== module {}" is {} words: a table cell '
827
+ 'holds one clause of at most {}'.format(module, len(text.split()),
828
+ MODULE_WORDS))
829
+
830
+ lines.append('| `{}` | {} | {} |'.format(module_name(module, common),
831
+ digits(n), publish.cell((text or '').replace('\n', ' '))))
832
+
833
+ for key in ctx.prose:
834
+ if key[0] == 'module' and key[1] not in modules:
835
+ ctx.used.add(key)
836
+ ctx.problems.add('prose "=== module {}": collection.tsv collected no '
837
+ 'test in that module (the modules: {})'.format(key[1], ', '.join(
838
+ sorted(modules))))
839
+
840
+ return lines
841
+
842
+
843
+ def parts_section(ctx):
844
+ data = ctx.tables['coverage']
845
+ files = data['files']
846
+ counted = [f for f in files if not f['excluded']]
847
+ excluded = [f for f in files if f['excluded']]
848
+ total = sum(f['lines'] for f in counted)
849
+
850
+ # One row per part, the excluded ones after the rest, then the total.
851
+ by_part = {}
852
+
853
+ for record in files:
854
+ by_part.setdefault(record['part'], []).append(record)
855
+
856
+ def tests(n):
857
+ return '–' if n is None else digits(n)
858
+
859
+ lines = ['## Tests and line coverage by part', '', '| Part | Tests before '
860
+ '| Tests after | Line coverage before | Line coverage after |',
861
+ '|---|---:|---:|---:|---:|']
862
+ unknown = {'before': None, 'after': None, 'excluded': False}
863
+ order = sorted(by_part, key=lambda part: (data['parts'].get(part,
864
+ unknown)['excluded'], re.sub(r'[`*_]', '', part).lower(), part))
865
+
866
+ for part in order:
867
+ members = by_part[part]
868
+ record = data['parts'].get(part, unknown)
869
+ lines.append('| {}{} | {} | {} | {} | {} |'.format(publish.cell(
870
+ pathlike(part)), ' (excluded)' if record['excluded'] else '',
871
+ tests(record['before']), tests(record['after']), percent(sum(
872
+ f['existing'] for f in members), sum(f['lines'] for f in members)),
873
+ percent(sum(f['both'] for f in members), sum(f['lines']
874
+ for f in members))))
875
+
876
+ lines.append('| **Total**{} | {} | {} | {} | {} |'.format(
877
+ ' (excluded parts left out)' if excluded else '',
878
+ tests(data['total']['before']), tests(data['total']['after']),
879
+ percent(sum(f['existing'] for f in counted), total),
880
+ percent(sum(f['both'] for f in counted), total)))
881
+ how = '"Before" is the existing tests, and "after" adds this suite.'
882
+
883
+ if data['counted'] == 'per-test':
884
+ how += ' Tests per part count the tests that ran at least one line of ' \
885
+ 'the part, from per-test coverage; a test counts once per part, so ' \
886
+ 'the rows do not sum to the total.'
887
+ elif data['counted'] == 'by-file':
888
+ how += ' Tests per part count the tests in the files written for that ' \
889
+ 'part, as no per-test coverage was recorded.'
890
+ else:
891
+ reason = ctx.get('parts.tests', why='*Line coverage*, whose parts.tsv '
892
+ 'has no tests per part,')
893
+ how += ' Tests per part were not counted: {}'.format(
894
+ (reason or '').strip().rstrip('.') + '.')
895
+
896
+ lines += ['', how]
897
+
898
+ return lines
899
+
900
+
901
+ def coverage_section(ctx):
902
+ data = ctx.tables['coverage']
903
+ files = data['files']
904
+ counted = [f for f in files if not f['excluded']]
905
+ excluded = [f for f in files if f['excluded']]
906
+ total = sum(f['lines'] for f in counted)
907
+
908
+ def share(n, bold=False):
909
+ text = '{} ({})'.format(digits(n), percent(n, total))
910
+ return '**{}**'.format(text) if bold else text
911
+
912
+ method = ctx.get('coverage.method', why='*Line coverage*') or ''
913
+ tally = '- **Lines counted:** each source line counts once: {} executable ' \
914
+ 'lines in {}.'.format(digits(total), plural(len(counted), 'file'))
915
+
916
+ if excluded:
917
+ tally = tally[:-1] + '; {} of vendored or generated code ({}) {} ' \
918
+ 'counted apart and left out of every total.'.format(plural(len(
919
+ excluded), 'file'), lines_of(sum(f['lines'] for f in excluded)),
920
+ 'is' if len(excluded) == 1 else 'are')
921
+
922
+ lines = ['## Line coverage', '', 'How it was measured:', '',
923
+ append_bullet(method, tally), '', '| Tests | Lines covered |', '|---|---:|']
924
+ labels = data['labels']
925
+
926
+ if len(labels) > 1:
927
+ for i, label in enumerate(labels):
928
+ lines.append('| {} | {} |'.format(publish.cell(label), share(sum(
929
+ f['labels'][i] for f in counted))))
930
+
931
+ lines.append('| **{}** | {} |'.format('Existing tests together'
932
+ if len(labels) > 1 else 'Existing tests', share(sum(f['existing']
933
+ for f in counted), True)))
934
+ lines.append('| This suite alone | {} |'.format(share(sum(f['suite']
935
+ for f in counted))))
936
+ lines.append('| **Existing tests and this suite** | {} |'.format(share(sum(
937
+ f['both'] for f in counted), True)))
938
+
939
+ # The files that gain the most, when parts hold several files each.
940
+ parts_counted = {f['part'] for f in counted}
941
+
942
+ if len(counted) > len(parts_counted):
943
+ gains = sorted((f for f in counted if f['both'] > f['existing']),
944
+ key=lambda f: (-(f['both'] - f['existing']), f['file']))[:GAINS_SHOWN]
945
+
946
+ if gains:
947
+ lines += ['', 'The files that gain the most:', '',
948
+ '| File | Lines | Existing tests | With this suite |',
949
+ '|---|---:|---:|---:|']
950
+
951
+ for i, f in enumerate(gains):
952
+ lines.append('| `{}` | {} | {} | {} (+{}{}) |'.format(f['file'],
953
+ digits(f['lines']), percent(f['existing'], f['lines']),
954
+ percent(f['both'], f['lines']), digits(f['both']
955
+ - f['existing']), ' ' + ('line' if f['both'] - f['existing']
956
+ == 1 else 'lines') if i == 0 else ''))
957
+
958
+ return lines
959
+
960
+
961
+ def listed_file(ctx, text):
962
+ """Whether `text` names, in backticks, a file the tests branch holds: True,
963
+ False, or None when there is nothing to check it against (no files.tsv
964
+ and no branch.json)."""
965
+
966
+ paths = [span[2:] if span.startswith('./') else span
967
+ for span in CODE_SPAN.findall(text)]
968
+ paths = [path for path in paths if '/' in path
969
+ or re.search(r'\.[A-Za-z]\w*$', path)]
970
+
971
+ if not paths:
972
+ return False
973
+
974
+ files = ctx.tables['files']
975
+
976
+ if files and any(path in files for path in paths):
977
+ return True
978
+
979
+ branch = ctx.tables.get('branch') or {}
980
+
981
+ if branch.get('suite') and branch.get('branch'):
982
+ return any(publish.run(['git', '-C', branch['suite'], 'cat-file', '-e',
983
+ '{}:{}'.format(branch['branch'], path)])[0] == 0 for path in paths)
984
+
985
+ return None if files is None else False
986
+
987
+
988
+ def listing_problem(ctx, text):
989
+ """Why `contradictions` does not say where its cases are listed, or
990
+ None."""
991
+
992
+ if ctx.bugs:
993
+ if REPORT_LINK.search(text):
994
+ return None
995
+
996
+ return ('prose "=== contradictions" names no bug report: write '
997
+ '#<bug issue>, an issue number or a URL')
998
+
999
+ if BUG_ISSUE in text or OTHER_LINK.search(text):
1000
+ # A #<bug issue> here is refused with every other one.
1001
+ return None
1002
+
1003
+ found = listed_file(ctx, text)
1004
+
1005
+ if found is None:
1006
+ sys.stderr.write('tests_pr_body: no files.tsv and no branch.json, so the '
1007
+ 'file `contradictions` names was not checked against the tests '
1008
+ 'branch\n')
1009
+ return None
1010
+
1011
+ if found:
1012
+ return None
1013
+
1014
+ return ('prose "=== contradictions" names no report and no file in the '
1015
+ 'repository: the bug report is not among the documents chosen at step '
1016
+ '5, so write an issue number, a URL or the path of a file the tests '
1017
+ 'branch holds, in backticks (files.tsv, or the branch in branch.json)')
1018
+
1019
+
1020
+ def gaps(ctx):
1021
+ """*What the suite does not cover*."""
1022
+
1023
+ lines = ['## What the suite does not cover', '']
1024
+ docs = ctx.get('docs') or 'the documentation'
1025
+ contradictions = ctx.get('contradictions', why='*What the suite does not '
1026
+ 'cover*') or ''
1027
+
1028
+ if contradictions.strip().lower().rstrip('.') == 'none':
1029
+ lines.append('**No behaviour that contradicts {} was found.**'.format(docs))
1030
+ else:
1031
+ # Where the suite records each case differs between suites, so the
1032
+ # prose says it: a fixed sentence would be false for some of them.
1033
+ marked = (ctx.get('contradictions.marked', why='the list of untested '
1034
+ 'behaviour in *What the suite does not cover*') or '').strip()
1035
+
1036
+ if marked and not one_paragraph(marked):
1037
+ ctx.problems.add('prose "=== contradictions.marked" must be one '
1038
+ 'paragraph of sentences, not a list: it sits inside the sentence '
1039
+ 'before the list of cases')
1040
+
1041
+ if '\n' in contradictions.strip() and LIST_ITEM.search(contradictions) \
1042
+ or LIST_ITEM.match(contradictions.strip()):
1043
+ ctx.problems.add('prose "=== contradictions" is a list: the cases '
1044
+ 'belong in the bug report or the file that lists them, so write '
1045
+ 'one paragraph that counts them and names it')
1046
+ else:
1047
+ problem = listing_problem(ctx, contradictions)
1048
+
1049
+ if problem:
1050
+ ctx.problems.add(problem)
1051
+
1052
+ lines.append('**Behaviour that contradicts {} is left untested**, so that '
1053
+ 'fixing it will not break the suite. {}{}'.format(docs, marked.rstrip(
1054
+ '.') + '. ' if marked else '', ' '.join(contradictions.split())))
1055
+
1056
+ names = ctx.tables['names']
1057
+
1058
+ if names is not None:
1059
+ unnamed = [row for row in names if not row['tests']]
1060
+ lines.append('')
1061
+
1062
+ if unnamed:
1063
+ shown = [code(row['name']) for row in unnamed[:NAMES_SHOWN]]
1064
+ more = len(unnamed) - NAMES_SHOWN
1065
+ lines.append('**Public names no test file names ({} of {}):** {}.'
1066
+ .format(digits(len(unnamed)), digits(len(names)), ', '.join(shown)
1067
+ + ', and {} more'.format(digits(more)) if more > 0
1068
+ else publish.series(shown)))
1069
+ else:
1070
+ lines.append('**Every public name is named by at least one test '
1071
+ 'file.**')
1072
+
1073
+ coverage = ctx.tables['coverage']
1074
+
1075
+ if coverage:
1076
+ counted = [f for f in coverage['files'] if not f['excluded']]
1077
+ total = sum(f['lines'] for f in counted)
1078
+ unreached = sorted((f for f in counted if f['both'] == 0 and f['lines']),
1079
+ key=lambda f: (-f['lines'], f['file']))
1080
+ reached = [f for f in counted if f['both']]
1081
+ lines += ['', '**Lines no test reaches:**', '']
1082
+
1083
+ if unreached:
1084
+ lost = sum(f['lines'] for f in unreached)
1085
+ without = percent(sum(f['both'] for f in counted), total - lost)
1086
+ largest = ['`{}` ({}{})'.format(f['file'], digits(f['lines']), ' ' + (
1087
+ 'line' if f['lines'] == 1 else 'lines') if i == 0 else '') for i, f in
1088
+ enumerate(unreached[:UNREACHED_SHOWN])]
1089
+
1090
+ if len(unreached) == 1:
1091
+ lines.append('- **One file, {}, runs in no test at all.** Without '
1092
+ 'it, coverage is {}.'.format(largest[0], without))
1093
+ elif len(unreached) <= UNREACHED_SHOWN:
1094
+ lines.append('- **{}, {}, run in no test at all:** {}. Without '
1095
+ 'them, coverage is {}.'.format(capital(plural(len(unreached),
1096
+ 'file')), lines_of(lost), publish.series(largest), without))
1097
+ else:
1098
+ lines.append('- **{}, {}, run in no test at all.** The largest '
1099
+ 'are {}. Without them, coverage is {}.'.format(capital(plural(
1100
+ len(unreached), 'file')), lines_of(lost), publish.series(
1101
+ largest), without))
1102
+ else:
1103
+ lines.append('- **Every file runs in at least one test.**')
1104
+
1105
+ widest = sorted((f for f in reached if f['lines'] > f['both']),
1106
+ key=lambda f: (-(f['lines'] - f['both']), f['file']))[:GAPS_SHOWN]
1107
+
1108
+ if widest:
1109
+ lines.append('- **The largest gaps in files that are reached** are in '
1110
+ '{}.'.format(publish.series('`{}` ({}{}, {} covered)'.format(
1111
+ f['file'], digits(f['lines'] - f['both']), ' {} not run'.format(
1112
+ 'line' if f['lines'] - f['both'] == 1 else 'lines') if i == 0
1113
+ else '', percent(f['both'], f['lines']))
1114
+ for i, f in enumerate(widest))))
1115
+
1116
+ platforms = ctx.get('platforms', why='*What the suite does not cover*') or ''
1117
+ lines += ['', '**Platforms:** ' + platforms.strip()]
1118
+
1119
+ return lines
1120
+
1121
+
1122
+ SECTIONS = (
1123
+ ('*Tests and line coverage by part*', 'coverage', parts_section),
1124
+ ('*Running it*', None, running),
1125
+ ('*How expected values are derived*', None, derivation),
1126
+ ('*What it covers*', None, covers),
1127
+ ('*Line coverage*', 'coverage', coverage_section),
1128
+ ('*What the suite does not cover*', None, gaps),
1129
+ )
1130
+
1131
+ SOURCES = {'coverage': 'coverage.tsv and parts.tsv'}
1132
+
1133
+
1134
+ def render(tables, prose, problems):
1135
+ ctx = Context(tables, prose, problems)
1136
+ blocks = [opening(ctx)]
1137
+ dropped = []
1138
+
1139
+ for title, needs, build in SECTIONS:
1140
+ if needs and not tables[needs]:
1141
+ dropped.append('{}: no {}'.format(title, SOURCES[needs]))
1142
+ continue
1143
+
1144
+ blocks.append(build(ctx))
1145
+
1146
+ if not ctx.bugs:
1147
+ for key, value in prose.items():
1148
+ if BUG_ISSUE in value:
1149
+ problems.add('prose "=== {}" holds {}, and the bug report is not '
1150
+ 'among the documents chosen at step 5 (after.ship_documents), so '
1151
+ 'that issue will not exist: name an issue number, a URL or a file '
1152
+ 'in the repository instead'.format(' '.join(key).strip(),
1153
+ BUG_ISSUE))
1154
+
1155
+ unused = [' '.join(key).strip() for key in prose if key not in ctx.used]
1156
+ text = '\n\n'.join('\n'.join(block) for block in blocks)
1157
+ text = re.sub(r'\n{3,}', '\n\n', text).strip('\n') + '\n'
1158
+
1159
+ return text, dropped, unused
1160
+
1161
+
1162
+ # The template ----------------------------------------------------------------
1163
+
1164
+ def template(tables):
1165
+ """A prose file with one <<FILL: …>> per field these tables call for."""
1166
+
1167
+ fields = [('opening', ''), ('support', ''), ('docs', ''),
1168
+ ('running.commands', ''), ('running.notes', ''), ('running.ci', ''),
1169
+ ('checked', ''), ('derivation', '')]
1170
+ fields += [('module', module) for module in sorted(tables['modules'])]
1171
+
1172
+ if any(os.path.basename(path) in DEPENDENCY_MANIFESTS
1173
+ for path in tables['files'] or []):
1174
+ fields.append(('declares', ''))
1175
+
1176
+ if tables['coverage']:
1177
+ fields.append(('coverage.method', ''))
1178
+
1179
+ if not tables['coverage']['counted']:
1180
+ fields.append(('parts.tests', ''))
1181
+
1182
+ fields += [('contradictions', ''), ('contradictions.marked', ''),
1183
+ ('platforms', '')]
1184
+ out = []
1185
+
1186
+ for field, argument in fields:
1187
+ out += ['=== {}{}'.format(field, ' ' + argument if argument else ''),
1188
+ '<<FILL: {}>>'.format(FIELDS[field][1]), '']
1189
+
1190
+ return '\n'.join(out)
1191
+
1192
+
1193
+ def read_config(path, problems):
1194
+ """The search's config.json as a dict; {} when it does not exist."""
1195
+
1196
+ try:
1197
+ with open(path, encoding='utf-8') as infile:
1198
+ config = json.load(infile)
1199
+ except FileNotFoundError:
1200
+ return {}
1201
+ except (OSError, ValueError) as error:
1202
+ problems.add('could not read {}: {}'.format(path, error))
1203
+ return {}
1204
+
1205
+ return config if isinstance(config, dict) else {}
1206
+
1207
+
1208
+ def main(argv=None):
1209
+ parser = argparse.ArgumentParser(description=__doc__,
1210
+ formatter_class=argparse.RawDescriptionHelpFormatter)
1211
+ parser.add_argument('data', help='the folder of tables and prose, '
1212
+ '$WORK/ship/pr-tests')
1213
+ parser.add_argument('--prose', help='the prose file (default: DIR/prose.md)')
1214
+ parser.add_argument('--out', help='write the body here (default: stdout), '
1215
+ 'and the title beside it as <out stem>.title; needs --title, unless a '
1216
+ 'title is stored there')
1217
+ parser.add_argument('--title', help='the PR\'s title, such as "Add unit '
1218
+ 'tests for pkg": a capital letter, no closing period, at most {} '
1219
+ 'characters (default: the one stored beside --out)'.format(
1220
+ attribution.TITLE_LIMIT))
1221
+ parser.add_argument('--config', help='the search\'s config.json, whose '
1222
+ 'after.tests_driver_edit allows a `driver` edit and whose '
1223
+ 'after.ship_documents says whether the bug report is posted (default: '
1224
+ 'DIR/../../autooptimize/config.json, when it exists)')
1225
+ parser.add_argument('--allow-source', action='append', default=[],
1226
+ metavar='PATH', help='a changed file outside the tests, other than a '
1227
+ 'manifest or the test driver, that the user approved by name (repeatable). '
1228
+ '`declares` must also name it; the opening then lists it instead of '
1229
+ 'claiming no source changes. Record their words in spec.md first')
1230
+ parser.add_argument('--template', action='store_true', help='print a prose '
1231
+ 'skeleton for these tables instead of a body')
1232
+ args = parser.parse_args(argv)
1233
+
1234
+ problems = Problems()
1235
+ tables = load(args.data, problems)
1236
+ tables['allow_source'] = args.allow_source
1237
+ config = read_config(args.config or os.path.join(args.data, '..', '..',
1238
+ 'autooptimize', 'config.json'), problems)
1239
+ after = config.get('after') or {}
1240
+ tables['driver_edit'] = after.get('tests_driver_edit')
1241
+
1242
+ if args.config:
1243
+ documents = list(after.get('ship_documents') or publish.FOLDERS)
1244
+ else:
1245
+ documents = publish.chosen(args.data)
1246
+
1247
+ tables['bugs'] = 'bugs' in documents
1248
+
1249
+ if args.template:
1250
+ if problems:
1251
+ sys.stderr.write('tests_pr_body: the tables have problems the body '
1252
+ 'will refuse:\n {}\n'.format('\n '.join(problems)))
1253
+
1254
+ sys.stdout.write(template(tables))
1255
+ return 0
1256
+
1257
+ prose = read_prose(args.prose or os.path.join(args.data, 'prose.md'),
1258
+ problems)
1259
+ text, dropped, unused = render(tables, prose, problems)
1260
+ text = publish.fill_numbers(text, args.data, problems)
1261
+
1262
+ return publish.emit('tests_pr_body', text, problems, args.title, args.out,
1263
+ dropped, unused)
1264
+
1265
+
1266
+ if __name__ == '__main__':
1267
+ sys.exit(main())