@orbit-build/cli 1.8.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,
@@ -27,8 +29,7 @@ from project_utils import (
27
29
  numeric_limit,
28
30
  question_numbers,
29
31
  )
30
- from evidence_freeze import evidence_differences
31
-
32
+ from script_runtime import configure_utf8_output
32
33
 
33
34
  INPUT_SUFFIXES = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
34
35
  SUPPORT_EXCLUDED_PARTS = {
@@ -53,7 +54,13 @@ GENERIC_FIGURE_STEMS = {
53
54
  "result",
54
55
  "summary",
55
56
  }
56
- 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
+ }
57
64
  HAN_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
58
65
  SPREADSHEET_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
59
66
  OFFICE_REL_NS = (
@@ -68,6 +75,26 @@ SCRATCH_DELIVERY_NAMES = {
68
75
  "rebuild_support.ps1",
69
76
  "verify_results.py",
70
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
+ )
71
98
 
72
99
 
73
100
  def sha256(path: Path) -> str:
@@ -164,31 +191,58 @@ def fixed_schema_source_error(root: Path, value: str) -> str | None:
164
191
  return None
165
192
 
166
193
 
167
- def delimited_header(
168
- path: Path, delimiter: str, allow_prescribed_encoding: bool = False
169
- ) -> tuple[bool, list[str]]:
194
+ def delimited_text(
195
+ path: Path, allow_prescribed_encoding: bool = False
196
+ ) -> tuple[bool, str, str]:
170
197
  raw = path.read_bytes()
171
198
  has_utf8_bom = raw.startswith(b"\xef\xbb\xbf")
172
- encodings = (
173
- ("utf-8-sig", "gb18030", "utf-16")
174
- if allow_prescribed_encoding
175
- else ("utf-8-sig",)
176
- )
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"),)
177
207
  decode_error: UnicodeDecodeError | None = None
178
- for encoding in encodings:
208
+ for codec, canonical_encoding in encodings:
179
209
  try:
180
- text = raw.decode(encoding)
210
+ text = raw.decode(codec)
181
211
  break
182
212
  except UnicodeDecodeError as error:
183
213
  decode_error = error
184
214
  else:
185
- assert decode_error is not None
186
- 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
+ )
187
229
  for row in csv.reader(io.StringIO(text), delimiter=delimiter):
188
230
  headers = [cell.strip() for cell in row]
189
231
  if any(headers):
190
- return has_utf8_bom, headers
191
- 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"
192
246
 
193
247
 
194
248
  def xlsx_sheet_headers(path: Path) -> list[tuple[str, list[str]]]:
@@ -446,7 +500,7 @@ def result_artifact_contract_errors(
446
500
  f"fixed-schema exception uses Excel-only scope for {relative}: sheet_names"
447
501
  )
448
502
  try:
449
- has_bom, headers = delimited_header(
503
+ has_bom, _, headers = delimited_header(
450
504
  path,
451
505
  "\t" if suffix == ".tsv" else ",",
452
506
  allow_prescribed_encoding="encoding" in allowances,
@@ -481,9 +535,11 @@ def result_artifact_contract_errors(
481
535
  + ", ".join(non_chinese)
482
536
  )
483
537
  elif suffix == ".xlsx":
484
- if "encoding" in allowances:
538
+ irrelevant = allowances & {"encoding", "line_endings"}
539
+ if irrelevant:
485
540
  errors.append(
486
- 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))
487
543
  )
488
544
  try:
489
545
  sheets = xlsx_sheet_headers(path)
@@ -513,9 +569,11 @@ def result_artifact_contract_errors(
513
569
  + ", ".join(non_chinese)
514
570
  )
515
571
  else:
516
- if "encoding" in allowances:
572
+ irrelevant = allowances & {"encoding", "line_endings"}
573
+ if irrelevant:
517
574
  errors.append(
518
- 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))
519
577
  )
520
578
  required_scopes = set()
