reqtable 0.1.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.
reqtable/gui.py ADDED
@@ -0,0 +1,952 @@
1
+ """Registry of the GUI's workflows and the pure functions that turn form values into commands.
2
+
3
+ The registry is the single source of truth: the server, the page and the tests all read WORKFLOWS.
4
+ Nothing here touches the disk or the network.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import shlex
11
+ import sys
12
+ from dataclasses import dataclass, replace
13
+ from pathlib import Path
14
+ from typing import Literal, Mapping, Sequence
15
+
16
+ from .signoff import DECISIONS
17
+
18
+ FieldKind = Literal[
19
+ "open",
20
+ "save",
21
+ "choice",
22
+ "radio",
23
+ "text",
24
+ "number",
25
+ "flag",
26
+ "column",
27
+ "table",
28
+ "sheet",
29
+ "gate",
30
+ "baseline",
31
+ "baselines",
32
+ "role",
33
+ "system",
34
+ "waivers",
35
+ ]
36
+ Panel = Literal["form", "mapping"]
37
+ Shell = Literal["sh", "powershell"]
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Field:
42
+ name: str
43
+ label: str
44
+ kind: FieldKind
45
+ flag: str | None
46
+ help: str
47
+ required: bool = False
48
+ choices: tuple[tuple[str, str], ...] = ()
49
+ default: str = ""
50
+ extensions: tuple[str, ...] = ()
51
+ advanced: bool = False
52
+ xlsx_only: bool = False
53
+ requires: str = ""
54
+ pair_flag: str | None = None
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Workflow:
59
+ """One task card. `fixed` argv is always emitted. `outcomes` give exit codes a plain label, and a code other than 0
60
+ answers the question rather than failing. `table` names the tab-separated columns of stdout, and `recorded` says what
61
+ permanent record a successful run leaves behind; such a run is never added to a workflow by itself, because running
62
+ the script again would record it again."""
63
+
64
+ id: str
65
+ title: str
66
+ summary: str
67
+ when: str
68
+ fields: tuple[Field, ...]
69
+ group: str = ""
70
+ fixed: tuple[str, ...] = ()
71
+ panel: Panel = "form"
72
+ outcomes: tuple[tuple[int, str], ...] = ()
73
+ table: tuple[str, ...] = ()
74
+ recorded: str = ""
75
+
76
+ @property
77
+ def records(self) -> bool:
78
+ return bool(self.recorded)
79
+
80
+
81
+ class GuiError(Exception):
82
+ """The form is not ready to become a command; the message is for the user."""
83
+
84
+
85
+ class BadRequest(GuiError):
86
+ """The caller sent a workflow, field or value this registry does not have."""
87
+
88
+
89
+ TABLE_EXTENSIONS = (".csv", ".xlsx")
90
+ ANY_FILE = ("*",)
91
+ ON_OFF = (("", "Automatic"), ("on", "Yes"), ("off", "No"))
92
+ YES = (("", "No"), ("on", "Yes"))
93
+ MAKE, COMPARE, EXCEL, GATES = (
94
+ "Make reports",
95
+ "Compare and review",
96
+ "Excel workbooks",
97
+ "Gates and sign-off",
98
+ )
99
+ GROUPS = (MAKE, COMPARE, EXCEL, GATES)
100
+
101
+
102
+ def _toggle(
103
+ name: str, label: str, flag: str, help: str, *, both: bool = False
104
+ ) -> Field:
105
+ return Field(
106
+ name, label, "flag", flag, help, choices=ON_OFF if both else YES, advanced=True
107
+ )
108
+
109
+
110
+ CONFIG = Field(
111
+ "config",
112
+ "Settings file",
113
+ "open",
114
+ "--config",
115
+ "A JSON file of saved reqtable settings. Leave empty to use the defaults.",
116
+ extensions=(".json",),
117
+ advanced=True,
118
+ )
119
+ GATE_CONFIG = replace(
120
+ CONFIG,
121
+ advanced=False,
122
+ help="A JSON file of saved reqtable settings. It can list your own review gates and choose where baselines are stored. Leave empty to use the defaults.",
123
+ )
124
+ ENCODING = Field(
125
+ "encoding",
126
+ "Text encoding",
127
+ "text",
128
+ "--encoding",
129
+ "Only change this if accented letters look wrong. The default handles most files, including ones saved by Excel.",
130
+ advanced=True,
131
+ )
132
+ DELIMITER = Field(
133
+ "delimiter",
134
+ "Column separator",
135
+ "text",
136
+ "--delimiter",
137
+ "The character between columns in a CSV file. The default is a comma.",
138
+ advanced=True,
139
+ )
140
+ ID_COLUMN = Field(
141
+ "id_column",
142
+ "ID column",
143
+ "column",
144
+ "--id-column",
145
+ "The column that holds each requirement's unique ID. Required unless your settings file names one.",
146
+ )
147
+ TITLE = Field(
148
+ "title",
149
+ "Report title",
150
+ "text",
151
+ "--title",
152
+ "Shown at the top of the report. Leave empty for the default.",
153
+ advanced=True,
154
+ )
155
+ TRACEABILITY = _toggle(
156
+ "traceability",
157
+ "Systems and traceability document",
158
+ "--traceability",
159
+ "Treat the file as a systems and traceability document. Automatic lets reqtable decide.",
160
+ both=True,
161
+ )
162
+ TABLE = Field(
163
+ "table",
164
+ "Excel table",
165
+ "table",
166
+ "--table",
167
+ "Which table in the workbook to read. A workbook with exactly one table needs no choice.",
168
+ xlsx_only=True,
169
+ )
170
+ SHEET = Field(
171
+ "sheet",
172
+ "Excel sheet",
173
+ "sheet",
174
+ "--sheet",
175
+ "Read a whole sheet instead of a table. Use this when the workbook has no tables.",
176
+ xlsx_only=True,
177
+ )
178
+ HEADER_ROW = Field(
179
+ "header_row",
180
+ "Header row number",
181
+ "number",
182
+ "--header-row",
183
+ "The row of the sheet that holds the column names. The default is the first non-empty row.",
184
+ xlsx_only=True,
185
+ requires="sheet",
186
+ )
187
+ WHICH_BLOCK = (TABLE, SHEET, HEADER_ROW, ID_COLUMN)
188
+ DOCUMENT_MODE = Field(
189
+ "document_mode",
190
+ "What is the report for?",
191
+ "radio",
192
+ "--document-mode",
193
+ "Review reports are for collecting comments. Develop reports let you edit the requirements themselves.",
194
+ choices=(
195
+ ("review", "Review: read it and leave comments"),
196
+ ("develop", "Develop: edit the requirements"),
197
+ ),
198
+ default="review",
199
+ )
200
+ BASELINES = Field(
201
+ "baselines",
202
+ "Compare against baselines",
203
+ "baselines",
204
+ "--baselines",
205
+ "Embed frozen gate baselines so the report can show what changed since each one. Needs baselines to exist already.",
206
+ advanced=True,
207
+ )
208
+
209
+
210
+ def _source(name: str, label: str, flag: str | None, help: str) -> Field:
211
+ return Field(
212
+ name, label, "open", flag, help, required=True, extensions=TABLE_EXTENSIONS
213
+ )
214
+
215
+
216
+ def _html_output(name: str, help: str) -> Field:
217
+ return Field(
218
+ "output",
219
+ "Save the report as",
220
+ "save",
221
+ "-o",
222
+ help,
223
+ required=True,
224
+ extensions=(".html",),
225
+ default=name,
226
+ )
227
+
228
+
229
+ def _report_fields(*, mode: bool) -> tuple[Field, ...]:
230
+ return (
231
+ _source("input", "Spreadsheet to read", None, "A CSV or Excel (.xlsx) file."),
232
+ *WHICH_BLOCK,
233
+ _html_output(
234
+ "requirements-report.html",
235
+ "Where the finished report goes. It is one self-contained file you can email.",
236
+ ),
237
+ *((DOCUMENT_MODE,) if mode else ()),
238
+ TITLE,
239
+ TRACEABILITY,
240
+ Field(
241
+ "reviewer_initials",
242
+ "Reviewer initials",
243
+ "text",
244
+ "--reviewer-initials",
245
+ "Initials stamped on comments made in the report.",
246
+ advanced=True,
247
+ ),
248
+ BASELINES,
249
+ CONFIG,
250
+ ENCODING,
251
+ DELIMITER,
252
+ )
253
+
254
+
255
+ def _table_input(help: str) -> Field:
256
+ return _source("input", "Requirements file", None, help)
257
+
258
+
259
+ def _gate(flag: str, help: str) -> Field:
260
+ return Field("gate", "Review gate", "gate", flag, help, required=True)
261
+
262
+
263
+ def _baseline(flag: str, help: str) -> Field:
264
+ return Field("baseline", "Baseline", "baseline", flag, help, required=True)
265
+
266
+
267
+ SYSTEM = Field(
268
+ "system",
269
+ "System",
270
+ "system",
271
+ "--system",
272
+ "Which system the gate covers. Only gates that cover one system and its subsystems ask for this.",
273
+ )
274
+ USER = Field(
275
+ "user",
276
+ "Who is doing this",
277
+ "text",
278
+ "--user",
279
+ "Recorded with the entry. Leave empty to use your git user name or your login name.",
280
+ )
281
+ GATE_TAIL = (TRACEABILITY, ENCODING, DELIMITER)
282
+
283
+ WORKFLOWS: tuple[Workflow, ...] = (
284
+ Workflow(
285
+ "report",
286
+ "Make a report from a spreadsheet",
287
+ "Turn a CSV or Excel file into a report you can open in any browser.",
288
+ "Use this when you have a requirements spreadsheet and want to read, filter, review or edit it as a report. If your Excel table has heading rows that name categories, use “Import several tables from one workbook” instead. One table is fine there.",
289
+ _report_fields(mode=True),
290
+ group=MAKE,
291
+ ),
292
+ Workflow(
293
+ "develop",
294
+ "Edit requirements (Develop report)",
295
+ "Turn a CSV or Excel file into a Develop report, where you add, edit and delete requirements right in the browser.",
296
+ "Use this when you want to change the requirements themselves, not only comment on them. Save the edited table back as a CSV from the report.",
297
+ _report_fields(mode=False),
298
+ group=MAKE,
299
+ fixed=("--document-mode", "develop"),
300
+ ),
301
+ Workflow(
302
+ "diff",
303
+ "Compare two versions",
304
+ "Show what was added, removed or changed between an older and a newer file.",
305
+ "Use this when a requirements file was revised and reviewers need to see exactly what changed.",
306
+ (
307
+ _source("old", "Older version", "--old", "The file to compare against."),
308
+ _source(
309
+ "new", "Newer version", "--new", "The file with the latest changes."
310
+ ),
311
+ *WHICH_BLOCK,
312
+ _html_output("requirements-diff.html", "Where the comparison report goes."),
313
+ DOCUMENT_MODE,
314
+ Field(
315
+ "initial_diff_view",
316
+ "How to show changes",
317
+ "choice",
318
+ "--initial-diff-view",
319
+ "Unified shows changes in one column. Side by side shows old and new next to each other.",
320
+ choices=(("unified", "Unified"), ("side-by-side", "Side by side")),
321
+ advanced=True,
322
+ ),
323
+ _toggle(
324
+ "changes_only",
325
+ "Start with changed rows only",
326
+ "--changes-only",
327
+ "Hide rows that did not change when the report opens.",
328
+ ),
329
+ _toggle(
330
+ "include_unchanged",
331
+ "Include unchanged rows",
332
+ "--include-unchanged",
333
+ "Keep rows that did not change in the report. Automatic uses your settings.",
334
+ both=True,
335
+ ),
336
+ TITLE,
337
+ TRACEABILITY,
338
+ BASELINES,
339
+ CONFIG,
340
+ ENCODING,
341
+ DELIMITER,
342
+ ),
343
+ group=COMPARE,
344
+ ),
345
+ Workflow(
346
+ "comments",
347
+ "Collect review comments from a reviewed report",
348
+ "Pull the comments reviewers made in a report back out into a CSV file.",
349
+ "Use this when reviewers have sent back their copy of a report and you want their comments in a spreadsheet.",
350
+ (
351
+ Field(
352
+ "report",
353
+ "Reviewed report",
354
+ "open",
355
+ "--extract-comments",
356
+ "The report file a reviewer saved, with their comments in it.",
357
+ required=True,
358
+ extensions=(".html",),
359
+ ),
360
+ Field(
361
+ "output",
362
+ "Save the comments as",
363
+ "save",
364
+ "-o",
365
+ "Where the CSV file of comments goes.",
366
+ required=True,
367
+ extensions=(".csv",),
368
+ default="review-comments.csv",
369
+ ),
370
+ Field(
371
+ "csv_base",
372
+ "Which rows to include",
373
+ "choice",
374
+ "--csv-base",
375
+ "For a comparison report. New keeps rows in the newer version, old the older one, union both.",
376
+ choices=(
377
+ ("new", "Rows in the newer version"),
378
+ ("old", "Rows in the older version"),
379
+ ("union", "Rows from both versions"),
380
+ ),
381
+ default="new",
382
+ advanced=True,
383
+ ),
384
+ Field(
385
+ "comments_format",
386
+ "Comment format in the CSV",
387
+ "choice",
388
+ "--comments-format",
389
+ "Text is easiest to read in a spreadsheet. JSON keeps every detail of each comment.",
390
+ choices=(("text", "Plain text"), ("json", "JSON")),
391
+ advanced=True,
392
+ ),
393
+ Field(
394
+ "comments_column",
395
+ "Comments column name",
396
+ "text",
397
+ "--comments-column",
398
+ "The CSV column that receives the comments.",
399
+ advanced=True,
400
+ ),
401
+ _toggle(
402
+ "allow_comment_loss",
403
+ "Allow losing some comments",
404
+ "--allow-comment-loss",
405
+ "Carry on even if some comments cannot be placed on a row. Without this, reqtable stops and tells you.",
406
+ ),
407
+ CONFIG,
408
+ DELIMITER,
409
+ ),
410
+ group=COMPARE,
411
+ ),
412
+ Workflow(
413
+ "list_tables",
414
+ "See what's inside an Excel workbook",
415
+ "List the sheets and tables in a workbook, with their column names.",
416
+ "Use this first when you are not sure which table or sheet to use.",
417
+ (
418
+ Field(
419
+ "workbook",
420
+ "Excel workbook",
421
+ "open",
422
+ "--list-tables",
423
+ "The .xlsx file to look inside.",
424
+ required=True,
425
+ extensions=(".xlsx",),
426
+ ),
427
+ ),
428
+ group=EXCEL,
429
+ ),
430
+ Workflow(
431
+ "to_csv",
432
+ "Convert an Excel table to CSV",
433
+ "Save one table or sheet of a workbook as a CSV file.",
434
+ "Use this when you need a plain CSV, for example to keep in version control or compare with an older version.",
435
+ (
436
+ Field(
437
+ "input",
438
+ "Excel workbook",
439
+ "open",
440
+ None,
441
+ "The .xlsx file to read.",
442
+ required=True,
443
+ extensions=(".xlsx",),
444
+ ),
445
+ *WHICH_BLOCK,
446
+ Field(
447
+ "output",
448
+ "Save the CSV as",
449
+ "save",
450
+ "-o",
451
+ "Where the CSV file goes. The name must end in .csv.",
452
+ required=True,
453
+ extensions=(".csv",),
454
+ default="workbook-table.csv",
455
+ ),
456
+ CONFIG,
457
+ DELIMITER,
458
+ ),
459
+ group=EXCEL,
460
+ ),
461
+ Workflow(
462
+ "mapping",
463
+ "Import several tables from one workbook (requirements, glossary, tests…)",
464
+ "Choose which tables of a workbook are requirements, glossary terms, allowed values, tests or test plans, and save the mapping.",
465
+ "Use this when one workbook holds your requirements and also your glossary, lookup lists or tests on other sheets. It also handles a single requirements table whose heading rows name the category of the rows below them.",
466
+ (
467
+ Field(
468
+ "input",
469
+ "Excel workbook",
470
+ "open",
471
+ None,
472
+ "The .xlsx file that holds the tables.",
473
+ required=True,
474
+ extensions=(".xlsx",),
475
+ ),
476
+ ),
477
+ group=EXCEL,
478
+ panel="mapping",
479
+ ),
480
+ Workflow(
481
+ "check_gate",
482
+ "Check whether a gate is ready",
483
+ "Run a review gate's readiness checks on your requirements and see which pass.",
484
+ "Use this before a review such as SRR or PDR, to see what still needs fixing. It changes nothing.",
485
+ (
486
+ _table_input("The CSV or Excel (.xlsx) file to check."),
487
+ *WHICH_BLOCK,
488
+ GATE_CONFIG,
489
+ _gate("--check-gate", "The review gate to check, such as SRR or PDR."),
490
+ SYSTEM,
491
+ *GATE_TAIL,
492
+ ),
493
+ group=GATES,
494
+ outcomes=((0, "This gate is ready"), (1, "Not ready yet")),
495
+ ),
496
+ Workflow(
497
+ "create_baseline",
498
+ "Freeze a baseline at a gate",
499
+ "Freeze the requirements as approved at a review gate, so later reports can compare against them.",
500
+ "Use this when a gate review is held and you want a permanent record of exactly what was reviewed.",
501
+ (
502
+ _table_input("The CSV or Excel (.xlsx) file to freeze."),
503
+ *WHICH_BLOCK,
504
+ GATE_CONFIG,
505
+ _gate("--create-baseline", "The review gate you are holding."),
506
+ SYSTEM,
507
+ Field(
508
+ "waivers",
509
+ "Waive a failing check",
510
+ "waivers",
511
+ "--waive",
512
+ "A strict gate refuses to freeze while a required check fails. Waive a check with a reason, and the waiver is recorded in the baseline.",
513
+ pair_flag="--reason",
514
+ ),
515
+ replace(USER, advanced=True),
516
+ *GATE_TAIL,
517
+ ),
518
+ group=GATES,
519
+ outcomes=((1, "Blocked by a required check"),),
520
+ recorded="A permanent baseline was recorded where the result below says. Freezing this gate again makes a new numbered baseline and never changes this one.",
521
+ ),
522
+ Workflow(
523
+ "list_baselines",
524
+ "List baselines",
525
+ "See every baseline that was frozen for this requirements file.",
526
+ "Use this to find a baseline's name before you sign it off or verify it.",
527
+ (
528
+ _table_input("The CSV or Excel (.xlsx) file whose baselines to list."),
529
+ *WHICH_BLOCK,
530
+ GATE_CONFIG,
531
+ *GATE_TAIL,
532
+ ),
533
+ group=GATES,
534
+ fixed=("--list-baselines",),
535
+ table=("Baseline", "Gate", "System", "Frozen", "By", "Hash"),
536
+ ),
537
+ Workflow(
538
+ "sign_off",
539
+ "Record a sign-off",
540
+ "Record a reviewer's decision on a frozen baseline.",
541
+ "Use this when a reviewer or approver has decided on a baseline and you want it on the record.",
542
+ (
543
+ _table_input("The CSV or Excel (.xlsx) file the baseline was frozen from."),
544
+ *WHICH_BLOCK,
545
+ GATE_CONFIG,
546
+ _baseline("--sign-off", "The baseline the decision is about."),
547
+ Field(
548
+ "role",
549
+ "Role",
550
+ "role",
551
+ "--role",
552
+ "The sign-off role the decision is made in. The roles come from the baseline's gate.",
553
+ required=True,
554
+ ),
555
+ Field(
556
+ "decision",
557
+ "Decision",
558
+ "choice",
559
+ "--decision",
560
+ "What was decided.",
561
+ required=True,
562
+ choices=tuple((d, d) for d in DECISIONS),
563
+ ),
564
+ USER,
565
+ Field(
566
+ "note",
567
+ "Note",
568
+ "text",
569
+ "--note",
570
+ "Anything worth keeping with the decision, such as the board meeting.",
571
+ advanced=True,
572
+ ),
573
+ Field(
574
+ "evidence",
575
+ "Evidence file",
576
+ "open",
577
+ "--evidence",
578
+ "A file that backs the decision, such as a signed PDF.",
579
+ extensions=ANY_FILE,
580
+ advanced=True,
581
+ ),
582
+ *GATE_TAIL,
583
+ ),
584
+ group=GATES,
585
+ recorded="Your decision was recorded where the result below says. Use Verify a baseline to see where the sign-offs stand.",
586
+ ),
587
+ Workflow(
588
+ "verify_baseline",
589
+ "Verify a baseline",
590
+ "Recheck that a baseline's content is unchanged and see whether it has the sign-offs it needs.",
591
+ "Use this to find out whether a gate is approved, or to prove a frozen baseline was not altered.",
592
+ (
593
+ _table_input("The CSV or Excel (.xlsx) file the baseline was frozen from."),
594
+ *WHICH_BLOCK,
595
+ GATE_CONFIG,
596
+ _baseline("--verify-baseline", "The baseline to check."),
597
+ *GATE_TAIL,
598
+ ),
599
+ group=GATES,
600
+ outcomes=(
601
+ (0, "Approved and unchanged"),
602
+ (1, "Not approved yet, or the content changed"),
603
+ ),
604
+ ),
605
+ Workflow(
606
+ "gate_package",
607
+ "Make a gate review package",
608
+ "Write the report reviewers receive for a baseline, with a cover for recording their decisions.",
609
+ "Use this when you want reviewers to read a frozen baseline and record their decisions in one file.",
610
+ (
611
+ _table_input("The CSV or Excel (.xlsx) file the baseline was frozen from."),
612
+ *WHICH_BLOCK,
613
+ GATE_CONFIG,
614
+ _baseline("--gate-package", "The baseline reviewers will look at."),
615
+ Field(
616
+ "output",
617
+ "Save the package as",
618
+ "save",
619
+ "-o",
620
+ "Where the package goes. It is one self-contained file you can email.",
621
+ required=True,
622
+ extensions=(".html",),
623
+ default="gate-package.html",
624
+ ),
625
+ *GATE_TAIL,
626
+ ),
627
+ group=GATES,
628
+ ),
629
+ Workflow(
630
+ "import_decisions",
631
+ "Import decisions from a returned package",
632
+ "Record the decisions reviewers saved in their copy of a gate package as sign-offs.",
633
+ "Use this when reviewers have sent back their saved copies of a gate package.",
634
+ (
635
+ _table_input("The CSV or Excel (.xlsx) file the package was made from."),
636
+ *WHICH_BLOCK,
637
+ GATE_CONFIG,
638
+ Field(
639
+ "package",
640
+ "Returned package",
641
+ "open",
642
+ "--import-decisions",
643
+ "The package file a reviewer saved, with their decision in it.",
644
+ required=True,
645
+ extensions=(".html",),
646
+ ),
647
+ *GATE_TAIL,
648
+ ),
649
+ group=GATES,
650
+ recorded="Each decision in the package was recorded as a sign-off, as the result below says.",
651
+ ),
652
+ )
653
+
654
+ WORKFLOWS_BY_ID = {workflow.id: workflow for workflow in WORKFLOWS}
655
+
656
+
657
+ def workflow_named(workflow_id: str) -> Workflow:
658
+ try:
659
+ return WORKFLOWS_BY_ID[workflow_id]
660
+ except KeyError:
661
+ raise BadRequest(f"unknown workflow {workflow_id!r}") from None
662
+
663
+
664
+ def column_source(workflow: Workflow) -> Field | None:
665
+ """The field whose file supplies the ID-column choices."""
666
+ return next(
667
+ (f for f in workflow.fields if f.kind == "open" and ".csv" in f.extensions),
668
+ None,
669
+ ) or next(
670
+ (f for f in workflow.fields if f.kind == "open" and ".xlsx" in f.extensions),
671
+ None,
672
+ )
673
+
674
+
675
+ def table_inputs(workflow: Workflow) -> list[Field]:
676
+ """The open fields that take a table. Only these decide whether the Excel fields apply; an evidence file does not."""
677
+ return [f for f in workflow.fields if f.kind == "open" and ".xlsx" in f.extensions]
678
+
679
+
680
+ def is_workbook_path(path: str) -> bool:
681
+ return path.lower().endswith(".xlsx")
682
+
683
+
684
+ def _shown_path(value: str, workdir: Path | None) -> str:
685
+ path = Path(value)
686
+ if workdir is not None and path.is_absolute():
687
+ try:
688
+ return path.relative_to(workdir).as_posix()
689
+ except ValueError:
690
+ pass
691
+ return value
692
+
693
+
694
+ def lookup_source(workflow: Workflow) -> Field | None:
695
+ """The field whose file the gate, baseline and system lists are read from: the table being worked on."""
696
+ return next(
697
+ (f for f in workflow.fields if f.name in ("input", "new") and f.kind == "open"),
698
+ None,
699
+ )
700
+
701
+
702
+ def guess_id_column(columns: Sequence[str]) -> str:
703
+ """The header that most likely holds each record's ID, or an empty string when none looks like one."""
704
+ names = [c for c in columns if c.strip()]
705
+ exact = next((c for c in names if c.strip().casefold() == "id"), None)
706
+ if exact is not None:
707
+ return exact
708
+ return next(
709
+ (
710
+ c
711
+ for c in names
712
+ if c.strip().casefold().endswith((" id", "_id")) or c.strip().endswith("Id")
713
+ ),
714
+ "",
715
+ )
716
+
717
+
718
+ def blocked_checks(stderr: str) -> list[str]:
719
+ """The check IDs a blocked --create-baseline suggests waiving, in the order the CLI names them."""
720
+ found = re.search(r"--waive (\S+) --reason", stderr)
721
+ return [part for part in found.group(1).split(",") if part] if found else []
722
+
723
+
724
+ def _waiver_args(field: Field, rows: object) -> list[str]:
725
+ if rows in (None, "", []):
726
+ return []
727
+ if not isinstance(rows, list) or not all(isinstance(row, Mapping) for row in rows):
728
+ raise BadRequest(f"{field.name!r} must be a list of {{check, reason}} rows")
729
+ assert field.flag is not None and field.pair_flag is not None
730
+ argv: list[str] = []
731
+ for row in rows:
732
+ check, reason = (str(row.get(key) or "").strip() for key in ("check", "reason"))
733
+ if not check and not reason:
734
+ continue
735
+ if not check or not reason:
736
+ raise GuiError("Each waiver needs both the check and the reason")
737
+ if "," in check or check.startswith("-"):
738
+ raise GuiError(f"{check!r} is not a check ID")
739
+ argv += [
740
+ field.flag,
741
+ check,
742
+ f"{field.pair_flag}={reason}"
743
+ if reason.startswith("-")
744
+ else field.pair_flag,
745
+ ]
746
+ if not reason.startswith("-"):
747
+ argv.append(reason)
748
+ return argv
749
+
750
+
751
+ def build_argv(
752
+ workflow: Workflow, values: Mapping[str, object], workdir: Path | None = None
753
+ ) -> list[str]:
754
+ """Registry-order command line (positional first) for the submitted form values.
755
+
756
+ Only checks the form is complete and well formed; the CLI itself validates what the values mean.
757
+ """
758
+ if workflow.panel != "form":
759
+ raise BadRequest(f"{workflow.id!r} builds a mapping file, not a command")
760
+ known = {f.name for f in workflow.fields}
761
+ unknown = sorted(set(values) - known)
762
+ if unknown:
763
+ raise BadRequest(f"unknown field {unknown[0]!r} for workflow {workflow.id!r}")
764
+ waivers = {f.name for f in workflow.fields if f.kind == "waivers"}
765
+ given = {
766
+ name: value
767
+ if name in waivers
768
+ else ("" if value is None else str(value)).strip()
769
+ for name, value in values.items()
770
+ }
771
+ has_workbook = any(
772
+ is_workbook_path(str(given.get(f.name, ""))) for f in table_inputs(workflow)
773
+ )
774
+ ordered = sorted(workflow.fields, key=lambda f: f.flag is not None)
775
+ argv: list[str] = []
776
+ missing: list[str] = []
777
+ for field in ordered:
778
+ if field.kind == "waivers":
779
+ argv += _waiver_args(field, given.get(field.name))
780
+ continue
781
+ value = str(given.get(field.name, ""))
782
+ if field.xlsx_only and not has_workbook:
783
+ continue
784
+ if field.requires and not given.get(field.requires):
785
+ continue
786
+ if not value:
787
+ if field.required:
788
+ missing.append(field.label)
789
+ continue
790
+ if field.kind in ("choice", "radio", "flag") and value not in dict(
791
+ field.choices
792
+ ):
793
+ raise BadRequest(f"{value!r} is not a choice for {field.name!r}")
794
+ if field.kind in ("open", "save"):
795
+ if value.startswith("-"):
796
+ raise GuiError(f"{field.label}: a file name cannot start with '-'")
797
+ value = _shown_path(value, workdir)
798
+ if field.kind == "flag":
799
+ assert field.flag is not None
800
+ argv.append(field.flag if value == "on" else "--no-" + field.flag[2:])
801
+ elif field.flag is None:
802
+ argv.append(value)
803
+ elif value.startswith("-"):
804
+ argv.append(f"{field.flag}={value}")
805
+ else:
806
+ argv += [field.flag, value]
807
+ if missing:
808
+ raise GuiError("Please fill in: " + ", ".join(missing))
809
+ return [*argv, *workflow.fixed]
810
+
811
+
812
+ PS_BARE = re.compile(r"[A-Za-z0-9_./\\:=+-]+")
813
+
814
+
815
+ def quote_powershell(token: str) -> str:
816
+ if PS_BARE.fullmatch(token):
817
+ return token
818
+ return "'" + token.replace("'", "''") + "'"
819
+
820
+
821
+ def quote_windows(token: str) -> str:
822
+ """The token quoted so the Windows C runtime reads it back unchanged from a command line (CommandLineToArgvW rules)."""
823
+ if token and not re.search(r'[\s"]', token):
824
+ return token
825
+ quoted, backslashes = '"', 0
826
+ for char in token:
827
+ if char == "\\":
828
+ backslashes += 1
829
+ continue
830
+ quoted += "\\" * (backslashes * 2 + 1 if char == '"' else backslashes) + char
831
+ backslashes = 0
832
+ return quoted + "\\" * (backslashes * 2) + '"'
833
+
834
+
835
+ def _needs_verbatim(token: str) -> bool:
836
+ """Windows PowerShell 5.1 and PowerShell 7 pass these differently to a native program, or drop them."""
837
+ return (
838
+ not token
839
+ or '"' in token
840
+ or (token.endswith("\\") and bool(re.search(r"\s", token)))
841
+ )
842
+
843
+
844
+ _SHELLS = {
845
+ "sh": ("python3", shlex.quote, " \\"),
846
+ "powershell": ("python", quote_powershell, " `"),
847
+ }
848
+ WIDTH = 78
849
+
850
+
851
+ def _is_flag(token: str) -> bool:
852
+ return token.startswith("-") and len(token) > 1
853
+
854
+
855
+ def _command(argv: Sequence[str], program: Sequence[str], shell: Shell) -> str:
856
+ interpreter, quote, continuation = _SHELLS[shell]
857
+ if shell == "powershell" and any(_needs_verbatim(t) for t in argv):
858
+ # After --% every PowerShell passes the rest of the line unchanged, so it can carry C runtime quoting.
859
+ return " ".join(
860
+ [
861
+ interpreter,
862
+ *(quote(t) for t in program),
863
+ "--%",
864
+ *(quote_windows(t) for t in argv),
865
+ ]
866
+ )
867
+ tokens = [quote(t) for t in argv]
868
+ start = next((i for i, t in enumerate(argv) if _is_flag(t)), len(argv))
869
+ head = " ".join([interpreter, *(quote(t) for t in program), *tokens[:start]])
870
+ groups: list[list[str]] = []
871
+ for original, token in zip(argv[start:], tokens[start:]):
872
+ if _is_flag(original) or not groups:
873
+ groups.append([token])
874
+ else:
875
+ groups[-1].append(token)
876
+ flat = " ".join([head, *(" ".join(g) for g in groups)])
877
+ if len(flat) <= WIDTH:
878
+ return flat
879
+ return (continuation + "\n").join([head, *(" " + " ".join(g) for g in groups)])
880
+
881
+
882
+ def posix_command(
883
+ argv: Sequence[str], program: Sequence[str] = ("reqtable.pyz",)
884
+ ) -> str:
885
+ return _command(argv, program, "sh")
886
+
887
+
888
+ def powershell_command(
889
+ argv: Sequence[str], program: Sequence[str] = ("reqtable.pyz",)
890
+ ) -> str:
891
+ return _command(argv, program, "powershell")
892
+
893
+
894
+ @dataclass(frozen=True)
895
+ class ScriptStep:
896
+ title: str
897
+ argv: Sequence[str]
898
+ records: bool = False
899
+
900
+
901
+ RECORDS_AGAIN = "# This step records a new entry each time the script runs."
902
+
903
+
904
+ def script(
905
+ steps: Sequence[ScriptStep],
906
+ shell: Shell,
907
+ workdir: Path,
908
+ program: Sequence[str] = ("reqtable.pyz",),
909
+ ) -> str:
910
+ """A runnable script. Titles become comments, and a step that records something says so above its command."""
911
+ if shell == "sh":
912
+ lines = ["#!/bin/sh", "set -e", f"cd {shlex.quote(str(workdir))}"]
913
+ after: list[str] = []
914
+ else:
915
+ lines = [
916
+ "$ErrorActionPreference = 'Stop'",
917
+ f"Set-Location -LiteralPath {quote_powershell(str(workdir))}",
918
+ ]
919
+ # Native commands do not throw on failure, so stop on a non-zero exit code.
920
+ after = ["if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }"]
921
+ for step in steps:
922
+ lines += [
923
+ "",
924
+ "# " + " ".join(step.title.split()),
925
+ *([RECORDS_AGAIN] if step.records else []),
926
+ _command(step.argv, program, shell),
927
+ *after,
928
+ ]
929
+ return "\n".join(lines) + "\n"
930
+
931
+
932
+ @dataclass(frozen=True)
933
+ class Launcher:
934
+ """How to start reqtable: the argv to run, its environment, and the tokens to show a user."""
935
+
936
+ run: tuple[str, ...]
937
+ shown: tuple[str, ...]
938
+ env: Mapping[str, str]
939
+
940
+
941
+ def launcher(workdir: Path, module_file: str | None = None) -> Launcher:
942
+ here = Path(module_file or __file__).resolve()
943
+ archive = next((p for p in here.parents if p.is_file()), None)
944
+ if archive is not None:
945
+ return Launcher(
946
+ (sys.executable, str(archive)), (_shown_path(str(archive), workdir),), {}
947
+ )
948
+ return Launcher(
949
+ (sys.executable, "-m", "reqtable"),
950
+ ("-m", "reqtable"),
951
+ {"PYTHONPATH": str(here.parent.parent)},
952
+ )