Merge remote-tracking branch 'origin/main' into fix/786-psd-section-recovery

This commit is contained in:
FredApps
2026-11-18 17:40:00 +01:00
7 changed files with 325 additions and 21 deletions
@@ -7,7 +7,7 @@ chromatic aberration (CA). LightCraft reads them and turns distortion into a DNG
reaches the same **Optics ▸ Enable Lens Corrections** (`optics.lens_profile`) as a DNG's embedded warp and Panasonic's
RW2 distortion data. Lateral CA is parsed and converts to the warp's red and blue planes, but it is **off by default**:
applied after demosaic it made the render's CA worse (Verification). Vignetting is read but not applied (below). The
conversion is verified on the **ILCE-7RM6** and, for distortion, the **ILCE-6700** ([ILCE-6700](#ilce-6700)); the
conversion is verified on the **ILCE-7RM6** and, for distortion, the **ILCE-6700** ([ILCE-6700](#ilce-6700)) and the **ZV-E10** ([ZV-E10](#zv-e10)); the
ILCE-7RM4A has its own conversion, with other conventions
([Two conventions](#two-conventions)), and other Sony bodies' tables give no correction until they are verified.
@@ -105,7 +105,7 @@ the photo (portrait files are covered) and is carried by DNG export, as RW2's is
## Which bodies get it
Only bodies on one of two allowlists in `arw_lens_rm6.rs` get an opcode: `FULL_FRAME_CROP` (today `ILCE-7RM6`,
9984 × 6656) and `APSC_BODIES` (today `ILCE-6700`, below). The unit and the knot spacing are verified per body; a body
9984 × 6656) and `APSC_BODIES` (today `ILCE-6700` and `ZV-E10`, below, each with its distortion unit). The unit and the knot spacing are verified per body; a body
with another sensor size or another unit would be warped wrongly. Other bodies get no correction from this conversion;
the ILCE-7RM4A gets its own, with other conventions (below). To add a body: collect photos of it shot with distortion
correction on (several lenses and focal lengths), repeat the camera-JPEG registration below against the uncorrected
@@ -113,7 +113,7 @@ render, confirm the unit, the knot spacing and the zoom rule (or measure the bod
default crop to `FULL_FRAME_CROP`, or an APS-C body whose knots span its own crop (as measured for the ILCE-6700) to
`APSC_BODIES`, with a test; an APS-C body also needs its fit gate checked against the camera JPEG (see *ILCE-6700*).
For bodies in `APSC_BODIES` (today `ILCE-6700`), the knots span the file's own default crop: spacing = its half
For bodies in `APSC_BODIES` (today `ILCE-6700` and `ZV-E10`), the knots span the file's own default crop: spacing = its half
diagonal / (knot count − 1). This crop-based rule applies only to that list. The ILCE-7RM6 keeps its sensor-fixed
400 px in both modes; in full frame (16 knots) the crop-based rule gives the same 400 px, and in its APS-C mode
(11 knots) it would give 392 px, which was only an alternative measurement there (it fits as well, above).
@@ -166,6 +166,29 @@ As rendered (`lightcraft-cli render`, Enable Lens Corrections on):
At 11.7 mm and longer an exception of this kind fits worse than the body's rule (412 px / 14500 on the grid: 0.73–1.19 px against 0.48–0.69 px), so it stops at
10.5 mm, the longest measured focal length where it helps; 10.6–11.6 mm is unmeasured and takes the body's rule.
## ZV-E10
The ZV-E10 (APS-C, 6000 × 4000 default crop at (12, 12) in 6048 × 4024 storage) writes 11-knot tables like the
ILCE-6700, zero-padded to the same 17 values. Measured as above on 4 photos shot with distortion correction Auto (the
E PZ 16-50 mm F3.5-5.6 OSS, which forces it; its owner's photos, only the summary numbers here): 2 at 16 mm, 1 at 29 mm
(portrait) and 1 at 32 mm. Feature matches between the uncorrected render and the camera JPEG
(LightCraft's `tools/sony_distortion_check.py`, SIFT agreement after the best similarity), the camera's map applied to the render's
points in a scan of knot spacing 340–380 px and unit 15000–17800:
| | p95 residual at 1440 px |
|---|---|
| Uncorrected | 2.7–18.7 px (16 mm: 18.6–18.7 px) |
| The ILCE-6700's rule (half diagonal / 10 = 360.56 px, unit 15000), as rendered | 0.45–2.18 px: the 16 mm photos over-corrected by about 9 % |
| Sensor-fixed 400 px, unit 16384 | 0.43–3.21 px |
| **Half diagonal / 10 = 360.56 px, unit 16384** (exact table) | **0.27–0.61 px** |
| The same as LightCraft renders it (`lightcraft-cli render`, Enable Lens Corrections on, fitted polynomial) | **0.26–0.64 px** (median residual 0.07–0.36 px) |
At 360.56 px every unit from 16300 to 17000 lands within 0.60–0.64 px worst (the measurement's floor on these scenes);
spacing and unit trade off along a ridge as on the ILCE-6700 (375 px / 15700 and 380 px / 15400 reach 0.59 px), so the
body keeps the ILCE-6700's crop-based spacing and takes its own unit, 16384, in `APSC_BODIES`. The fitted polynomial
passes the 0.5 px APS-C fit gate on all four tables, the strongest (16 mm, −1905 at the last knot) included. An HDR
merge of a ZV-E10 bracket keeps the warp in the merged DNG's `OpcodeList3`, as for any raw with embedded corrections.
## Two conventions
A second Sony decoder, `src/arw_lens.rs`
@@ -344,7 +367,7 @@ the resampled source by the source, framing and output size, so tone, colour and
## Limits
- **ILCE-7RM6 and ILCE-6700 only.** Other Sony bodies record the same tags; their knot spacing (defined here by the
- **ILCE-7RM6, ILCE-6700 and ZV-E10 only.** Other Sony bodies record the same tags; their knot spacing (defined here by the
full-frame crop, or an APS-C body's own crop), unit and zoom rule are unverified, so they get no correction from this conversion (the ILCE-7RM4A's distortion has
its own: [Two conventions](#two-conventions)).
- **ILCE-6700 at strong barrel distortion:** the body's rule leaves 1.36–1.38 px at the Sigma 10–18 mm's 10 mm end;
@@ -355,6 +378,10 @@ the resampled source by the source, framing and output size, so tone, colour and
6656 × 4608 frame, misses the 0.5 px fit gate, so that photo stays uncorrected (5.3 px). Other wide lenses with
similarly strong tables are unmeasured. Its vignetting and lateral CA tables are read, not applied: measured in
#2801 (the camera JPEG doesn't compensate vignetting, as on the ILCE-7RM6).
- **ZV-E10: one lens, four photos.** Only the E PZ 16-50 mm (16–32 mm) is measured. Its unit, 16384, differs from
the ILCE-6700's 15000; the ILCE-6700's own E 16–55 mm at 16 mm also fits a higher unit (16000, above), so the unit
may belong to the lens rather than the body. Other lenses on the ZV-E10 are unmeasured and take 16384. The
ZV-E10M2 (another sensor) is not covered.
- **APS-C distortion is unverified in camera on the ILCE-7RM6:** no APS-C photo with distortion correction on was available; the APS-C
knot spacing is verified on CA only, and the APS-C zoom follows the full-frame rule.
- **Aspect-ratio crops** (in-camera 4:3, 16:9, 1:1) were not measured; the correction uses the crop the file records.
+45 -9
View File
@@ -40,9 +40,10 @@
//! The correction is produced whatever the in-camera flag says. Only bodies listed in [`FULL_FRAME_CROP`] or
//! [`APSC_BODIES`] get it: the unit and the knot spacing are verified on the ILCE-7RM6 and, for distortion, on the
//! ILCE-6700 (APS-C, 11 knots spanning its own crop, the same unit 15000: 0.73 px worst over 27 photos with three
//! lenses as rendered, 1.38 px at the 10–18 mm's 10 mm end). Another body is added by repeating the measurement on its photos shot
//! with distortion correction on and listing its full-frame default crop (or, for an APS-C body, its model). The method
//! and the numbers: docs/sony-ilce7rm6-lens-corrections.md.
//! lenses as rendered, 1.38 px at the 10–18 mm's 10 mm end) and the ZV-E10 (the same APS-C rule with unit 16384:
//! 0.64 px worst over 4 photos with the E PZ 16–50 mm at 16–32 mm as rendered). Another body is added by repeating the
//! measurement on its photos shot with distortion correction on and listing its full-frame default crop (or, for an
//! APS-C body, its model). The method and the numbers: docs/sony-ilce7rm6-lens-corrections.md.
use crate::opcodes::max_radius;
use crate::shared::fit_radial_warp;
@@ -59,9 +60,15 @@ pub(crate) const CA_FLAG: u16 = 0x7034;
/// The bodies whose tables are verified (Exif `Model`), with their full-frame default crop (width, height) in px.
const FULL_FRAME_CROP: &[(&str, (f64, f64))] = &[("ILCE-7RM6", (9984.0, 6656.0))];
/// The verified APS-C bodies (Exif `Model`): their knots span the file's own default crop, the last knot at its corner.
/// Measured on the ILCE-6700 (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700).
const APSC_BODIES: &[&str] = &["ILCE-6700"];
/// The verified APS-C bodies (Exif `Model`) with their distortion unit: their knots span the file's own default crop,
/// the last knot at its corner. Measured against the camera JPEG (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700,
/// ZV-E10): the ILCE-6700 at the ILCE-7RM6's 15000; the ZV-E10 at 16384, where 15000 over-corrects by about 9 %.
const APSC_BODIES: &[(&str, f64)] = &[("ILCE-6700", DISTORTION_UNIT), ("ZV-E10", 16384.0)];
/// The distortion unit of an [`APSC_BODIES`] body.
fn apsc_unit(model: &str) -> Option<f64> {
APSC_BODIES.iter().find(|(m, _)| *m == model.trim()).map(|&(_, unit)| unit)
}
/// A lens whose tables follow its body's convention with another knot spacing and unit, at the focal lengths up to
/// `max_focal_mm`; measured like the body, against the camera JPEG.
@@ -153,7 +160,7 @@ fn knot_spacing(model: &str, knots: usize, crop: Rect) -> Option<f64> {
}
let gaps = knots.checked_sub(1).filter(|&n| n > 0)?;
let half_diagonal = (crop.width as f64).hypot(crop.height as f64) / 2.0;
(APSC_BODIES.contains(&model) && crate::arw_lens::is_3_2(crop)).then(|| half_diagonal / gaps as f64)
(apsc_unit(model).is_some() && crate::arw_lens::is_3_2(crop)).then(|| half_diagonal / gaps as f64)
}
/// The knot table at radius `r` px: knot `i` at `i · spacing`, linear in between, the last segment extended beyond
@@ -261,8 +268,8 @@ pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, lens: Option<&str>, focal_mm:
let Some(spacing) = knot_spacing(model, knots, crop) else { return Vec::new() };
let op = if let Some(e) = lens_exception(model, lens, focal_mm) {
gated_warp_opcode(&tables, e.knot_spacing, e.unit, active, crop, false, APSC_FIT_ERROR_PX_AT_1440)
} else if APSC_BODIES.contains(&model.trim()) {
gated_warp_opcode(&tables, spacing, DISTORTION_UNIT, active, crop, false, APSC_FIT_ERROR_PX_AT_1440)
} else if let Some(unit) = apsc_unit(model) {
gated_warp_opcode(&tables, spacing, unit, active, crop, false, APSC_FIT_ERROR_PX_AT_1440)
} else {
warp_opcode(&tables, spacing, active, crop, false)
};
@@ -310,6 +317,8 @@ mod tests {
const FF_HQ_R: [f64; 4] = [0.9715153129, 0.02236266369, 0.0007060224765, 0.005666341563];
const FF_HQ_B: [f64; 4] = [0.97137946, 0.02277016389, 0.0003830082563, 0.005727820598];
const APSC_G: [f64; 4] = [1.01627551, -0.0618606692, 0.02768349621, -0.005595798468];
/// The ZV-E10 16 mm example's G plane (unit 16384, knots over its crop's half diagonal / 10), from the same recipe.
const ZV_E10_G: [f64; 4] = [1.051925248, -0.1972416727, 0.09393523723, -0.0282770833];
const APSC_R: [f64; 4] = [1.016503991, -0.06206460153, 0.0278447625, -0.005644118171];
const APSC_B: [f64; 4] = [1.016155702, -0.06162477627, 0.02753315326, -0.005554915901];
@@ -629,6 +638,33 @@ mod tests {
assert!(matches!(ops.as_slice(), [Opcode::WarpRectilinear { planes, .. }] if planes.len() == 1), "{ops:?}");
}
/// A ZV-E10 file (E PZ 16-50 mm at 16 mm): 11 knots, zero-padded as this body stores them.
const ZV_E10_16MM_DISTORTION: [i16; 17] = [11, 72, -7, -129, -266, -446, -640, -877, -1114, -1380, -1639, -1905, 0, 0, 0, 0, 0];
/// The ZV-E10's decoded geometry: 6048 × 4024 storage, a 6000 × 4000 default crop at (12, 12).
const ZV_E10_ACTIVE: Rect = Rect { x: 0, y: 0, width: 6048, height: 4024 };
const ZV_E10_CROP: Rect = Rect { x: 12, y: 12, width: 6000, height: 4000 };
/// The ZV-E10 follows the ILCE-6700's APS-C rule (knots over its own crop's half diagonal / 10, the APS-C fit
/// gate) with its own unit, 16384; its zero padding is not read as knots, and its successor (ZV-E10M2) stays
/// unverified.
#[test]
fn zv_e10_uses_the_apsc_rule_with_its_own_unit() {
let s = knot_spacing("ZV-E10", 11, ZV_E10_CROP).unwrap();
assert!((s - 360.5551).abs() < 1e-3, "{s}");
let ifd = sony_lens_ifd(&ZV_E10_16MM_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [17, 2, 1]);
let t = read_tables(&ifd);
assert_eq!(t.distortion.as_ref().map(Vec::len), Some(11));
let gated = gated_warp_opcode(&t, s, 16384.0, ZV_E10_ACTIVE, ZV_E10_CROP, false, APSC_FIT_ERROR_PX_AT_1440);
let ops = lens_opcodes(&ifd, " ZV-E10 ", Some("E PZ 16-50mm F3.5-5.6 OSS"), Some(16.0), ZV_E10_ACTIVE, ZV_E10_CROP);
assert_warp(ops.first().cloned(), [3011.5 / 6047.0, 0.5], &[ZV_E10_G]);
assert_eq!(ops, gated.into_iter().collect::<Vec<_>>());
// the ILCE-6700's unit would warp it differently
let at_15000 = gated_warp_opcode(&t, s, DISTORTION_UNIT, ZV_E10_ACTIVE, ZV_E10_CROP, false, APSC_FIT_ERROR_PX_AT_1440);
assert_ne!(ops.first(), at_15000.as_ref());
assert_eq!(apsc_unit("ILCE-6700"), Some(DISTORTION_UNIT));
assert!(lens_opcodes(&ifd, "ZV-E10M2", None, None, ZV_E10_ACTIVE, ZV_E10_CROP).is_empty());
}
const SIGMA_10_18: &str = "10-18mm F2.8 DC DN | Contemporary 023";
/// The Sigma 10-18 mm exception: its spacing and unit at 10-10.5 mm, the body's rule from 11.7 mm (and without a
+36 -1
View File
@@ -8,6 +8,7 @@ use crate::{
BlackLevel, Camera, Cfa, CinemaTags, ColorData, LevelSource, LevelSources, Limits, Matrix3, Mode, Orientation, RawData, RawError, RawFormat,
RawImage, RawNotices, Rect, Result, Timecode, opcodes,
};
use craft_tiff::image::{ImageInfo, Layout};
use craft_tiff::tags::{self as t, photometric};
use craft_tiff::{ByteOrder, Ifd, Tiff, Value};
@@ -273,7 +274,10 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f
{
return Err(RawError::Unsupported(format!("DNG compression {c} (GoPro VC-5) is not decoded yet")));
}
let info = pixels.image()?;
let mut info = pixels.image()?;
if std::ptr::eq(pixels, raw) {
extend_understated_strip(bytes, &mut info, raw);
}
let (w, h, cpp) = (info.width as usize, info.height as usize, info.samples_per_pixel as usize);
// one sample (CFA or monochrome), RGB or four colours; two are neither and can't be developed (storytold/lightcraft#1511)
if !matches!(cpp, 1 | 3 | 4) {
@@ -522,6 +526,37 @@ fn cinema_tags(ifd0: &Ifd, raw: &Ifd) -> CinemaTags {
}
}
/// Trust the file over `StripByteCounts` for an uncompressed single-strip image whose byte count is exactly
/// `ActiveArea` columns by `ImageLength` rows while the file holds the whole `ImageWidth` by `ImageLength` raster from
/// the strip's offset on. DJI Mavic 3 DNGs write the count of the active columns (5280) for a strip of full 5376-wide
/// rows that ends at the end of the file, so reading only the counted bytes refuses a complete image
/// (storytold/craft-libs#2040). The strip is lengthened only then, so every other short strip is still refused, and
/// it never reaches past the end of the file. The active area has to start at column 0, so it is the stored rows'
/// leading columns.
fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) {
let bits = u64::from(info.bits());
if !matches!(info.layout, Layout::Strips { .. })
|| info.compression != t::compression::NONE
|| info.samples_per_pixel != 1
|| info.planar == 2
|| !matches!(info.sample_format, 1 | 2)
|| !matches!(bits, 8 | 16)
{
return;
}
let ([offset], [count]) = (&info.offsets[..], &info.byte_counts[..]) else { return };
let Some([top, left, bottom, right]) = raw.u64s(t::ACTIVE_AREA).and_then(|a| <[u64; 4]>::try_from(a).ok()) else { return };
if left != 0 || bottom <= top || bottom > u64::from(info.height) || right == 0 || right >= u64::from(info.width) {
return;
}
let row_bytes = |width: u64| width.checked_mul(u64::from(info.height))?.checked_mul(bits / 8);
let (Some(counted), Some(needed)) = (row_bytes(right), row_bytes(u64::from(info.width))) else { return };
let fits = offset.checked_add(needed).is_some_and(|end| end <= bytes.len() as u64);
if *count == counted && fits {
info.byte_counts = vec![needed];
}
}
/// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent
/// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop
/// preserves the entire active image. Valid partly overlapping rectangles retain the
+71
View File
@@ -118,3 +118,74 @@ fn decoded_notices_record_actual_crop_gain_table_and_cfa_decisions() {
let limits = Limits { max_samples: 47, ..Default::default() };
assert!(matches!(decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &limits), Err(RawError::Limit(_))));
}
/// A 16-bit CFA DNG of `width` x `height` whose strip holds every row in full but whose `StripByteCounts` says
/// `counted` bytes.
fn understated_strip_dng(width: u32, height: u32, counted: u32, active_area: Option<[u32; 4]>) -> Vec<u8> {
understated_strip_dng_with(width, height, counted, active_area, &[])
}
/// [`understated_strip_dng`] with `extra` tags set on the raw IFD.
fn understated_strip_dng_with(width: u32, height: u32, counted: u32, active_area: Option<[u32; 4]>, extra: &[(u16, Value)]) -> Vec<u8> {
let mut raw = IfdBuilder::new();
for (tag, value) in extra {
raw.set(*tag, value.clone());
}
for (tag, value) in [
(t::IMAGE_WIDTH, Value::Long(vec![width])),
(t::IMAGE_LENGTH, Value::Long(vec![height])),
(t::BITS_PER_SAMPLE, Value::Short(vec![16])),
(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])),
(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])),
(t::COMPRESSION, Value::Short(vec![1])),
(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])),
(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])),
] {
raw.set(tag, value);
}
if let Some(area) = active_area {
raw.set(t::ACTIVE_AREA, Value::Long(area.to_vec()));
}
let samples = (width * height) as u16;
raw.set_image(ImageData::Strips { rows_per_strip: height, strips: vec![(0..samples).flat_map(u16::to_le_bytes).collect()] });
let mut bytes = TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap();
// the writer counts the real bytes: understate that one count, a LONG in the IFD
let count = (width * height * 2).to_le_bytes();
let at = bytes.windows(4).position(|w| w == count).unwrap();
bytes[at..at + 4].copy_from_slice(&counted.to_le_bytes());
bytes
}
/// storytold/craft-libs#2040: the DJI Mavic 3 counts 5280 x 3956 x 2 bytes for a strip that holds 5376-wide rows
/// to the end of the file.
#[test]
fn a_strip_counted_only_active_area_wide_is_read_in_full() {
let bytes = understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6]));
for mode in [Mode::Full, Mode::Header] {
let img = decode_as(&bytes, mode, RawFormat::Dng, &Limits::default()).unwrap();
assert_eq!((img.width, img.height), (8, 4));
}
let img = decode_as(&bytes, Mode::Full, RawFormat::Dng, &Limits::default()).unwrap();
let RawData::U16(v) = &img.data else { panic!("integer samples") };
assert_eq!(v, &(0..32).collect::<Vec<u16>>());
}
/// Any other short strip is still a corrupt file.
#[test]
fn other_short_strips_are_still_refused() {
let refused = |bytes: Vec<u8>| matches!(decode_as(&bytes, Mode::Full, RawFormat::Dng, &Limits::default()), Err(RawError::Corrupt(_)));
// no ActiveArea to explain the count
assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, None)));
// the count is not exactly the area's bytes
assert!(refused(understated_strip_dng(8, 4, 5 * 4 * 2, Some([0, 0, 4, 6]))));
// samples that are neither integer nor absent-format (SampleFormat 4 is undefined)
assert!(refused(understated_strip_dng_with(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6]), &[(t::SAMPLE_FORMAT, Value::Short(vec![4]))])));
// the area reaches below the image, so decode would discard it
assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([4, 0, 5, 6]))));
// the area does not start at column 0
assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 2, 4, 8]))));
// the file does not hold the whole raster
let mut cut = understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6]));
cut.truncate(cut.len() - 8);
assert!(refused(cut));
}
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Check every workspace package separately to bound rustfmt's Windows argv."""
import json
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def workspace_names(metadata):
members = metadata["workspace_members"]
packages = metadata["packages"]
if not members or len(members) != len(set(members)):
raise ValueError("workspace member inventory is empty or duplicated")
by_id = {package["id"]: package for package in packages}
if len(by_id) != len(packages):
raise ValueError("metadata contains duplicate package IDs")
names = []
for member in members:
name = by_id[member]["name"]
# Package names are data, never command text or option fragments.
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", name):
raise ValueError("invalid workspace package name")
names.append(name)
if len(names) != len(set(names)):
raise ValueError("workspace package names are ambiguous")
return sorted(names)
def check_workspace():
result = subprocess.run(
["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"],
cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True, encoding="utf-8",
)
names = workspace_names(json.loads(result.stdout))
# From this virtual workspace root, cargo fmt normally checks all workspace packages.
# Keep Cargo responsible for target kinds, editions and rustfmt configuration.
# One package per call retains all its targets without the workspace-sized argv.
print(f"Checking formatting for {len(names)} workspace packages", flush=True)
for name in names:
subprocess.run(["cargo", "fmt", "--check", "--package", name], cwd=ROOT, check=True)
if __name__ == "__main__":
check_workspace()
+6 -1
View File
@@ -5,7 +5,12 @@ unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES
if [ "${RUNNER_OS:-}" = Windows ]; then
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
fi
cargo fmt --check
# Windows cannot spawn one rustfmt command with every workspace target (#2200).
if [ "${RUNNER_OS:-}" = Windows ]; then
python scripts/ci-format-workspace.py
else
cargo fmt --check
fi
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
# cargo test includes docs and ordinary example linking, as required by AGENTS.md.
+90 -6
View File
@@ -29,7 +29,11 @@ unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES
if [ "${RUNNER_OS:-}" = Windows ]; then
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
fi
cargo fmt --check
if [ "${RUNNER_OS:-}" = Windows ]; then
python scripts/ci-format-workspace.py
else
cargo fmt --check
fi
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
cargo test --workspace --locked
@@ -54,6 +58,7 @@ cargo() {
if [ "$*" = "$FAIL" ]; then return 17; fi
}
powershell.exe() { printf 'print-queue\n'; }
python() { test "$*" = "scripts/ci-format-workspace.py" || return 31; cargo fmt --check; }
"""
return subprocess.run([BASH, "-c", mock + SOURCE], env=env,
capture_output=True, text=True, check=False)
@@ -89,11 +94,13 @@ class FullValidation(unittest.TestCase):
(["print-queue"] if name == "Windows" else []) + COMMANDS)
def test_every_failure_stops_the_gate(self):
for i, command in enumerate(COMMANDS):
with self.subTest(command=command):
p = run("Linux", command)
self.assertEqual(p.returncode, 17, p.stdout + p.stderr)
self.assertEqual(p.stdout.splitlines(), COMMANDS[:i + 1])
for name in ["Linux", "macOS", "Windows"]:
for i, command in enumerate(COMMANDS):
with self.subTest(os=name, command=command):
p = run(name, command)
self.assertEqual(p.returncode, 17, p.stdout + p.stderr)
self.assertEqual(p.stdout.splitlines(),
(["print-queue"] if name == "Windows" else []) + COMMANDS[:i + 1])
def test_workflow_preserves_fork_and_platform_boundaries(self):
text = (ROOT / ".github/workflows/full-validation.yml").read_text()
@@ -120,5 +127,82 @@ class FullValidation(unittest.TestCase):
self.assertIn("macos-latest", pdf)
class PackageFormatting(unittest.TestCase):
@staticmethod
def helper():
import importlib.util
spec = importlib.util.spec_from_file_location("ci_format_workspace", ROOT / "scripts/ci-format-workspace.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@staticmethod
def metadata():
return {"workspace_members": ["id-b", "id-a"], "workspace_default_members": ["id-a"],
"packages": [{"id": "id-a", "name": "craft-a"},
{"id": "id-b", "name": "craft-b"},
{"id": "external", "name": "not-a-member"}]}
def test_all_workspace_members_not_only_defaults_and_no_external_dependencies(self):
helper = self.helper()
self.assertEqual(helper.workspace_names(self.metadata()), ["craft-a", "craft-b"])
def test_new_package_automatically_included(self):
helper = self.helper()
data = self.metadata()
data["workspace_members"].append("id-new")
data["packages"].append({"id": "id-new", "name": "craft-new"})
self.assertEqual(helper.workspace_names(data), ["craft-a", "craft-b", "craft-new"])
def test_bad_inventory_fails_closed(self):
helper = self.helper()
for members in ([], ["id-a", "id-a"], ["missing"]):
data = self.metadata()
data["workspace_members"] = members
with self.subTest(members=members), self.assertRaises((ValueError, KeyError)):
helper.workspace_names(data)
for name in ("--all", "craft-a;echo injected", "craft-a", ""):
data = self.metadata()
data["packages"][1]["name"] = name
with self.subTest(name=name), self.assertRaises(ValueError):
helper.workspace_names(data)
def test_calls_cargo_with_one_package_and_no_shell(self):
import json
helper = self.helper()
result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata()))
with patch.object(helper.subprocess, "run", return_value=result) as execute:
helper.check_workspace()
self.assertEqual([call.args[0] for call in execute.call_args_list], [
["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"],
["cargo", "fmt", "--check", "--package", "craft-a"],
["cargo", "fmt", "--check", "--package", "craft-b"],
])
self.assertEqual(execute.call_args_list[0].kwargs["encoding"], "utf-8")
for call in execute.call_args_list:
self.assertEqual(call.kwargs["cwd"], ROOT)
self.assertTrue(call.kwargs["check"])
self.assertNotIn("shell", call.kwargs)
def test_metadata_failure_prevents_formatting(self):
helper = self.helper()
failure = subprocess.CalledProcessError(17, ["cargo", "metadata"])
with patch.object(helper.subprocess, "run", side_effect=failure) as execute:
with self.assertRaises(subprocess.CalledProcessError):
helper.check_workspace()
self.assertEqual(execute.call_count, 1)
def test_first_format_failure_stops_later_packages(self):
import json
helper = self.helper()
result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata()))
failure = subprocess.CalledProcessError(17, ["cargo", "fmt"])
with patch.object(helper.subprocess, "run", side_effect=[result, failure]) as execute:
with self.assertRaises(subprocess.CalledProcessError):
helper.check_workspace()
self.assertEqual(execute.call_count, 2)
if __name__ == "__main__":
unittest.main()