521
579
  if flags["require_chinese_headers"]:
@@ -556,6 +614,20 @@ def figure_artifact_contract_errors(
556
614
  ):
557
615
  errors.append("result_artifacts.min_png_dpi must be a number >= 300")
558
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
559
631
  figures = root / "figures"
560
632
  if not figures.is_dir() or figures.is_symlink():
561
633
  return errors
@@ -573,7 +645,18 @@ def figure_artifact_contract_errors(
573
645
  errors.append(
574
646
  f"figure filename must be descriptive Chinese, not a generic name: {relative}"
575
647
  )
576
- 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
+ )
577
660
  if dpi is None:
578
661
  errors.append(
579
662
  f"PNG figure must contain valid resolution metadata at or above {minimum_dpi:g} dpi: {relative}"
@@ -587,34 +670,159 @@ def figure_artifact_contract_errors(
587
670
  return errors
588
671
 
589
672
 
590
- def png_dpi(path: Path) -> float | None:
591
- """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."""
592
727
  try:
593
728
  with path.open("rb") as stream:
594
- if stream.read(8) != b"\x89PNG\r\n\x1a\n":
729
+ if stream.read(8) != PNG_SIGNATURE:
595
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
596
738
  while True:
597
739
  length_bytes = stream.read(4)
598
740
  if len(length_bytes) != 4:
599
741
  return None
600
742
  length = struct.unpack(">I", length_bytes)[0]
743
+ if length > PNG_MAX_CHUNK_BYTES:
744
+ return None
601
745
  chunk_type = stream.read(4)
602
746
  if len(chunk_type) != 4:
603
747
  return None
604
748
  data = stream.read(length)
605
- 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:
606
751
  return None
607
- if chunk_type == b"pHYs" and len(data) >= 9:
608
- pixels_x, pixels_y, unit = struct.unpack(">IIB", data[:9])
609
- 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:
610
787
  return None
611
- return min(pixels_x, pixels_y) * 0.0254
612
- 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:
613
814
  return None
614
- except (OSError, struct.error):
815
+ if seen_idat and chunk_type != b"IDAT":
816
+ idat_closed = True
817
+ except (IndexError, OSError, struct.error):
615
818
  return None
616
819
 
617
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
+
618
826
  def fixed_schema_congruence_errors(
619
827
  target: Path, source: Path, allowances: set[str], relative: str
620
828
  ) -> list[str]:
@@ -634,10 +842,10 @@ def fixed_schema_congruence_errors(
634
842
  if target_suffix in {".csv", ".tsv"}:
635
843
  delimiter = "\t" if target_suffix == ".tsv" else ","
636
844
  try:
637
- target_bom, target_headers = delimited_header(
845
+ target_bom, target_encoding, target_headers = delimited_header(
638
846
  target, delimiter, allow_prescribed_encoding=True
639
847
  )
640
- source_bom, source_headers = delimited_header(
848
+ source_bom, source_encoding, source_headers = delimited_header(
641
849
  source, delimiter, allow_prescribed_encoding=True
642
850
  )
643
851
  except (OSError, UnicodeDecodeError, csv.Error) as error:
@@ -646,10 +854,24 @@ def fixed_schema_congruence_errors(
646
854
  errors.append(
647
855
  f"fixed-schema headers differ from the cited source for {relative}"
648
856
  )
649
- 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
+ ):
650
860
  errors.append(
651
- 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
652
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
+ )
653
875
  elif target_suffix == ".xlsx":
654
876
  try:
655
877
  target_sheets = xlsx_sheet_headers(target)
@@ -1410,4 +1632,5 @@ def main() -> None:
1410
1632
 
1411
1633
 
1412
1634
  if __name__ == "__main__":
1635
+ configure_utf8_output()
1413
1636
  main()
@@ -1 +0,0 @@
1
- # 只填写实际求解代码直接使用的第三方依赖;不要保留未使用的工具箱。