-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplan_editor.py
More file actions
2007 lines (1706 loc) · 79.8 KB
/
Copy pathplan_editor.py
File metadata and controls
2007 lines (1706 loc) · 79.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Plan Generator for Magentic UI
Generates ready-to-import plan JSON files from templates by replacing
placeholders (e.g. {{VALIDATION_ID}}, {{APP_NAME}}) with actual values.
Supports secure PAT retrieval from Azure Key Vault (recommended) or
manual PAT via --pat / ADO_PAT env var.
Usage:
# Auto-fill from ADO work item (Key Vault PAT — recommended)
python plan_editor.py --interactive templates/MetadataTC_1-15.json \
--ado-url "https://domoreexp.visualstudio.com/MSTeams/_workitems/edit/4941424"
# CLI mode with explicit variables
python plan_editor.py --template templates/MetadataTC_1-15.json \
--ado-url "https://domoreexp.visualstudio.com/MSTeams/_workitems/edit/4941424" \
--var TEAMS_ID=admin@M365x48062851.onmicrosoft.com \
--var TEAMS_PASSWORD="mypassword" \
--output output/plan_4941424.json
python plan_editor.py --list-vars templates/MetadataTC_1-15.json
"""
import argparse
import base64
import io
import json
import os
import re
import struct
import sys
import urllib.request
import urllib.error
import zipfile
from html.parser import HTMLParser
from pathlib import Path
from typing import Dict, List, Optional, Tuple
# Force UTF-8 output on Windows so Unicode characters print correctly
if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
if sys.stderr.encoding and sys.stderr.encoding.lower() != "utf-8":
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
PLACEHOLDER_RE = re.compile(r"\{\{([A-Za-z_][A-Za-z0-9_]*)\}\}")
# Regex to parse ADO work-item URLs like:
# https://domoreexp.visualstudio.com/MSTeams/_workitems/edit/4941424/?view=edit
ADO_URL_RE = re.compile(
r"https?://([^/]+)/([^/]+)/_workitems/edit/(\d+)"
)
# Default values for common placeholders (can be overridden via --var)
DEFAULTS: Dict[str, str] = {
"TEAMS_URL": os.environ.get("TEAMS_URL", "https://teams.microsoft.com/v2/"),
"SMP_API_URL": os.environ.get("SMP_API_URL", "https://msteamspmewebapi.azurewebsites.net"),
}
# Credential placeholders that must NEVER be substituted. They stay as literal
# {{TEAMS_ID}} / {{TEAMS_PASSWORD}} in output so secrets are never baked into
# plans or uploaded. CLI --var and prompts for these are ignored.
CREDENTIAL_PLACEHOLDERS = {"TEAMS_ID", "TEAMS_PASSWORD"}
# ── Azure Key Vault PAT configuration ───────────────────────────────────
# When --pat is NOT provided, the PAT is fetched from Azure Key Vault.
# Requires: pip install azure-identity azure-keyvault-secrets
# Auth: az login (or Managed Identity / VS Code auth)
KEY_VAULT_URL = os.environ.get("KEY_VAULT_URL", "https://kv-msteamsappcert-prod.vault.azure.net/")
PAT_SECRET_NAME = os.environ.get("PAT_SECRET_NAME", "VSO-PAT")
# ADO org defaults (used when only a work-item ID or URL is given)
# Can be overridden via ADO_ORG_URL and ADO_PROJECT env vars from .env
ADO_ORG_URL = os.environ.get("ADO_ORG_URL", "https://domoreexp.visualstudio.com")
ADO_PROJECT = os.environ.get("ADO_PROJECT", "MSTeams")
# ── ADO integration ──────────────────────────────────────────────────────
class _HTMLTextExtractor(HTMLParser):
"""Strip HTML tags and return plain text, preserving line breaks."""
def __init__(self):
super().__init__()
self._parts: List[str] = []
def handle_starttag(self, tag: str, attrs):
if tag in ("br", "p", "div"):
self._parts.append("\n")
def handle_data(self, data: str):
self._parts.append(data)
def get_text(self) -> str:
return "".join(self._parts)
def _html_to_text(html: str) -> str:
parser = _HTMLTextExtractor()
parser.feed(html)
return parser.get_text()
def _extract_labeled_block(text: str, label: str, next_labels: List[str]) -> str:
"""Extract text after 'Label:' until next known label or end of text."""
if not text:
return ""
stop = "|".join(re.escape(x) for x in next_labels)
pattern = rf"{re.escape(label)}\s*:\s*(.*?)(?=\n(?:{stop})\s*:|\Z)"
m = re.search(pattern, text, re.IGNORECASE | re.DOTALL)
if not m:
return ""
return re.sub(r"\s+", " ", m.group(1)).strip()
# ── Environment file loading ────────────────────────────────────────────
def load_env_file(env_path: str = ".env") -> None:
"""Load environment variables from a .env file (only if it exists).
Uses only stdlib - no external dependencies.
Skips lines that are empty or start with '#'.
"""
if not os.path.exists(env_path):
return
try:
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith("#"):
continue
# Parse KEY=VALUE format
if "=" in line:
key, _, value = line.partition("=")
key = key.strip()
value = value.strip()
# Remove quotes if present
if (value.startswith('"') and value.endswith('"')) or \
(value.startswith("'") and value.endswith("'")):
value = value[1:-1]
# Only set if not already in environment (env vars take precedence)
if key and key not in os.environ:
os.environ[key] = value
except Exception as e:
print(f"Warning: Could not load {env_path}: {e}", file=sys.stderr)
# ── Key Vault PAT retrieval ──────────────────────────────────────────────
_cached_kv_pat: Optional[str] = None
def resolve_pat(explicit_pat: Optional[str] = None) -> str:
"""Return the ADO PAT using the following priority:
1. Explicit --pat argument
2. ADO_PAT environment variable
3. Azure Key Vault secret (KEY_VAULT_URL / PAT_SECRET_NAME)
"""
global _cached_kv_pat # noqa: PLW0603
# 1. Explicit PAT
if explicit_pat:
return explicit_pat
# 2. Environment variable
env_pat = os.environ.get("ADO_PAT", "")
if env_pat:
return env_pat
# 3. Azure Key Vault
if _cached_kv_pat:
return _cached_kv_pat
print(f" Retrieving PAT from Azure Key Vault ({KEY_VAULT_URL}) ...")
try:
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
client = SecretClient(vault_url=KEY_VAULT_URL, credential=credential)
secret = client.get_secret(PAT_SECRET_NAME)
token = secret.value or ""
if not token:
raise ValueError(f"Secret '{PAT_SECRET_NAME}' is empty")
_cached_kv_pat = token
print(" PAT retrieved successfully from Azure Key Vault.")
return _cached_kv_pat
except ImportError as exc:
print(
f"ERROR: Azure SDK not installed: {exc}\n"
" Install with: pip install azure-identity azure-keyvault-secrets",
file=sys.stderr,
)
sys.exit(1)
except Exception as exc:
print(f"ERROR: Failed to retrieve PAT from Azure Key Vault: {exc}", file=sys.stderr)
print(" Tip: run 'az login', or provide PAT via --pat / ADO_PAT env var.", file=sys.stderr)
sys.exit(1)
# ── ADO REST API ─────────────────────────────────────────────────────────
def parse_ado_url(url: str) -> Tuple[str, str, str]:
"""Extract (org_host, project, work_item_id) from an ADO URL."""
m = ADO_URL_RE.search(url)
if not m:
raise ValueError(f"Could not parse ADO URL: {url}")
return m.group(1), m.group(2), m.group(3)
def fetch_ado_work_item(org_host: str, project: str, work_item_id: str,
pat: str) -> dict:
"""Fetch work item JSON from ADO REST API (stdlib only)."""
api_url = (
f"https://{org_host}/{project}/_apis/wit/workitems/{work_item_id}"
f"?api-version=7.1"
)
token = base64.b64encode(f":{pat}".encode()).decode()
req = urllib.request.Request(api_url, headers={
"Authorization": f"Basic {token}",
"Accept": "application/json",
})
with urllib.request.urlopen(req, timeout=60) as resp:
return json.loads(resp.read().decode())
def extract_fields_from_work_item(wi: dict) -> Dict[str, str]:
"""Parse work item fields into placeholder values.
Extracts:
VALIDATION_ID — work item id
APP_NAME — from Description "AppName: ..." line
PRODUCT_ID — from AppSpecificData "Product Id: ..." (fallback: Custom.AppID)
SUBMISSION_ID — from AppSpecificData "SubmissionId: ..."
short_desc — from Description "Short Description: ..." block
long_desc — from Description "Long Description: ..." block
"""
fields = wi.get("fields", {})
result: Dict[str, str] = {}
# VALIDATION_ID = work item id
result["VALIDATION_ID"] = str(wi.get("id", ""))
# ── APP_NAME from Description HTML ──
desc_html = fields.get("System.Description", "")
desc_text = ""
if desc_html:
desc_text = _html_to_text(desc_html)
m = re.search(r"AppName\s*:\s*(.+)", desc_text)
if m:
app_name = m.group(1).strip().split("\n")[0].strip()
result["APP_NAME"] = app_name
# Extract short/long description blocks from the Description field.
short_desc = _extract_labeled_block(
desc_text,
"Short Description",
["Long Description", "App Capability", "AppID", "Manifest Version", "Languages"],
)
if short_desc:
result["short_desc"] = short_desc
result["SHORT_DESC"] = short_desc
long_desc = _extract_labeled_block(
desc_text,
"Long Description",
["App Capability", "AppID", "Manifest Version", "Languages"],
)
if long_desc:
result["long_desc"] = long_desc
result["LONG_DESC"] = long_desc
# Fallback: derive APP_NAME from Title (e.g. "Forrester AI-Dormant" → "Forrester AI")
if "APP_NAME" not in result:
title = fields.get("System.Title", "")
if title:
result["APP_NAME"] = title.split("-")[0].strip()
# ── Parse Custom.AppSpecificData for Product Id and SubmissionId ──
app_specific_html = fields.get("Custom.AppSpecificData", "")
app_specific_text = _html_to_text(app_specific_html) if app_specific_html else ""
# PRODUCT_ID from AppSpecificData "Product Id: <guid>"
# [\s\u00a0] matches regular and non-breaking spaces from HTML
m = re.search(r"Product[\s\u00a0]*Id[\s\u00a0]*:[\s\u00a0]*([0-9a-f\-]{36})", app_specific_text, re.IGNORECASE)
if not m:
m = re.search(r"Product\s*Id\s*(?:<[^>]+>)?\s*:[\s\u00a0]*([0-9a-f\-]{36})", app_specific_html, re.IGNORECASE)
if m:
result["PRODUCT_ID"] = m.group(1).strip()
else:
# Fallback: Custom.AppID field
app_id = fields.get("Custom.AppID", "")
if app_id and re.match(r"[0-9a-f]{8}-[0-9a-f]{4}", str(app_id), re.IGNORECASE):
result["PRODUCT_ID"] = str(app_id).strip()
# SUBMISSION_ID from AppSpecificData "SubmissionId: <number>"
# Try on plain text first, then fall back to raw HTML (handles <b>SubmissionId</b>: format)
m = re.search(r"SubmissionId[\s\u00a0]*:[\s\u00a0]*(\d+)", app_specific_text, re.IGNORECASE)
if not m:
m = re.search(r"SubmissionId\s*(?:<[^>]+>)?\s*:[\s\u00a0]*(\d+)", app_specific_html, re.IGNORECASE)
if m:
result["SUBMISSION_ID"] = m.group(1).strip()
else:
# Fallback: try known direct ADO field names
for field_name in ("Custom.SubmissionID", "Custom.SubmissionId",
"Custom.Submissionid", "Custom.submission_id"):
val = fields.get(field_name, "")
if val and str(val).strip().isdigit():
result["SUBMISSION_ID"] = str(val).strip()
break
# Fallbacks for description fields from direct custom fields.
if "short_desc" not in result:
for field_name in ("Custom.ShortDescription", "Custom.ShortDesc"):
val = str(fields.get(field_name, "")).strip()
if val:
result["short_desc"] = val
result["SHORT_DESC"] = val
break
if "long_desc" not in result:
for field_name in ("Custom.LongDescription", "Custom.LongDesc"):
val = str(fields.get(field_name, "")).strip()
if val:
result["long_desc"] = val
result["LONG_DESC"] = val
break
return result
def fetch_and_extract(ado_url: str, pat: str) -> Dict[str, str]:
"""One-shot: parse ADO URL → fetch work item → extract all fields."""
org_host, project, wi_id = parse_ado_url(ado_url)
print(f" Parsed ADO URL → VALIDATION_ID = {wi_id}")
print(f" Fetching work item {wi_id} from ADO API ...")
wi = fetch_ado_work_item(org_host, project, wi_id, pat)
extracted = extract_fields_from_work_item(wi)
# Print what we found
for k, v in sorted(extracted.items()):
print(f" Extracted → {k} = {v}")
# Warn about fields we couldn't extract
expected_from_ado = {
"VALIDATION_ID", "APP_NAME", "PRODUCT_ID", "SUBMISSION_ID", "short_desc", "long_desc"
}
missing = expected_from_ado - set(extracted.keys())
if missing:
print(f" Warning: Could not auto-extract: {', '.join(sorted(missing))}")
return extracted
# ── SMP API + PNG dimension extraction ──────────────────────────────────
def read_png_dimensions_from_bytes(data: bytes) -> Tuple[int, int]:
"""Return (width, height) from a PNG file's IHDR chunk (stdlib only).
PNG layout:
bytes 0-7 : 8-byte PNG signature
bytes 8-11 : IHDR chunk length (always 13)
bytes 12-15 : chunk type "IHDR"
bytes 16-19 : image width (big-endian uint32)
bytes 20-23 : image height (big-endian uint32)
"""
PNG_SIGNATURE = b'\x89PNG\r\n\x1a\n'
if len(data) < 24:
raise ValueError("File too short to be a valid PNG")
if data[:8] != PNG_SIGNATURE:
raise ValueError("Not a valid PNG file (bad signature)")
if data[12:16] != b'IHDR':
raise ValueError("First chunk is not IHDR")
width = struct.unpack('>I', data[16:20])[0]
height = struct.unpack('>I', data[20:24])[0]
return width, height
def fetch_smp_sasuri(api_base_url: str, product_id: str, submission_id: str,
pat: Optional[str] = None) -> str:
"""Call the SMP WorkFlow Manifest API and return the SAS URI for the zip package.
Endpoint: GET {api_base_url}/api/GetSMPWorkFlowManifestDetails/{productId}/{submissionId}
The response JSON contains a top-level "sasUri" field with the Azure Blob
Storage SAS URL that can be used to download the app package zip.
"""
url = (
f"{api_base_url.rstrip('/')}"
f"/api/GetSMPWorkFlowManifestDetails/{product_id}/{submission_id}"
)
headers: Dict[str, str] = {"Accept": "application/json"}
if pat:
token = base64.b64encode(f":{pat}".encode()).decode()
headers["Authorization"] = f"Basic {token}"
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
payload = json.loads(resp.read().decode())
except urllib.error.HTTPError as exc:
raise RuntimeError(
f"SMP API returned HTTP {exc.code} for {url}"
) from exc
# Unwrap single-element list responses
if isinstance(payload, list):
if not payload:
raise ValueError("SMP API returned an empty list")
payload = payload[0]
sas_uri = payload.get("sasUri", "")
if not sas_uri:
raise ValueError(
f"Could not find 'sasUri' in SMP API response. "
f"Available keys: {list(payload.keys())}"
)
return str(sas_uri)
def analyze_png_background(data: bytes) -> Dict[str, str]:
"""Analyze a PNG file's background compliance using Pillow.
Checks:
- Is the image square (width == height)?
- Are all pixels either fully opaque (alpha=255) or fully transparent (alpha=0)?
Semi-transparent pixels (0 < alpha < 255) are non-compliant.
- What is the background type: SOLID, TRANSPARENT, or NON_COMPLIANT?
Returns a dict with keys (STEM is filled in by the caller):
IS_SQUARE → "PASS" / "FAIL"
BACKGROUND_TYPE → "SOLID" / "TRANSPARENT" / "NON_COMPLIANT"
BG_COMPLIANT → "PASS" / "FAIL"
SEMI_TRANSPARENT_COUNT → number of semi-transparent pixels as string
Requires Pillow. Returns an empty dict if Pillow is unavailable.
"""
try:
from PIL import Image # type: ignore[import-not-found]
except ImportError:
print(" Note: Pillow not installed — skipping background analysis. "
"Install with: pip install Pillow")
return {}
img = Image.open(io.BytesIO(data)).convert("RGBA")
w, h = img.size
pixels = list(img.getdata())
total = len(pixels)
is_square = w == h
# ── Strict alpha counts (used for BG_TYPE / BG_COMPLIANT) ────────────
semi_transparent = sum(1 for _, _, _, a in pixels if 0 < a < 255)
fully_transparent = sum(1 for _, _, _, a in pixels if a == 0)
if semi_transparent > 0:
bg_type = "NON_COMPLIANT"
elif fully_transparent > 0:
bg_type = "TRANSPARENT"
else:
bg_type = "SOLID"
bg_compliant = bg_type in ("SOLID", "TRANSPARENT")
result: Dict[str, str] = {
"IS_SQUARE": "PASS" if is_square else "FAIL",
"BACKGROUND_TYPE": bg_type,
"BG_COMPLIANT": "PASS" if bg_compliant else "FAIL",
"SEMI_TRANSPARENT_COUNT": str(semi_transparent),
}
# ── Color / outline-type classification (threshold-based) ────────────
# Uses lenient alpha thresholds so anti-aliased edge pixels (common in
# PNG exports) don't block classification.
#
# effectively transparent : alpha <= 10
# effectively opaque : alpha >= 245
# anti-aliasing edge : everything in between (tolerated)
#
# WHITE_ON_TRANSPARENT — all effectively-opaque pixels are white
# AND the image has effectively-transparent pixels
# TRANSPARENT_ON_WHITE — all effectively-opaque pixels are white
# AND the image has NO effectively-transparent pixels
# (transparent pixels are the "symbol cutout")
# NON_COMPLIANT — any effectively-opaque pixel is non-white (colored)
WHITE_THRESHOLD = 200 # R, G, B all >= this → "white"
ALPHA_OPAQUE_TH = 245 # alpha >= this → "effectively opaque"
ALPHA_TRANSP_TH = 10 # alpha <= this → "effectively transparent"
effectively_opaque = [(r, g, b, a) for r, g, b, a in pixels if a >= ALPHA_OPAQUE_TH]
effectively_transparent = [(r, g, b, a) for r, g, b, a in pixels if a <= ALPHA_TRANSP_TH]
non_white_opaque = [
(r, g, b, a) for r, g, b, a in effectively_opaque
if not (r >= WHITE_THRESHOLD and g >= WHITE_THRESHOLD and b >= WHITE_THRESHOLD)
]
has_eff_transparent = len(effectively_transparent) > 0
has_eff_opaque = len(effectively_opaque) > 0
all_opaque_white = len(non_white_opaque) == 0
if not has_eff_opaque:
# Entirely transparent image — nothing to classify
color_type = "NON_COMPLIANT"
color_type_note = "image contains no opaque pixels"
elif not all_opaque_white:
color_type = "NON_COMPLIANT"
color_type_note = (
f"{len(non_white_opaque)} non-white opaque pixel(s) found "
f"(colored content detected)"
)
elif has_eff_transparent:
color_type = "WHITE_ON_TRANSPARENT"
color_type_note = (
f"{len(effectively_opaque)} white px, "
f"{len(effectively_transparent)} transparent px"
+ (f", {semi_transparent} anti-aliased edge px" if semi_transparent else "")
)
else:
# All opaque + white, no transparent pixels → likely transparent-on-white
color_type = "TRANSPARENT_ON_WHITE"
color_type_note = (
f"{len(effectively_opaque)} white opaque px"
+ (f", {semi_transparent} anti-aliased edge px" if semi_transparent else "")
)
result["COLOR_TYPE"] = color_type
result["COLOR_TYPE_NOTE"] = color_type_note
# ── Padding check (threshold-based bounding box) ─────────────────────
# "Symbol" pixels = anything with alpha > ALPHA_TRANSP_TH (catches both
# opaque content and anti-aliased edge pixels).
# Extra padding = more than PADDING_THRESHOLD px of empty space on any side.
PADDING_THRESHOLD = 2
try:
from PIL import Image as _PILImage # already imported above
if color_type in ("WHITE_ON_TRANSPARENT", "TRANSPARENT_ON_WHITE"):
# Build a binary mask: 255 where pixel is "symbol content", 0 where background
if color_type == "WHITE_ON_TRANSPARENT":
# Symbol = opaque/semi-transparent pixels (alpha > ALPHA_TRANSP_TH)
mask = _PILImage.new("L", (w, h), 0)
mask_data = [255 if a > ALPHA_TRANSP_TH else 0 for _, _, _, a in pixels]
else:
# TRANSPARENT_ON_WHITE: symbol = transparent pixels (the cutout)
mask = _PILImage.new("L", (w, h), 0)
mask_data = [255 if a <= ALPHA_TRANSP_TH else 0 for _, _, _, a in pixels]
mask.putdata(mask_data)
bbox = mask.getbbox()
if bbox:
bleft, btop, bright, bbottom = bbox
pad_left = bleft
pad_top = btop
pad_right = w - bright
pad_bottom = h - bbottom
has_extra = any(
p > PADDING_THRESHOLD
for p in (pad_left, pad_top, pad_right, pad_bottom)
)
result["PADDING_STATUS"] = "FAIL" if has_extra else "PASS"
result["PADDING_INFO"] = (
f"symbol {bright - bleft}x{bbottom - btop}px; "
f"padding L:{pad_left} T:{pad_top} R:{pad_right} B:{pad_bottom}"
)
else:
result["PADDING_STATUS"] = "UNKNOWN"
result["PADDING_INFO"] = "Mask is empty — could not determine bounding box"
else:
# NON_COMPLIANT color type — still try a best-effort bounding box
# using any non-transparent pixel as "content"
mask_data = [255 if a > ALPHA_TRANSP_TH else 0 for _, _, _, a in pixels]
from PIL import Image as _PIL2
mask = _PIL2.new("L", (w, h), 0)
mask.putdata(mask_data)
bbox = mask.getbbox()
if bbox:
bleft, btop, bright, bbottom = bbox
pad_left = bleft
pad_top = btop
pad_right = w - bright
pad_bottom = h - bbottom
has_extra = any(
p > PADDING_THRESHOLD
for p in (pad_left, pad_top, pad_right, pad_bottom)
)
result["PADDING_STATUS"] = "FAIL" if has_extra else "PASS"
result["PADDING_INFO"] = (
f"symbol {bright - bleft}x{bbottom - btop}px (best-effort); "
f"padding L:{pad_left} T:{pad_top} R:{pad_right} B:{pad_bottom}"
)
else:
result["PADDING_STATUS"] = "UNKNOWN"
result["PADDING_INFO"] = "No content pixels found"
except Exception as exc:
result["PADDING_STATUS"] = "UNKNOWN"
result["PADDING_INFO"] = f"Padding analysis failed: {exc}"
return result
def download_zip_and_get_png_dimensions(sasuri: str) -> Dict[str, str]:
"""Download a zip from the SAS URI, locate all PNG files inside, and
return a variable dict with dimensions and background compliance info.
For example, if the zip contains:
color.png (192 × 192, solid background)
outline.png (32 × 32, transparent background)
The returned dict will include:
COLOR_WIDTH, COLOR_HEIGHT, COLOR_IS_SQUARE, COLOR_BACKGROUND_TYPE,
COLOR_BG_COMPLIANT, COLOR_SEMI_TRANSPARENT_COUNT
OUTLINE_WIDTH, OUTLINE_HEIGHT, OUTLINE_IS_SQUARE, ...
Use these keys as placeholders in your template, e.g. {{COLOR_WIDTH}},
{{COLOR_BACKGROUND_TYPE}}, {{COLOR_BG_COMPLIANT}}.
"""
print(f" Downloading zip package from SAS URI ...")
try:
with urllib.request.urlopen(sasuri, timeout=120) as resp:
zip_data = resp.read()
except Exception as exc:
raise RuntimeError(f"Failed to download zip from SAS URI: {exc}") from exc
print(f" Downloaded {len(zip_data):,} bytes. Scanning for PNG files ...")
variables: Dict[str, str] = {}
with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:
# ── Parse manifest.json for icons section ─────────────────────────
manifest_entries = [
name for name in zf.namelist()
if Path(name).name.lower() == "manifest.json"
]
if manifest_entries:
try:
with zf.open(manifest_entries[0]) as mf:
manifest = json.loads(mf.read().decode("utf-8"))
icons = manifest.get("icons", {})
color_val = icons.get("color", "")
outline_val = icons.get("outline", "")
variables["MANIFEST_HAS_COLOR_ICON"] = "YES" if color_val else "NO"
variables["MANIFEST_HAS_OUTLINE_ICON"] = "YES" if outline_val else "NO"
variables["MANIFEST_COLOR_ICON_VALUE"] = color_val
variables["MANIFEST_OUTLINE_ICON_VALUE"] = outline_val
print(f" manifest.json icons.color = {color_val!r}")
print(f" manifest.json icons.outline = {outline_val!r}")
except Exception as exc:
print(f" Warning: Could not parse manifest.json: {exc}")
variables["MANIFEST_HAS_COLOR_ICON"] = "UNKNOWN"
variables["MANIFEST_HAS_OUTLINE_ICON"] = "UNKNOWN"
else:
print(" Warning: manifest.json not found in zip package.")
variables["MANIFEST_HAS_COLOR_ICON"] = "MISSING"
variables["MANIFEST_HAS_OUTLINE_ICON"] = "MISSING"
png_entries = [name for name in zf.namelist() if name.lower().endswith(".png")]
if not png_entries:
print(" Warning: No PNG files found inside the zip package.")
return variables
print(f" Found {len(png_entries)} PNG file(s): {png_entries}")
raw_bytes: Dict[str, bytes] = {} # stem → raw bytes (for shape comparison)
for entry in png_entries:
# Derive a safe placeholder stem: "icons/color.png" → "COLOR"
stem = (
Path(entry).stem
.upper()
.replace("-", "_")
.replace(" ", "_")
.replace(".", "_")
)
# Normalize common icon filename variants to expected stem names
# e.g. "icon-color.png" → ICON_COLOR → COLOR
# "icon-outline.png" → ICON_OUTLINE → OUTLINE
STEM_MAP = {
"ICON_COLOR": "COLOR",
"COLOR_ICON": "COLOR",
"ICON_OUTLINE": "OUTLINE",
"OUTLINE_ICON": "OUTLINE",
}
stem = STEM_MAP.get(stem, stem)
try:
with zf.open(entry) as f:
data = f.read()
raw_bytes[stem] = data
width, height = read_png_dimensions_from_bytes(data)
variables[f"{stem}_WIDTH"] = str(width)
variables[f"{stem}_HEIGHT"] = str(height)
print(f" {entry}: {width} × {height}")
# Background compliance analysis (requires Pillow)
bg_info = analyze_png_background(data)
for key, val in bg_info.items():
variables[f"{stem}_{key}"] = val
print(f" {stem}_{key} = {val}")
except Exception as exc:
print(f" Warning: Could not read dimensions from {entry}: {exc}")
return variables
def fetch_png_dimensions_from_smp(api_base_url: str, product_id: str, submission_id: str,
pat: Optional[str] = None) -> Dict[str, str]:
"""End-to-end: call SMP API → download zip → return PNG dimension variables.
Returns an empty dict (with a warning) rather than raising if anything fails,
so the rest of plan generation can continue uninterrupted.
"""
print(f"\n── Fetching PNG dimensions from SMP API ──")
print(f" PRODUCT_ID = {product_id}")
print(f" SUBMISSION_ID = {submission_id}")
try:
sasuri = fetch_smp_sasuri(api_base_url, product_id, submission_id, pat)
print(f" SAS URI obtained (length={len(sasuri)})")
dims = download_zip_and_get_png_dimensions(sasuri)
for k, v in sorted(dims.items()):
print(f" Extracted → {k} = {v}")
return dims
except Exception as exc:
print(f" Warning: PNG dimension extraction failed: {exc}", file=sys.stderr)
return {}
# ── Test case framework ──────────────────────────────────────────────────
from typing import Callable # noqa: E402 (already imported via typing above)
def _tc(tc_id: str, title: str, check: Callable[[Dict[str, str]], Tuple[bool, str]],
recommendation: str = "") -> dict:
return {"id": tc_id, "title": title, "check": check, "recommendation": recommendation}
# ---------------------------------------------------------------------------
# Icon test cases — evaluated against the variables dict (populated from the
# zip package via the SMP API).
# ---------------------------------------------------------------------------
def _check_color_icon(v: Dict[str, str]) -> Tuple[bool, str]:
"""TC-1140.4.1.2.1 — Combined check:
1. Color icon must be exactly 192x192 px (square).
2. Must sit on a solid or fully transparent background (no semi-transparent pixels).
"""
w = v.get("COLOR_WIDTH", "")
h = v.get("COLOR_HEIGHT", "")
is_square = v.get("COLOR_IS_SQUARE", "")
bg_type = v.get("COLOR_BACKGROUND_TYPE", "")
semi = v.get("COLOR_SEMI_TRANSPARENT_COUNT", "0")
findings: List[str] = []
passed = True
# --- Dimension check ---
if not w or not h:
passed = False
findings.append("Dimensions unavailable (SMP data missing)")
elif w == "192" and h == "192":
findings.append(f"Dimensions: {w}x{h} px (PASS)")
else:
passed = False
findings.append(f"Dimensions: {w}x{h} px -- expected 192x192 px (FAIL)")
# --- Square check ---
if is_square and is_square != "PASS":
passed = False
findings.append("Icon is not square (FAIL)")
# --- Background check ---
if not bg_type:
passed = False
findings.append("Background type unavailable (Pillow not installed or SMP data missing)")
elif bg_type == "SOLID":
findings.append("Background: solid / fully opaque (PASS)")
elif bg_type == "TRANSPARENT":
findings.append("Background: fully transparent (PASS)")
else:
passed = False
findings.append(
f"Background: non-compliant -- {semi} semi-transparent pixel(s) found "
f"(alpha must be 0 or 255 only) (FAIL)"
)
return passed, "; ".join(findings)
def _check_outline_icon(v: Dict[str, str]) -> Tuple[bool, str]:
"""TC-1140.4.1.2.2 — Combined check for outline icon:
1. Must be exactly 32x32 pixels.
2. Must be white with a transparent background OR transparent with a white background.
3. Must not have any extra padding around the symbol.
"""
w = v.get("OUTLINE_WIDTH", "")
h = v.get("OUTLINE_HEIGHT", "")
color_type = v.get("OUTLINE_COLOR_TYPE", "")
color_note = v.get("OUTLINE_COLOR_TYPE_NOTE", "")
padding_st = v.get("OUTLINE_PADDING_STATUS", "")
padding_info = v.get("OUTLINE_PADDING_INFO", "")
semi = v.get("OUTLINE_SEMI_TRANSPARENT_COUNT", "0")
findings: List[str] = []
passed = True
# --- Dimension check ---
if not w or not h:
passed = False
findings.append("Dimensions unavailable (SMP data missing)")
elif w == "32" and h == "32":
findings.append(f"Dimensions: {w}x{h} px (PASS)")
else:
passed = False
findings.append(f"Dimensions: {w}x{h} px -- expected 32x32 px (FAIL)")
# --- Color / background check ---
if not color_type:
passed = False
findings.append(
"Color type unavailable (Pillow not installed or SMP data missing)"
)
elif color_type == "WHITE_ON_TRANSPARENT":
note = f" ({color_note})" if color_note else ""
findings.append(f"Color: white symbol on transparent background{note} (PASS)")
elif color_type == "TRANSPARENT_ON_WHITE":
note = f" ({color_note})" if color_note else ""
findings.append(f"Color: transparent symbol on white background{note} (PASS)")
else:
passed = False
findings.append(
f"Color: non-compliant -- {semi} semi-transparent pixel(s) detected; "
f"outline icon must be white-on-transparent or transparent-on-white (FAIL)"
)
# --- Padding check ---
if padding_st == "PASS":
findings.append(f"Padding: none detected ({padding_info}) (PASS)")
elif padding_st == "FAIL":
passed = False
findings.append(f"Padding: extra padding detected -- {padding_info} (FAIL)")
elif padding_st == "UNKNOWN" and padding_info:
findings.append(f"Padding: {padding_info} (could not verify)")
return passed, "; ".join(findings)
def _check_icons_manifest(v: Dict[str, str]) -> Tuple[bool, str]:
"""TC-1140.4.1.2.4 — App package must contain both color and outline icon
entries in the manifest.json 'icons' section.
"""
has_color = v.get("MANIFEST_HAS_COLOR_ICON", "")
has_outline = v.get("MANIFEST_HAS_OUTLINE_ICON", "")
color_val = v.get("MANIFEST_COLOR_ICON_VALUE", "")
outline_val = v.get("MANIFEST_OUTLINE_ICON_VALUE", "")
findings: List[str] = []
passed = True
if has_color == "MISSING" or has_outline == "MISSING":
return False, "manifest.json not found in the app package zip (FAIL)"
if has_color == "UNKNOWN" or has_outline == "UNKNOWN":
return False, "manifest.json could not be parsed (FAIL)"
if has_color == "YES":
findings.append(f'icons.color = "{color_val}" (PASS)')
else:
passed = False
findings.append('icons.color entry missing from manifest.json (FAIL)')
if has_outline == "YES":
findings.append(f'icons.outline = "{outline_val}" (PASS)')
else:
passed = False
findings.append('icons.outline entry missing from manifest.json (FAIL)')
return passed, "; ".join(findings)
def _check_icon_mismatch(v: Dict[str, str]) -> Tuple[bool, str]:
"""TC-1140.4.1.2.5 — Mismatch between app color and outline icon.
Passes only when BOTH:
- TC-1140.4.1.2.1 (color icon) passes
- TC-1140.4.1.2.2 (outline icon) passes
Fails otherwise.
"""
color_pass, color_reason = _check_color_icon(v)
outline_pass, outline_reason = _check_outline_icon(v)
if color_pass and outline_pass:
return True, (
"No mismatch detected: "
"TC-1140.4.1.2.1 (color icon) and TC-1140.4.1.2.2 (outline icon) both PASS."
)
reasons: List[str] = []
if not color_pass:
reasons.append(f"TC-1140.4.1.2.1 failed ({color_reason})")
if not outline_pass:
reasons.append(f"TC-1140.4.1.2.2 failed ({outline_reason})")
return False, "Mismatch detected between color and outline icon checks: " + "; ".join(reasons)
# Master list of icon-related test cases (extend freely)
ICON_TEST_CASES: List[dict] = [
_tc(
"1140.4.1.2.1",
"Incorrect dimensions of color icon",
_check_color_icon,
recommendation=(
"The color version of your icon must be 192x192 pixels. Your icon symbol can be "
"any color or colors, but it must sit on a solid or fully transparent square "
"background. Every pixel's alpha must be either 0 (fully transparent) or 255 "
"(fully opaque) -- no semi-transparent pixels allowed. "
"Re-export as a 192x192 square PNG and resubmit the package."
),
),
_tc(
"1140.4.1.2.2",
"Outline icon not transparent",
_check_outline_icon,
recommendation=(
"The outline icon must be exactly 32x32 pixels. It can be white with a transparent "
"background or transparent with a white background -- no other colors or "
"semi-transparent pixels are allowed. The icon symbol must not have any extra "
"padding around it; the content should fill the canvas without excessive surrounding "
"empty space. Re-export as a 32x32 square PNG and resubmit the package."
),
),
_tc(
"1140.4.1.2.4",
"App package does not contain both icons",
_check_icons_manifest,
recommendation=(
"The app package (.zip) manifest.json must declare both icons under the 'icons' "
"section: \"color\" (pointing to the color PNG) and \"outline\" (pointing to the "
"outline PNG). Add the missing entry to manifest.json and resubmit the package."
),
),
_tc(
"1140.4.1.2.5",
"Mismatch between app color and outline icon",
_check_icon_mismatch,
recommendation=(
"Ensure both icon validations pass together: "
"TC-1140.4.1.2.1 (color icon) and TC-1140.4.1.2.2 (outline icon). "
"Fix whichever icon check is failing and resubmit."
),
),
]
def run_icon_test_cases(variables: Dict[str, str]) -> List[dict]:
"""Run all ICON_TEST_CASES against the resolved variables dict.
Returns a list of result dicts:
{id, title, result: "PASS"|"FAIL"|"SKIP", reason, recommendation}
"""
results: List[dict] = []
for tc in ICON_TEST_CASES:
try:
passed, reason = tc["check"](variables)
results.append({
"id": tc["id"],
"title": tc["title"],
"result": "PASS" if passed else "FAIL",
"reason": reason,
# recommendation only included on FAIL
"recommendation": tc["recommendation"] if not passed else "",
})
except Exception as exc:
results.append({
"id": tc["id"],
"title": tc["title"],
"result": "SKIP",
"reason": f"Error during evaluation: {exc}",
"recommendation": tc["recommendation"],
})
return results
def print_test_report(results: List[dict], app_name: str = "", validation_id: str = "") -> None:
"""Print a formatted test report to stdout."""
header = "Icon Test Case Report"
if app_name:
header += f" -- {app_name}"
if validation_id:
header += f" (ID: {validation_id})"
print(f"\n{'='*60}")
print(header)