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,1193 @@
1
+ #!/usr/bin/env python3
2
+ """Step 5: ship an ended search (`references/step5-ship.md`).
3
+
4
+ python3 ship.py plan WORK [--json] # what this search can ship, and the question to ask
5
+ python3 ship.py apply WORK [--id N] [--to DIR] [--yes]
6
+ python3 ship.py branch WORK [--id N] [--name N] [--repo PATH] [--yes]
7
+ python3 ship.py brief WORK # the document writer's prompt for the GitHub documents
8
+ python3 ship.py status WORK # each chosen document: inputs, body, posted
9
+ python3 ship.py render WORK [--only bugs|tests|optimization]
10
+ python3 ship.py rehearse WORK [--branch DOC=NAME] # render and preview every chosen document together
11
+ python3 ship.py post WORK all --approved --digest D [--branch DOC=NAME] [--other-owner]
12
+
13
+ The user answers one question first: how to ship. `apply` writes a plain
14
+ search's change into the original files; `branch` makes a branch in the
15
+ original repository holding one commit per kept change; the GitHub route
16
+ opens the documents the user checked (the optimization PR, the unit-test PR,
17
+ the bug report), reviewed together and posted together. Every command
18
+ previews by default and writes nothing until `--yes` (apply, branch) or
19
+ `post --approved` (GitHub).
20
+
21
+ Standard library only.
22
+ """
23
+
24
+ import os
25
+ import sys
26
+ import json
27
+ import hashlib
28
+ import argparse
29
+ import tempfile
30
+ import subprocess
31
+
32
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33
+
34
+ import autoopt
35
+ import publish
36
+
37
+ HERE = os.path.dirname(os.path.abspath(__file__))
38
+
39
+
40
+ def fail(message):
41
+ publish.fail('ship', message)
42
+
43
+
44
+ def search(work_arg):
45
+ """`(work, root, config)` for a search directory, the one holding
46
+ `autooptimize/` (or `autooptimize/` itself)."""
47
+
48
+ work = os.path.abspath(os.path.expanduser(work_arg))
49
+
50
+ if os.path.basename(work) == 'autooptimize':
51
+ work = os.path.dirname(work)
52
+
53
+ root = os.path.join(work, 'autooptimize')
54
+
55
+ if not os.path.exists(os.path.join(root, 'config.json')):
56
+ fail('{} holds no search (no autooptimize/config.json)'.format(work))
57
+
58
+ return work, root, autoopt.load_config(root)
59
+
60
+
61
+ def after_of(config):
62
+ return dict(autoopt.AFTER_DEFAULTS, **(config.get('after') or {}))
63
+
64
+
65
+ def show(git_dir, ref, path):
66
+ """The bytes of `path` at `ref`, and its git mode, or (None, None)."""
67
+
68
+ try:
69
+ entry = autoopt.git('-C', git_dir, 'ls-tree', ref, '--', path).split()
70
+ except RuntimeError:
71
+ return None, None
72
+
73
+ if not entry:
74
+ return None, None
75
+
76
+ data = subprocess.run(['git', '-C', git_dir, 'cat-file', 'blob', entry[2]],
77
+ capture_output=True, check=True).stdout
78
+
79
+ return data, entry[0]
80
+
81
+
82
+ def read_bytes(path):
83
+ try:
84
+ with open(path, 'rb') as handle:
85
+ return handle.read()
86
+ except OSError:
87
+ return None
88
+
89
+
90
+ ###
91
+ # apply: a plain search's change, written into the original files
92
+ ###
93
+
94
+ def applied_record(work):
95
+ """`ship/applied.json`, what an earlier `apply --yes` wrote, or None."""
96
+
97
+ try:
98
+ return autoopt.read_json(autoopt.work_path(work, 'ship',
99
+ 'applied.json'))
100
+ except OSError:
101
+ return None
102
+
103
+
104
+ def apply_plan(work, root, config, identifier, to, by_hand=False):
105
+ """What `apply` would do: `{'rows': [(path, destination, action)],
106
+ 'skipped': [paths the search wrote], 'problems': [...], 'hand':
107
+ [(path, destination)]}`. With `by_hand`, a file that holds neither the
108
+ copy nor the winner is one the user merged the change into by hand, on
109
+ their word, and goes in `hand` rather than `problems`. A path is
110
+ applied where it came from: under `to`, else under the folder that held
111
+ the files `init --copy` took (`config['copied']`).
112
+
113
+ A file may hold what the copy held, or what an earlier `apply --yes`
114
+ wrote (`ship/applied.json`), as when a winner promoted after the end
115
+ replaces the one applied; a file that earlier apply wrote and this
116
+ winner leaves as the copy had it goes back to the copy."""
117
+
118
+ bare = os.path.join(root, 'repo.git')
119
+ head = autoopt.branch_of(root, identifier)
120
+ changed = [line.split('\t') for line in autoopt.git('-C', bare, 'diff',
121
+ '--name-status', '--no-renames', 'autoopt/0', head).splitlines() if
122
+ line.strip()]
123
+ base_files = set(autoopt.git('-C', bare, 'ls-tree', '-r', '--name-only',
124
+ 'autoopt/0').splitlines())
125
+ earlier = applied_record(work) or {}
126
+ prior = earlier.get('commit')
127
+
128
+ for row in (earlier.get('files') or []) + (earlier.get('already') or []):
129
+ if row.get('path') not in {path for _, path in changed}:
130
+ changed.append(('D' if show(bare, head, row['path'])[0] is None
131
+ else 'M', row['path']))
132
+
133
+ copied = config.get('copied') or []
134
+ names = [entry['as'] for entry in copied]
135
+ problems, rows, skipped, already, hand = [], [], [], [], []
136
+
137
+ def from_user(path):
138
+ return any(path == name or path.startswith(name + '/') for name in
139
+ names)
140
+
141
+ if to:
142
+ destination = lambda path: os.path.join(to, path)
143
+ elif copied:
144
+ parents = {os.path.dirname(entry['source']) for entry in copied}
145
+
146
+ def destination(path):
147
+ for entry in copied:
148
+ if path == entry['as'] or path.startswith(entry['as'] + '/'):
149
+ return os.path.join(os.path.dirname(entry['source']), path)
150
+
151
+ # A file the change adds beside the copied ones goes into their
152
+ # folder, when they all came from one.
153
+ return os.path.join(next(iter(parents)), path) if len(parents) \
154
+ == 1 else None
155
+ else:
156
+ fail('this search does not record where its files came from (it was '
157
+ 'made before `init` kept that record): pass --to DIR, the folder '
158
+ 'that holds {}'.format(', '.join(sorted(base_files)[:5])))
159
+
160
+ for status, path in changed:
161
+ # The baseline holds files the search wrote itself (the benchmark):
162
+ # they are no part of the user's code.
163
+ if path in base_files and not from_user(path) and (copied or not to):
164
+ skipped.append(path)
165
+ continue
166
+
167
+ target = destination(path)
168
+
169
+ if target is None:
170
+ problems.append('{} is new, and the copied files came from more '
171
+ 'than one folder: pass --to DIR for it'.format(path))
172
+ continue
173
+
174
+ before = show(bare, 'autoopt/0', path)[0]
175
+ after = show(bare, head, path)[0] if status != 'D' else None
176
+ current = read_bytes(target)
177
+ # What the earlier apply left there (None: it left nothing).
178
+ applied = prior and current == show(bare, prior, path)[0]
179
+
180
+ if current == after:
181
+ already.append((path, target))
182
+ continue
183
+
184
+ # A file the user merged the change into by hand, on their word: it
185
+ # matches neither the copy nor the winner, and is left as it is.
186
+ if by_hand and current is not None and not applied:
187
+ hand.append((path, target))
188
+ continue
189
+
190
+ if applied:
191
+ pass
192
+ elif status == 'A':
193
+ if current is not None:
194
+ problems.append('{} exists already, and the change adds it'
195
+ .format(target))
196
+ continue
197
+ elif current is None:
198
+ problems.append('{} is missing; the search copied it from there'
199
+ .format(target))
200
+ continue
201
+ elif current != before:
202
+ problems.append('{} changed since the search copied it; the '
203
+ 'change was measured on the copy, so it is not written over '
204
+ 'edits it never saw'.format(target))
205
+ continue
206
+
207
+ rows.append((path, target, {'A': 'add', 'D': 'delete'}.get(status,
208
+ 'change')))
209
+
210
+ return {'rows': rows, 'skipped': skipped, 'problems': problems,
211
+ 'head': head, 'already': already, 'hand': hand}
212
+
213
+
214
+ def apply(args):
215
+ work, root, config = search(args.work)
216
+ autoopt.require_ended(root, 'apply its change')
217
+
218
+ if config.get('repo'):
219
+ fail('this is a repository search: `ship.py branch` makes a branch in '
220
+ 'the original, and the GitHub documents open PRs; `apply` is for a '
221
+ 'search made with `init --copy`')
222
+
223
+ identifier = autoopt.resolve_id(root, config, args.id)
224
+ problem = autoopt.measured_problem(root, config, identifier)
225
+
226
+ if problem:
227
+ fail(problem)
228
+
229
+ if args.yes and after_of(config).get('ship') != 'apply':
230
+ fail('after.ship is {}: the original files are written only on the '
231
+ 'user\'s choice. Ask with `ship.py plan` and record it (`autoopt.py '
232
+ 'config <work> --set after.ship=apply --reason "<their words>"`)'
233
+ .format(after_of(config).get('ship')))
234
+
235
+ to = os.path.abspath(os.path.expanduser(args.to)) if args.to else None
236
+ plan = apply_plan(work, root, config, identifier, to, args.by_hand)
237
+ bare = os.path.join(root, 'repo.git')
238
+ stat = autoopt.git('-C', bare, 'diff', '--stat', 'autoopt/0', plan['head'],
239
+ '--', *[path for path, _, _ in plan['rows']]).rstrip() if plan[
240
+ 'rows'] else ''
241
+
242
+ print('{} ({}): {} file(s)'.format(autoopt.label(root, identifier),
243
+ (autoopt.load_result(root, identifier) or {}).get('title'),
244
+ len(plan['rows'])))
245
+
246
+ for path, target, action in plan['rows']:
247
+ print(' {:7} {}'.format(action, target))
248
+
249
+ for path in plan['skipped']:
250
+ print(' not applied: {}, which the search wrote itself (it was not '
251
+ 'copied from your files)'.format(path))
252
+
253
+ for path, target in plan['already']:
254
+ print(' already holds the change: {}'.format(target))
255
+
256
+ for path, target in plan['hand']:
257
+ print(' applied by hand, on the user\'s word: {} (left as it is)'
258
+ .format(target))
259
+
260
+ if stat:
261
+ print('\n' + stat)
262
+
263
+ if plan['problems']:
264
+ fail('nothing was written:\n ' + '\n '.join(plan['problems']))
265
+
266
+ if not plan['rows'] and not plan['already'] and not plan['hand']:
267
+ fail('the change touches none of the copied files; nothing to apply')
268
+
269
+ if not plan['rows'] and not args.yes:
270
+ print('\nthe change is applied already; nothing to write. `--yes` '
271
+ 'records it as applied once the user has agreed.')
272
+ return 0
273
+
274
+ if not args.yes:
275
+ print('\npreview only: nothing was written. `--yes` writes these '
276
+ 'files once the user has agreed.')
277
+ return 0
278
+
279
+ # Every file's new bytes first, then every write, so a failure while
280
+ # reading leaves the originals as they were.
281
+ writes = []
282
+
283
+ for path, target, action in plan['rows']:
284
+ data, mode = show(bare, plan['head'], path) if action != 'delete' \
285
+ else (None, None)
286
+ writes.append((target, action, data, mode))
287
+
288
+ for target, action, data, mode in writes:
289
+ if action == 'delete':
290
+ os.remove(target)
291
+ continue
292
+
293
+ os.makedirs(os.path.dirname(target) or '.', exist_ok=True)
294
+
295
+ with open(target + '.ship-tmp', 'wb') as out:
296
+ out.write(data)
297
+
298
+ if mode == '100755':
299
+ os.chmod(target + '.ship-tmp', 0o755)
300
+ elif os.path.exists(target):
301
+ os.chmod(target + '.ship-tmp', os.stat(target).st_mode & 0o7777)
302
+
303
+ os.replace(target + '.ship-tmp', target)
304
+
305
+ # The record, the hold on `end --reopen` and NOTES.md, also when every
306
+ # file held the change already: the stage is done either way.
307
+ folder = autoopt.work_path(work, 'ship')
308
+ record_path = os.path.join(folder, 'applied.json')
309
+ commit = autoopt.git('-C', bare, 'rev-parse', plan['head']).strip()
310
+
311
+ try:
312
+ earlier = autoopt.read_json(record_path)
313
+ except OSError:
314
+ earlier = None
315
+
316
+ # The same winner applied again, with nothing left to write: the first
317
+ # record already says what was written, so keep it as it is.
318
+ if not writes and not plan['hand'] and earlier and earlier.get(
319
+ 'commit') == commit:
320
+ autoopt.hold_reopen(root, 'apply', 'written into the original files')
321
+ autoopt.refresh_notes(root)
322
+ print('\nthe change is applied already, as {} records'.format(
323
+ record_path))
324
+ return 0
325
+
326
+ # The patch is the whole change the original files now hold: the files
327
+ # written now and those that held it already (an earlier apply's, or
328
+ # the user's own), so it stands alone after an --after-end winner.
329
+ held = [path for path, _, _ in plan['rows']] + [path for path, _ in
330
+ plan['already'] + plan['hand']]
331
+ patch = os.path.join(folder, 'applied.patch') if held else None
332
+
333
+ os.makedirs(folder, exist_ok=True)
334
+
335
+ if patch:
336
+ publish.write(patch, autoopt.git('-C', bare, 'diff', '--binary',
337
+ 'autoopt/0', plan['head'], '--', *held))
338
+
339
+ publish.write_json(record_path, {'id': identifier,
340
+ 'label': autoopt.label(root, identifier), 'commit': commit,
341
+ 'files': [{'path': path, 'destination': target, 'action': action}
342
+ for path, target, action in plan['rows']], 'already': [{'path':
343
+ path, 'destination': target} for path, target in plan['already']],
344
+ 'by_hand': [{'path': path, 'destination': target} for path, target
345
+ in plan['hand']],
346
+ 'skipped': plan['skipped'], 'patch': patch, 'at': autoopt.now()})
347
+ autoopt.hold_reopen(root, 'apply', 'written into the original files')
348
+ autoopt.refresh_notes(root)
349
+
350
+ if writes:
351
+ print('\nwrote {} file(s); the patch is {}'.format(len(writes), patch))
352
+ else:
353
+ print('\nthe change is applied already; recorded in {}, with the '
354
+ 'patch {}'.format(record_path, patch))
355
+
356
+ return 0
357
+
358
+
359
+ ###
360
+ # branch: a repository search's change, as a branch in the original
361
+ ###
362
+
363
+ def local_messages(root, steps):
364
+ """Each step's commit message: its `## Commit message`, else its title,
365
+ with `after.commit_trailer` added."""
366
+
367
+ trailer = autoopt.commit_trailer(root)
368
+ messages = {}
369
+
370
+ for step, _ in steps:
371
+ message = autoopt.change_fragment(root, step).get('message')
372
+
373
+ if not message:
374
+ message = (autoopt.load_result(root, step) or {}).get('title') or \
375
+ 'Change {}'.format(autoopt.label(root, step))
376
+
377
+ messages[step] = autoopt.with_trailer(message, trailer)
378
+
379
+ return messages
380
+
381
+
382
+ def path_steps(root, config, identifier):
383
+ bare = os.path.join(root, 'repo.git')
384
+ strip = autoopt.outputs_stripper(root, config)
385
+ start = config['repo']['commit']
386
+
387
+ return autoopt.winning_steps(root, autoopt.lineage(root, identifier),
388
+ lambda i: strip(autoopt.git('-C', bare, 'rev-parse', autoopt.branch_of(
389
+ root, i) + '^{tree}').strip()), strip(autoopt.git('-C', bare,
390
+ 'rev-parse', start + '^{tree}').strip()))
391
+
392
+
393
+ def prefix_problem(config):
394
+ """Refuse a branch named before the user said whether branch names start
395
+ with `auto-optimize/`, the third question of `ship.py plan`."""
396
+
397
+ if after_of(config).get('branch_prefix') not in ('yes', 'no'):
398
+ fail('the user has not said whether the branch names start with {} '
399
+ '(after.branch_prefix): ask it with the other questions of `ship.py '
400
+ 'plan`'.format(autoopt.BRANCH_PREFIX))
401
+
402
+
403
+ def branch(args):
404
+ work, root, config = search(args.work)
405
+ autoopt.require_ended(root, 'make a branch from it')
406
+
407
+ if not config.get('repo'):
408
+ fail('this search was made with `init --copy`; `ship.py apply` writes '
409
+ 'its change into the original files')
410
+
411
+ identifier = autoopt.resolve_id(root, config, args.id)
412
+ problem = autoopt.measured_problem(root, config, identifier)
413
+
414
+ if problem:
415
+ fail(problem)
416
+
417
+ original = autoopt.original_of(work, config)
418
+ path = os.path.abspath(os.path.expanduser(args.repo)) if args.repo else \
419
+ original.get('path')
420
+
421
+ if not path:
422
+ fail('the original repository\'s folder is not recorded: pass --repo '
423
+ 'PATH')
424
+
425
+ if not args.name:
426
+ prefix_problem(config)
427
+
428
+ if args.yes and after_of(config).get('ship') != 'branch':
429
+ fail('after.ship is {}: a branch is made in the original repository '
430
+ 'only on the user\'s choice. Ask with `ship.py plan` and record it '
431
+ '(`autoopt.py config <work> --set after.ship=branch --reason "<their '
432
+ 'words>"`)'.format(after_of(config).get('ship')))
433
+
434
+ messages = local_messages(root, path_steps(root, config, identifier))
435
+ made = autoopt.pr_commits(root, config, identifier, messages)
436
+ bare = os.path.join(root, 'repo.git')
437
+ name = args.name or autoopt.ship_branch(config, 'optimized-{}'.format(
438
+ autoopt.now()[:10]))
439
+ listing = autoopt.git('-C', bare, 'log', '--reverse', '--format=%h %s',
440
+ '{}..{}'.format(made['base'], made['tip'])).rstrip()
441
+ stat = autoopt.git('-C', bare, 'diff', '--stat', made['base'],
442
+ made['tip']).rstrip()
443
+
444
+ print('{} commit(s) on {} ({}) -> branch {} in {}'.format(len(
445
+ made['series']), original.get('branch') or '?', made['base'][:10], name,
446
+ path))
447
+
448
+ if made['suite']:
449
+ print('without the unit-test suite: each change applied to the '
450
+ 'original\'s commit')
451
+
452
+ print('\nthe commits, oldest first:\n' + listing + '\n\n' + stat)
453
+
454
+ exists = subprocess.run(['git', '-C', path, 'rev-parse', '--verify', '-q',
455
+ 'refs/heads/' + name], capture_output=True).returncode == 0
456
+
457
+ if exists:
458
+ fail('{} already has a branch {}: pass --name'.format(path, name))
459
+
460
+ if not args.yes:
461
+ print('\npreview only: nothing was written. `--yes` makes the branch '
462
+ 'once the user has agreed; it does not check it out.')
463
+ return 0
464
+
465
+ autoopt.git('-C', path, 'fetch', '-q', bare, 'refs/pr/{}:refs/heads/{}'
466
+ .format(identifier, name))
467
+ publish.write_json(autoopt.work_path(work, 'ship', 'branch.json'), {
468
+ 'id': identifier, 'label': autoopt.label(root, identifier), 'repo': path,
469
+ 'branch': name, 'base': made['base'], 'tip': made['tip'],
470
+ 'commits': [sha for _, sha in made['series']], 'at': autoopt.now()})
471
+ autoopt.hold_reopen(root, 'branch', 'branch {} in {}'.format(name, path))
472
+ autoopt.refresh_notes(root)
473
+ print('\nmade branch {} in {}: `git -C {} switch {}` checks it out'.format(
474
+ name, path, path, name))
475
+
476
+ return 0
477
+
478
+
479
+ ###
480
+ # plan: what this search can ship, and the question to ask
481
+ ###
482
+
483
+ def bug_folders(work):
484
+ folder = os.path.join(autoopt.work_path(work, 'tests'), 'work', 'bugs')
485
+
486
+ try:
487
+ return sorted(name for name in os.listdir(folder) if os.path.isdir(
488
+ os.path.join(folder, name)))
489
+ except OSError:
490
+ return []
491
+
492
+
493
+ def choices(work, config):
494
+ """What step 5 offers this search, read from its files alone (no `gh`):
495
+ `{'mode', 'routes': [choice], 'documents': [document], 'original',
496
+ 'slug', 'bugs'}`. `plan` asks from it; `stages.py` reads an answer
497
+ outside it as no answer, and `github()` refuses one."""
498
+
499
+ if not config.get('repo'):
500
+ return {'mode': 'plain', 'routes': ['apply', 'none'], 'documents': [],
501
+ 'original': None, 'slug': None, 'bugs': []}
502
+
503
+ original = autoopt.original_of(work, config)
504
+ slug = autoopt.github_slug(original.get('remote_url'))
505
+ bugs = bug_folders(work)
506
+ documents = ['optimization'] + (['tests'] if original.get('suite') else
507
+ []) + (['bugs'] if bugs else []) if slug else []
508
+
509
+ return {'mode': 'repository', 'routes': (['github'] if slug else []) +
510
+ ['branch', 'none'], 'documents': documents, 'original': original,
511
+ 'slug': slug, 'bugs': bugs}
512
+
513
+
514
+ def offer(work, root, config):
515
+ """`{'mode', 'routes': [(choice, label, description)], 'documents':
516
+ [(document, label, description)], 'facts': [lines]}`."""
517
+
518
+ facts, documents = [], []
519
+ found = choices(work, config)
520
+ ended = autoopt.load_ended(root) or {}
521
+ winner = ended.get('winner') or {}
522
+ medians = ended.get('medians') or {}
523
+ facts.append('the search ended on {}: {} {} {} -> {}'.format((ended.get(
524
+ 'ended_at') or '?')[:10], winner.get('label', '?'), medians.get(
525
+ 'objective', ''), autoopt.fmt(medians.get('A0')), autoopt.fmt(
526
+ medians.get('winner'))))
527
+
528
+ if found['mode'] == 'plain':
529
+ copied = config.get('copied') or []
530
+ facts.append('plain mode; copied from: {}'.format(', '.join(entry[
531
+ 'source'] for entry in copied) if copied else 'not recorded (apply '
532
+ 'needs --to DIR)'))
533
+ return {'mode': 'plain', 'facts': facts, 'documents': [], 'branches':
534
+ [], 'routes': [
535
+ ('apply', 'Apply the change to the original file(s)', 'writes the '
536
+ 'measured files over the originals after a preview; refuses a file '
537
+ 'that changed since the search copied it'),
538
+ ('none', 'Not now', 'nothing is written; the change stays in the '
539
+ 'search, and step 6 copies it out')]}
540
+
541
+ original, slug, bugs = found['original'], found['slug'], found['bugs']
542
+ suite = original.get('suite')
543
+ facts.append('repository mode: {} on {} at {}'.format(original.get('path')
544
+ or '(original folder not recorded)', original.get('branch'),
545
+ (original.get('commit') or '?')[:10]))
546
+ facts.append('remote: {}{}'.format(original.get('remote_url') or 'none',
547
+ ' (GitHub {})'.format(slug) if slug else ' (not GitHub)'))
548
+
549
+ if slug:
550
+ push = publish.can_push(slug)
551
+ facts.append('gh: {}; push to {}: {}'.format(publish.login() or
552
+ 'not logged in or not installed', slug, {True: 'yes', False: 'no, '
553
+ 'so the PRs come from a fork (after.pr_remote, after.pr_head_owner)',
554
+ None: 'unknown'}[push]))
555
+
556
+ facts.append('unit-test suite from step 1: {}'.format('yes, branch {}'
557
+ .format(suite.get('tests_branch')) if suite else 'no'))
558
+ facts.append('bugs step 1 recorded: {}'.format(', '.join(bugs) if bugs else
559
+ 'none'))
560
+ routes = []
561
+
562
+ if slug:
563
+ routes.append(('github', 'Open GitHub documents', 'you pick which: '
564
+ 'the optimization PR{}{}; all are shown to you together before '
565
+ 'anything is posted'.format(', the unit-test PR' if suite else '',
566
+ ', the bug report' if bugs else '')))
567
+ documents.append(('optimization', 'The optimization PR', 'one commit '
568
+ 'per kept change, on {}{}'.format(original.get('branch'),
569
+ ', separate from the unit tests' if suite else '')))
570
+
571
+ if suite:
572
+ documents.append(('tests', 'The unit-test PR', 'the new suite '
573
+ 'alone, as step 1 squashed it'))
574
+
575
+ if bugs:
576
+ documents.append(('bugs', 'The bug report', 'one GitHub issue for '
577
+ 'the {} bug(s) step 1 found, each reproduction re-run on {} '
578
+ 'first'.format(len(bugs), original.get('branch'))))
579
+
580
+ routes.append(('branch', 'A branch in your local repository', 'one commit '
581
+ 'per kept change, as a new branch in {}; nothing is pushed'.format(
582
+ original.get('path') or 'the original')))
583
+ routes.append(('none', 'Not now', 'nothing is posted or written; the '
584
+ 'change stays in the search'))
585
+
586
+ # The names step 5 would give, both ways: the optimization PR's comes
587
+ # from its title, written later, so it is shown by its form.
588
+ date = autoopt.now()[:10]
589
+ tests_branch = (suite or {}).get('tests_branch') or \
590
+ '{}{}-unit-tests'.format(autoopt.BRANCH_PREFIX, date)
591
+ branches = []
592
+
593
+ for answer, label in (('no', 'No'), ('yes', 'Yes')):
594
+ named = dict(config, after=dict(after_of(config), branch_prefix=answer))
595
+ names = ['`{}`'.format(autoopt.ship_branch(named, '<from-the-pr-title>'))]
596
+
597
+ if suite:
598
+ names.append('`{}`'.format(autoopt.tests_branch_remote(named,
599
+ tests_branch)))
600
+
601
+ names.append('`{}`'.format(autoopt.ship_branch(named,
602
+ 'optimized-{}'.format(date))))
603
+ branches.append((label, ', '.join(names)))
604
+
605
+ return {'mode': 'repository', 'facts': facts, 'routes': routes,
606
+ 'documents': documents, 'branches': branches}
607
+
608
+
609
+ def plan(args):
610
+ work, root, config = search(args.work)
611
+ autoopt.require_ended(root, 'ship')
612
+ offered = offer(work, root, config)
613
+ after = after_of(config)
614
+
615
+ if args.json:
616
+ print(json.dumps(offered, indent=1))
617
+ return 0
618
+
619
+ print('\n'.join(offered['facts']))
620
+ print('\nAsk the user (AskUserQuestion), "How do you want to ship?":')
621
+
622
+ for number, (choice, text, description) in enumerate(offered['routes'],
623
+ 1):
624
+ print(' {}. {}{}: {}'.format(number, text, ' (Recommended)' if
625
+ number == 1 and choice != 'none' else '', description))
626
+
627
+ if offered['documents']:
628
+ print('\nOn "Open GitHub documents", a multiSelect checklist, "Which '
629
+ 'documents?":')
630
+
631
+ for document, text, description in offered['documents']:
632
+ print(' - {}: {}'.format(text, description))
633
+
634
+ if offered['branches']:
635
+ print('\nFor a branch or a PR, "Start the branch names with {}?":'
636
+ .format(autoopt.BRANCH_PREFIX))
637
+
638
+ for choice, names in offered['branches']:
639
+ print(' - {}: {}'.format(choice, names))
640
+
641
+ print('\nRecord the answers in the user\'s words:\n python3 {0} config '
642
+ '{1} --set after.ship=<{2}> --reason "<their words>"'.format(
643
+ os.path.join(HERE, 'autoopt.py'), work, '|'.join(choice for choice, _,
644
+ _ in offered['routes'])))
645
+
646
+ if offered['documents']:
647
+ print(' python3 {} config {} --set after.ship_documents={} --reason '
648
+ '"<their words>"'.format(os.path.join(HERE, 'autoopt.py'), work,
649
+ ','.join(document for document, _, _ in offered['documents'])))
650
+
651
+ if offered['branches']:
652
+ print(' python3 {} config {} --set after.branch_prefix=<no|yes> '
653
+ '--reason "<their words>"'.format(os.path.join(HERE, 'autoopt.py'),
654
+ work))
655
+
656
+ if after.get('ship') not in (None, 'ask'):
657
+ print('\nalready answered: after.ship = {}{}'.format(after['ship'],
658
+ '; documents: {}'.format(', '.join(after['ship_documents'])) if
659
+ after.get('ship_documents') else ''))
660
+
661
+ return 0
662
+
663
+
664
+ ###
665
+ # The GitHub documents: brief, status, render, rehearse, post
666
+ ###
667
+
668
+ ORDER = autoopt.SHIP_DOCUMENTS
669
+ NAMES = {'bugs': 'the bug report', 'tests': 'the unit-test PR',
670
+ 'optimization': 'the optimization PR'}
671
+ REFERENCES = {'bugs': 'references/issue-bugs.md', 'tests':
672
+ 'references/pr-tests.md', 'optimization': 'references/pr-optimization.md'}
673
+ # What a document's folder holds that is rendered or posted from its inputs,
674
+ # not an input: left out of the digest the review approves.
675
+ OUTPUTS = {'body.md', 'pr.json', 'filed.json', 'dupes.tsv'}
676
+ OUTPUT_DIRS = {'verify-logs', 'work'}
677
+
678
+
679
+ def folder(work, document):
680
+ return autoopt.work_path(work, 'ship', autoopt.SHIP_FOLDERS[document])
681
+
682
+
683
+ def github(work, config):
684
+ """`(after, documents, slug)` of a search whose user chose GitHub
685
+ documents; `fail`s otherwise."""
686
+
687
+ after = after_of(config)
688
+
689
+ if after.get('ship') != 'github':
690
+ fail('after.ship is {!r}: the GitHub documents are for a user who chose '
691
+ 'them (`ship.py plan` gives the question)'.format(after.get('ship')))
692
+
693
+ documents = [one for one in ORDER if one in (after.get('ship_documents')
694
+ or [])]
695
+
696
+ if not documents:
697
+ fail('after.ship_documents names no document: record the user\'s '
698
+ 'checklist (`ship.py plan`)')
699
+
700
+ found = choices(work, config)
701
+ slug = found['slug']
702
+
703
+ if not slug:
704
+ fail('the original\'s remote is not on GitHub')
705
+
706
+ extra = [one for one in documents if one not in found['documents']]
707
+
708
+ if extra:
709
+ fail('after.ship_documents names {}, which this search does not offer '
710
+ '(the unit-test PR needs a suite from step 1, the bug report the bugs '
711
+ 'it recorded): record the user\'s checklist again (`ship.py plan`)'
712
+ .format(', '.join(NAMES[one] for one in extra)))
713
+
714
+ return after, documents, slug
715
+
716
+
717
+ def allow_source(directory):
718
+ """The `--allow-source` flags the unit-test PR is rendered and pushed
719
+ with: one path per line of `allow-source.txt`, when the document writer
720
+ kept one."""
721
+
722
+ try:
723
+ with open(os.path.join(directory, 'allow-source.txt'),
724
+ encoding='utf-8') as handle:
725
+ paths = [line.strip() for line in handle if line.strip()]
726
+ except OSError:
727
+ return []
728
+
729
+ return [flag for path in paths for flag in ('--allow-source', path)]
730
+
731
+
732
+ def render_command(work, document):
733
+ directory = folder(work, document)
734
+ out = os.path.join(directory, 'body.md')
735
+
736
+ if document == 'bugs':
737
+ return [os.path.join(HERE, 'issue_body.py'), directory, '--out', out]
738
+
739
+ if document == 'tests':
740
+ return [os.path.join(HERE, 'tests_pr_body.py'), directory, '--out', out,
741
+ '--config', os.path.join(work, 'autooptimize', 'config.json')] + \
742
+ allow_source(directory)
743
+
744
+ return [os.path.join(HERE, 'opt_pr_body.py'), directory, '--out', out]
745
+
746
+
747
+ def post_command(work, document, slug, post, other_owner, names=None):
748
+ """The preview (or, with `post`, the post) of `document`; `names` are the
749
+ `--branch DOC=NAME` flags, a pushed branch's name in place of its
750
+ default."""
751
+
752
+ directory = folder(work, document)
753
+ flags = (['--post'] if post else []) + (['--other-owner'] if other_owner
754
+ else [])
755
+ named = (names or {}).get(document)
756
+
757
+ if document == 'bugs':
758
+ return [os.path.join(HERE, 'issue_body.py'), 'file', directory,
759
+ '--repo', slug] + flags
760
+
761
+ if document == 'tests':
762
+ return [os.path.join(HERE, 'tests_pr_push.py'), directory, '--repo',
763
+ slug] + allow_source(directory) + (['--remote-branch', named] if
764
+ named else []) + flags
765
+
766
+ return [os.path.join(HERE, 'autoopt.py'), 'pr', work] + (['--branch',
767
+ named] if named else []) + flags
768
+
769
+
770
+ def branch_names(values):
771
+ """`--branch DOC=NAME` flags as `{document: name}`: the name the
772
+ optimization PR's or the unit-test PR's branch is pushed under, when the
773
+ default is taken on the remote."""
774
+
775
+ names = {}
776
+
777
+ for value in values or []:
778
+ document, _, name = value.partition('=')
779
+
780
+ if document not in ('optimization', 'tests') or not name.strip():
781
+ fail('--branch takes optimization=NAME or tests=NAME; got {!r}'
782
+ .format(value))
783
+
784
+ names[document] = name.strip()
785
+
786
+ return names
787
+
788
+
789
+ def call(command):
790
+ """`(exit code, stdout + stderr)` of a script of this skill."""
791
+
792
+ done = subprocess.run([sys.executable] + command, capture_output=True,
793
+ text=True, stdin=subprocess.DEVNULL)
794
+
795
+ return done.returncode, (done.stdout + done.stderr).rstrip()
796
+
797
+
798
+ def render_document(work, document):
799
+ directory = folder(work, document)
800
+
801
+ if not os.path.exists(os.path.join(directory, 'body.title')):
802
+ return 1, ('{} has no body.title: the document writer renders it once '
803
+ 'with --title ({})'.format(directory, REFERENCES[document]))
804
+
805
+ return call(render_command(work, document))
806
+
807
+
808
+ # The answers that name the pushed branches and the fork, which the user
809
+ # reviews with the documents.
810
+ DIGEST_AFTER = ('branch_prefix', 'pr_remote', 'pr_head_owner')
811
+
812
+
813
+ def inputs_digest(work, documents, after, names=None):
814
+ """A digest of everything the chosen documents are rendered and pushed
815
+ from: every file in their folders except what is rendered or posted from
816
+ them, the unit-test branch's tip commit, the `after` answers of
817
+ DIGEST_AFTER, the `--branch` names, and the winner, so a promotion after
818
+ the rehearsal makes it stale."""
819
+
820
+ ended = autoopt.load_ended(os.path.join(work, 'autooptimize')) or {}
821
+ hasher = hashlib.sha256()
822
+ hasher.update(json.dumps([{key: after.get(key) for key in DIGEST_AFTER},
823
+ names or {}, (ended.get('winner') or {}).get('id')], sort_keys=True
824
+ ).encode() + b'\0')
825
+
826
+ for document in documents:
827
+ base = folder(work, document)
828
+
829
+ # The unit-test PR pushes its branch by name: its tip is an input,
830
+ # so a commit made after the rehearsal is never pushed unreviewed.
831
+ if document == 'tests':
832
+ try:
833
+ known = autoopt.read_json(os.path.join(base, 'branch.json'))
834
+ tip = autoopt.git('-C', known['suite'], 'rev-parse',
835
+ known['branch']).strip()
836
+ except (OSError, ValueError, KeyError, TypeError, RuntimeError):
837
+ tip = ''
838
+ hasher.update('tests tip {}'.format(tip).encode() + b'\0')
839
+
840
+ for top, dirs, files in os.walk(base):
841
+ dirs[:] = sorted(name for name in dirs if name not in OUTPUT_DIRS
842
+ and not name.startswith('before-renumber-'))
843
+
844
+ for name in sorted(files):
845
+ if name in OUTPUTS or name.endswith('.tmp') or name.startswith(
846
+ 'body.comment-'):
847
+ continue
848
+
849
+ path = os.path.join(top, name)
850
+ hasher.update(os.path.relpath(path, autoopt.work_path(work,
851
+ 'ship')).encode() + b'\0')
852
+
853
+ with open(path, 'rb') as handle:
854
+ hasher.update(handle.read())
855
+
856
+ hasher.update(b'\0')
857
+
858
+ return hasher.hexdigest()[:16]
859
+
860
+
861
+ def rehearsal_path(work):
862
+ return autoopt.work_path(work, 'ship', 'rehearsal.json')
863
+
864
+
865
+ def brief(args):
866
+ work, root, config = search(args.work)
867
+ autoopt.require_ended(root, 'ship')
868
+ after, documents, slug = github(work, config)
869
+ original = autoopt.original_of(work, config)
870
+ lines = ['You are the document writer for step 5 of the ended search in '
871
+ '{}: you write {}. Write their inputs and render them; post nothing, '
872
+ 'which the user approves after one review of all of them.'.format(work,
873
+ ', '.join(NAMES[one] for one in documents)), '',
874
+ 'AO={}'.format(HERE), 'WORK={}'.format(work), '',
875
+ 'Read {}/../references/documents.md first, then each document\'s '
876
+ 'reference before its work. They open on {} (branch {}).'.format(HERE,
877
+ slug, original.get('branch')), '',
878
+ 'Inputs already in a document\'s folder (its tables, prose.md, '
879
+ 'messages/, bugs.tsv) are kept and completed, never regenerated over: '
880
+ 'a document writer before you may have started them. Run '
881
+ '`opt_pr_body.py --template` only when prose.md does not exist yet, and '
882
+ '`opt_pr_tables.py` only when the folder has no branch.json or a '
883
+ 'refusal asks for it (it keeps the messages/ files it finds).']
884
+
885
+ if 'bugs' in documents:
886
+ lines += ['', '**The bug report** ({}): turn each folder of {} into a '
887
+ 'row of bugs.tsv and its prose fields in {}; check `issue_body.py '
888
+ 'dupes`; run `issue_body.py verify` on the original\'s build until '
889
+ 'every bug passes or is marked manual; render it with a title.'
890
+ .format(REFERENCES['bugs'], os.path.join(autoopt.work_path(work,
891
+ 'tests'), 'work', 'bugs'), folder(work, 'bugs'))]
892
+
893
+ if 'tests' in documents:
894
+ lines += ['', '**The unit-test PR** ({}): make its tables in {} from '
895
+ 'the suite in {} and step 1\'s coverage files in {}, write the '
896
+ 'prose, and render it with a title.'.format(REFERENCES['tests'],
897
+ folder(work, 'tests'), autoopt.work_path(work, 'tests-suite'),
898
+ os.path.join(autoopt.work_path(work, 'tests'), 'work'))]
899
+
900
+ if 'optimization' in documents:
901
+ lines += ['', '**The optimization PR** ({}): `python3 $AO/opt_pr_tables.py '
902
+ '$WORK`, then, when there is no prose.md yet, `opt_pr_body.py {} '
903
+ '--template` into prose.md; fill it from the kept changes\' diffs '
904
+ 'and READMEs, write each messages/<id>.txt the tables left as a '
905
+ 'skeleton, and render it with a title.'.format(REFERENCES[
906
+ 'optimization'], folder(work, 'optimization'))]
907
+
908
+ lines += ['', 'Rules: every number comes from a table, so prose writes a '
909
+ 'token where it needs one; no document names the tool, the lab, or the '
910
+ 'search\'s own words (winner, baseline, iteration labels, local '
911
+ 'paths), or says how it was written (no "Generated with" line); the '
912
+ 'diffs decide what a change does. Then run `python3 '
913
+ '$AO/ship.py rehearse $WORK` and fix every problem it lists until it '
914
+ 'exits 0. Report each title, the rehearsal\'s digest, and anything you '
915
+ 'could not settle.']
916
+
917
+ print('\n'.join(lines))
918
+ return 0
919
+
920
+
921
+ def status(args):
922
+ work, root, config = search(args.work)
923
+ after = after_of(config)
924
+ print('after.ship: {}'.format(after.get('ship')))
925
+
926
+ if after.get('ship') != 'github':
927
+ return 0
928
+
929
+ documents = [one for one in ORDER if one in (after.get('ship_documents')
930
+ or [])]
931
+ record = None
932
+
933
+ try:
934
+ record = autoopt.read_json(rehearsal_path(work))
935
+ except OSError:
936
+ pass
937
+
938
+ for document in documents:
939
+ directory = folder(work, document)
940
+ posted = autoopt.ship_posted(work, document)
941
+ title = publish.stored_title(os.path.join(directory, 'body.md'))
942
+
943
+ if posted:
944
+ state = 'posted: {}'.format(posted['url'])
945
+ elif not os.path.isdir(directory):
946
+ state = 'not started'
947
+ elif not title:
948
+ state = 'inputs only; not rendered with a title yet'
949
+ else:
950
+ state = 'rendered: "{}"'.format(title)
951
+
952
+ print('{:20} {}'.format(NAMES[document], state))
953
+
954
+ if record:
955
+ current = inputs_digest(work, documents, after, record.get('branches'))
956
+ print('rehearsal: digest {}{}{}'.format(record['digest'], '' if
957
+ record.get('ok') else ', with problems', '' if current == record[
958
+ 'digest'] else '; the inputs changed since (rehearse again)'))
959
+ else:
960
+ print('rehearsal: none yet (`ship.py rehearse`)')
961
+
962
+ return 0
963
+
964
+
965
+ def render(args):
966
+ work, root, config = search(args.work)
967
+ after, documents, slug = github(work, config)
968
+
969
+ for document in documents:
970
+ if args.only and document != args.only:
971
+ continue
972
+
973
+ code, out = render_document(work, document)
974
+ print('{}: {}'.format(NAMES[document], 'rendered' if code == 0 else
975
+ 'refused'))
976
+
977
+ if code:
978
+ print(out)
979
+ return 1
980
+
981
+ return 0
982
+
983
+
984
+ def rehearse(args):
985
+ """Render every chosen document, run each one's preview (nothing is
986
+ posted), and record a digest of their inputs for `post`."""
987
+
988
+ work, root, config = search(args.work)
989
+ autoopt.require_ended(root, 'ship')
990
+ after, documents, slug = github(work, config)
991
+ prefix_problem(config)
992
+ names = branch_names(args.branch)
993
+ scratch = autoopt.work_path(work, 'ship', 'rehearsal')
994
+ os.makedirs(scratch, exist_ok=True)
995
+ problems, lines = [], []
996
+
997
+ for document in documents:
998
+ directory = folder(work, document)
999
+ code, out = render_document(work, document)
1000
+
1001
+ if code == 0:
1002
+ code, out = call(post_command(work, document, slug, False, False,
1003
+ names))
1004
+
1005
+ publish.write(os.path.join(scratch, '{}.txt'.format(document)), out +
1006
+ '\n')
1007
+ title = publish.stored_title(os.path.join(directory, 'body.md'))
1008
+ lines.append('{}: {}'.format(NAMES[document], '"{}"'.format(title) if
1009
+ title else 'no title'))
1010
+ lines.append(' body {}'.format(os.path.join(directory, 'body.md')))
1011
+ lines.append(' preview {}'.format(os.path.join(scratch,
1012
+ '{}.txt'.format(document))))
1013
+
1014
+ if code:
1015
+ problems.append('{}: {}'.format(NAMES[document], out.splitlines()[-1]
1016
+ if out else 'exit {}'.format(code)))
1017
+ lines.append(' REFUSED; the preview file has every problem')
1018
+ elif autoopt.ship_posted(work, document):
1019
+ lines.append(' posted already')
1020
+
1021
+ digest = inputs_digest(work, documents, after, names)
1022
+ publish.write_json(rehearsal_path(work), {'digest': digest, 'documents':
1023
+ documents, 'branches': names, 'ok': not problems, 'problems': problems,
1024
+ 'at': autoopt.now()})
1025
+ autoopt.refresh_notes(root)
1026
+ print('\n'.join(lines))
1027
+
1028
+ if problems:
1029
+ print('\nrefused, nothing can be posted until these are fixed:\n ' +
1030
+ '\n '.join(problems))
1031
+ return 1
1032
+
1033
+ print('\nShow the user every document above together. Once they ask for '
1034
+ 'posting, `python3 {} post {} all --approved --digest {}{}` posts them '
1035
+ 'in this order, filling each number into the next.'.format(
1036
+ os.path.join(HERE, 'ship.py'), work, digest, ''.join(
1037
+ ' --branch {}={}'.format(document, name) for document, name in
1038
+ sorted(names.items()))))
1039
+ return 0
1040
+
1041
+
1042
+ def post(args):
1043
+ work, root, config = search(args.work)
1044
+ autoopt.require_ended(root, 'ship')
1045
+ after, documents, slug = github(work, config)
1046
+ names = branch_names(args.branch)
1047
+
1048
+ if not args.approved or not args.digest:
1049
+ fail('posting needs --approved and the --digest of the rehearsal the '
1050
+ 'user reviewed (`ship.py rehearse`)')
1051
+
1052
+ try:
1053
+ record = autoopt.read_json(rehearsal_path(work))
1054
+ except OSError:
1055
+ fail('no rehearsal: run `ship.py rehearse` and show the user every '
1056
+ 'document first')
1057
+
1058
+ if record.get('digest') != args.digest:
1059
+ fail('--digest {} is not the last rehearsal\'s ({}): show the user the '
1060
+ 'documents of the last one'.format(args.digest, record.get(
1061
+ 'digest')))
1062
+
1063
+ if not record.get('ok'):
1064
+ fail('the last rehearsal had problems; fix them and rehearse again')
1065
+
1066
+ if (record.get('branches') or {}) != names:
1067
+ fail('--branch {} is not what the rehearsal the user reviewed pushed '
1068
+ '({}): give the same --branch flags, or rehearse again with these'
1069
+ .format(' '.join('{}={}'.format(*item) for item in sorted(
1070
+ names.items())) or '(none)', ' '.join('{}={}'.format(*item) for item
1071
+ in sorted((record.get('branches') or {}).items())) or 'none'))
1072
+
1073
+ if inputs_digest(work, documents, after, names) != args.digest:
1074
+ fail('the documents\' inputs changed since the rehearsal the user '
1075
+ 'reviewed (their files, or after.branch_prefix, after.pr_remote or '
1076
+ 'after.pr_head_owner): rehearse again and show them the new batch')
1077
+
1078
+ if record.get('documents') != documents:
1079
+ fail('the chosen documents changed since the rehearsal: rehearse again')
1080
+
1081
+ for document in documents:
1082
+ if autoopt.ship_posted(work, document):
1083
+ print('{}: posted already, {}'.format(NAMES[document],
1084
+ autoopt.ship_posted(work, document)['url']))
1085
+ continue
1086
+
1087
+ # Rendered again first, so the numbers of the documents posted
1088
+ # before it are filled in.
1089
+ code, out = render_document(work, document)
1090
+
1091
+ if code == 0:
1092
+ code, out = call(post_command(work, document, slug, True,
1093
+ args.other_owner, names))
1094
+
1095
+ print('{}:\n{}'.format(NAMES[document], out))
1096
+
1097
+ if code:
1098
+ autoopt.refresh_notes(root)
1099
+ fail('{} was not posted; fix the cause and run the same command '
1100
+ 'again: what was posted is skipped'.format(NAMES[document]))
1101
+
1102
+ autoopt.hold_reopen(root, 'step 5', 'GitHub documents posted')
1103
+
1104
+ autoopt.refresh_notes(root)
1105
+
1106
+ return 0
1107
+
1108
+
1109
+ def main(argv=None):
1110
+ parser = argparse.ArgumentParser(description=__doc__,
1111
+ formatter_class=argparse.RawDescriptionHelpFormatter)
1112
+ commands = parser.add_subparsers(dest='command', required=True)
1113
+
1114
+ branch_help = ('DOC=NAME: push the optimization PR\'s (optimization=NAME) '
1115
+ 'or the unit-test PR\'s (tests=NAME) branch under NAME instead of its '
1116
+ 'default, when that is taken on the remote; repeatable, and the same '
1117
+ 'for rehearse and post')
1118
+ id_help = 'the iteration to ship (default best: ended.json\'s winner)'
1119
+
1120
+ for name, function, text in (('brief', brief, 'the document writer\'s '
1121
+ 'prompt for the chosen GitHub documents'), ('status', status, 'where '
1122
+ 'each chosen document stands')):
1123
+ sub = commands.add_parser(name, help=text)
1124
+ sub.add_argument('work')
1125
+ sub.set_defaults(func=function)
1126
+
1127
+ sub = commands.add_parser('rehearse', help='render every chosen document '
1128
+ 'and preview it; posts nothing')
1129
+ sub.add_argument('work')
1130
+ sub.add_argument('--branch', action='append', default=[],
1131
+ metavar='DOC=NAME', help=branch_help)
1132
+ sub.set_defaults(func=rehearse)
1133
+
1134
+ sub = commands.add_parser('render', help='render every chosen document '
1135
+ 'again, in posting order')
1136
+ sub.add_argument('work')
1137
+ sub.add_argument('--only', choices=ORDER, help='render this document '
1138
+ 'alone')
1139
+ sub.set_defaults(func=render)
1140
+
1141
+ sub = commands.add_parser('post', help='post every chosen document, once '
1142
+ 'the user approved the rehearsal')
1143
+ sub.add_argument('work')
1144
+ sub.add_argument('which', choices=('all',), help='every chosen document; '
1145
+ 'none is posted on its own')
1146
+ sub.add_argument('--approved', action='store_true', help='the user asked '
1147
+ 'for posting after seeing every document of the rehearsal')
1148
+ sub.add_argument('--digest', help='the digest the rehearsal the user '
1149
+ 'reviewed printed')
1150
+ sub.add_argument('--branch', action='append', default=[],
1151
+ metavar='DOC=NAME', help=branch_help)
1152
+ sub.add_argument('--other-owner', action='store_true', help='confirm a '
1153
+ 'repository another account owns, once the user has seen it')
1154
+ sub.set_defaults(func=post)
1155
+
1156
+ sub = commands.add_parser('plan', help='what this search can ship, and '
1157
+ 'the question to ask the user')
1158
+ sub.add_argument('work')
1159
+ sub.add_argument('--json', action='store_true', help='print the facts, '
1160
+ 'routes, documents and branch names as JSON')
1161
+ sub.set_defaults(func=plan)
1162
+
1163
+ sub = commands.add_parser('apply', help='a plain search: write the '
1164
+ 'change into the original files (preview without --yes)')
1165
+ sub.add_argument('work')
1166
+ sub.add_argument('--id', default='best', help=id_help)
1167
+ sub.add_argument('--to', help='the folder the change applies under, for a '
1168
+ 'search that does not record where its files came from')
1169
+ sub.add_argument('--yes', action='store_true', help='write the files (or '
1170
+ 'record them as applied, when they hold the change already)')
1171
+ sub.add_argument('--by-hand', action='store_true', help='a file that holds '
1172
+ 'neither the copy nor the winner is one the user merged the change '
1173
+ 'into by hand, on their word: left as it is and recorded as applied')
1174
+ sub.set_defaults(func=apply)
1175
+
1176
+ sub = commands.add_parser('branch', help='a repository search: a branch '
1177
+ 'in the original with one commit per kept change (preview without '
1178
+ '--yes)')
1179
+ sub.add_argument('work')
1180
+ sub.add_argument('--id', default='best', help=id_help)
1181
+ sub.add_argument('--name', help='the branch (default optimized-<date>)')
1182
+ sub.add_argument('--repo', help='the original repository, when the '
1183
+ 'search does not record it')
1184
+ sub.add_argument('--yes', action='store_true', help='make the branch')
1185
+ sub.set_defaults(func=branch)
1186
+
1187
+ args = parser.parse_args(argv)
1188
+
1189
+ return args.func(args)
1190
+
1191
+
1192
+ if __name__ == '__main__':
1193
+ sys.exit(main())