合入小壹 P2-5 交付结果文件优化

This commit is contained in:
WuYongJie 2026-11-27 23:25:24 +08:00
commit de9eaf8a81
4 changed files with 239 additions and 56 deletions

View File

@ -72,15 +72,22 @@ export async function verifyDeliveryBundle(directory, expected = []) {
const files = [];
const entries = new Map();
const root = path.resolve(directory);
let missingOutputs = 0;
let missing = [];
let project;
let bundle;
try {
bundle = JSON.parse(await readFile(path.join(root, '交付清单.json'), 'utf8'));
requireThat(bundle.version === 1 && typeof bundle.deliveryId === 'string' && bundle.deliveryId
&& Array.isArray(bundle.files) && bundle.counts && Number.isInteger(bundle.totalOutputs)
&& bundle.totalOutputs > 0 && bundle.allOutputsCompleted === true
&& bundle.completedOutputs === bundle.totalOutputs, '交付清单字段无效或输出未全部完成');
for (const field of ['failedCount', 'missingCount', 'failedOutputs', 'missingOutputs']) {
&& Number.isInteger(bundle.completedOutputs) && bundle.completedOutputs >= 0
&& bundle.totalOutputs > 0 && bundle.completedOutputs <= bundle.totalOutputs
&& bundle.allOutputsCompleted === (bundle.completedOutputs === bundle.totalOutputs), '交付清单字段无效');
missingOutputs = bundle.totalOutputs - bundle.completedOutputs;
missing = bundle.missing ?? [];
requireThat((bundle.missingOutputs ?? missingOutputs) === missingOutputs
&& Array.isArray(missing) && missing.length <= missingOutputs, '输出缺项记录与清单不符');
for (const field of ['failedCount', 'missingCount', 'failedOutputs']) {
requireThat((bundle[field] ?? 0) === 0, `${field} 必须为 0`);
}
for (const record of bundle.files) {
@ -140,23 +147,24 @@ export async function verifyDeliveryBundle(directory, expected = []) {
&& path.posix.dirname(row.relativePath) === category + folder), `缺少 ${category}${folder}`);
}
}
for (const category of ['PSD', ...new Set(Object.values(outputs).flatMap(([, ...categories]) => categories))]) {
if (!counts[category]) continue;
const diskEntries = await readdir(path.join(root, category), { recursive: true, withFileTypes: true });
for (const entry of diskEntries) {
if (!entry.isFile() || !/\.(jpe?g|psd|psb)$/i.test(entry.name)) continue;
const relativePath = path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join('/');
requireThat(entries.has(relativePath), `磁盘文件未列入清单 ${relativePath}`);
for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) {
if (!entry.isFile()) continue;
const relativePath = path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join('/');
if (relativePath !== '交付清单.json' && !entries.has(relativePath)) {
errors.push({ path: relativePath, message: '磁盘文件未列入清单', missing: false });
}
}
requireThat(outputCount === bundle.totalOutputs, '磁盘输出数与清单不符');
for (const id of expected) requireThat(selected.has(id), `缺少期望输出 ${id}`);
requireThat(outputCount === bundle.completedOutputs, '磁盘输出数与清单不符');
for (const id of expected) {
if (!selected.has(id)) errors.push({ outputId: id, message: `缺少期望输出 ${id}`, missing: true });
}
} catch (error) {
errors.push({ message: error.message, missing: error.code === 'ENOENT' || error.message.startsWith('缺少') });
}
return { ok: errors.length === 0, deliveryDir: root, counts, files,
return { ok: errors.length === 0 && missingOutputs === 0, deliveryDir: root, counts, files, missingOutputs, missing,
failedCount: errors.filter(error => !error.missing).length,
missingCount: errors.filter(error => error.missing).length, errors };
missingCount: errors.filter(error => error.missing && !error.outputId).length
+ Math.max(missingOutputs, errors.filter(error => error.missing && error.outputId).length), errors };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {

View File

@ -67,3 +67,28 @@ test('rejects a fake JPG header even when the digest matches', async t => {
assert.equal(report.ok, false);
assert.match(report.errors[0].message, /JPG 文件头/);
});
test('reports incomplete outputs alongside verified deliverables', async t => {
const root = await fixture(t);
const manifestPath = path.join(root, '交付清单.json');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const missing = [{ outputId: 'sku_images', variantName: '米白', reason: '尚未导出' }];
await fs.writeFile(manifestPath, JSON.stringify({
...manifest, totalOutputs: 2, allOutputsCompleted: false, missingOutputs: 1, missing,
}));
const report = await verifyDeliveryBundle(root, ['main_images', 'sku_images']);
assert.equal(report.ok, false);
assert.equal(report.failedCount, 0);
assert.equal(report.missingCount, 1);
assert.deepEqual(report.missing, missing);
assert.equal(report.files.length, manifest.files.length);
});
test('reports unlisted files in the bundle root and project resources', async t => {
const root = await fixture(t);
await fs.writeFile(path.join(root, 'debug.json'), '{}');
await fs.writeFile(path.join(root, '工程文件', '项目 资源', 'preview.png'), 'preview');
const report = await verifyDeliveryBundle(root);
assert.equal(report.ok, false);
assert.deepEqual(report.errors.map(error => error.path).sort(), ['debug.json', '工程文件/项目 资源/preview.png']);
});

View File

@ -42,20 +42,13 @@ fn file_record(root: &Path, path: &Path, category: &str, size: Option<(u32, u32)
fn artifact_size(path: &Path, format: &str) -> R<Option<(u32, u32)>> {
let size = match format {
"jpg" => {
let bytes = fs::read(path).map_err(disk)?;
if !bytes.starts_with(&[0xff, 0xd8, 0xff]) {
return Err("JPG 文件头无效".into());
}
photocraft_codecs::probe_size(&bytes).map_err(|error| format!("无法读取 JPG 尺寸:{error}"))?
}
"psd" | "psb" => canvas_workspace::layered_size(&path.to_string_lossy(), &fs::read(path).map_err(disk)?)?,
"pcraft" => {
transfer::check_pcraft_file(path)?;
let doc = photocraft_format::load_path(path).map_err(|error| format!("无法重开成品原稿:{error}"))?;
(doc.size.width, doc.size.height)
}
"jpeg" | "png" | "webp" => {
"jpg" | "jpeg" | "png" | "webp" => {
photocraft_codecs::probe_size(&fs::read(path).map_err(disk)?).map_err(|error| format!("无法读取工程资源图像尺寸:{error}"))?
}
_ => return Ok(None),
@ -74,7 +67,14 @@ fn copy_artifact(root: &Path, generation: &Path, source: &Value, category: &str,
return Err("成品清单含重复文件名".into());
}
fs::copy(&from, &to).map_err(disk)?;
let size = artifact_size(&to, format)?.ok_or("成品清单含不支持的格式")?;
let size = if format == "jpg" {
let bytes = fs::read(&to).map_err(disk)?;
let image = photocraft_codecs::decode_as(photocraft_codecs::Format::Jpeg, &bytes)
.map_err(|error| format!("无法解码 JPG:{error}"))?;
(image.width(), image.height())
} else {
artifact_size(&to, format)?.ok_or("成品清单含不支持的格式")?
};
let record = file_record(root, &to, category, Some(size))?;
if ["width", "height", "sizeBytes", "sha256"].iter().any(|field| record[*field] != source[*field]) {
return Err(format!("{name}.{format} 与已验证成品不一致"));
@ -82,7 +82,15 @@ fn copy_artifact(root: &Path, generation: &Path, source: &Value, category: &str,
Ok(record)
}
fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, files: &mut Vec<Value>) -> R<()> {
fn variant_name(brief: &Value, variant: &str) -> Option<String> {
let row = brief["variants"].as_array().into_iter().flatten().find(|row| row["id"] == variant);
let (source, field) = row.map_or((brief, "variant"), |row| (row, "name"));
[field, "colorName"].into_iter().filter_map(|key| source[key].as_str())
.find(|name| !name.trim_matches(|ch: char| ch == '.' || ch.is_whitespace()).is_empty())
.map(name_component)
}
fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec<Value>) -> R<()> {
let component = output["outputId"].as_str().ok_or("成品类型缺失")?;
let label = match component {
"detail" => "详情页",
@ -124,8 +132,14 @@ fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, f
files.push(copy_artifact(root, generation, screen, "详情页切片", folder, &format!("详情页-{:02}", index + 1))?);
}
} else {
let sku_name = color.filter(|_| component == "sku_images").map(|name| format!("SKU-{name}"));
for (index, image) in images.iter().enumerate() {
files.push(copy_artifact(root, generation, image, label, folder, &format!("{label}-{:02}", index + 1))?);
let name = match &sku_name {
Some(name) if images.len() == 1 => name.clone(),
Some(name) => format!("{name}-{:02}", index + 1),
None => format!("{label}-{:02}", index + 1),
};
files.push(copy_artifact(root, generation, image, label, folder, &name)?);
}
}
Ok(())
@ -160,7 +174,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
read_json(&target.join("交付清单.json"))
.ok()
.filter(|saved| saved["deliveryId"] == delivery_id)
.map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"]}))
.map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"],
"missingOutputs":saved["missingOutputs"],"missing":saved["missing"]}))
};
// Recover a committed directory if the client lost the completion event.
for number in 1.. {
@ -179,7 +194,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
let project_file = package_root.join(format!("{name}.xiaoyi"));
let mut package = json!({"version":2,"localId":policy.project,"scope":policy.scope,
"snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":format!("{name} 资源")});
project_file::write_project(project, &project_file, &mut package, policy)?;
project_file::write_project(project, &project_file, &mut package, policy, true)?;
let reopened = read_json(&project_file)?;
if reopened != package {
return Err("小壹工程清单读回不一致".into());
@ -194,8 +209,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
let format = file.extension().and_then(|extension| extension.to_str()).unwrap_or("");
let size = artifact_size(&file, format)?;
let record = file_record(root, &file, "工程资源", size)?;
// The portable checkpoint normalizes its context and stops any active run.
if !matches!(relative, "context.json" | "production-run.json")
// The portable checkpoint normalizes its context.
if relative != "context.json"
&& record["sha256"] != canvas_workspace::file_digest(&project.join(relative)).map_err(disk)?
{
return Err("工程资源与本机草稿内容不一致".into());
@ -213,29 +228,42 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
if !seen.insert((variant, component)) {
return Err("本轮交付含重复输出".into());
}
let color = variant_name(&creation["brief"], variant);
let index = variant_folders.len() + 1;
let folder = variant_folders.entry(variant).or_insert_with(|| {
if variants.len() == 1 {
return PathBuf::new();
}
let label = creation["brief"]["variants"]
.as_array()
.into_iter()
.flatten()
.find(|row| row["id"] == variant)
.and_then(|row| row["name"].as_str())
.unwrap_or("花色");
PathBuf::from(format!("{index:02} {}", name_component(label)))
PathBuf::from(format!("{index:02} {}", color.as_deref().unwrap_or("花色")))
});
copy_generation(root, project, input, output, folder, &mut files)?;
copy_generation(root, project, input, output, folder, color.as_deref(), &mut files)?;
}
let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?;
let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?;
let all_outputs_completed = missing_outputs == 0;
let mut missing = Vec::new();
if missing_outputs > 0
&& let Ok(checkpoint) = read_json(&project.join("production-run.json"))
&& checkpoint["deliveryId"] == delivery_id
&& checkpoint["workspaceId"] == input["workspaceId"]
{
for output in checkpoint["requestedOutputs"].as_array().into_iter().flatten() {
let (Some(variant), Some(component)) = (output["variantId"].as_str(), output["outputId"].as_str()) else { continue; };
if seen.contains(&(variant, component)) { continue; }
let reason = checkpoint["drafts"].as_array().into_iter().flatten()
.find(|row| row["variantId"] == variant && row["outputId"] == component)
.and_then(|row| row["reason"].as_str());
missing.push(json!({"outputId":component,"variantId":variant,
"variantName":variant_name(&creation["brief"], variant),"label":output["label"],"reason":reason}));
}
}
let all_outputs_completed = input["total"].as_u64() == Some(outputs.len() as u64);
let mut counts = BTreeMap::new();
for category in files.iter().filter_map(|file| file["category"].as_str()) {
*counts.entry(category.to_owned()).or_insert(0) += 1;
}
let manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed,
"completedOutputs":outputs.len(),"totalOutputs":input["total"],"counts":counts,"files":files});
"completedOutputs":outputs.len(),"totalOutputs":total,"missingOutputs":missing_outputs,"missing":missing,
"counts":counts,"files":files});
transfer::no_credentials(&manifest)?;
write_json(&root.join("交付清单.json"), &manifest)?;
sync_tree(root)?;
@ -253,7 +281,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
Ok(()) => {
let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error));
return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed,
"counts":counts,"durabilityWarning":flush}));
"counts":counts,"missingOutputs":missing_outputs,"missing":missing,"durabilityWarning":flush}));
}
Err(_) if target.exists() => continue,
Err(error) => return Err(disk(error)),
@ -313,8 +341,9 @@ mod tests {
let canvas = Document::new("天青椅", Size::new(8, 10), ColorMode::Rgb, SampleType::U8);
photocraft_format::PcraftWriter::new().save_path(&canvas, &project.join("canvas.pcraft"), &Default::default()).unwrap();
write_json(&project.join("context.json"), &json!({"localId":local,"owner":"owner"})).unwrap();
write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅"}})).unwrap();
let variant = Uuid::new_v4().to_string();
write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅",
"variants":[{"id":variant,"name":"浅橡木"}]}})).unwrap();
let workspace = Uuid::new_v4().to_string();
let mut published = Vec::new();
for (component, regions, screens) in [
@ -379,19 +408,52 @@ mod tests {
("详情页切片/详情页-02.jpg", 8, 6),
("主图/主图-01.jpg", 8, 4),
("主图/主图-02.jpg", 8, 6),
("SKU/SKU-01.jpg", 8, 10),
("SKU/SKU-浅橡木.jpg", 8, 10),
] {
let bytes = fs::read(final_dir.join(path)).unwrap();
assert_eq!(photocraft_codecs::probe_size(&bytes).unwrap(), (width, height));
}
for name in ["详情页", "主图", "SKU"] {
let filename = format!("{name}.psd");
let bytes = fs::read(final_dir.join("PSD").join(&filename)).unwrap();
assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10));
let image = photocraft_codecs::decode(&bytes).unwrap();
assert_eq!((image.width(), image.height()), (width, height));
eprintln!("{path}:{} 字节,JPEG 质量 {:?}", bytes.len(), photocraft_codecs::jpeg_quality(&bytes));
}
let resources = read_json(&final_dir.join("工程文件/天青椅.xiaoyi")).unwrap();
let snapshot = project_file::resource_checkpoint(&final_dir.join("工程文件/天青椅.xiaoyi"), &resources).unwrap();
assert!(!snapshot.join("product-exports").exists());
let baseline_file = root.path().join("baseline.xiaoyi");
let mut baseline = json!({"version":2,"localId":local,"scope":"owner","snapshot":Uuid::new_v4().to_string(),
"sourceRoot":project,"resources":"baseline 资源"});
project_file::write_project(&project, &baseline_file, &mut baseline, &policy, false).unwrap();
let baseline_root = project_file::resource_checkpoint(&baseline_file, &baseline).unwrap();
let baseline_bytes: u64 = baseline["projectManifest"]["included"].as_array().unwrap().iter()
.map(|entry| fs::metadata(baseline_root.join(entry.as_str().unwrap())).unwrap().len()).sum();
let resource_bytes: u64 = manifest["files"].as_array().unwrap().iter().filter(|entry| entry["category"] == "工程资源")
.map(|entry| entry["sizeBytes"].as_u64().unwrap()).sum();
assert!(resource_bytes < baseline_bytes);
eprintln!("工程资源:{baseline_bytes} → {resource_bytes} 字节");
let clean = root.path().join("clean");
fs::create_dir(&clean).unwrap();
assert_eq!(project_file::open(&final_dir.join("工程文件/天青椅.xiaoyi"), &clean, "owner").unwrap(), local);
for name in ["详情页", "主图", "SKU"] {
let native = clean.join(format!("{name}.pcraft"));
fs::copy(final_dir.join("工程文件").join(format!("{name}.pcraft")), &native).unwrap();
let doc = photocraft_format::load_path(&native).unwrap();
assert_eq!(doc.size, Size::new(8, 10));
let filename = format!("{name}.psd");
let layered = clean.join(&filename);
fs::copy(final_dir.join("PSD").join(&filename), &layered).unwrap();
let bytes = fs::read(layered).unwrap();
assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10));
}
let packaged = clean.join("天青椅.xiaoyi");
fs::copy(final_dir.join("工程文件/天青椅.xiaoyi"), &packaged).unwrap();
let clean_snapshot = project_file::resource_checkpoint(&packaged, &resources).unwrap();
for entry in resources["projectManifest"]["included"].as_array().unwrap() {
let relative = entry.as_str().unwrap();
let destination = clean_snapshot.join(relative);
fs::create_dir_all(destination.parent().unwrap()).unwrap();
fs::copy(snapshot.join(relative), destination).unwrap();
}
fs::rename(&project, root.path().join("hidden-source")).unwrap();
assert_eq!(project_file::open(&packaged, &clean.join("drafts"), "owner").unwrap(), local);
fs::rename(root.path().join("hidden-source"), &project).unwrap();
let original = fs::read(manifest_path).unwrap();
assert_eq!(deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap()["path"], delivered["path"]);
input["deliveryId"] = json!(Uuid::new_v4().to_string());
@ -400,6 +462,78 @@ mod tests {
assert_eq!(fs::read(final_dir.join("交付清单.json")).unwrap(), original);
}
#[test]
fn multiple_colors_keep_their_numbered_images_and_missing_outputs_are_reported() {
let (_root, project, local, mut input) = fixture();
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
let second_color = Uuid::new_v4().to_string();
let mut creation = creation::load(&project).unwrap();
creation["brief"]["variants"].as_array_mut().unwrap()
.push(json!({"id":second_color,"colorName":"暖白"}));
write_json(&project.join("creation.json"), &creation).unwrap();
let doc = Document::new("暖白", Size::new(8, 10), ColorMode::Rgb, SampleType::U8);
let mut sku = json!({"workspaceId":input["workspaceId"],"variantId":second_color,"outputId":"sku_images"});
let receipt = canvas_workspace::receipt_path(&project, &second_color, "sku_images");
canvas_workspace::publish_product_generation(&receipt, &doc, &json!(8), &mut sku, &[(0, 8, 4), (4, 8, 6)], &[]).unwrap();
input["published"].as_array_mut().unwrap().push(json!({"variantId":second_color,"outputId":"sku_images","generationId":sku["generationId"]}));
input["total"] = json!(5);
let missing = json!({"variantId":second_color,"outputId":"main_images","label":"主图","reason":"尚未导出"});
write_json(&project.join("production-run.json"), &json!({
"deliveryId":input["deliveryId"],"workspaceId":input["workspaceId"],"requestedOutputs":[missing],"drafts":[missing],
})).unwrap();
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
assert_eq!(delivered["allOutputsCompleted"], false);
assert_eq!(delivered["missingOutputs"], 1);
assert_eq!(delivered["missing"][0]["reason"], "尚未导出");
let bundle = Path::new(delivered["path"].as_str().unwrap());
for relative in ["SKU/01 浅橡木/SKU-浅橡木.jpg", "SKU/02 暖白/SKU-暖白-01.jpg", "SKU/02 暖白/SKU-暖白-02.jpg"] {
assert!(bundle.join(relative).is_file(), "{relative}");
}
let manifest = read_json(&bundle.join("交付清单.json")).unwrap();
assert_eq!(manifest["missing"], delivered["missing"]);
let reopened = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
assert_eq!(reopened["missing"], delivered["missing"]);
assert_eq!(reopened["path"], delivered["path"]);
}
#[test]
fn delivered_long_canvas_reopens_as_layered_psb_with_editable_text() {
use photocraft_doc::{Layer, LayerContent, TextLayer, text::{CharStyle, TextRun}};
let (root, project, local, mut input) = fixture();
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
let mut canvas = Document::new("长详情", Size::new(16, 30_001), ColorMode::Rgb, SampleType::U8);
let style = CharStyle { font_family: "Arial".into(), size_pt: 18.0, ..Default::default() };
let text = TextLayer {
text: "AB".into(), font_family: style.font_family.clone(), size_pt: style.size_pt,
runs: vec![
TextRun { len: 1, style: style.clone() },
TextRun { len: 1, style: CharStyle { size_pt: 24.0, ..style } },
],
..Default::default()
};
canvas.layers.push(Layer::new("成稿文案", LayerContent::Text(text)));
let variant = input["published"][0]["variantId"].as_str().unwrap().to_owned();
let receipt = canvas_workspace::receipt_path(&project, &variant, "detail");
let mut detail = json!({"workspaceId":input["workspaceId"],"variantId":variant,"outputId":"detail"});
canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(8), &mut detail,
&[(0, 16, 30_001)], &[(0, 16, 30_000), (30_000, 16, 1)]).unwrap();
input["published"] = json!([{"variantId":variant,"outputId":"detail","generationId":detail["generationId"]}]);
input["total"] = json!(1);
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
let final_dir = Path::new(delivered["path"].as_str().unwrap());
let copy = root.path().join("详情页.psb");
fs::copy(final_dir.join("PSD/详情页.psb"), &copy).unwrap();
let bytes = fs::read(copy).unwrap();
let imported = photocraft_io::import("详情页.psb", &bytes).unwrap().document;
assert_eq!(imported.size, canvas.size);
let layer = imported.layers.iter().find(|layer| layer.name == "成稿文案").unwrap();
let LayerContent::Text(text) = &layer.content else { panic!("保留可编辑文字图层"); };
assert_eq!(text.text, "AB");
assert_eq!(text.font_family, "Arial");
assert_eq!(text.runs.iter().map(|run| run.style.size_pt).collect::<Vec<_>>(), [18.0, 24.0]);
}
#[test]
fn invalid_destination_cancellation_and_credentials_leave_generations_intact() {
let (root, project, local, mut input) = fixture();

View File

@ -134,8 +134,15 @@ fn checkpoint_file(source: &Path, output: &Path, logical: &str, previous: Option
Ok(())
}
#[derive(Clone, Copy)]
enum CheckpointCopy<'a> {
Save,
Deliver,
Reopen(&'a Path, &'a Path),
}
fn copy_project(
root: &Path, dir: &Path, target: &Path, previous: Option<&Path>, reopen: Option<(&Path, &Path)>,
root: &Path, dir: &Path, target: &Path, previous: Option<&Path>, mode: CheckpointCopy<'_>,
policy: &Policy<'_>, selection: &mut Selection,
) -> R<()> {
let relative_dir = dir.strip_prefix(root).map_err(disk)?;
@ -152,6 +159,10 @@ fn copy_project(
let path = entry.path();
let relative = path.strip_prefix(root).map_err(disk)?;
let logical = relative.to_string_lossy().replace('\\', "/");
if matches!(mode, CheckpointCopy::Deliver) && matches!(logical.as_str(), "product-exports" | "production-run.json") {
selection.excluded.push(transfer::exclusion(&logical, "outside_delivery_checkpoint"));
continue;
}
if let Some(ids) = &published
&& entry.file_name().to_str().is_none_or(|name| !ids.iter().any(|id| id == name)) {
selection.excluded.push(transfer::exclusion(&logical, "unpublished_output"));
@ -160,7 +171,7 @@ fn copy_project(
let kind = entry.file_type().map_err(disk)?;
if kind.is_dir() && (dir != root || ["creation-assets", "creation-generated", "creation-tasks", "template-outputs",
"product-exports", "composer-attachments", "image-jobs", "reference-previews", "agent"].iter().any(|name| relative == Path::new(name))) {
copy_project(root, &path, target, previous, reopen, policy, selection)?;
copy_project(root, &path, target, previous, mode, policy, selection)?;
} else if kind.is_file() {
let allowed = if relative.starts_with("agent") {
policy.agent_file(&logical)
@ -171,6 +182,10 @@ fn copy_project(
}
let output = target.join(relative);
fs::create_dir_all(output.parent().ok_or("工程资源路径无效")?).map_err(disk)?;
let reopen = match mode {
CheckpointCopy::Reopen(old, new) => Some((old, new)),
_ => None,
};
checkpoint_file(&path, &output, &logical, previous.map(|p| p.join(relative)).as_deref(), reopen, policy.chat)?;
selection.included.push(logical);
} else {
@ -180,7 +195,7 @@ fn copy_project(
Ok(())
}
pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>) -> R<()> {
pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R<()> {
let checkpoint = resource_checkpoint(file, manifest)?;
let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?;
fs::create_dir_all(resource_dir).map_err(disk)?;
@ -190,7 +205,8 @@ pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, polic
.filter(|previous| previous.is_dir());
let stage = tempfile::tempdir_in(resource_dir).map_err(disk)?;
let mut selection = Selection::default();
copy_project(dir, dir, stage.path(), previous.as_deref(), None, policy, &mut selection)?;
let mode = if delivery { CheckpointCopy::Deliver } else { CheckpointCopy::Save };
copy_project(dir, dir, stage.path(), previous.as_deref(), mode, policy, &mut selection)?;
if !["canvas.pcraft", CONTEXT].into_iter().all(|required| selection.included.iter().any(|path| path == required)) {
return Err("工程缺少必要的编辑数据,未写入工程包".into());
}
@ -241,7 +257,7 @@ pub(super) fn save(
let policy = Policy { chat, scope, project: local };
let mut manifest = json!({"version":2,"localId":local,"scope":scope,"snapshot":snapshot,
"sourceRoot":dir,"resources":format!("{name} 资源")});
write_project(dir, &file, &mut manifest, &policy)?;
write_project(dir, &file, &mut manifest, &policy, false)?;
context["projectFile"] = json!({"path":file,"snapshot":snapshot,"syncChatHistory":chat});
result["path"] = json!(file);
result["localSave"] = json!({"state":"saved","path":file,"manifest":manifest["projectManifest"]});
@ -325,7 +341,7 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R<String> {
fs::create_dir_all(projects).map_err(disk)?;
let stage = tempfile::tempdir_in(projects).map_err(disk)?;
let mut selection = Selection::default();
copy_project(&resources, &resources, stage.path(), None, Some((old, &destination)), &policy, &mut selection)?;
copy_project(&resources, &resources, stage.path(), None, CheckpointCopy::Reopen(old, &destination), &policy, &mut selection)?;
if manifest["version"] == 2 {
let restored = policy.manifest(stage.path(), selection.included, selection.excluded)?;
if manifest["projectManifest"]["version"] != 1 || restored["included"] != manifest["projectManifest"]["included"]