sdtk-spec-kit 0.9.1 → 0.10.0
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.
- package/LICENSE +21 -0
- package/README.md +1 -1
- package/assets/manifest/toolkit-bundle.manifest.json +200 -25
- package/assets/manifest/toolkit-bundle.sha256.txt +47 -12
- package/assets/toolkit/toolkit/AGENTS.md +1 -1
- package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +7 -3
- package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +3 -0
- package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +28 -0
- package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +18 -0
- package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +2 -0
- package/assets/toolkit/toolkit/skills/sdtk-qa/SKILL.md +1 -1
- package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/SKILL.md +69 -0
- package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/scripts/test_validate_smoke_test.py +58 -0
- package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/scripts/validate_smoke_test.py +152 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/SKILL.md +297 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/prompts/agent_brief_template.md +59 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/check_coverage.py +50 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/extract_sources.py +224 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/merge_parts.py +78 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/render_testcase.py +421 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/template_set.py +57 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/test_write_results.py +89 -0
- package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/write_results.py +126 -0
- package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/SKILL.md +146 -0
- package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/pictures.py +68 -0
- package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/test_pictures.py +55 -0
- package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsafe.py +137 -0
- package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsx_xml_edit.py +153 -0
- package/assets/toolkit/toolkit/skills/skills.catalog.yaml +76 -0
- package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +1 -1
- package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +1 -1
- package/assets/toolkit/toolkit/skills-claude/smoke-test-spec/SKILL.md +66 -0
- package/assets/toolkit/toolkit/skills-claude/test-case-xlsx/SKILL.md +294 -0
- package/assets/toolkit/toolkit/skills-claude/xlsx-safe-edit/SKILL.md +143 -0
- package/assets/toolkit/toolkit/templates/README.md +8 -1
- package/assets/toolkit/toolkit/templates/smoke-test/PROFILE_TEMPLATE.md +36 -0
- package/assets/toolkit/toolkit/templates/smoke-test/vi-default/AUTHORING_RULES.md +32 -0
- package/assets/toolkit/toolkit/templates/smoke-test/vi-default/SMOKE_TEST_TEMPLATE.md +147 -0
- package/assets/toolkit/toolkit/templates/smoke-test/vi-default/TEMPLATE.md +25 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/PROFILE_TEMPLATE.md +78 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/TEMPLATE.md +28 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/README.md +73 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/_template.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/common/common.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/mobile_app.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/smartphone_web.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/web.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/windows_app.xlsx +0 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default//343/203/206/343/202/271/343/203/210/344/273/225/346/247/230/346/233/270/344/275/234/346/210/220/343/203/253/343/203/274/343/203/253.md +514 -0
- package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default//343/203/206/343/202/271/343/203/210/344/273/225/346/247/230/346/233/270/351/233/233/345/236/213.xlsx +0 -0
- package/package.json +1 -1
- package/src/lib/scope.js +4 -2
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Writes test results into one sheet of a test-specification workbook — only the result cells of the listed cases.
|
|
3
|
+
|
|
4
|
+
python write_results.py <workbook.xlsx> <sheet name> <results.json> [--template-dir <set>] [--backup-dir <dir>]
|
|
5
|
+
|
|
6
|
+
results.json:
|
|
7
|
+
{"tester": "…", "date": "2026-11-21",
|
|
8
|
+
"cases": {"13": {"result": "OK", "note": "…", "shots": ["13.png"], "reviewer": "…", "reviewer_comment": "…"}}}
|
|
9
|
+
|
|
10
|
+
Columns, first data row and note labels come from the template set's TEMPLATE.md (`results` block). The workbook is
|
|
11
|
+
written through the XML route of sdtk-xlsx-safe-edit: only that sheet's part changes, every other part (pictures,
|
|
12
|
+
styles, other sheets) stays byte-identical — a plain openpyxl save would drop the drawings of every other sheet.
|
|
13
|
+
A result of 要目視 (needs a human look) is refused: settle it first.
|
|
14
|
+
"""
|
|
15
|
+
import argparse
|
|
16
|
+
import datetime
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import shutil
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
|
|
23
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
24
|
+
sys.path.insert(0, HERE)
|
|
25
|
+
import template_set # noqa: E402
|
|
26
|
+
|
|
27
|
+
for name in ("sdtk-xlsx-safe-edit", "xlsx-safe-edit"): # toolkit layout / Claude skills layout
|
|
28
|
+
candidate = os.path.join(HERE, "..", "..", name, "scripts")
|
|
29
|
+
if os.path.isdir(candidate):
|
|
30
|
+
sys.path.insert(0, os.path.normpath(candidate))
|
|
31
|
+
break
|
|
32
|
+
from xlsx_xml_edit import SheetXml, package_diff # noqa: E402
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ResultsError(RuntimeError):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def case_rows(workbook, sheet, id_column, first_row):
|
|
40
|
+
"""case id (as text) -> row, read with openpyxl in read-only mode (nothing is saved through it)."""
|
|
41
|
+
import openpyxl
|
|
42
|
+
from openpyxl.utils import column_index_from_string
|
|
43
|
+
wb = openpyxl.load_workbook(workbook, read_only=True, data_only=True)
|
|
44
|
+
try:
|
|
45
|
+
ws = wb[sheet]
|
|
46
|
+
col = column_index_from_string(id_column)
|
|
47
|
+
rows = {}
|
|
48
|
+
for r, row in enumerate(ws.iter_rows(min_row=first_row, min_col=col, max_col=col, values_only=True), first_row):
|
|
49
|
+
v = row[0]
|
|
50
|
+
if v is None or v == "":
|
|
51
|
+
continue
|
|
52
|
+
key = str(int(v)) if isinstance(v, float) and v.is_integer() else str(v).strip()
|
|
53
|
+
rows[key] = r
|
|
54
|
+
return rows
|
|
55
|
+
finally:
|
|
56
|
+
wb.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def note_text(case, labels):
|
|
60
|
+
parts = []
|
|
61
|
+
if case.get("shots"):
|
|
62
|
+
parts.append(labels.get("evidence", "") + ", ".join(dict.fromkeys(case["shots"])))
|
|
63
|
+
if case.get("note"):
|
|
64
|
+
parts.append(case["note"])
|
|
65
|
+
if case.get("reviewer_comment"):
|
|
66
|
+
parts.append(labels.get("reviewer_comment", "") + case["reviewer_comment"])
|
|
67
|
+
return "\n".join(parts)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write(workbook, sheet, results, set_dir, backup_dir=None) -> list[str]:
|
|
71
|
+
cfg = template_set.config(set_dir).get("results")
|
|
72
|
+
if not cfg:
|
|
73
|
+
raise ResultsError(f"{set_dir}/TEMPLATE.md has no results block")
|
|
74
|
+
if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(workbook)), "~$" + os.path.basename(workbook))):
|
|
75
|
+
raise ResultsError("the workbook is open in Excel (~$ lock file): close it first; nothing written")
|
|
76
|
+
cols, labels = cfg["columns"], cfg.get("labels", {})
|
|
77
|
+
rows = case_rows(workbook, sheet, cfg["id_column"], cfg["first_row"])
|
|
78
|
+
date = datetime.datetime.strptime(results["date"], "%Y-%m-%d").strftime(cfg.get("date_format", "%Y/%m/%d"))
|
|
79
|
+
sx = SheetXml(workbook, sheet)
|
|
80
|
+
written = []
|
|
81
|
+
for case_id, case in results["cases"].items():
|
|
82
|
+
if case.get("result") == "要目視":
|
|
83
|
+
raise ResultsError(f"case {case_id}: 要目視 — settle it before writing; nothing written")
|
|
84
|
+
if case_id not in rows:
|
|
85
|
+
raise ResultsError(f"case {case_id}: not in column {cfg['id_column']} of {sheet}; nothing written")
|
|
86
|
+
tester = case.get("tester", results.get("tester", ""))
|
|
87
|
+
if case.get("reviewer"):
|
|
88
|
+
tester = f"{tester}/{labels.get('reviewer', '')}{case['reviewer']}"
|
|
89
|
+
values = {cols["date"]: date, cols["tester"]: tester, cols["result"]: case["result"]}
|
|
90
|
+
if "note" in cols:
|
|
91
|
+
values[cols["note"]] = note_text(case, labels)
|
|
92
|
+
sx.set_row(rows[case_id], values, template_row=rows[case_id])
|
|
93
|
+
written.append(case_id)
|
|
94
|
+
backup_dir = backup_dir or tempfile.gettempdir()
|
|
95
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
96
|
+
stem, ext = os.path.splitext(os.path.basename(workbook))
|
|
97
|
+
backup = os.path.join(backup_dir, f"{stem}.before-results-{datetime.datetime.now():%Y%m%d-%H%M%S}{ext}")
|
|
98
|
+
shutil.copy2(workbook, backup)
|
|
99
|
+
out = backup + ".out" + ext
|
|
100
|
+
sx.save(out)
|
|
101
|
+
changed = package_diff(backup, out)
|
|
102
|
+
if changed != [sx.part]:
|
|
103
|
+
raise ResultsError(f"unexpected parts changed {changed}; nothing written (backup {backup})")
|
|
104
|
+
shutil.copyfile(out, workbook)
|
|
105
|
+
os.remove(out)
|
|
106
|
+
print(f"{len(written)} case(s) written to {sheet}; backup {backup}")
|
|
107
|
+
return written
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def main(argv=None):
|
|
111
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
112
|
+
a = argparse.ArgumentParser()
|
|
113
|
+
a.add_argument("workbook")
|
|
114
|
+
a.add_argument("sheet")
|
|
115
|
+
a.add_argument("results")
|
|
116
|
+
a.add_argument("--template-dir")
|
|
117
|
+
a.add_argument("--backup-dir")
|
|
118
|
+
args = a.parse_args(argv)
|
|
119
|
+
with open(args.results, encoding="utf-8") as f:
|
|
120
|
+
results = json.load(f)
|
|
121
|
+
write(args.workbook, args.sheet, results, template_set.resolve(args.template_dir or results.get("template_set")),
|
|
122
|
+
args.backup_dir)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__":
|
|
126
|
+
main()
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: sdtk-xlsx-safe-edit
|
|
3
|
+
description: Use when reading or modifying a hand-maintained .xlsx/.xlsm (manuals, specs, test-case sheets, Q&A logs, design documents) — adding sheets or rows, changing cells, inserting pictures, or updating a generated workbook the person has since edited; also when a save changed fonts, row heights or widths elsewhere. Windows + Excel + pywin32.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# SDTK-SPEC Safe Edits to Hand-Maintained Workbooks
|
|
7
|
+
|
|
8
|
+
People's workbooks carry pictures, shapes, hand-tuned formatting and edits made after your last
|
|
9
|
+
look. The failure modes are silent: the save succeeds and something the person made is gone, or
|
|
10
|
+
their own Excel window is disturbed. Every rule below comes from a real incident. Other SDTK skills
|
|
11
|
+
that write Excel (`sdtk-test-case-xlsx`, `sdtk-screen-design-xlsx`, document and Q&A sheets) write
|
|
12
|
+
through this skill's scripts.
|
|
13
|
+
|
|
14
|
+
<!-- neutral-only -->
|
|
15
|
+
> **Installed as a runtime skill** (for example under `.codex/skills/`): read `toolkit/skills/sdtk-<name>/` in the
|
|
16
|
+
> paths below as the installed skill folder of that name (this one or a sibling) and `toolkit/templates/` as
|
|
17
|
+
> `references/templates/` inside this skill's folder.
|
|
18
|
+
<!-- /neutral-only -->
|
|
19
|
+
|
|
20
|
+
## Critical Constraints
|
|
21
|
+
|
|
22
|
+
1. **Never save with `openpyxl`.** It drops every picture/shape/drawing on sheets it does not
|
|
23
|
+
rewrite. `openpyxl.load_workbook(...)` for *reading* is fine.
|
|
24
|
+
2. **Never `win32com.client.Dispatch("Excel.Application")`.** When the person has Excel open,
|
|
25
|
+
`Dispatch` attaches to *their* instance: setting `Visible=False` hides their window and
|
|
26
|
+
`Quit()` closes their work. Always `DispatchEx` (a private, new instance). To merely *look*
|
|
27
|
+
at the person's instance use `GetActiveObject` and change nothing on it.
|
|
28
|
+
3. **Never kill `EXCEL.EXE`** or close the person's workbooks. If the target is open, stop and ask
|
|
29
|
+
them to save and close it.
|
|
30
|
+
4. **Preflight before every write:** no `~$<name>` lock file next to the target, and neither the
|
|
31
|
+
target nor any workbook with the same file name is open in a running Excel (Excel cannot open
|
|
32
|
+
two workbooks of the same name, even from different folders). A same-name workbook in another
|
|
33
|
+
folder is a *different file*: never switch the target to it and never edit it in the person's
|
|
34
|
+
open Excel — the target stays the path the person named; ask them to save and close the other one.
|
|
35
|
+
5. **Back up first**, to a scratch location (`<name>.before-<change>.xlsx`).
|
|
36
|
+
6. **Touch only what was asked** — and that includes layout. An Excel save rewrites the *whole
|
|
37
|
+
package*: a hidden instance re-resolves theme fonts (on thousands of cells), renames the Normal
|
|
38
|
+
style, re-measures auto-height rows and column widths on **every** sheet, rewrites comment
|
|
39
|
+
headers and recompresses images. Comparing values and shapes does not see this.
|
|
40
|
+
7. **"Check" / "review" requests are read-only.** Open with `ReadOnly=True` or openpyxl; do not save.
|
|
41
|
+
8. **Re-read the current file before each edit round.** The person edits between your rounds. Keep
|
|
42
|
+
the sha256 of the file you last read (`xlsafe.fingerprint`); if it changed, re-read before
|
|
43
|
+
editing. Locate anchors by content (a heading's text), never by remembered row numbers, and abort
|
|
44
|
+
if the anchor text is not where you expect.
|
|
45
|
+
|
|
46
|
+
## Process
|
|
47
|
+
|
|
48
|
+
1. **Classify the request.** "Check" / "review" / "is it OK" → read-only: report, save nothing, stop.
|
|
49
|
+
2. **Re-read** the current file and record `xlsafe.fingerprint(path)`; locate anchors by content.
|
|
50
|
+
3. **Preflight**: lock file and same-name workbook (rule 4). If it fails, say why and stop — never
|
|
51
|
+
close or kill anything to make it pass.
|
|
52
|
+
4. **Back up** to a scratch location.
|
|
53
|
+
5. **Choose the route** (table below) and write to a scratch copy first.
|
|
54
|
+
6. **Verify** (section below), then copy over the target (preflight again) and compare sha256.
|
|
55
|
+
7. **Report** (section at the end).
|
|
56
|
+
|
|
57
|
+
## Choose the route
|
|
58
|
+
|
|
59
|
+
| Change | Route |
|
|
60
|
+
|---|---|
|
|
61
|
+
| Cell values, new/filled rows, row heights, extending data-validation / conditional-format ranges — in one sheet | **XML route** `toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsx_xml_edit.py`: rewrites only that sheet's part; every other part stays byte-identical |
|
|
62
|
+
| Pictures, shapes, inserted sheets, anything Excel must lay out | **COM route** `toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsafe.py`. After the save it diffs layout against the backup; on drift it restores the backup and raises. Accept drift only after the person agrees (`accept_layout_drift=True`) |
|
|
63
|
+
| A generated workbook the person has finalized by hand | **Final mode** (below): no re-render |
|
|
64
|
+
|
|
65
|
+
### XML route
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
import sys
|
|
69
|
+
sys.path.insert(0, r"toolkit/skills/sdtk-xlsx-safe-edit/scripts")
|
|
70
|
+
from xlsx_xml_edit import SheetXml, package_diff, excel_open_check
|
|
71
|
+
|
|
72
|
+
sx = SheetXml(BACKUP, "Sheet name") # read from the backup copy
|
|
73
|
+
sx.set_row(46, {"D": 43, "N": "line 1\nline 2"}, template_row=48, height=120)
|
|
74
|
+
sx.extend_ranges(old_last_row=48, new_last_row=58) # only if rows were added past the old end
|
|
75
|
+
sx.save(OUT) # write to scratch first
|
|
76
|
+
assert package_diff(BACKUP, OUT) == [sx.part]
|
|
77
|
+
excel_open_check(OUT, "Sheet name", ["N46"]) # private instance, read-only; fails if repaired
|
|
78
|
+
# then copy OUT over the target (preflight again) and compare sha256
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Row heights: Excel does not auto-fit on open. Measure with a COM `--dry` run (`Rows(r).AutoFit()`,
|
|
82
|
+
nothing saved) or copy a height of an existing row with the same line count; add a few points.
|
|
83
|
+
|
|
84
|
+
### COM route
|
|
85
|
+
|
|
86
|
+
`open_for_edit` runs the preflight, the backup, the untouched-sheet check and the layout diff
|
|
87
|
+
itself — call it rather than re-implementing them (`xlsafe.preflight(path)` alone for a check).
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from xlsafe import open_for_edit
|
|
91
|
+
with open_for_edit(PATH, touch=["New sheet"], backup_dir=SCRATCH, dry="--dry" in sys.argv) as (xl, wb):
|
|
92
|
+
ws = wb.Worksheets("New sheet")
|
|
93
|
+
...
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Pictures under a heading (COM)
|
|
97
|
+
|
|
98
|
+
Screenshots go into the empty rows between a step's text and the next heading. A fixed gap overflows
|
|
99
|
+
as soon as a picture is taller than it, and the picture covers the next heading.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from pictures import rows_needed, insert_pictures_below
|
|
103
|
+
# pictures: [(path, width_pt), ...]; first_row: one empty row under the step text
|
|
104
|
+
insert_pictures_below(ws, first_row=11, next_heading_text="② …", pictures=pictures)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`insert_pictures_below` finds the next heading by its text, inserts the missing rows before it,
|
|
108
|
+
places the pictures (`Placement = xlMove`, as hand-inserted ones), and fails if any picture's
|
|
109
|
+
`BottomRightCell.Row` reaches the heading. Pictures already below keep their place relative to their
|
|
110
|
+
own step because they move with the inserted rows.
|
|
111
|
+
|
|
112
|
+
### Final mode — a generated workbook the person finalized by hand
|
|
113
|
+
|
|
114
|
+
When a workbook was generated (by a skill) and then edited by hand, the person's file is the source
|
|
115
|
+
of truth. Do **not** re-render it, not even one sheet, unless the person says so.
|
|
116
|
+
1. Make the change in the generator's source (spec / YAML) so the next generation is right.
|
|
117
|
+
2. Apply the same change to the person's file with the XML or COM route — only the cells / shapes
|
|
118
|
+
it touches.
|
|
119
|
+
3. Report a change table: `sheet | cell or shape | before | after`, so the person can review or merge
|
|
120
|
+
by hand. If you cannot apply a change surgically, give the table and stop.
|
|
121
|
+
|
|
122
|
+
## Verify (both routes)
|
|
123
|
+
|
|
124
|
+
- Package: `package_diff(backup, result)` lists exactly the parts you meant to change.
|
|
125
|
+
- Layout: `layout_diff(backup, result, skip_sheets=[...])` is empty for untouched sheets.
|
|
126
|
+
- Content: read the written cells back; picture counts per sheet unchanged elsewhere.
|
|
127
|
+
- Pictures: every picture ends above the next heading (`insert_pictures_below` checks it).
|
|
128
|
+
|
|
129
|
+
## Pitfalls seen in practice
|
|
130
|
+
|
|
131
|
+
| Situation | What goes wrong | Do instead |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| Rows added after the last formatted row | Data validation / conditional formatting stop at the old last row | `extend_ranges` (XML) or copy the template row (COM) |
|
|
134
|
+
| Text starting with `=`, `@`, `$`, `-` (commands, formulas shown as text) | Excel parses it as a formula | XML: inline string; COM: `NumberFormat = "@"` first |
|
|
135
|
+
| Adding pictures to a fixed gap of empty rows | Picture covers the next heading | `insert_pictures_below` |
|
|
136
|
+
| Inserting rows above existing pictures | Free-floating pictures do not move | Read `Shape.Placement`; new pictures `Placement = 2` |
|
|
137
|
+
| Re-rendering a generated sheet edited by hand | Their edits disappear | Final mode |
|
|
138
|
+
| Reading page breaks through COM (`HPageBreaks`) | Throws on some sheets | Read `row_breaks` with openpyxl (read-only) |
|
|
139
|
+
| Windows paths in a heredoc script | `\` sequences mangled | Write scripts with a file tool; raw strings |
|
|
140
|
+
| Screenshots for the document | Desktop corners, personal data (e-mail, tokens, user names) | Trim ~8 px; point out personal data before publishing |
|
|
141
|
+
| Metadata of a shared template (`docProps`) | Author / company names travel with the file | Clear `dc:creator`, `cp:lastModifiedBy`, `Company` |
|
|
142
|
+
|
|
143
|
+
## Reporting
|
|
144
|
+
|
|
145
|
+
Say which sheets/cells changed, the route used, the backup path, the package and layout diff
|
|
146
|
+
results, and anything you saw but did not change. If preflight failed, say why and stop.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Pictures (screenshots) under a step's text in a hand-maintained workbook, without covering the next heading.
|
|
3
|
+
|
|
4
|
+
from pictures import insert_pictures_below
|
|
5
|
+
insert_pictures_below(ws, first_row=11, next_heading_text="② …", pictures=[(r"C:\\shots\\1.png", 400), ...])
|
|
6
|
+
|
|
7
|
+
`ws` is a worksheet of a workbook opened through xlsafe.open_for_edit (a private Excel instance). Pictures are
|
|
8
|
+
stacked from `first_row`, one empty row between them; rows are inserted before the next heading when the gap is
|
|
9
|
+
too small, so everything below (pictures included, Placement = xlMove) moves down with its own step.
|
|
10
|
+
"""
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
|
|
14
|
+
XL_MOVE = 2 # Shape.Placement: move with cells, keep size (what hand-inserted pictures use)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PictureLayoutError(RuntimeError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def image_size(path) -> tuple[int, int]:
|
|
22
|
+
from PIL import Image
|
|
23
|
+
with Image.open(path) as im:
|
|
24
|
+
return im.size
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def rows_needed(heights_pt, row_height_pt, gap_rows=1) -> list[int]:
|
|
28
|
+
"""Rows each picture takes when stacked (its height rounded up + `gap_rows` empty rows under it)."""
|
|
29
|
+
if row_height_pt <= 0:
|
|
30
|
+
raise ValueError("row height must be positive")
|
|
31
|
+
return [math.ceil(h / row_height_pt) + gap_rows for h in heights_pt]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def find_row(ws, text, start_row, column=1, max_rows=5000) -> int:
|
|
35
|
+
for r in range(start_row, start_row + max_rows):
|
|
36
|
+
if ws.Cells(r, column).Value == text:
|
|
37
|
+
return r
|
|
38
|
+
raise PictureLayoutError(f"heading {text!r} not found in column {column} from row {start_row}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def insert_pictures_below(ws, first_row, next_heading_text, pictures, gap_rows=1, keep_rows_before_heading=1, column=1):
|
|
42
|
+
"""Places `pictures` ([(path, width_pt)]) from `first_row` down; inserts rows before the heading whose text is
|
|
43
|
+
`next_heading_text` when they do not fit. Returns [(path, top_row, bottom_row)]. Fails if a picture would reach
|
|
44
|
+
the heading (nothing is saved by this function: the caller's open_for_edit decides)."""
|
|
45
|
+
heading = find_row(ws, next_heading_text, first_row, column)
|
|
46
|
+
row_h = ws.Rows(first_row).RowHeight
|
|
47
|
+
sizes = []
|
|
48
|
+
for path, width in pictures:
|
|
49
|
+
if not os.path.exists(path):
|
|
50
|
+
raise PictureLayoutError(f"no picture at {path}")
|
|
51
|
+
w_px, h_px = image_size(path)
|
|
52
|
+
sizes.append((path, width, width * h_px / w_px))
|
|
53
|
+
need = sum(rows_needed([h for _, _, h in sizes], row_h, gap_rows))
|
|
54
|
+
missing = first_row + need + keep_rows_before_heading - heading
|
|
55
|
+
if missing > 0:
|
|
56
|
+
ws.Rows(f"{heading}:{heading + missing - 1}").Insert()
|
|
57
|
+
heading += missing
|
|
58
|
+
placed, row = [], first_row
|
|
59
|
+
for (path, width, height), rows in zip(sizes, rows_needed([h for _, _, h in sizes], row_h, gap_rows)):
|
|
60
|
+
cell = ws.Cells(row, column)
|
|
61
|
+
shape = ws.Shapes.AddPicture(os.path.abspath(path), False, True, cell.Left, cell.Top, width, height)
|
|
62
|
+
shape.Placement = XL_MOVE
|
|
63
|
+
bottom = shape.BottomRightCell.Row
|
|
64
|
+
if bottom >= heading:
|
|
65
|
+
raise PictureLayoutError(f"{os.path.basename(path)} ends at row {bottom}, the heading is at row {heading}")
|
|
66
|
+
placed.append((path, row, bottom))
|
|
67
|
+
row += rows
|
|
68
|
+
return placed
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""pictures.py — python -m unittest test_pictures (from this folder). The COM test needs Windows + desktop Excel and
|
|
3
|
+
uses a private instance (DispatchEx) on a temp workbook; it is skipped elsewhere."""
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
10
|
+
import pictures # noqa: E402
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import win32com.client # noqa: F401
|
|
14
|
+
HAVE_EXCEL = sys.platform == "win32"
|
|
15
|
+
except ImportError:
|
|
16
|
+
HAVE_EXCEL = False
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RowsNeeded(unittest.TestCase):
|
|
20
|
+
def test_rounds_up_and_adds_gap(self):
|
|
21
|
+
self.assertEqual(pictures.rows_needed([210, 13, 14], 13, gap_rows=1), [18, 2, 3])
|
|
22
|
+
|
|
23
|
+
def test_rejects_zero_row_height(self):
|
|
24
|
+
with self.assertRaises(ValueError):
|
|
25
|
+
pictures.rows_needed([10], 0)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@unittest.skipUnless(HAVE_EXCEL, "needs Windows + desktop Excel")
|
|
29
|
+
class InsertBelowHeading(unittest.TestCase):
|
|
30
|
+
def test_inserts_rows_and_keeps_heading_clear(self):
|
|
31
|
+
import openpyxl
|
|
32
|
+
from PIL import Image
|
|
33
|
+
from xlsafe import open_for_edit
|
|
34
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
35
|
+
book = os.path.join(tmp, "manual.xlsx")
|
|
36
|
+
wb = openpyxl.Workbook() # a fresh fixture: no drawings to lose
|
|
37
|
+
ws = wb.active
|
|
38
|
+
ws.title = "Steps"
|
|
39
|
+
ws["A1"], ws["A2"], ws["A20"] = "① step one", "text of step one", "② step two"
|
|
40
|
+
wb.save(book)
|
|
41
|
+
shots = []
|
|
42
|
+
for i, (w, h) in enumerate([(533, 252), (940, 354)]):
|
|
43
|
+
p = os.path.join(tmp, f"{i}.png")
|
|
44
|
+
Image.new("RGB", (w, h), "white").save(p)
|
|
45
|
+
shots.append((p, 400))
|
|
46
|
+
with open_for_edit(book, touch=["Steps"], backup_dir=os.path.join(tmp, "bk")) as (xl, wbc):
|
|
47
|
+
placed = pictures.insert_pictures_below(wbc.Worksheets("Steps"), 4, "② step two", shots)
|
|
48
|
+
heading = pictures.find_row(wbc.Worksheets("Steps"), "② step two", 1)
|
|
49
|
+
self.assertGreater(heading, 20) # rows were inserted
|
|
50
|
+
self.assertTrue(all(bottom < heading for _, _, bottom in placed))
|
|
51
|
+
self.assertEqual(wbc.Worksheets("Steps").Shapes.Count, 2)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
if __name__ == "__main__":
|
|
55
|
+
unittest.main()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Safe editing of a hand-maintained workbook through a private Excel instance.
|
|
3
|
+
|
|
4
|
+
with open_for_edit(path, touch=["Sheet A"], backup_dir=scratch, dry=False) as (xl, wb):
|
|
5
|
+
...edit only the sheets named in `touch` (they may also be new)...
|
|
6
|
+
|
|
7
|
+
On entry: preflight (lock file, workbook of the same name open in a running Excel), backup, a NEW Excel instance
|
|
8
|
+
(DispatchEx: never the person's own), a snapshot of every sheet. On exit: every sheet not in `touch` must have the
|
|
9
|
+
same values and shapes as before and no sheet may disappear, else nothing is saved. `dry=True` never saves.
|
|
10
|
+
"""
|
|
11
|
+
import contextlib
|
|
12
|
+
import hashlib
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
import win32com.client as win32
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PreflightError(RuntimeError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def running_workbooks():
|
|
25
|
+
"""Full names of the workbooks open in the person's Excel, read without changing anything; [] if none."""
|
|
26
|
+
try:
|
|
27
|
+
xl = win32.GetActiveObject("Excel.Application")
|
|
28
|
+
except Exception:
|
|
29
|
+
return []
|
|
30
|
+
try:
|
|
31
|
+
return [b.FullName for b in xl.Workbooks]
|
|
32
|
+
except Exception:
|
|
33
|
+
return []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def preflight(path):
|
|
37
|
+
folder, name = os.path.split(os.path.abspath(path))
|
|
38
|
+
if not os.path.exists(path):
|
|
39
|
+
raise PreflightError(f"not found: {path}")
|
|
40
|
+
open_same = [w for w in running_workbooks() if os.path.basename(w).lower() == name.lower()]
|
|
41
|
+
if open_same:
|
|
42
|
+
raise PreflightError(f"a workbook named {name} is open in Excel ({open_same[0]}): ask to save and close it")
|
|
43
|
+
lock = os.path.join(folder, "~$" + name)
|
|
44
|
+
if os.path.exists(lock):
|
|
45
|
+
print(f"note: stale lock file {lock} (no running Excel has it open)")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def backup(path, backup_dir, label="before-edit"):
|
|
49
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
50
|
+
stem, ext = os.path.splitext(os.path.basename(path))
|
|
51
|
+
dst = os.path.join(backup_dir, f"{stem}.{label}-{time.strftime('%Y%m%d-%H%M%S')}{ext}")
|
|
52
|
+
shutil.copy2(path, dst)
|
|
53
|
+
return dst
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _sheet_state(ws):
|
|
57
|
+
used = ws.UsedRange
|
|
58
|
+
values = repr((used.Address, used.Value2)).encode("utf-8", "replace")
|
|
59
|
+
shapes = []
|
|
60
|
+
for i in range(1, ws.Shapes.Count + 1):
|
|
61
|
+
s = ws.Shapes(i)
|
|
62
|
+
shapes.append((s.Name, round(s.Top, 1), round(s.Left, 1), round(s.Width, 1), round(s.Height, 1)))
|
|
63
|
+
return hashlib.sha256(values).hexdigest(), tuple(shapes)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def snapshot(wb):
|
|
67
|
+
return {wb.Worksheets(i).Name: _sheet_state(wb.Worksheets(i)) for i in range(1, wb.Worksheets.Count + 1)}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def verify(before, after, touch):
|
|
71
|
+
problems = []
|
|
72
|
+
for name, state in before.items():
|
|
73
|
+
if name in touch:
|
|
74
|
+
continue
|
|
75
|
+
if name not in after:
|
|
76
|
+
problems.append(f"sheet {name!r} disappeared")
|
|
77
|
+
elif after[name][0] != state[0]:
|
|
78
|
+
problems.append(f"values changed on untouched sheet {name!r}")
|
|
79
|
+
elif after[name][1] != state[1]:
|
|
80
|
+
problems.append(f"shapes changed on untouched sheet {name!r}: {len(state[1])} -> {len(after[name][1])}")
|
|
81
|
+
for name in after:
|
|
82
|
+
if name not in before and name not in touch:
|
|
83
|
+
problems.append(f"unexpected new sheet {name!r}")
|
|
84
|
+
return problems
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@contextlib.contextmanager
|
|
88
|
+
def open_for_edit(path, touch, backup_dir, dry=False, read_only=False, accept_layout_drift=False):
|
|
89
|
+
"""COM route. After saving, the file is compared with the backup: if Excel re-measured row heights, column
|
|
90
|
+
widths or fonts on a sheet outside `touch` (it rewrites the whole package on save), the backup is restored and
|
|
91
|
+
RuntimeError is raised. Pass accept_layout_drift=True only after the person accepted that drift."""
|
|
92
|
+
path = os.path.abspath(path)
|
|
93
|
+
preflight(path)
|
|
94
|
+
backup_path = None
|
|
95
|
+
if not dry and not read_only:
|
|
96
|
+
backup_path = backup(path, backup_dir)
|
|
97
|
+
print("backup:", backup_path)
|
|
98
|
+
xl = win32.DispatchEx("Excel.Application") # private instance, never the person's
|
|
99
|
+
xl.Visible = False
|
|
100
|
+
xl.DisplayAlerts = False
|
|
101
|
+
wb = None
|
|
102
|
+
saved = False
|
|
103
|
+
try:
|
|
104
|
+
wb = xl.Workbooks.Open(path, UpdateLinks=0, ReadOnly=read_only)
|
|
105
|
+
before = snapshot(wb)
|
|
106
|
+
yield xl, wb
|
|
107
|
+
if read_only:
|
|
108
|
+
return
|
|
109
|
+
problems = verify(before, snapshot(wb), set(touch))
|
|
110
|
+
if problems:
|
|
111
|
+
raise RuntimeError("not saved: " + "; ".join(problems))
|
|
112
|
+
if dry:
|
|
113
|
+
print("dry run: nothing saved")
|
|
114
|
+
else:
|
|
115
|
+
wb.Save()
|
|
116
|
+
saved = True
|
|
117
|
+
print("saved; untouched sheets: same values and shapes:", [n for n in before if n not in touch])
|
|
118
|
+
finally:
|
|
119
|
+
if wb is not None:
|
|
120
|
+
wb.Close(False)
|
|
121
|
+
xl.Quit()
|
|
122
|
+
if saved:
|
|
123
|
+
from xlsx_xml_edit import layout_diff
|
|
124
|
+
drift = layout_diff(backup_path, path, skip_sheets=set(touch))
|
|
125
|
+
if drift and not accept_layout_drift:
|
|
126
|
+
shutil.copy2(backup_path, path)
|
|
127
|
+
raise RuntimeError("Excel re-laid-out sheets outside `touch` (row heights / column widths / fonts); "
|
|
128
|
+
f"backup restored, nothing changed: {drift}. Use the XML route (xlsx_xml_edit.py), "
|
|
129
|
+
"or accept_layout_drift=True once the person accepts this drift.")
|
|
130
|
+
print("layout of untouched sheets:", "unchanged" if not drift else f"DRIFT ACCEPTED {drift}")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def fingerprint(path) -> str:
|
|
134
|
+
"""sha256 of the file: keep the value of the last read and compare before the next edit round — the person edits
|
|
135
|
+
between rounds, and a changed file must be read again before anything is written."""
|
|
136
|
+
with open(path, "rb") as f:
|
|
137
|
+
return hashlib.sha256(f.read()).hexdigest()
|