@harmonyos-arkts/d2h 0.1.36 → 0.1.37
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/.agents/plugins/marketplace.json +22 -0
- package/.claude-plugin/marketplace.json +21 -6
- package/.claude-plugin/plugin.json +9 -3
- package/.codex-plugin/plugin.json +37 -0
- package/README.md +1 -1
- package/agents/android-to-hmos-00-orchestrator.md +1 -1
- package/agents/d2h.md +13 -10
- package/docs/environment-check.md +2 -2
- package/package.json +3 -1
- package/schemas/migration-report-index.schema.json +6 -0
- package/skills/d2h-app-solution/SKILL.md +25 -6
- package/skills/d2h-app-solution/agents/openai.yaml +2 -2
- package/skills/d2h-app-solution/scripts/export_inventory_xlsx.py +377 -0
- package/skills/d2h-cloud-knowledge/SKILL.md +172 -58
- package/skills/d2h-cloud-knowledge/build-index.mjs +238 -0
- package/skills/d2h-cloud-knowledge/scenario-audit.mjs +212 -0
- package/skills/d2h-cloud-knowledge/scenario-map.json +72 -0
- package/skills/d2h-dashboard/SKILL.md +26 -1
- package/skills/d2h-dashboard/app/assets/Analysis-BT2XmI3C.js +1 -0
- package/skills/d2h-dashboard/app/assets/CodeAudit-BuyDgDM3.js +1 -0
- package/skills/d2h-dashboard/app/assets/CodeAudit-hkE0DSw-.css +1 -0
- package/skills/d2h-dashboard/app/assets/FeaturesList-C38X4yvD.js +1 -0
- package/skills/d2h-dashboard/app/assets/FeaturesList-DQldjxuT.css +1 -0
- package/skills/d2h-dashboard/app/assets/Overview-DcJSNtDr.js +1 -0
- package/skills/d2h-dashboard/app/assets/Overview-DfJtZ2zJ.css +1 -0
- package/skills/d2h-dashboard/app/assets/Project-CssSwlh6.js +1 -0
- package/skills/d2h-dashboard/app/assets/SpecDetail--ohkiDwo.css +1 -0
- package/skills/d2h-dashboard/app/assets/SpecDetail-DcAYGyNb.js +1 -0
- package/skills/d2h-dashboard/app/assets/SpecItemDetail-CJ-vmNJm.css +1 -0
- package/skills/d2h-dashboard/app/assets/{SpecItemDetail-BDl_Qqfx.js → SpecItemDetail-DTViQrsC.js} +9 -9
- package/skills/d2h-dashboard/app/assets/{index-CnjP19Vs.css → index-DmIexyDt.css} +1 -1
- package/skills/d2h-dashboard/app/assets/index-UvzKcmSu.js +3 -0
- package/skills/d2h-dashboard/app/assets/{navigation-BGPexEv8.js → navigation-CuZGAjCp.js} +1 -1
- package/skills/d2h-dashboard/app/dashboard.standalone.html +88 -0
- package/skills/d2h-dashboard/app/dataApi.mjs +133 -31
- package/skills/d2h-dashboard/app/index.html +2 -2
- package/skills/d2h-dashboard/app/serve.mjs +75 -1
- package/skills/d2h-dashboard/lib/data-subscription.mjs +106 -0
- package/skills/d2h-dashboard/lib/stage-timing.mjs +18 -0
- package/skills/d2h-hypium-forge/SKILL.md +0 -2
- package/skills/d2h-spec-develop/SKILL.md +1 -4
- package/skills/d2h-spec-generate/SKILL.md +1 -1
- package/skills/managing-d2h-toolchain/environment-requirements.json +2 -2
- package/skills/managing-d2h-toolchain/toolchain.json +2 -2
- package/skills/preparing-migration-workspace/SKILL.md +4 -3
- package/skills/d2h-dashboard/app/assets/Analysis-S3iFh2nP.js +0 -1
- package/skills/d2h-dashboard/app/assets/CodeAudit-BI5iNy2f.css +0 -1
- package/skills/d2h-dashboard/app/assets/CodeAudit-BeZMoO_s.js +0 -1
- package/skills/d2h-dashboard/app/assets/FeaturesList-CZ40orVY.css +0 -1
- package/skills/d2h-dashboard/app/assets/FeaturesList-CdKAoNw5.js +0 -1
- package/skills/d2h-dashboard/app/assets/Overview-C43KVHdP.js +0 -1
- package/skills/d2h-dashboard/app/assets/Overview-CzysQJHh.css +0 -1
- package/skills/d2h-dashboard/app/assets/Project-D5loWYjZ.js +0 -1
- package/skills/d2h-dashboard/app/assets/SpecDetail-BHB6smtT.css +0 -1
- package/skills/d2h-dashboard/app/assets/SpecDetail-XCDyawZ3.js +0 -1
- package/skills/d2h-dashboard/app/assets/SpecItemDetail-Bf4pGDEN.css +0 -1
- package/skills/d2h-dashboard/app/assets/datetime-DBOJn2GA.js +0 -1
- package/skills/d2h-dashboard/app/assets/index-C1bO3C02.js +0 -3
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Export the feature inventory as an XLSX using the Python standard library."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from itertools import groupby
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import posixpath
|
|
12
|
+
import re
|
|
13
|
+
import tempfile
|
|
14
|
+
import unicodedata
|
|
15
|
+
import xml.etree.ElementTree as ET
|
|
16
|
+
from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
MAIN_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
|
20
|
+
OFFICE_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
21
|
+
PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
22
|
+
CONTENT_TYPE_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
|
|
23
|
+
SHEET_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml."
|
|
24
|
+
FEATURE_SHEET, REPORT_SHEET, LEGEND_SHEET = "功能清单", "质量报告", "状态说明"
|
|
25
|
+
FEATURE_HEADER_ROW = 4
|
|
26
|
+
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
|
|
27
|
+
EXCEL_ESCAPES = re.compile(r"_x[0-9A-Fa-f]{4}_|[\x00-\x08\x0B-\x0D\x0E-\x1F\uD800-\uDFFF\uFFFE\uFFFF]")
|
|
28
|
+
|
|
29
|
+
STATUS_ROWS = (
|
|
30
|
+
("implemented", "有", "正式入口可达且主要效果已接线", "可见性 + 交互/路由 + 目标/效果证据"),
|
|
31
|
+
("partial", "部分实现", "只实现部分路径、条件或效果", "明确缺失部分"),
|
|
32
|
+
("mock", "有(mock)", "UI/路由存在但业务效果为占位", "静态数据、空回调、占位页或仅 toast"),
|
|
33
|
+
("unreachable", "代码存在但入口不可达", "实现文件存在但正式入口不可达", "记录断开的入口链"),
|
|
34
|
+
("absent", "无", "系统性负向复核后确认未实现", "必须记录 negative_searches"),
|
|
35
|
+
("uncertain", "待确认", "动态行为或证据缺口无法判定", "列入待确认项"),
|
|
36
|
+
("not-applicable", "不适用", "产品或平台语义不适用", "说明适用范围"),
|
|
37
|
+
)
|
|
38
|
+
STATUS_LABEL = {status: label for status, label, _, _ in STATUS_ROWS}
|
|
39
|
+
CONFIDENCE_LABEL = {"high": "高", "medium": "中", "low": "低"}
|
|
40
|
+
|
|
41
|
+
BODY, TITLE, SUBTITLE, HEADER, ATTENTION, POSITIVE, MISSING = range(7)
|
|
42
|
+
STATUS_STYLE = {
|
|
43
|
+
"有": POSITIVE, "有(mock)": ATTENTION, "部分实现": ATTENTION,
|
|
44
|
+
"待确认": ATTENTION, "无": MISSING, "代码存在但入口不可达": MISSING,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# Style indexes follow the constants above. Wrap text in every style.
|
|
48
|
+
STYLES = f"""<styleSheet xmlns="{MAIN_NS}">
|
|
49
|
+
<fonts count="3">
|
|
50
|
+
<font><sz val="11"/><name val="Arial"/></font>
|
|
51
|
+
<font><b/><sz val="15"/><color rgb="FFFFFFFF"/><name val="Arial"/></font>
|
|
52
|
+
<font><b/><sz val="11"/><color rgb="FF17365D"/><name val="Arial"/></font>
|
|
53
|
+
</fonts>
|
|
54
|
+
<fills count="8">
|
|
55
|
+
<fill><patternFill patternType="none"/></fill>
|
|
56
|
+
<fill><patternFill patternType="gray125"/></fill>
|
|
57
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FF1F4E78"/></patternFill></fill>
|
|
58
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FFD9EAF7"/></patternFill></fill>
|
|
59
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FF8DB4E2"/></patternFill></fill>
|
|
60
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FFFFF2CC"/></patternFill></fill>
|
|
61
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FFE2F0D9"/></patternFill></fill>
|
|
62
|
+
<fill><patternFill patternType="solid"><fgColor rgb="FFFCE4D6"/></patternFill></fill>
|
|
63
|
+
</fills>
|
|
64
|
+
<borders count="2">
|
|
65
|
+
<border><left/><right/><top/><bottom/><diagonal/></border>
|
|
66
|
+
<border><left/><right/><top/><bottom style="thin"><color rgb="FFD9E2F3"/></bottom><diagonal/></border>
|
|
67
|
+
</borders>
|
|
68
|
+
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
|
|
69
|
+
<cellXfs count="7">
|
|
70
|
+
<xf fontId="0" fillId="0" borderId="1" numFmtId="0" xfId="0" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
|
|
71
|
+
<xf fontId="1" fillId="2" borderId="0" numFmtId="0" xfId="0" applyFont="1" applyFill="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>
|
|
72
|
+
<xf fontId="0" fillId="3" borderId="0" numFmtId="0" xfId="0" applyFill="1" applyAlignment="1"><alignment vertical="center" wrapText="1"/></xf>
|
|
73
|
+
<xf fontId="2" fillId="4" borderId="1" numFmtId="0" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center" wrapText="1"/></xf>
|
|
74
|
+
<xf fontId="0" fillId="5" borderId="1" numFmtId="0" xfId="0" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
|
|
75
|
+
<xf fontId="0" fillId="6" borderId="1" numFmtId="0" xfId="0" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
|
|
76
|
+
<xf fontId="0" fillId="7" borderId="1" numFmtId="0" xfId="0" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
|
|
77
|
+
</cellXfs>
|
|
78
|
+
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
|
|
79
|
+
</styleSheet>"""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class Worksheet:
|
|
84
|
+
name: str
|
|
85
|
+
rows: list[list[str]]
|
|
86
|
+
widths: list[int]
|
|
87
|
+
freeze_rows: int
|
|
88
|
+
freeze_columns: int = 0
|
|
89
|
+
merges: list[str] = field(default_factory=list)
|
|
90
|
+
row_styles: dict[int, int] = field(default_factory=dict)
|
|
91
|
+
row_heights: dict[int, int] = field(default_factory=dict)
|
|
92
|
+
status_columns: tuple[int, ...] = ()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def column_name(number: int) -> str:
|
|
96
|
+
name = ""
|
|
97
|
+
while number:
|
|
98
|
+
number, digit = divmod(number - 1, 26)
|
|
99
|
+
name = chr(ord("A") + digit) + name
|
|
100
|
+
return name
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def evidence_text(items: list[dict]) -> str:
|
|
104
|
+
return ";".join(
|
|
105
|
+
f"{item['path']}:{item['line_start']}({item['type']},{item.get('summary') or ''})"
|
|
106
|
+
for item in items
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def feature_sheet(inventory: dict) -> Worksheet:
|
|
111
|
+
repos = inventory["repositories"]
|
|
112
|
+
features = inventory["features"]
|
|
113
|
+
headers = ["一级模块", "二级模块", "三级模块", "四级模块", "入口上下文", "类型", "触发方式", "结果/目标"]
|
|
114
|
+
widths = [20, 20, 20, 20, 15, 15, 30, 30]
|
|
115
|
+
for repo in repos:
|
|
116
|
+
label = repo.get("label") or repo["id"]
|
|
117
|
+
headers.extend(f"{label}{name}" for name in ("状态", "置信度", "证据", "备注"))
|
|
118
|
+
widths.extend([19, 16, 53, 31])
|
|
119
|
+
headers.extend(["条件", "公共备注"])
|
|
120
|
+
widths.extend([30, 30])
|
|
121
|
+
|
|
122
|
+
body = []
|
|
123
|
+
for feature in features:
|
|
124
|
+
levels = list(feature["path"])
|
|
125
|
+
if not 1 <= len(levels) <= 4:
|
|
126
|
+
raise ValueError("Each feature path must have one to four levels.")
|
|
127
|
+
row = levels + [""] * (4 - len(levels))
|
|
128
|
+
row.extend([feature["entry_context"], feature["kind"], feature["trigger"], feature.get("effect") or ""])
|
|
129
|
+
for repo in repos:
|
|
130
|
+
impl = feature["implementations"][repo["id"]]
|
|
131
|
+
status, confidence = impl["status"], impl["confidence"]
|
|
132
|
+
row.extend([
|
|
133
|
+
STATUS_LABEL.get(status, status), CONFIDENCE_LABEL.get(confidence, confidence),
|
|
134
|
+
evidence_text(impl.get("evidence", [])), impl.get("notes") or "",
|
|
135
|
+
])
|
|
136
|
+
row.extend([";".join(feature.get("conditions", [])), feature.get("notes") or ""])
|
|
137
|
+
body.append(row)
|
|
138
|
+
|
|
139
|
+
last_column = column_name(len(headers))
|
|
140
|
+
merges = [f"A1:{last_column}1", f"A2:{last_column}2"]
|
|
141
|
+
for level in range(4):
|
|
142
|
+
groups = groupby(
|
|
143
|
+
enumerate(features),
|
|
144
|
+
key=lambda item: (item[1]["entry_context"], *item[1]["path"][:level + 1]),
|
|
145
|
+
)
|
|
146
|
+
for prefix, group in groups:
|
|
147
|
+
indexes = [index for index, _ in group]
|
|
148
|
+
if len(prefix) != level + 2 or len(indexes) < 2:
|
|
149
|
+
continue
|
|
150
|
+
column = column_name(level + 1)
|
|
151
|
+
merges.append(f"{column}{indexes[0] + 5}:{column}{indexes[-1] + 5}")
|
|
152
|
+
for index in indexes[1:]:
|
|
153
|
+
body[index][level] = ""
|
|
154
|
+
|
|
155
|
+
title = inventory.get("title") or "应用功能清单"
|
|
156
|
+
subtitle = f"共 {len(body)} 条功能路径;{len(repos)} 个代码仓;层级按用户可见入口与点击路径组织"
|
|
157
|
+
return Worksheet(
|
|
158
|
+
FEATURE_SHEET, [[title], [subtitle], [], headers, *body], widths,
|
|
159
|
+
freeze_rows=FEATURE_HEADER_ROW, freeze_columns=4, merges=merges,
|
|
160
|
+
row_styles={1: TITLE, 2: SUBTITLE, FEATURE_HEADER_ROW: HEADER},
|
|
161
|
+
row_heights={1: 28, 2: 22, FEATURE_HEADER_ROW: 29},
|
|
162
|
+
status_columns=tuple(range(9, 9 + 4 * len(repos), 4)),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def report_sheet(inventory: dict) -> Worksheet:
|
|
167
|
+
repos = inventory["repositories"]
|
|
168
|
+
rows = [["分析范围与质量报告"], [], ["代码仓", "平台", "修订版本", "路径"]]
|
|
169
|
+
rows.extend([
|
|
170
|
+
repo.get("label") or repo["id"], repo.get("platform") or "",
|
|
171
|
+
repo.get("revision") or "", repo["path"],
|
|
172
|
+
] for repo in repos)
|
|
173
|
+
rows.extend([[], [], ["待确认项"]])
|
|
174
|
+
question_start = len(rows)
|
|
175
|
+
questions = inventory.get("open_questions") or ["无"]
|
|
176
|
+
rows.extend([item if isinstance(item, str) else json.dumps(item, ensure_ascii=False)] for item in questions)
|
|
177
|
+
widths = [30, 17, 33, 70]
|
|
178
|
+
question_heights = {
|
|
179
|
+
number: max(28, text_height(row[0], sum(widths)))
|
|
180
|
+
for number, row in enumerate(rows[question_start:], start=question_start + 1)
|
|
181
|
+
}
|
|
182
|
+
return Worksheet(
|
|
183
|
+
REPORT_SHEET, rows, widths, freeze_rows=3,
|
|
184
|
+
merges=["A1:D1", *(f"A{number}:D{number}" for number in range(question_start, len(rows) + 1))],
|
|
185
|
+
row_styles={1: TITLE, 3: HEADER, question_start: ATTENTION},
|
|
186
|
+
row_heights={1: 28, 3: 24, question_start: 22, **question_heights},
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def text_height(value: str, width: int) -> int:
|
|
191
|
+
available = width - 2
|
|
192
|
+
lines = 0
|
|
193
|
+
for line in value.split("\n"):
|
|
194
|
+
units = sum(2 if unicodedata.east_asian_width(char) in {"F", "W"} else 1 for char in line)
|
|
195
|
+
lines += max(1, (units + available - 1) // available)
|
|
196
|
+
return min(409, 16 * lines + 3)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def excel_text(value: str) -> str:
|
|
200
|
+
# Encode XML-invalid characters and protect literal sequences Excel would decode.
|
|
201
|
+
return EXCEL_ESCAPES.sub(
|
|
202
|
+
lambda match: f"_x{ord(match[0]):04X}_" if len(match[0]) == 1 else "_x005F_" + match[0][1:],
|
|
203
|
+
value,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def worksheet_xml(sheet: Worksheet) -> bytes:
|
|
208
|
+
if len(sheet.rows) > 1_048_576 or len(sheet.widths) > 16_384:
|
|
209
|
+
raise ValueError(f"{sheet.name} exceeds the Excel worksheet size limit.")
|
|
210
|
+
root = ET.Element("worksheet", xmlns=MAIN_NS)
|
|
211
|
+
ET.SubElement(root, "dimension", ref=f"A1:{column_name(len(sheet.widths))}{len(sheet.rows)}")
|
|
212
|
+
views = ET.SubElement(root, "sheetViews")
|
|
213
|
+
view = ET.SubElement(views, "sheetView", workbookViewId="0", showGridLines="0")
|
|
214
|
+
first_cell = f"{column_name(sheet.freeze_columns + 1)}{sheet.freeze_rows + 1}"
|
|
215
|
+
active_pane = "bottomRight" if sheet.freeze_columns else "bottomLeft"
|
|
216
|
+
pane = {"ySplit": str(sheet.freeze_rows), "topLeftCell": first_cell, "activePane": active_pane, "state": "frozen"}
|
|
217
|
+
if sheet.freeze_columns:
|
|
218
|
+
pane["xSplit"] = str(sheet.freeze_columns)
|
|
219
|
+
ET.SubElement(view, "pane", pane)
|
|
220
|
+
ET.SubElement(view, "selection", pane=active_pane, activeCell=first_cell, sqref=first_cell)
|
|
221
|
+
ET.SubElement(root, "sheetFormatPr", defaultRowHeight="16")
|
|
222
|
+
columns = ET.SubElement(root, "cols")
|
|
223
|
+
for number, width in enumerate(sheet.widths, start=1):
|
|
224
|
+
ET.SubElement(columns, "col", min=str(number), max=str(number), width=str(width), customWidth="1")
|
|
225
|
+
|
|
226
|
+
data = ET.SubElement(root, "sheetData")
|
|
227
|
+
for number, values in enumerate(sheet.rows, start=1):
|
|
228
|
+
if not values:
|
|
229
|
+
continue
|
|
230
|
+
style = sheet.row_styles.get(number, BODY)
|
|
231
|
+
height = sheet.row_heights.get(number)
|
|
232
|
+
if height is None:
|
|
233
|
+
height = max(text_height(value, width) for value, width in zip(values, sheet.widths))
|
|
234
|
+
row = ET.SubElement(data, "row", r=str(number), ht=str(height), customHeight="1")
|
|
235
|
+
if style != BODY:
|
|
236
|
+
values = values + [""] * (len(sheet.widths) - len(values))
|
|
237
|
+
for column, value in enumerate(values, start=1):
|
|
238
|
+
address = f"{column_name(column)}{number}"
|
|
239
|
+
cell_style = STATUS_STYLE.get(value, style) if column in sheet.status_columns else style
|
|
240
|
+
cell = ET.SubElement(row, "c", r=address, s=str(cell_style))
|
|
241
|
+
if value:
|
|
242
|
+
if len(value.encode("utf-16-le", errors="surrogatepass")) > 65_534:
|
|
243
|
+
raise ValueError(f"{sheet.name}!{address} exceeds the Excel cell text limit.")
|
|
244
|
+
cell.set("t", "inlineStr")
|
|
245
|
+
text = ET.SubElement(ET.SubElement(cell, "is"), "t", {XML_SPACE: "preserve"})
|
|
246
|
+
text.text = excel_text(value)
|
|
247
|
+
if sheet.merges:
|
|
248
|
+
merges = ET.SubElement(root, "mergeCells", count=str(len(sheet.merges)))
|
|
249
|
+
for address in sheet.merges:
|
|
250
|
+
ET.SubElement(merges, "mergeCell", ref=address)
|
|
251
|
+
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def verify_workbook(path: Path, feature_count: int) -> int:
|
|
255
|
+
ns = {"x": MAIN_NS}
|
|
256
|
+
with ZipFile(path) as archive:
|
|
257
|
+
def read_xml(part: str, namespace: str, tag: str) -> ET.Element:
|
|
258
|
+
root = ET.fromstring(archive.read(part))
|
|
259
|
+
if root.tag != f"{{{namespace}}}{tag}":
|
|
260
|
+
raise ValueError(f"Invalid workbook part: {part}.")
|
|
261
|
+
return root
|
|
262
|
+
|
|
263
|
+
read_xml("[Content_Types].xml", CONTENT_TYPE_NS, "Types")
|
|
264
|
+
package_rels = read_xml("_rels/.rels", PACKAGE_REL_NS, "Relationships")
|
|
265
|
+
if not any(
|
|
266
|
+
rel.get("Type") == OFFICE_REL_NS + "/officeDocument"
|
|
267
|
+
and rel.get("Target", "").lstrip("/") == "xl/workbook.xml"
|
|
268
|
+
for rel in package_rels
|
|
269
|
+
):
|
|
270
|
+
raise ValueError("Workbook is missing its package relationship.")
|
|
271
|
+
|
|
272
|
+
workbook = read_xml("xl/workbook.xml", MAIN_NS, "workbook")
|
|
273
|
+
read_xml("xl/styles.xml", MAIN_NS, "styleSheet")
|
|
274
|
+
sheets = workbook.findall("x:sheets/x:sheet", ns)
|
|
275
|
+
if [sheet.get("name") for sheet in sheets] != [FEATURE_SHEET, REPORT_SHEET, LEGEND_SHEET]:
|
|
276
|
+
raise ValueError("Expected the 功能清单, 质量报告, and 状态说明 sheets in order.")
|
|
277
|
+
|
|
278
|
+
relationships = read_xml("xl/_rels/workbook.xml.rels", PACKAGE_REL_NS, "Relationships")
|
|
279
|
+
targets = {
|
|
280
|
+
rel.attrib["Id"]: rel.attrib["Target"]
|
|
281
|
+
for rel in relationships
|
|
282
|
+
if rel.get("Type") == OFFICE_REL_NS + "/worksheet"
|
|
283
|
+
}
|
|
284
|
+
worksheet_parts = set()
|
|
285
|
+
for sheet in sheets:
|
|
286
|
+
target = targets[sheet.attrib[f"{{{OFFICE_REL_NS}}}id"]]
|
|
287
|
+
part = target.lstrip("/") if target.startswith("/") else posixpath.join("xl", target)
|
|
288
|
+
part = posixpath.normpath(part)
|
|
289
|
+
if part in worksheet_parts:
|
|
290
|
+
raise ValueError(f"Multiple sheets use workbook part {part}.")
|
|
291
|
+
worksheet_parts.add(part)
|
|
292
|
+
data = read_xml(part, MAIN_NS, "worksheet").find("x:sheetData", ns)
|
|
293
|
+
if data is None:
|
|
294
|
+
raise ValueError(f"Worksheet {sheet.get('name')} has no sheet data.")
|
|
295
|
+
if sheet.get("name") == FEATURE_SHEET:
|
|
296
|
+
rows = [
|
|
297
|
+
int(row.attrib["r"])
|
|
298
|
+
for row in data.findall("x:row", ns)
|
|
299
|
+
if any(
|
|
300
|
+
cell.find("x:v", ns) is not None or cell.find("x:is", ns) is not None
|
|
301
|
+
for cell in row.findall("x:c", ns)
|
|
302
|
+
)
|
|
303
|
+
]
|
|
304
|
+
if FEATURE_HEADER_ROW not in rows:
|
|
305
|
+
raise ValueError(f"Missing feature headers on row {FEATURE_HEADER_ROW}.")
|
|
306
|
+
actual_count = sum(row > FEATURE_HEADER_ROW for row in rows)
|
|
307
|
+
if actual_count != feature_count:
|
|
308
|
+
raise ValueError(f"Expected {feature_count} feature rows, found {actual_count} feature rows.")
|
|
309
|
+
return len(sheets)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def write_workbook(output: Path, sheets: list[Worksheet], feature_count: int) -> int:
|
|
313
|
+
types = ET.Element("Types", xmlns=CONTENT_TYPE_NS)
|
|
314
|
+
ET.SubElement(types, "Default", Extension="rels", ContentType="application/vnd.openxmlformats-package.relationships+xml")
|
|
315
|
+
ET.SubElement(types, "Default", Extension="xml", ContentType="application/xml")
|
|
316
|
+
ET.SubElement(types, "Override", PartName="/xl/workbook.xml", ContentType=SHEET_TYPE + "sheet.main+xml")
|
|
317
|
+
ET.SubElement(types, "Override", PartName="/xl/styles.xml", ContentType=SHEET_TYPE + "styles+xml")
|
|
318
|
+
root_rels = ET.Element("Relationships", xmlns=PACKAGE_REL_NS)
|
|
319
|
+
ET.SubElement(root_rels, "Relationship", Id="rId1", Type=OFFICE_REL_NS + "/officeDocument", Target="xl/workbook.xml")
|
|
320
|
+
workbook_rels = ET.Element("Relationships", xmlns=PACKAGE_REL_NS)
|
|
321
|
+
ET.SubElement(workbook_rels, "Relationship", Id="rIdStyles", Type=OFFICE_REL_NS + "/styles", Target="styles.xml")
|
|
322
|
+
workbook = ET.Element("workbook", xmlns=MAIN_NS, attrib={"xmlns:r": OFFICE_REL_NS})
|
|
323
|
+
ET.SubElement(ET.SubElement(workbook, "bookViews"), "workbookView")
|
|
324
|
+
sheet_list = ET.SubElement(workbook, "sheets")
|
|
325
|
+
|
|
326
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
327
|
+
with tempfile.TemporaryDirectory(prefix=".inventory-xlsx-", dir=output.parent) as staging:
|
|
328
|
+
staged = Path(staging) / output.name
|
|
329
|
+
with ZipFile(staged, "w", compression=ZIP_DEFLATED) as archive:
|
|
330
|
+
for number, sheet in enumerate(sheets, start=1):
|
|
331
|
+
part = f"worksheets/sheet{number}.xml"
|
|
332
|
+
relation_id = f"rId{number}"
|
|
333
|
+
ET.SubElement(sheet_list, "sheet", name=sheet.name, sheetId=str(number), attrib={"r:id": relation_id})
|
|
334
|
+
ET.SubElement(workbook_rels, "Relationship", Id=relation_id, Type=OFFICE_REL_NS + "/worksheet", Target=part)
|
|
335
|
+
ET.SubElement(types, "Override", PartName=f"/xl/{part}", ContentType=SHEET_TYPE + "worksheet+xml")
|
|
336
|
+
archive.writestr(f"xl/{part}", worksheet_xml(sheet))
|
|
337
|
+
archive.writestr("xl/styles.xml", STYLES)
|
|
338
|
+
for part, element in (
|
|
339
|
+
("[Content_Types].xml", types), ("_rels/.rels", root_rels),
|
|
340
|
+
("xl/workbook.xml", workbook), ("xl/_rels/workbook.xml.rels", workbook_rels),
|
|
341
|
+
):
|
|
342
|
+
archive.writestr(part, ET.tostring(element, encoding="utf-8", xml_declaration=True))
|
|
343
|
+
sheet_count = verify_workbook(staged, feature_count)
|
|
344
|
+
staged.replace(output)
|
|
345
|
+
return sheet_count
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def main() -> None:
|
|
349
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
350
|
+
parser.add_argument("inventory", type=Path, help="validated inventory.json")
|
|
351
|
+
parser.add_argument("--output", type=Path, help="defaults to feature-inventory.xlsx next to the JSON")
|
|
352
|
+
parser.add_argument("--check", action="store_true", help="verify the existing workbook without changing it")
|
|
353
|
+
args = parser.parse_args()
|
|
354
|
+
output = args.output or args.inventory.with_name("feature-inventory.xlsx")
|
|
355
|
+
if output.suffix.lower() != ".xlsx" or output.resolve() == args.inventory.resolve():
|
|
356
|
+
parser.error("Specify an .xlsx output distinct from the input.")
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
inventory = json.loads(args.inventory.read_text(encoding="utf-8-sig"))
|
|
360
|
+
feature_count = len(inventory["features"])
|
|
361
|
+
if args.check:
|
|
362
|
+
sheet_count = verify_workbook(output, feature_count)
|
|
363
|
+
else:
|
|
364
|
+
legend = Worksheet(
|
|
365
|
+
LEGEND_SHEET, [["状态", "含义", "判定要点"], *[list(row[1:]) for row in STATUS_ROWS]],
|
|
366
|
+
[25, 43, 58], freeze_rows=1, row_styles={1: HEADER}, row_heights={1: 24},
|
|
367
|
+
)
|
|
368
|
+
sheets = [feature_sheet(inventory), report_sheet(inventory), legend]
|
|
369
|
+
sheet_count = write_workbook(output, sheets, feature_count)
|
|
370
|
+
except (BadZipFile, ET.ParseError, KeyError, TypeError, AttributeError, ValueError, OSError) as error:
|
|
371
|
+
action = "verification" if args.check else "export"
|
|
372
|
+
parser.exit(1, f"Excel {action} failed: {error}\n")
|
|
373
|
+
print(json.dumps({"output": str(output.resolve()), "features": feature_count, "sheets": sheet_count}, ensure_ascii=False))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
if __name__ == "__main__":
|
|
377
|
+
main()
|