@orbit-build/cli 1.9.1 → 1.9.2

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.
@@ -12,11 +12,13 @@ import struct
12
12
  import subprocess
13
13
  import sys
14
14
  import zipfile
15
+ import zlib
15
16
  from datetime import date
16
17
  from pathlib import Path, PurePosixPath
17
18
  from typing import Any
18
19
  from xml.etree import ElementTree
19
20
 
21
+ from evidence_freeze import evidence_differences
20
22
  from project_utils import (
21
23
  build_directory,
22
24
  control_path,
@@ -28,8 +30,6 @@ from project_utils import (
28
30
  question_numbers,
29
31
  )
30
32
  from script_runtime import configure_utf8_output
31
- from evidence_freeze import evidence_differences
32
-
33
33
 
34
34
  INPUT_SUFFIXES = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
35
35
  SUPPORT_EXCLUDED_PARTS = {
@@ -54,7 +54,13 @@ GENERIC_FIGURE_STEMS = {
54
54
  "result",
55
55
  "summary",
56
56
  }
57
- RESULT_EXCEPTION_SCOPES = {"filename", "headers", "sheet_names", "encoding"}
57
+ RESULT_EXCEPTION_SCOPES = {
58
+ "filename",
59
+ "headers",
60
+ "sheet_names",
61
+ "encoding",
62
+ "line_endings",
63
+ }
58
64
  HAN_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
59
65
  SPREADSHEET_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
60
66
  OFFICE_REL_NS = (
@@ -69,6 +75,26 @@ SCRATCH_DELIVERY_NAMES = {
69
75
  "rebuild_support.ps1",
70
76
  "verify_results.py",
71
77
  }
78
+ PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
79
+ PNG_MAX_CHUNK_BYTES = 64 * 1024 * 1024
80
+ PNG_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024
81
+ PNG_COLOR_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
82
+ PNG_VALID_BIT_DEPTHS = {
83
+ 0: {1, 2, 4, 8, 16},
84
+ 2: {8, 16},
85
+ 3: {1, 2, 4, 8},
86
+ 4: {8, 16},
87
+ 6: {8, 16},
88
+ }
89
+ PNG_ADAM7_PASSES = (
90
+ (0, 0, 8, 8),
91
+ (4, 0, 8, 8),
92
+ (0, 4, 4, 8),
93
+ (2, 0, 4, 4),
94
+ (0, 2, 2, 4),
95
+ (1, 0, 2, 2),
96
+ (0, 1, 1, 2),
97
+ )
72
98
 
73
99
 
74
100
  def sha256(path: Path) -> str:
@@ -165,31 +191,58 @@ def fixed_schema_source_error(root: Path, value: str) -> str | None:
165
191
  return None
166
192
 
167
193
 
168
- def delimited_header(
169
- path: Path, delimiter: str, allow_prescribed_encoding: bool = False
170
- ) -> tuple[bool, list[str]]:
194
+ def delimited_text(
195
+ path: Path, allow_prescribed_encoding: bool = False
196
+ ) -> tuple[bool, str, str]:
171
197
  raw = path.read_bytes()
172
198
  has_utf8_bom = raw.startswith(b"\xef\xbb\xbf")
173
- encodings = (
174
- ("utf-8-sig", "gb18030", "utf-16")
175
- if allow_prescribed_encoding
176
- else ("utf-8-sig",)
177
- )
199
+ if has_utf8_bom:
200
+ encodings = (("utf-8-sig", "utf-8-sig"),)
201
+ elif raw.startswith((b"\xff\xfe", b"\xfe\xff")):
202
+ encodings = (("utf-16", "utf-16"),) if allow_prescribed_encoding else ()
203
+ else:
204
+ encodings = (("utf-8", "utf-8"),)
205
+ if allow_prescribed_encoding:
206
+ encodings += (("gb18030", "gb18030"),)
178
207
  decode_error: UnicodeDecodeError | None = None
179
- for encoding in encodings:
208
+ for codec, canonical_encoding in encodings:
180
209
  try:
181
- text = raw.decode(encoding)
210
+ text = raw.decode(codec)
182
211
  break
183
212
  except UnicodeDecodeError as error:
184
213
  decode_error = error
185
214
  else:
186
- assert decode_error is not None
187
- raise decode_error
215
+ if decode_error is not None:
216
+ raise decode_error
217
+ raise UnicodeDecodeError(
218
+ "utf-8", raw, 0, min(len(raw), 1), "encoding is not permitted"
219
+ )
220
+ return has_utf8_bom, canonical_encoding, text
221
+
222
+
223
+ def delimited_header(
224
+ path: Path, delimiter: str, allow_prescribed_encoding: bool = False
225
+ ) -> tuple[bool, str, list[str]]:
226
+ has_utf8_bom, encoding, text = delimited_text(
227
+ path, allow_prescribed_encoding
228
+ )
188
229
  for row in csv.reader(io.StringIO(text), delimiter=delimiter):
189
230
  headers = [cell.strip() for cell in row]
190
231
  if any(headers):
191
- return has_utf8_bom, headers
192
- return has_utf8_bom, []
232
+ return has_utf8_bom, encoding, headers
233
+ return has_utf8_bom, encoding, []
234
+
235
+
236
+ def line_ending_style(text: str) -> str:
237
+ without_crlf = text.replace("\r\n", "")
238
+ styles = []
239
+ if "\r\n" in text:
240
+ styles.append("CRLF")
241
+ if "\n" in without_crlf:
242
+ styles.append("LF")
243
+ if "\r" in without_crlf:
244
+ styles.append("CR")
245
+ return "+".join(styles) if styles else "none"
193
246
 
194
247
 
195
248
  def xlsx_sheet_headers(path: Path) -> list[tuple[str, list[str]]]:
@@ -447,7 +500,7 @@ def result_artifact_contract_errors(
447
500
  f"fixed-schema exception uses Excel-only scope for {relative}: sheet_names"
448
501
  )
449
502
  try:
450
- has_bom, headers = delimited_header(
503
+ has_bom, _, headers = delimited_header(
451
504
  path,
452
505
  "\t" if suffix == ".tsv" else ",",
453
506
  allow_prescribed_encoding="encoding" in allowances,
@@ -482,9 +535,11 @@ def result_artifact_contract_errors(
482
535
  + ", ".join(non_chinese)
483
536
  )
484
537
  elif suffix == ".xlsx":
485
- if "encoding" in allowances:
538
+ irrelevant = allowances & {"encoding", "line_endings"}
539
+ if irrelevant:
486
540
  errors.append(
487
- f"fixed-schema exception uses CSV-only scope for {relative}: encoding"
541
+ f"fixed-schema exception uses CSV-only scope for {relative}: "
542
+ + ", ".join(sorted(irrelevant))
488
543
  )
489
544
  try:
490
545
  sheets = xlsx_sheet_headers(path)
@@ -514,9 +569,11 @@ def result_artifact_contract_errors(
514
569
  + ", ".join(non_chinese)
515
570
  )
516
571
  else:
517
- if "encoding" in allowances:
572
+ irrelevant = allowances & {"encoding", "line_endings"}
573
+ if irrelevant:
518
574
  errors.append(
519
- f"fixed-schema exception uses CSV-only scope for {relative}: encoding"
575
+ f"fixed-schema exception uses CSV-only scope for {relative}: "
576
+ + ", ".join(sorted(irrelevant))
520
577
  )
521
578
  required_scopes = set()
522
579
  if flags["require_chinese_headers"]:
@@ -557,6 +614,20 @@ def figure_artifact_contract_errors(
557
614
  ):
558
615
  errors.append("result_artifacts.min_png_dpi must be a number >= 300")
559
616
  minimum_dpi = 300
617
+ minimum_short_edge = profile.get("min_png_short_edge_px", 600)
618
+ minimum_long_edge = profile.get("min_png_long_edge_px", 1000)
619
+ for field, value, minimum in (
620
+ ("min_png_short_edge_px", minimum_short_edge, 600),
621
+ ("min_png_long_edge_px", minimum_long_edge, 1000),
622
+ ):
623
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
624
+ errors.append(
625
+ f"result_artifacts.{field} must be an integer >= {minimum}"
626
+ )
627
+ if not isinstance(minimum_short_edge, int) or isinstance(minimum_short_edge, bool):
628
+ minimum_short_edge = 600
629
+ if not isinstance(minimum_long_edge, int) or isinstance(minimum_long_edge, bool):
630
+ minimum_long_edge = 1000
560
631
  figures = root / "figures"
561
632
  if not figures.is_dir() or figures.is_symlink():
562
633
  return errors
@@ -574,7 +645,18 @@ def figure_artifact_contract_errors(
574
645
  errors.append(
575
646
  f"figure filename must be descriptive Chinese, not a generic name: {relative}"
576
647
  )
577
- dpi = png_dpi(path)
648
+ metadata = png_metadata(path)
649
+ if metadata is None:
650
+ errors.append(
651
+ f"PNG figure is invalid or missing dimensions: {relative}"
652
+ )
653
+ continue
654
+ width, height, dpi = metadata
655
+ if min(width, height) < minimum_short_edge or max(width, height) < minimum_long_edge:
656
+ errors.append(
657
+ f"PNG figure pixel dimensions {width}x{height} are below the required "
658
+ f"short/long edges {minimum_short_edge}/{minimum_long_edge}: {relative}"
659
+ )
578
660
  if dpi is None:
579
661
  errors.append(
580
662
  f"PNG figure must contain valid resolution metadata at or above {minimum_dpi:g} dpi: {relative}"
@@ -588,34 +670,159 @@ def figure_artifact_contract_errors(
588
670
  return errors
589
671
 
590
672
 
591
- def png_dpi(path: Path) -> float | None:
592
- """Read PNG pHYs metadata without requiring Pillow at validation time."""
673
+ def png_pass_dimension(size: int, start: int, step: int) -> int:
674
+ return 0 if size <= start else (size - start + step - 1) // step
675
+
676
+
677
+ def png_scanline_layout(
678
+ width: int, height: int, bits_per_pixel: int, interlace: int
679
+ ) -> tuple[int, list[tuple[int, int]]] | None:
680
+ passes = ((0, 0, 1, 1),) if interlace == 0 else PNG_ADAM7_PASSES
681
+ layout: list[tuple[int, int]] = []
682
+ expected = 0
683
+ for x_start, y_start, x_step, y_step in passes:
684
+ pass_width = png_pass_dimension(width, x_start, x_step)
685
+ pass_height = png_pass_dimension(height, y_start, y_step)
686
+ if pass_width == 0 or pass_height == 0:
687
+ continue
688
+ row_bytes = (pass_width * bits_per_pixel + 7) // 8
689
+ expected += pass_height * (row_bytes + 1)
690
+ if expected > PNG_MAX_DECOMPRESSED_BYTES:
691
+ return None
692
+ layout.append((pass_height, row_bytes))
693
+ return expected, layout
694
+
695
+
696
+ def valid_png_scanlines(
697
+ compressed: bytes, expected: int, layout: list[tuple[int, int]]
698
+ ) -> bool:
699
+ try:
700
+ inflater = zlib.decompressobj()
701
+ raw = inflater.decompress(compressed, expected + 1)
702
+ if len(raw) > expected or inflater.unconsumed_tail:
703
+ return False
704
+ remaining = expected + 1 - len(raw)
705
+ if remaining > 0:
706
+ raw += inflater.flush(remaining)
707
+ except zlib.error:
708
+ return False
709
+ if (
710
+ len(raw) != expected
711
+ or not inflater.eof
712
+ or inflater.unused_data
713
+ or inflater.unconsumed_tail
714
+ ):
715
+ return False
716
+ offset = 0
717
+ for pass_height, row_bytes in layout:
718
+ for _ in range(pass_height):
719
+ if raw[offset] > 4:
720
+ return False
721
+ offset += row_bytes + 1
722
+ return offset == len(raw)
723
+
724
+
725
+ def png_metadata(path: Path) -> tuple[int, int, float | None] | None:
726
+ """Validate a complete PNG and return dimensions plus pHYs resolution."""
593
727
  try:
594
728
  with path.open("rb") as stream:
595
- if stream.read(8) != b"\x89PNG\r\n\x1a\n":
729
+ if stream.read(8) != PNG_SIGNATURE:
596
730
  return None
731
+ width = height = bit_depth = color_type = interlace = 0
732
+ dpi: float | None = None
733
+ idat = bytearray()
734
+ seen_ihdr = False
735
+ seen_idat = False
736
+ idat_closed = False
737
+ seen_palette = False
597
738
  while True:
598
739
  length_bytes = stream.read(4)
599
740
  if len(length_bytes) != 4:
600
741
  return None
601
742
  length = struct.unpack(">I", length_bytes)[0]
743
+ if length > PNG_MAX_CHUNK_BYTES:
744
+ return None
602
745
  chunk_type = stream.read(4)
603
746
  if len(chunk_type) != 4:
604
747
  return None
605
748
  data = stream.read(length)
606
- if len(data) != length or len(stream.read(4)) != 4:
749
+ crc_bytes = stream.read(4)
750
+ if len(data) != length or len(crc_bytes) != 4:
607
751
  return None
608
- if chunk_type == b"pHYs" and len(data) >= 9:
609
- pixels_x, pixels_y, unit = struct.unpack(">IIB", data[:9])
610
- if unit != 1 or not pixels_x or not pixels_y:
752
+ expected_crc = struct.unpack(">I", crc_bytes)[0]
753
+ actual_crc = zlib.crc32(chunk_type + data) & 0xFFFFFFFF
754
+ if expected_crc != actual_crc:
755
+ return None
756
+ if not seen_ihdr and chunk_type != b"IHDR":
757
+ return None
758
+ if chunk_type == b"IHDR":
759
+ if seen_ihdr or length != 13:
760
+ return None
761
+ (
762
+ width,
763
+ height,
764
+ bit_depth,
765
+ color_type,
766
+ compression,
767
+ filtering,
768
+ interlace,
769
+ ) = struct.unpack(">IIBBBBB", data)
770
+ if (
771
+ width == 0
772
+ or height == 0
773
+ or color_type not in PNG_COLOR_CHANNELS
774
+ or bit_depth not in PNG_VALID_BIT_DEPTHS[color_type]
775
+ or compression != 0
776
+ or filtering != 0
777
+ or interlace not in {0, 1}
778
+ ):
779
+ return None
780
+ seen_ihdr = True
781
+ elif chunk_type == b"PLTE":
782
+ if seen_idat or length == 0 or length % 3 != 0 or length > 768:
783
+ return None
784
+ seen_palette = True
785
+ elif chunk_type == b"IDAT":
786
+ if idat_closed or len(idat) + length > PNG_MAX_CHUNK_BYTES:
611
787
  return None
612
- return min(pixels_x, pixels_y) * 0.0254
613
- if chunk_type == b"IEND":
788
+ seen_idat = True
789
+ idat.extend(data)
790
+ elif chunk_type == b"pHYs":
791
+ if length != 9:
792
+ return None
793
+ pixels_x, pixels_y, unit = struct.unpack(">IIB", data)
794
+ if unit == 1 and pixels_x and pixels_y:
795
+ dpi = min(pixels_x, pixels_y) * 0.0254
796
+ elif chunk_type == b"IEND":
797
+ if length != 0 or stream.read(1) or not seen_idat:
798
+ return None
799
+ if color_type == 3 and not seen_palette:
800
+ return None
801
+ bits_per_pixel = PNG_COLOR_CHANNELS[color_type] * bit_depth
802
+ scanlines = png_scanline_layout(
803
+ width, height, bits_per_pixel, interlace
804
+ )
805
+ if scanlines is None:
806
+ return None
807
+ expected, layout = scanlines
808
+ return (
809
+ (width, height, dpi)
810
+ if valid_png_scanlines(bytes(idat), expected, layout)
811
+ else None
812
+ )
813
+ elif chunk_type[0] & 0x20 == 0:
614
814
  return None
615
- except (OSError, struct.error):
815
+ if seen_idat and chunk_type != b"IDAT":
816
+ idat_closed = True
817
+ except (IndexError, OSError, struct.error):
616
818
  return None
617
819
 
618
820
 
821
+ def png_dpi(path: Path) -> float | None:
822
+ metadata = png_metadata(path)
823
+ return metadata[2] if metadata is not None else None
824
+
825
+
619
826
  def fixed_schema_congruence_errors(
620
827
  target: Path, source: Path, allowances: set[str], relative: str
621
828
  ) -> list[str]:
@@ -635,10 +842,10 @@ def fixed_schema_congruence_errors(
635
842
  if target_suffix in {".csv", ".tsv"}:
636
843
  delimiter = "\t" if target_suffix == ".tsv" else ","
637
844
  try:
638
- target_bom, target_headers = delimited_header(
845
+ target_bom, target_encoding, target_headers = delimited_header(
639
846
  target, delimiter, allow_prescribed_encoding=True
640
847
  )
641
- source_bom, source_headers = delimited_header(
848
+ source_bom, source_encoding, source_headers = delimited_header(
642
849
  source, delimiter, allow_prescribed_encoding=True
643
850
  )
644
851
  except (OSError, UnicodeDecodeError, csv.Error) as error:
@@ -647,10 +854,24 @@ def fixed_schema_congruence_errors(
647
854
  errors.append(
648
855
  f"fixed-schema headers differ from the cited source for {relative}"
649
856
  )
650
- if "encoding" in allowances and target_bom != source_bom:
857
+ if "encoding" in allowances and (
858
+ target_bom != source_bom or target_encoding != source_encoding
859
+ ):
651
860
  errors.append(
652
- f"fixed-schema BOM/encoding marker differs from the cited source for {relative}"
861
+ f"fixed-schema encoding differs from the cited source for {relative}: "
862
+ f"{target_encoding} != {source_encoding}"
863
+ )
864
+ if "line_endings" in allowances:
865
+ _, _, target_text = delimited_text(
866
+ target, allow_prescribed_encoding=True
653
867
  )
868
+ _, _, source_text = delimited_text(
869
+ source, allow_prescribed_encoding=True
870
+ )
871
+ if line_ending_style(target_text) != line_ending_style(source_text):
872
+ errors.append(
873
+ f"fixed-schema line endings differ from the cited source for {relative}"
874
+ )
654
875
  elif target_suffix == ".xlsx":
655
876
  try:
656
877
  target_sheets = xlsx_sheet_headers(target)
@@ -1 +0,0 @@
1
- # 只填写实际求解代码直接使用的第三方依赖;不要保留未使用的工具箱。