mirror of
https://github.com/storytold/designcraft.git
synced 2026-10-25 02:37:00 -06:00
Conflicts resolved per file (both sides kept unless noted):
crates/engine/src/atomic.rs | 1 | main's: `write_file` removed (main routes command writes through `crate::io::write_file`); its one caller in file.rs now uses `crate::io::write_file`
crates/engine/src/cmd/datamerge/fill.rs | 1 | next's `Graphic` literal (has `clip` and `wrap`, which next's `Graphic` carries)
crates/engine/src/cmd/datamerge/mod.rs | 1 | main's `read_path_capped` (crate::io metadata/read_capped, roots checked); next's capped read is the same behaviour
crates/engine/src/cmd/datamerge/parse.rs | 1 | main's (`crate::io::metadata`, `crate::io::Metadata`)
crates/engine/src/cmd/edit.rs | 1 | next's `spread_param(p, "edit.paste")` (the second argument is the command id on both sides)
crates/engine/src/cmd/export.rs | 3 | main's: EPUB params doc, `toc_title` once (main's position; next's duplicate dropped)
crates/engine/src/cmd/file.rs | 7 | place doc: next's (lists page/rect/autoflow params #803 checks); next's recent-file functions + main's `foreign_document`; next's open (load_bytes, warnings, non-DesignCraft refusal) with main's checked `crate::io::read_file` for the bytes; main's `check_write` be
crates/engine/src/cmd/find.rs | 7 | main's Find scope (FindContext, scope/selection/story, continuation, UTF-8 repair) on next's `designcraft_compose::grep::Grep` (dialect GREP): find uses `find_all` capped at MAX_MATCHES, change uses `replacements`/`find_all` (literal change text not expanded), fin
crates/engine/src/cmd/fonts.rs | 1 | next's (`has_style`, resolved/replacement face); `has_style` already compares styles ignoring spacing and case, which is main's `same_style` fix; main's test kept
crates/engine/src/cmd/interchange.rs | 1 | next's `import_idml_report_with_previews` (previews for unreadable links)
crates/engine/src/cmd/layout.rs | 8 | pages.insert: main's overflow-safe `after` + next's checked `parent_ref`; main's duplicateSpread doc; layout.section: next's `SectionEdit` (already keeps unnamed settings, #717) with main's `d.repaginate()` moved into `SectionEdit::apply` (remove and set paths),
crates/engine/src/cmd/links.rs | 5 | next's links.list (no doc clone); main's `text_status` via crate::io; `use std::io::Read` dropped (unused after main's read_capped); test literals main's. `link_missing` (next) uses `crate::io::exists` for the file-guard scan
crates/engine/src/cmd/object.rs | 4 | object.fill/stroke tint-alone: main's (23e1680e7; out-of-range tint is an error, which main's test asserts); object.fit doc: next's (lists `axis`)
crates/engine/src/cmd/paths.rs | 1 | next's (shatai transform on outlines)
crates/engine/src/cmd/place_text.rs | 1 | next's `add_flow_frame` (used by autoflow)
crates/engine/src/cmd/preflight.rs | 2 | next's overset/unplacedStory issue (its `overset_location` already applies the parent transform main's #738 fix adds); next's two test modules kept with main's
crates/engine/src/cmd/scripts.rs | 1 | combined: next's `in_undo_step = false` (#406) + main's full rollback of a failed script (#709)
crates/engine/src/cmd/style.rs | 14 | param docs next's (gradient swatch.create, swatch stops, model colours); create_para next's; rename_style main's structure (rename entry, then `redirect_style_refs`), redirect has next's full reference set (cells, defaults, notes, TOC) + main's never-based-on-it
crates/engine/src/cmd/text.rs | 10 | main's selectSentence/Paragraph/Story + select_around; next's selectionAttrs (mixed) + main's openTypeFeatures/type.feature; main's comments; tracked typing: next's `reserve_command_text` + main's `insert_format_at`; empty-paragraph mark formatting main's (with `
crates/engine/src/cmd/thread.rs | 1 | next's `spread_param(p, "text.thread")`
crates/engine/src/dtd.rs | 1 | next's linear, depth-bounded `expand_parameter_entities` with main's budget (input + 1 MiB, `MAX_EXPANDED_BYTES`) and message ("expand the DTD beyond"); 16 MiB constant removed; both sides' tests pass on message
crates/engine/src/guard.rs | 2 | main's whole-transaction snapshot (docs, active, journal; #742) + next's `in_undo_step` restore; tests both
crates/engine/src/lib.rs | 5 | LoadedGraphic doc next's; next's `new_document_preview`; execute: main's `discard_stale_find_scope()` before next's nested-undo run; modules both (tests_autosize, tests_file_guard, tests_params, tests_roots)
crates/engine/src/recovery.rs | 1 | next's test (superset of main's assertion)
crates/engine/src/tests.rs | 4 | moved tests deduplicated (identical on both sides); next's preflight and direct-selection/kerning tests + main's style-delete, locked-frame and baseline-fit tests
crates/engine/src/tests_idml.rs | 3 | main's order (drop cap and margins tests identical on both sides, once each)
crates/ui-egui/src/canvas.rs | 3 | next's screen_options/DisplayKey block and tests kept; two tests that auto-merge had added twice (parent_guides_on_a_page_are_not_picked_there, baseline_grid_lines_are_the_ones_on_the_page) kept once; main's `typing`/`screen_at`/`click` helpers and its tests clicks
crates/ui-egui/src/control.rs | 3 | main's `count` check and pending budget (control queue + synthetic queue); exact-budget test runs both sides' cases (click 255 on 9,492 pending; drag 9492×255)
crates/ui-egui/src/cursors.rs | 1 | main's (same Pen cursor set)
crates/ui-egui/src/dialogs.rs | 14 | dialog body (newDocument … alert match) is next's text, with main's Find/Change scope reset (`set_field`, `reset_find_scope`, `find_change_params`) and main's Create Guides / Margins and Columns arms ported in; `Dialog::new` ruby section (next) + main's `set_fi
crates/ui-egui/src/i18n.rs | 7 | ka and pl modules, languages, statics and lookups both; `category_first` covers uk, ru, pl, ka and `count_label` keeps next's Czech plurals; shared TABLE union; next's duplicate rows for Auto, Number:, Gutter:, Top:, Bottom:, Inside:, Outside:, Left:, Right: dropped
crates/ui-egui/src/i18n/ar.rs | 2 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/it.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/ja.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/pt_br.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/uk.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/icons.rs | 2 | both tests (main's typography icon, next's distribute icons)
crates/ui-egui/src/lib.rs | 11 | UiState: next's tabs_panel + main's last_color/last_gradient; `cursors` field once; next's SVG paste and paste-on-spread-in-view; next's extensionless document open; opens_as_document next's comment; tests both (next's control bar / key-name tests, main's rich black
crates/ui-egui/src/menus.rs | 15 | app.language doc next's text with pl and ka; UI_COMMANDS both (next's Tabs, Toggle Presentation, Apply None text; main's panel commands, Apply Color, Apply Gradient); Edit › Interface Language stays out (next moved it to Preferences); Type menu main's order with
crates/ui-egui/src/panels/glyphs.rs | 1 | next's (already has main's scroll-bar fix); the scroll-bar test module auto-merge had added twice kept once
crates/ui-egui/src/panels/layers.rs | 3 | next's drag-and-drop `object_rows`, with main's features ported into it: selection reveal (layer opens, row scrolls into view once), selected rows highlighted (also a group whose member is selected), double-click rename in place (`object.rename` queued like
crates/ui-egui/src/panels/mod.rs | 6 | tabs + typography modules and color_panel_tests; SelInfo has wrap_side/wrap_contour and wrap_offsets (offsets from the graphic's own wrap when it is selected); next's swatch_picker returning the chip response; next's content_selection_tests
crates/ui-egui/src/panels/pages.rs | 1 | next's (parents dragged by id)
crates/ui-egui/src/panels/properties.rs | 4 | next's swatch popup (Apply To, Tint); main's four wrap offsets then next's Wrap To / Contour Type; test fixtures main's (`..Default::default()`, no unused builder)
crates/ui-egui/src/panels/swatches.rs | 3 | main's Delete Swatch button + next's New Swatch comment; next's draggable rows; click: main's PICKED + fill/stroke in front, with next's no-apply on double-click
crates/ui-egui/src/toolbar.rs | 2 | main's Apply Color / Gradient / None wells and functions; next's apply_none doc line
crates/compose/src/lib.rs | 5 | next's line loop kept (mark_leading + last_line_mark, wrap segments/carry, grid gyoudori); main's mark-chars base_leading block (auto-merged) stays beside it. `fits`: next's #106 rule (baseline fit for horizontal frames, full descent for paths, vertical text, footnote
crates/compose/src/tests.rs | 5 | next's tests (tombstone set, sliver/one-sided/contour/clipping wrap tests, borders, lists, kenten, grid, anchored wrap, balance, shaped frames) plus main's an_empty_last_paragraph_isnt_overset; main's wrap_object_beside_one_narrow_column_leaves_the_other_alone re-ad
crates/doc/src/assets.rs | 1 | main's doc comment (same meaning)
crates/doc/src/build.rs | 3 | parent_page_for: next's parent_page_for_side (RTL-aware); single_sided_page_shows_first_parent_page test kept once, at main's position
crates/doc/src/item.rs | 1 | next's rotated_group_bounds_follow_the_children_outlines test kept
crates/doc/src/lib.rs | 1 | next's kerning_increment field kept; main's "Bulleted & Numbered" wording
crates/doc/src/page.rs | 1 | next's outer_page_indices + parent_page_for_side (integration of parent-margins with rtl-master-sides); main's parent_page_index dropped, its only caller (build.rs) uses parent_page_for_side
crates/doc/src/slice.rs | 5 | extract: next's `marked()` (get-based, fix_notes/fix_endnotes/fix_marks; main's version indexed slices and could panic); insert_story: main's take() limit on endnote/editorial payload copies with next's id comment, redundant `let ne`/`let nn` dropped; main's excess_note
crates/geom/src/corners.rs | 1 | next's box_outline_rounds_only_closed_corners test kept
crates/render/src/damage.rs | 1 | next's wrapping-anchored-object damage test kept
crates/render/src/fx.rs | 2 | feather: next's choke/corners sigma+join inside main's structure (body and clip at device resolution, with_filters(.., None)); inner glow centre: next's blend `mix` with main's clip argument (bp, xf)
crates/render/src/lib.rs | 3 | next's layer comment; next's front baseline grid draw after items; gradient match on g.kind (main's tuple scrutinee did not match the single-pattern arms)
crates/render/src/text.rs | 5 | paint_glyphs: main's paint_stroke closure structure with next's stroke overprint (overprinting helper, stroke `(TextPaint, bool)`); callers pass next's overprint_fill/overprint_stroke
crates/render/tests/placed_pdf.rs | 1 | main's `near` helper version
crates/tools/src/lib.rs | 1 | main's (PenConvert already declared below, avoids a duplicate variant)
crates/tools/src/pen.rs | 1 | main's module doc
crates/tools/src/select.rs | 1 | next's Drag::Corner variant (live corners) kept
crates/tools/src/tests.rs | 4 | next's tests (content drag, live corners, table border drag, eyedropper matchFrom, fitting handles, pen cursors once); eyedropper_ignores_inactive keeps next's samples_image check (main's exact-JSON compare lacks matchFrom) with main's `..Default::default()` Asset lit
crates/tools/src/text.rs | 2 | next's table border drag (BorderDrag, border_at) kept, then main's comment on locked text frames
crates/tools/src/xform.rs | 2 | main's explicit `Vec<&Item>` for shown children; next's eyedropper matchFrom (integration 796e9d713)
Cargo.toml | 2 | main's craft-pdf workspace dep added (craft-print stays once, in next's craft-libs block); [patch.crates-io] keeps next's winit (rust-windowing #4694 backport) and adds main's krilla patch; main's skylartaylor winit left out (see UNSURE 1)
Cargo.lock | 1 | union: next's craft-atomic and craft-cms entries plus main's craft-pdf entry; needs `cargo` normalisation
README.md | 1 | Open bullet combines INDD import via indd-utils (next) and editable PowerPoint export (main); main's paragraph break kept
contributors/people.toml | 1 | both people kept (switch87 from next, Nmarello from main)
apps/designcraft-cli/src/main.rs | 4 | next's `Export` enum dispatch kept; main's .pptx export added as `Export::Pptx` (run prints slides and warnings, script runs file.exportPptx); main's `--pdf-options` null-as-{} parse; usage lines list .pptx
apps/designcraft/src/main.rs | 3 | `startup.leave()` right after `app.ui` (main #380) and next's macOS `sync_movable` kept after the IME discard; next's Apple Events install kept; main's macOS Dock Quit `with_close_requested_on_terminate` block left out (needs the skylartaylor winit; UNSURE 1)
crates/fonts/src/fontdb.rs | 9 | FONT6 aliases (next) combined with #911 WWS names (main): ScannedFace and both CatalogEntry constructors carry `wws` and `aliases`; `canonical_family` falls back to WWS family names; `exact_style_traits` canonicalises then tries typographic, then WWS names (`named_st
crates/format/src/lib.rs | 1 | tests: both sides kept (next's r7a nullable-default tests; main's oversized ZIP entry/asset/entry-count tests)
crates/idml/src/import.rs | 11 | main's bounded `Package` reader under next's `import_idml_report_with_previews` (metadata read through `pkg.part`); next's `tab_list_repaired` kept; ruler origin: next's `settings.ruler_origin`, and main's guide import reads it (main's private `RulerOrigin` enum and
crates/idml/src/tests.rs | 6 | item-level union: all next tests plus main's new ones (ruler guides, package limits, CJK leading model, liquid page rules module, mojikumi); no test dropped
crates/mcp/src/backend.rs | 1 | test comment merged from both
crates/pdf/src/tests.rs | 1 | tests: both sides kept
crates/pdf/src/text.rs | 4 | next's (skew `tan`, cluster `start`, ruby overprint warning); main had no change here beyond base
crates/textimport/src/docx.rs | 5 | next's (ListCounter integration for list levels, page-break test position); main's side was the older form of the same code
crates/epub/src/lib.rs | 30 | non-test code is next's (StoryWriter holds img_src/images/no_alt/heading_ids; covers main's #787/#791/#782 fixes, plus #314 group transforms, anchored images in images_without_alt, endnote story skipped in the TOC); tests: next's set plus main's extra css_weight_style a
docs/control-protocol.md | 2 | next's rows (ui.paste, count 1–255, documentGrid) and wording
docs/file-format-parity.md | 1 | rows combined (next's ICC notes, main's TIFF indexed colour)
docs/gaps.md | 2 | status change notes unioned; Flex Layout removed from missing (main implemented it), next's Parent Options sentence kept
docs/localization-parity.md | 4 | Polish and Georgian rows; 5 languages beyond the twelve; file list includes cs and ka; both history rows
docs/roadmap.md | 1 | M1 next's (#186 fixed on next), M2 main's IME wording
docs/target-app-parity.md | 6 | next's status line; File formats row next's, UI/UX row main's (IME no longer failing); UI line next's plus main's Swatches detail; one Page tool line (main's fuller one); Load styles and main's fuller Pathfinder line both kept, main's duplicate short Pathfinder line r
docs/ui-parity.md | 1 | IME row main's, Font menu row next's
i18n/fr.rs: five rows dropped that main's shared table now has (Row, Open Path, Flex Layout, Current Page Number, Rulers).
424 lines
22 KiB
Rust
424 lines
22 KiB
Rust
//! The agent-facing command line: scripts with references, describe, filtered command lists.
|
|
|
|
use std::io::Write;
|
|
use std::process::{Command, Stdio};
|
|
|
|
fn cli() -> Command {
|
|
Command::new(env!("CARGO_BIN_EXE_designcraft-cli"))
|
|
}
|
|
|
|
#[test]
|
|
fn script_from_stdin_with_references_saves_and_exports() {
|
|
let dir = std::env::temp_dir().join(format!("dc-cli-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let (doc, png) = (dir.join("a.designcraft"), dir.join("a.png"));
|
|
let mut child = cli()
|
|
.args(["script", "-", "--save", doc.to_str().unwrap(), "--export", png.to_str().unwrap()])
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.spawn()
|
|
.unwrap();
|
|
child
|
|
.stdin
|
|
.take()
|
|
.unwrap()
|
|
.write_all(
|
|
b"# comment\nframe.create {\"rect\": [72, 72, 300, 200], \"content\": \"text\", \"text\": \"Hi\"}\nstory.get {\"story\": \"$0.story\"}\n",
|
|
)
|
|
.unwrap();
|
|
let out = child.wait_with_output().unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
|
assert_eq!(v["completed"], 2);
|
|
assert_eq!(v["results"][1]["text"], "Hi");
|
|
assert!(doc.exists() && png.exists());
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
/// `--export` wrote a PNG of the page under every name it did not know: `out.html`, `out.txt` and
|
|
/// `OUT.PDF` were page images, and so was `out.designcraft` from `script` (#432).
|
|
#[test]
|
|
fn export_writes_the_file_type_its_extension_names() {
|
|
let frame = r#"{"rect": [72, 72, 400, 200], "content": "text", "text": "Hello"}"#;
|
|
let types: [(&str, &[u8]); 13] = [
|
|
// No extension: a PNG, as before.
|
|
("a", b"\x89PNG"),
|
|
("a.png", b"\x89PNG"),
|
|
("a.jpg", b"\xFF\xD8"),
|
|
("A.JPEG", b"\xFF\xD8"),
|
|
("a.pdf", b"%PDF"),
|
|
("A.PDF", b"%PDF"),
|
|
("a.designcraft", b"PK"),
|
|
("a.idml", b"PK"),
|
|
("a.epub", b"PK"),
|
|
("a.html", b"<!DOCTYPE html>"),
|
|
("a.htm", b"<!DOCTYPE html>"),
|
|
("a.rtf", b"{\\rtf"),
|
|
("a.txt", b"Hello"),
|
|
];
|
|
for mode in ["run", "script"] {
|
|
let dir = std::env::temp_dir().join(format!("dc-cli-types-{mode}-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let script = dir.join("page.dcs");
|
|
std::fs::write(&script, format!("frame.create {frame}\n")).unwrap();
|
|
let mut args: Vec<String> = match mode {
|
|
"run" => vec!["run".into(), "--cmd".into(), format!("frame.create={frame}")],
|
|
_ => vec!["script".into(), script.to_str().unwrap().into()],
|
|
};
|
|
for (name, _) in types {
|
|
args.extend(["--export".into(), dir.join(name).to_str().unwrap().into()]);
|
|
}
|
|
let out = cli().args(&args).output().unwrap();
|
|
assert!(out.status.success(), "{mode}: {}", String::from_utf8_lossy(&out.stderr));
|
|
for (name, start) in types {
|
|
let bytes = std::fs::read(dir.join(name)).unwrap();
|
|
assert!(bytes.starts_with(start), "{mode} --export {name} wrote {:?}", String::from_utf8_lossy(&bytes[..bytes.len().min(16)]));
|
|
}
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
}
|
|
|
|
/// A file type `--export` does not write is an error, before anything runs or is written.
|
|
#[test]
|
|
fn export_to_an_unknown_file_type_is_an_error() {
|
|
let dir = std::env::temp_dir().join(format!("dc-cli-unknown-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let (png, doc, unknown) = (dir.join("a.png"), dir.join("a.designcraft"), dir.join("a.xyz"));
|
|
let (png, doc, unknown) = (png.to_str().unwrap(), doc.to_str().unwrap(), unknown.to_str().unwrap());
|
|
for args in [["run", "--sample", "--export", png, "--export", unknown], ["script", "-", "--save", doc, "--export", unknown]] {
|
|
let out = cli().args(args).output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(!out.status.success(), "{args:?}: {err}");
|
|
assert!(err.contains(unknown) && err.contains(".html"), "{args:?}: {err}");
|
|
}
|
|
assert!(std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing is written when a file type is unknown");
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
/// With `--connect` the exports happen in the running app. `--export copy.designcraft` saves a
|
|
/// copy there: Save As would make the copy the file the open document saves to from then on.
|
|
#[test]
|
|
fn script_export_of_the_document_in_the_running_app_saves_a_copy() {
|
|
use std::io::{BufRead, BufReader};
|
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let port = listener.local_addr().unwrap().port().to_string();
|
|
// Stands in for the app: answers every request and keeps what was asked.
|
|
let app = std::thread::spawn(move || {
|
|
let (stream, _) = listener.accept().unwrap();
|
|
let mut reply = stream.try_clone().unwrap();
|
|
let mut asked = Vec::new();
|
|
for line in BufReader::new(stream).lines() {
|
|
let request: serde_json::Value = serde_json::from_str(&line.unwrap()).unwrap();
|
|
asked.push((request["params"]["command"].clone(), request["params"]["params"]["path"].clone()));
|
|
writeln!(reply, r#"{{"ok": true, "result": {{}}}}"#).unwrap();
|
|
}
|
|
asked
|
|
});
|
|
let out = cli().args(["script", "-", "--connect", &port, "--export", "copy.designcraft"]).output().unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
assert_eq!(app.join().unwrap(), [(serde_json::json!("file.saveACopy"), serde_json::json!("copy.designcraft"))]);
|
|
}
|
|
|
|
#[test]
|
|
fn failing_script_exits_nonzero_with_the_step() {
|
|
let mut child = cli().args(["script", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
|
child.stdin.take().unwrap().write_all(b"document.inspect\nno.such.command\n").unwrap();
|
|
let out = child.wait_with_output().unwrap();
|
|
assert!(!out.status.success());
|
|
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
|
assert_eq!(v["failedIndex"], 1);
|
|
}
|
|
|
|
#[test]
|
|
fn run_cmd_references_and_describe() {
|
|
let out = cli()
|
|
.args([
|
|
"run",
|
|
"--cmd",
|
|
r#"frame.create={"rect":[72,72,300,200],"content":"text","text":"Hello"}"#,
|
|
"--cmd",
|
|
r#"story.get={"story":"$0.story"}"#,
|
|
])
|
|
.output()
|
|
.unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
assert!(String::from_utf8_lossy(&out.stdout).contains("\"text\":\"Hello\""));
|
|
let out = cli().args(["describe", "footnote.insert"]).output().unwrap();
|
|
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
|
assert_eq!(v["label"], "Insert Footnote");
|
|
let out = cli().args(["commands", "footnote."]).output().unwrap();
|
|
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
|
assert!(v.as_array().unwrap().iter().all(|c| c.to_string().contains("footnote")));
|
|
}
|
|
|
|
/// #776: a key the command doesn't take fails the run (`--cmd`) or the step (`script`) instead of
|
|
/// being ignored.
|
|
#[test]
|
|
fn unknown_params_fail() {
|
|
let out = cli().args(["run", "--cmd", r#"style.list={"bogus":1}"#]).output().unwrap();
|
|
assert!(!out.status.success());
|
|
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown parameter `bogus`; the command takes no parameters"));
|
|
let mut child = cli().args(["script", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
|
child.stdin.take().unwrap().write_all(b"document.inspect\nfile.new {\"widht\": 300}\n").unwrap();
|
|
let out = child.wait_with_output().unwrap();
|
|
assert!(!out.status.success());
|
|
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
|
assert_eq!(v["failedIndex"], 1);
|
|
assert!(v.to_string().contains("did you mean `width`?"), "{v}");
|
|
}
|
|
|
|
/// `designcraft-cli --help` printed usage to stderr and exited 1; asking for help is not an
|
|
/// error (#243). It now goes to stdout and succeeds, while an unknown command keeps the same
|
|
/// usage on stderr and fails.
|
|
#[test]
|
|
fn help_goes_to_stdout_and_unknown_args_to_stderr() {
|
|
for flag in ["--help", "-h", "help"] {
|
|
let out = cli().arg(flag).output().unwrap();
|
|
let stdout = String::from_utf8_lossy(&out.stdout);
|
|
assert!(out.status.success(), "{flag}: {:?}", out.status);
|
|
assert!(stdout.starts_with("usage: designcraft-cli"), "{flag}: {stdout:?}");
|
|
assert!(stdout.contains("designcraft-cli --version"), "{flag}: {stdout:?}");
|
|
assert!(out.stderr.is_empty(), "{flag} wrote to stderr: {}", String::from_utf8_lossy(&out.stderr));
|
|
}
|
|
// An unknown option is still an error: usage on stderr, nothing on stdout, non-zero exit.
|
|
let out = cli().arg("--no-such-option").output().unwrap();
|
|
assert!(!out.status.success(), "{:?}", out.status);
|
|
assert!(out.stdout.is_empty(), "unexpected stdout: {}", String::from_utf8_lossy(&out.stdout));
|
|
assert!(String::from_utf8_lossy(&out.stderr).starts_with("usage: designcraft-cli"));
|
|
}
|
|
|
|
/// `script --help` was "unknown script option `--help`"; the line syntax was only in
|
|
/// `describe script.run` (#654).
|
|
#[test]
|
|
fn script_help_documents_the_syntax() {
|
|
for flag in ["--help", "-h"] {
|
|
let out = cli().args(["script", flag]).output().unwrap();
|
|
let stdout = String::from_utf8_lossy(&out.stdout);
|
|
assert!(out.status.success(), "{flag}: {:?} {}", out.status, String::from_utf8_lossy(&out.stderr));
|
|
assert!(stdout.starts_with("usage: designcraft-cli script"), "{flag}: {stdout:?}");
|
|
for needle in ["0-based", "$1.story", "$3.ids.0", "\\u2028", "ignore"] {
|
|
assert!(stdout.contains(needle), "{flag}: no {needle:?} in {stdout:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `designcraft-cli commands | head -1` panicked with "failed printing to
|
|
/// stdout: Broken pipe (os error 32)" and exit status 101.
|
|
#[test]
|
|
fn closed_stdout_ends_quietly() {
|
|
use std::io::Read;
|
|
let mut child = cli().arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
|
let mut first = [0u8; 16];
|
|
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
|
|
drop(child.stdout.take());
|
|
let out = child.wait_with_output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(out.status.success() && !err.contains("panicked"), "{:?}: {err}", out.status);
|
|
}
|
|
|
|
/// `--pdf-options` that was JSON but no object (`[1]`) panicked when the PDF's path was added to it.
|
|
#[test]
|
|
fn run_pdf_options_that_are_no_object_are_an_error() {
|
|
let pdf = std::env::temp_dir().join(format!("dc-cli-options-{}.pdf", std::process::id()));
|
|
for options in ["[1]", "\"all\"", "1", "null"] {
|
|
let out = cli().args(["run", "--sample", "--pdf-options", options, "--export", pdf.to_str().unwrap()]).output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(!out.status.success(), "{options}: {err}");
|
|
assert!(err.contains("--pdf-options") && !err.contains("panicked"), "{options}: {err}");
|
|
}
|
|
assert!(!pdf.exists());
|
|
}
|
|
|
|
/// `--scale`, `--page` and `--pdf-options` apply to the exports after them; one with no export
|
|
/// after it was silently ignored.
|
|
#[test]
|
|
fn run_export_options_come_before_their_export() {
|
|
let dir = std::env::temp_dir().join(format!("dc-cli-order-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let (a, b) = (dir.join("a.png"), dir.join("b.png"));
|
|
let (a, b) = (a.to_str().unwrap(), b.to_str().unwrap());
|
|
for (opt, val) in [("--scale", "0.5"), ("--page", "1"), ("--pdf-options", r#"{"pages":"1"}"#)] {
|
|
let out = cli().args(["run", "--sample", "--export", a, opt, val]).output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(!out.status.success(), "{opt} after the last --export: {err}");
|
|
assert!(err.contains(opt) && err.contains("before"), "{err}");
|
|
}
|
|
assert!(!std::path::Path::new(a).exists(), "nothing is exported when the arguments are wrong");
|
|
let out = cli().args(["run", "--sample", "--scale", "0.5", "--export", a, "--scale", "0.25", "--export", b]).output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(out.status.success(), "{err}");
|
|
assert!(err.contains("wrote") && std::path::Path::new(a).exists() && std::path::Path::new(b).exists(), "{err}");
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
/// `--pdf-options` must be a JSON object; any other JSON value used to panic when the PDF path was set on it.
|
|
#[test]
|
|
fn pdf_options_that_are_not_an_object_are_an_error_not_a_panic() {
|
|
let dir = std::env::temp_dir().join(format!("dc-cli-pdfopts-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let pdf = dir.join("out.pdf");
|
|
let pdf = pdf.to_str().unwrap();
|
|
for val in ["[]", "true", "1", r#""x""#] {
|
|
let out = cli().args(["run", "--sample", "--pdf-options", val, "--export", pdf]).output().unwrap();
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert_eq!(out.status.code(), Some(1), "{val}: {err}");
|
|
assert!(err.contains("--pdf-options") && !err.contains("panicked"), "{val}: {err}");
|
|
}
|
|
let out = cli().args(["run", "--sample", "--pdf-options", "null", "--export", pdf]).output().unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn raster_export_preserves_an_existing_reader_and_private_symlink_target() {
|
|
use std::io::Read;
|
|
use std::os::unix::fs::{PermissionsExt, symlink};
|
|
struct Fixture(std::path::PathBuf);
|
|
impl Drop for Fixture {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.0);
|
|
}
|
|
}
|
|
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
|
let dir = std::env::temp_dir().join(format!("designcraft-cli-atomic-{}-{stamp}", std::process::id()));
|
|
std::fs::create_dir(&dir).unwrap();
|
|
let fixture = Fixture(dir);
|
|
let target = fixture.0.join(format!("{}.png", "a".repeat(243)));
|
|
let old = b"previous private export";
|
|
std::fs::write(&target, old).unwrap();
|
|
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();
|
|
let alias = fixture.0.join("linked.png");
|
|
symlink(target.file_name().unwrap(), &alias).unwrap();
|
|
let mut reader = std::fs::File::open(&target).unwrap();
|
|
let out = cli().args(["run", "--sample", "--scale", "0.1", "--export", alias.to_str().unwrap()]).output().unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
let mut observed = Vec::new();
|
|
reader.read_to_end(&mut observed).unwrap();
|
|
assert!(observed == old, "CLI export changed bytes under an existing reader");
|
|
assert!(std::fs::read(&target).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
|
|
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o600);
|
|
assert!(std::fs::symlink_metadata(alias).unwrap().file_type().is_symlink());
|
|
}
|
|
|
|
/// Send `calls` (tool name, arguments) to `designcraft-cli mcp <args>`; returns whether it exited
|
|
/// cleanly, its stderr, and the stdout lines after `initialize`, one per call.
|
|
fn mcp_session(args: &[&str], calls: &[(&str, serde_json::Value)]) -> (bool, String, Vec<serde_json::Value>) {
|
|
let mut child = cli().arg("mcp").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
|
{
|
|
let stdin = child.stdin.as_mut().unwrap();
|
|
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
|
|
for (i, (name, arguments)) in calls.iter().enumerate() {
|
|
let call = serde_json::json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}});
|
|
writeln!(stdin, "{call}").unwrap();
|
|
}
|
|
}
|
|
let out = child.wait_with_output().unwrap();
|
|
let stdout = String::from_utf8(out.stdout).unwrap();
|
|
let replies = stdout.lines().skip(1).map(|l| serde_json::from_str(l).unwrap()).collect();
|
|
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned(), replies)
|
|
}
|
|
|
|
fn text(reply: &serde_json::Value) -> &str {
|
|
reply["result"]["content"][0]["text"].as_str().unwrap()
|
|
}
|
|
|
|
/// A `.designcraft` file with one page, made with the CLI itself.
|
|
fn make_document(path: &std::path::Path) {
|
|
let out = cli().args(["run", "--cmd", "file.new={}", "--cmd"]).arg(format!("file.save={}", serde_json::json!({"path": path}))).output().unwrap();
|
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
assert!(path.exists());
|
|
}
|
|
|
|
#[test]
|
|
fn mcp_automation_roots_confine_the_server() {
|
|
let base = std::env::temp_dir().join(format!("dc-cli-roots-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&base);
|
|
let (work, elsewhere) = (base.join("work"), base.join("elsewhere"));
|
|
std::fs::create_dir_all(&work).unwrap();
|
|
std::fs::create_dir_all(&elsewhere).unwrap();
|
|
make_document(&work.join("in.designcraft"));
|
|
make_document(&elsewhere.join("secret.designcraft"));
|
|
let work_s = work.to_str().unwrap();
|
|
let secret = elsewhere.join("secret.designcraft").to_str().unwrap().to_string();
|
|
|
|
// Both spellings of the flags; inside works, outside is refused with a readable message.
|
|
let read_flag = format!("--automation-read-root={work_s}");
|
|
let calls = [
|
|
("open_document", serde_json::json!({"path": work.join("in.designcraft").to_str().unwrap()})),
|
|
("open_document", serde_json::json!({"path": secret})),
|
|
("save_document", serde_json::json!({"path": work.join("saved.designcraft").to_str().unwrap()})),
|
|
("save_document", serde_json::json!({"path": elsewhere.join("saved.designcraft").to_str().unwrap()})),
|
|
("export_png", serde_json::json!({"path": elsewhere.join("page.png").to_str().unwrap()})),
|
|
("render_page", serde_json::json!({"path": elsewhere.join("render.png").to_str().unwrap()})),
|
|
];
|
|
let (success, stderr, replies) = mcp_session(&[&read_flag, "--automation-write-root", work_s], &calls);
|
|
assert!(success, "{stderr}");
|
|
assert!(stderr.contains("files confined"), "{stderr}");
|
|
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
|
|
assert_eq!(replies[1]["result"]["isError"], true);
|
|
assert!(text(&replies[1]).contains("outside the read root"), "{}", text(&replies[1]));
|
|
assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]);
|
|
assert!(work.join("saved.designcraft").exists());
|
|
for reply in &replies[3..] {
|
|
assert_eq!(reply["result"]["isError"], true, "{reply}");
|
|
assert!(text(reply).contains("outside the write root"), "{}", text(reply));
|
|
}
|
|
for name in ["saved.designcraft", "page.png", "render.png"] {
|
|
assert!(!elsewhere.join(name).exists(), "{name} was written outside the write root");
|
|
}
|
|
|
|
// A root left out grants none of its access.
|
|
let save = [("new_document", serde_json::json!({})), calls[2].clone()];
|
|
let (_, _, replies) = mcp_session(&[&read_flag], &save);
|
|
assert_eq!(replies[1]["result"]["isError"], true);
|
|
assert!(text(&replies[1]).contains("write authority is absent"), "{}", text(&replies[1]));
|
|
let (_, _, replies) = mcp_session(&["--automation-write-root", work_s], &calls[..1]);
|
|
assert_eq!(replies[0]["result"]["isError"], true);
|
|
assert!(text(&replies[0]).contains("read authority is absent"), "{}", text(&replies[0]));
|
|
|
|
// No flags: nothing is confined.
|
|
let (success, _, replies) = mcp_session(&[], &calls[1..2]);
|
|
assert!(success);
|
|
assert_eq!(replies[0]["result"]["isError"], false, "{}", replies[0]);
|
|
let _ = std::fs::remove_dir_all(base);
|
|
}
|
|
|
|
#[test]
|
|
fn mcp_automation_root_flags_are_checked_up_front() {
|
|
let base = std::env::temp_dir().join(format!("dc-cli-roots-args-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&base);
|
|
std::fs::create_dir_all(&base).unwrap();
|
|
let dir = base.to_str().unwrap();
|
|
let missing = base.join("missing");
|
|
let fails = |args: &[&str], needle: &str| {
|
|
let mut full = vec!["mcp"];
|
|
full.extend_from_slice(args);
|
|
let o = cli().args(&full).output().unwrap();
|
|
assert!(!o.status.success(), "{args:?}");
|
|
let err = String::from_utf8_lossy(&o.stderr).into_owned();
|
|
assert!(err.contains(needle), "{args:?}: {err}");
|
|
};
|
|
// The flags confine the in-process server, so they cannot be combined with --connect.
|
|
fails(&["--connect", "7979", "--automation-read-root", dir], "--connect");
|
|
fails(&["--automation-write-root", dir, "--connect", "7979"], "--connect");
|
|
fails(&["--automation-read-root", dir, "--automation-read-root", dir], "given twice");
|
|
fails(&["--automation-write-root", dir, "--automation-write-root", dir], "given twice");
|
|
fails(&["--automation-read-root", dir, "--automation-read-root=x"], "given twice");
|
|
fails(&["--automation-read-root"], "needs a folder");
|
|
fails(&["--automation-write-root", "--sample"], "needs a folder");
|
|
fails(&["--automation-read-root", missing.to_str().unwrap()], "cannot open the automation read root");
|
|
fails(&["--automation-write-root="], "needs a non-empty folder");
|
|
// A file is not a folder.
|
|
std::fs::write(base.join("f.txt"), "x").unwrap();
|
|
fails(&["--automation-write-root", base.join("f.txt").to_str().unwrap()], "cannot open the automation write root");
|
|
let _ = std::fs::remove_dir_all(base);
|
|
}
|
|
|
|
#[test]
|
|
fn usage_lists_the_automation_root_flags() {
|
|
let out = cli().arg("--help").output().unwrap();
|
|
let usage = String::from_utf8_lossy(&out.stdout);
|
|
assert!(usage.contains("--automation-read-root DIR") && usage.contains("--automation-write-root DIR"), "{usage}");
|
|
}
|