feat: ship the unique offline marqdo web Tool (WEB-02 candidate)
Implement the first Preview candidate in its unique owner repository: - marqdo web check/preview/handoff with explicit ENTRY/--unit/--root/--out/ --theme; independent executable packaged with tool.json (command web, api_revision/analysis requirements). - Consume only the public marqdo-web-design crate at a fixed git revision (Cargo.lock pinned; no ../design path dependency, no Markdown re-parsing). - preview renders one offline index.html: strict hashed CSP (default-src 'none', no network), visible prototype banner and build summary, escaped Design ContentBlocks (raw HTML stays inert), finite-state scenario panels with hashed inline script and reset, no server/timer/eval business logic. - Publication refuses existing outputs and symlink targets, builds in a private sibling staging dir and renames atomically; 0/1/2 exit codes with stderr diagnostics. - scripts/ci.sh installs the Tool through the real CLI, runs all three commands on a fixture project, asserts the offline/safety facts, verifies the CLI binary digest is unchanged and removes the Tool. - Evidence records we do NOT yet claim real-browser/responsive acceptance, image assets, the full negative matrix, budgets/timeouts or WEB-05 cold install. Refs cflmy/marqdo-web-preview#1, cflmy/marqdo#6
This commit was merged in pull request #2.
This commit is contained in:
1 parent
8b3281bac0
commit
e739f4504a
12 files changed
+928
-26
No files matched your search
+638
@@ -0,0 +1,638 @@
|
||||
//! `marqdo web` — the unique Web Tool: offline preview, check and handoff.
|
||||
//!
|
||||
//! The tool consumes only the public `marqdo-web-design` crate (fixed git
|
||||
//! revision) and the CLI Analysis the design layer produces. It never parses
|
||||
//! Markdown, never calls document `@exec` business functions, never opens the
|
||||
//! network and never starts a server. Output is a static `file://` artifact with
|
||||
//! a strict CSP, an inert prototype banner, escaped content and deterministic
|
||||
//! staging→rename publication.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use marqdo_web_design::{
|
||||
handoff, load, ComponentDef, ContentBlock, Design, Error, Instance, LoadConfig, Scenario, Width,
|
||||
};
|
||||
|
||||
const CSS: &str = r#"
|
||||
:root{color-scheme:light dark}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:system-ui,-apple-system,"Noto Sans CJK SC",sans-serif;background:#f7f7f8;color:#1d1d1f}
|
||||
body[data-theme="dark"]{background:#151517;color:#e8e8ea}
|
||||
header{position:sticky;top:0;background:#fff8e1;color:#5b4500;border-bottom:1px solid #e0c56b;padding:.6rem 1rem;font-weight:600}
|
||||
body[data-theme="dark"] header{background:#3a2f00;color:#ffe08a;border-color:#6b5600}
|
||||
main{padding:1rem;max-width:1200px;margin:0 auto}
|
||||
.component{border:1px dashed #b9b9c0;border-radius:8px;padding:.75rem;margin:.5rem 0;background:rgba(255,255,255,.6)}
|
||||
body[data-theme="dark"] .component{background:rgba(255,255,255,.04);border-color:#4a4a52}
|
||||
.grid{display:grid;gap:.75rem}
|
||||
.content p,.content pre{margin:.4rem 0}
|
||||
pre{overflow:auto;background:#f0f0f4;padding:.6rem;border-radius:6px;max-height:24rem}
|
||||
body[data-theme="dark"] pre{background:#232329}
|
||||
button{margin:.25rem .35rem .25rem 0;padding:.35rem .7rem;border-radius:6px;border:1px solid #888;background:#fff;cursor:pointer}
|
||||
body[data-theme="dark"] button{background:#2a2a31;color:#eee;border-color:#666}
|
||||
.badge{display:inline-block;font-size:.75rem;padding:.1rem .45rem;border-radius:999px;background:#ffe08a;color:#3a2f00;margin-right:.4rem}
|
||||
.summary{font-size:.8rem;color:#555;margin-top:2rem;border-top:1px solid #ccc;padding-top:.75rem}
|
||||
body[data-theme="dark"] .summary{color:#aaa;border-color:#444}
|
||||
.hidden{display:none}
|
||||
"#;
|
||||
|
||||
const SCRIPT: &str = r#"
|
||||
(function(){
|
||||
function setup(root){
|
||||
var panels = root.querySelectorAll('[data-scenario-panel]');
|
||||
function show(state){
|
||||
panels.forEach(function(panel){
|
||||
panel.classList.toggle('hidden', panel.getAttribute('data-scenario-panel') !== state);
|
||||
});
|
||||
root.setAttribute('data-current-state', state);
|
||||
}
|
||||
root.querySelectorAll('button[data-next]').forEach(function(button){
|
||||
button.addEventListener('click', function(){
|
||||
show(button.getAttribute('data-next'));
|
||||
});
|
||||
});
|
||||
var reset = root.querySelector('button[data-reset]');
|
||||
if(reset){ reset.addEventListener('click', function(){ show(root.getAttribute('data-initial-state')); }); }
|
||||
}
|
||||
document.querySelectorAll('[data-scenario]').forEach(setup);
|
||||
})();
|
||||
"#;
|
||||
|
||||
struct Args {
|
||||
command: String,
|
||||
entry: String,
|
||||
unit: String,
|
||||
root: Option<String>,
|
||||
out: Option<String>,
|
||||
theme: String,
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Args, String> {
|
||||
let mut argv = std::env::args().skip(1);
|
||||
let Some(command) = argv.next() else {
|
||||
return Err(
|
||||
"usage: web <check|preview|handoff> ENTRY --unit ANCHOR [--root DIR] [--out PATH]"
|
||||
.into(),
|
||||
);
|
||||
};
|
||||
if !matches!(command.as_str(), "check" | "preview" | "handoff") {
|
||||
return Err(format!(
|
||||
"unknown web subcommand {command:?}; expected check|preview|handoff"
|
||||
));
|
||||
}
|
||||
let mut entry = None;
|
||||
let mut unit = None;
|
||||
let mut root = None;
|
||||
let mut out = None;
|
||||
let mut theme = "light".to_string();
|
||||
let mut rest: Vec<String> = argv.collect();
|
||||
let mut index = 0;
|
||||
while index < rest.len() {
|
||||
let item = rest[index].clone();
|
||||
match item.as_str() {
|
||||
"--unit" => {
|
||||
index += 1;
|
||||
unit = rest.get(index).cloned();
|
||||
}
|
||||
"--root" => {
|
||||
index += 1;
|
||||
root = rest.get(index).cloned();
|
||||
}
|
||||
"--out" => {
|
||||
index += 1;
|
||||
out = rest.get(index).cloned();
|
||||
}
|
||||
"--theme" => {
|
||||
index += 1;
|
||||
theme = rest.get(index).cloned().unwrap_or_default();
|
||||
}
|
||||
other if other.starts_with("--") => {
|
||||
return Err(format!("unknown option {other:?}"));
|
||||
}
|
||||
other => {
|
||||
if entry.is_some() {
|
||||
return Err("exactly one ENTRY is required".into());
|
||||
}
|
||||
entry = Some(other.to_string());
|
||||
let _ = &mut rest;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if !matches!(theme.as_str(), "light" | "dark") {
|
||||
return Err("--theme must be light or dark".into());
|
||||
}
|
||||
Ok(Args {
|
||||
command,
|
||||
entry: entry.ok_or("missing ENTRY")?,
|
||||
unit: unit.ok_or("--unit ANCHOR is required")?,
|
||||
root,
|
||||
out,
|
||||
theme,
|
||||
})
|
||||
}
|
||||
|
||||
fn hex_escape(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len());
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn base64(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::new();
|
||||
for chunk in bytes.chunks(3) {
|
||||
let mut value = 0u32;
|
||||
for (index, byte) in chunk.iter().enumerate() {
|
||||
value |= u32::from(*byte) << (16 - 8 * index);
|
||||
}
|
||||
out.push(ALPHABET[((value >> 18) & 63) as usize] as char);
|
||||
out.push(ALPHABET[((value >> 12) & 63) as usize] as char);
|
||||
out.push(if chunk.len() > 1 {
|
||||
ALPHABET[((value >> 6) & 63) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
out.push(if chunk.len() > 2 {
|
||||
ALPHABET[(value & 63) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn csp_hash(content: &str) -> String {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
// SHA-256 is required for CSP; use the design-independent tiny implementation.
|
||||
sha256_b64(content.as_bytes()).unwrap_or_else(|| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
content.hash(&mut hasher);
|
||||
format!("sha256-{}", hasher.finish())
|
||||
})
|
||||
}
|
||||
|
||||
fn sha256_b64(bytes: &[u8]) -> Option<String> {
|
||||
// Minimal SHA-256; preview must not add dependencies beyond the Design crate.
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
|
||||
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
|
||||
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
|
||||
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
||||
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
||||
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
|
||||
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
|
||||
0xc67178f2,
|
||||
];
|
||||
let mut h: [u32; 8] = [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
|
||||
0x5be0cd19,
|
||||
];
|
||||
let mut message = bytes.to_vec();
|
||||
let bit_len = (bytes.len() as u64) * 8;
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&bit_len.to_be_bytes());
|
||||
for chunk in message.chunks(64) {
|
||||
let mut w = [0u32; 64];
|
||||
for index in 0..16 {
|
||||
w[index] = u32::from_be_bytes([
|
||||
chunk[4 * index],
|
||||
chunk[4 * index + 1],
|
||||
chunk[4 * index + 2],
|
||||
chunk[4 * index + 3],
|
||||
]);
|
||||
}
|
||||
for index in 16..64 {
|
||||
let s0 = w[index - 15].rotate_right(7)
|
||||
^ w[index - 15].rotate_right(18)
|
||||
^ (w[index - 15] >> 3);
|
||||
let s1 = w[index - 2].rotate_right(17)
|
||||
^ w[index - 2].rotate_right(19)
|
||||
^ (w[index - 2] >> 10);
|
||||
w[index] = w[index - 16]
|
||||
.wrapping_add(s0)
|
||||
.wrapping_add(w[index - 7])
|
||||
.wrapping_add(s1);
|
||||
}
|
||||
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
|
||||
(h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
|
||||
for index in 0..64 {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let ch = (e & f) ^ ((!e) & g);
|
||||
let temp1 = hh
|
||||
.wrapping_add(s1)
|
||||
.wrapping_add(ch)
|
||||
.wrapping_add(K[index])
|
||||
.wrapping_add(w[index]);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
let temp2 = s0.wrapping_add(maj);
|
||||
hh = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d.wrapping_add(temp1);
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1.wrapping_add(temp2);
|
||||
}
|
||||
h[0] = h[0].wrapping_add(a);
|
||||
h[1] = h[1].wrapping_add(b);
|
||||
h[2] = h[2].wrapping_add(c);
|
||||
h[3] = h[3].wrapping_add(d);
|
||||
h[4] = h[4].wrapping_add(e);
|
||||
h[5] = h[5].wrapping_add(f);
|
||||
h[6] = h[6].wrapping_add(g);
|
||||
h[7] = h[7].wrapping_add(hh);
|
||||
}
|
||||
let mut digest = Vec::new();
|
||||
for word in h {
|
||||
digest.extend_from_slice(&word.to_be_bytes());
|
||||
}
|
||||
Some(base64(&digest))
|
||||
}
|
||||
|
||||
fn render_blocks(blocks: &[ContentBlock]) -> String {
|
||||
let mut out = String::new();
|
||||
for block in blocks {
|
||||
let text = hex_escape(&block.text);
|
||||
match block.kind.as_str() {
|
||||
"paragraph" => out.push_str(&format!("<p>{text}</p>\n")),
|
||||
"heading" => out.push_str(&format!("<h3>{text}</h3>\n")),
|
||||
"list" | "table" | "code" | "quote" => out.push_str(&format!("<pre>{text}</pre>\n")),
|
||||
_ => out.push_str(&format!("<p class=\"inert\">{text}</p>\n")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn slot_columns(definition: &ComponentDef, row: u32) -> String {
|
||||
definition
|
||||
.slots
|
||||
.iter()
|
||||
.filter(|slot| slot.row == row)
|
||||
.map(|slot| match slot.width {
|
||||
Width::Auto => "minmax(0,auto)".to_string(),
|
||||
Width::Fr(value) => format!("minmax(0,{value}fr)"),
|
||||
Width::Px(value) => format!("minmax(0,{value}px)"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn render_instance(
|
||||
design: &Design,
|
||||
instance: &Instance,
|
||||
instance_by_id: &BTreeMap<String, &Instance>,
|
||||
depth: usize,
|
||||
) -> Result<String, String> {
|
||||
if depth > 40 {
|
||||
return Err("instance rendering depth exceeded".into());
|
||||
}
|
||||
let definition = design
|
||||
.definitions
|
||||
.get(&instance.definition)
|
||||
.ok_or_else(|| format!("missing definition {}", instance.definition))?;
|
||||
let mut out = format!(
|
||||
"<section class=\"component\" data-instance=\"{}\">\n",
|
||||
hex_escape(&instance.id)
|
||||
);
|
||||
out.push_str(&format!(
|
||||
"<div class=\"source\"><span class=\"badge\">原型</span>{}#{} </div>\n",
|
||||
hex_escape(&definition.source.path),
|
||||
hex_escape(&definition.source.anchor)
|
||||
));
|
||||
if !definition.content.is_empty() {
|
||||
out.push_str("<div class=\"content\">");
|
||||
out.push_str(&render_blocks(&definition.content));
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
let rows: Vec<u32> = {
|
||||
let mut rows: Vec<u32> = definition.slots.iter().map(|slot| slot.row).collect();
|
||||
rows.sort_unstable();
|
||||
rows.dedup();
|
||||
rows
|
||||
};
|
||||
for row in rows {
|
||||
let columns = slot_columns(definition, row);
|
||||
out.push_str(&format!(
|
||||
"<div class=\"grid\" style=\"grid-template-columns:{columns}\">\n"
|
||||
));
|
||||
for slot in definition.slots.iter().filter(|slot| slot.row == row) {
|
||||
let child_id = format!("{}/{}", instance.id, slot.slot);
|
||||
let child = instance_by_id
|
||||
.get(&child_id)
|
||||
.ok_or_else(|| format!("missing child instance {child_id}"))?;
|
||||
out.push_str(&render_instance(design, child, instance_by_id, depth + 1)?);
|
||||
}
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
if let Some(scenario_markup) = render_scenarios(instance, definition) {
|
||||
out.push_str(&scenario_markup);
|
||||
}
|
||||
out.push_str("</section>\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn render_scenarios(instance: &Instance, definition: &ComponentDef) -> Option<String> {
|
||||
if definition.scenarios.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let initial = definition
|
||||
.scenarios
|
||||
.iter()
|
||||
.find(|scene| scene.initial)
|
||||
.map(|scene| scene.state.clone())
|
||||
.unwrap_or_default();
|
||||
let mut out = format!(
|
||||
"<div class=\"scenario\" data-scenario data-initial-state=\"{}\" data-current-state=\"{}\">\n",
|
||||
hex_escape(&initial),
|
||||
hex_escape(&initial)
|
||||
);
|
||||
for scene in &definition.scenarios {
|
||||
let hidden = if scene.state == initial {
|
||||
""
|
||||
} else {
|
||||
" hidden"
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"<div class=\"scenario-panel{hidden}\" data-scenario-panel=\"{}\">\n",
|
||||
hex_escape(&scene.state)
|
||||
));
|
||||
out.push_str(&render_blocks(&scene.content_blocks));
|
||||
for interaction in definition
|
||||
.interactions
|
||||
.iter()
|
||||
.filter(|interaction| interaction.current == scene.state)
|
||||
{
|
||||
out.push_str(&format!(
|
||||
"<button type=\"button\" data-next=\"{}\">模拟:{}</button>\n",
|
||||
hex_escape(&interaction.next),
|
||||
hex_escape(&interaction.event)
|
||||
));
|
||||
}
|
||||
out.push_str("</div>\n");
|
||||
}
|
||||
out.push_str("<button type=\"button\" data-reset>重置原型</button>\n");
|
||||
let _ = instance;
|
||||
out.push_str("</div>\n");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn render(design: &Design, theme: &str) -> Result<String, String> {
|
||||
let mut instance_by_id: BTreeMap<String, &Instance> = BTreeMap::new();
|
||||
for instance in &design.instances {
|
||||
instance_by_id.insert(instance.id.clone(), instance);
|
||||
}
|
||||
let root = instance_by_id
|
||||
.get("root")
|
||||
.ok_or_else(|| "design has no root instance".to_string())?;
|
||||
let mut body = render_instance(design, root, &instance_by_id, 0)?;
|
||||
let mut summary =
|
||||
String::from("<div class=\"summary\">\n<strong>本轮构建摘要</strong>\n<ul>\n");
|
||||
summary.push_str(&format!("<li>root: {}</li>\n", hex_escape(&design.root)));
|
||||
for source in &design.sources {
|
||||
summary.push_str(&format!(
|
||||
"<li>{} sha256:{}</li>\n",
|
||||
hex_escape(&source.path),
|
||||
hex_escape(&source.source_digest)
|
||||
));
|
||||
}
|
||||
summary.push_str("</ul>\n<p>原型 / 模拟:不连接网络、不执行文档 @exec 业务函数、不代表生产站点。</p>\n</div>\n");
|
||||
body.push_str(&summary);
|
||||
let style_hash = csp_hash(CSS);
|
||||
let script_hash = csp_hash(SCRIPT);
|
||||
let csp = format!(
|
||||
"default-src 'none'; style-src 'sha256-{style_hash}'; script-src 'sha256-{script_hash}'; img-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'"
|
||||
);
|
||||
Ok(format!(
|
||||
"<!DOCTYPE html>\n<html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\"><title>Marqdo Web 原型预览</title><style>{CSS}</style></head><body data-theme=\"{theme}\"><header>原型 / 模拟:本地离线预览,不连接网络,不代表生产站点</header><main>{body}</main><script>{SCRIPT}</script></body></html>\n"
|
||||
))
|
||||
}
|
||||
|
||||
fn diagnostic_text(error: &Error) -> (u8, String) {
|
||||
let (code, diagnostics) = match error {
|
||||
Error::Engine(items) => (2u8, items),
|
||||
Error::Design(items) => (1u8, items),
|
||||
};
|
||||
let mut text = String::new();
|
||||
for diagnostic in diagnostics {
|
||||
text.push_str(&format!(
|
||||
"{} [{:?}] {}",
|
||||
diagnostic.code, diagnostic.severity, diagnostic.message
|
||||
));
|
||||
if let Some(path) = &diagnostic.path {
|
||||
text.push_str(&format!(" at {path}"));
|
||||
}
|
||||
if let Some(span) = &diagnostic.span {
|
||||
text.push_str(&format!(" [{}..{}]", span.start, span.end));
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
(code, text)
|
||||
}
|
||||
|
||||
fn design_load(args: &Args) -> Result<Design, (u8, String)> {
|
||||
let cli = std::env::var("MARQDO_BIN")
|
||||
.map(PathBuf::from)
|
||||
.map_err(|_| {
|
||||
(
|
||||
2u8,
|
||||
"MARQDO_BIN must name the verified marqdo executable\n".to_string(),
|
||||
)
|
||||
})?;
|
||||
let entry = PathBuf::from(&args.entry);
|
||||
let root = args
|
||||
.root
|
||||
.clone()
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| entry.parent().unwrap_or(Path::new(".")).to_path_buf());
|
||||
let config = LoadConfig::new(cli, entry, args.unit.clone(), root);
|
||||
load(&config).map_err(|error| diagnostic_text(&error))
|
||||
}
|
||||
|
||||
fn staging_for(out: &Path) -> Result<PathBuf, String> {
|
||||
let parent = out
|
||||
.parent()
|
||||
.ok_or_else(|| "output path has no parent".to_string())?;
|
||||
if !parent.is_dir() {
|
||||
return Err(format!(
|
||||
"output parent is not a directory: {}",
|
||||
parent.display()
|
||||
));
|
||||
}
|
||||
if out.exists() {
|
||||
return Err(format!("output already exists: {}", out.display()));
|
||||
}
|
||||
if out
|
||||
.symlink_metadata()
|
||||
.map(|meta| meta.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(format!("output is a symbolic link: {}", out.display()));
|
||||
}
|
||||
let staging = parent.join(format!(".web-staging-{}", std::process::id()));
|
||||
if staging.exists() {
|
||||
fs::remove_dir_all(&staging).map_err(|error| format!("cannot reset staging: {error}"))?;
|
||||
}
|
||||
fs::create_dir(&staging).map_err(|error| format!("cannot create staging: {error}"))?;
|
||||
Ok(staging)
|
||||
}
|
||||
|
||||
fn publish(staging: &Path, out: &Path) -> Result<(), String> {
|
||||
fs::rename(staging, out).map_err(|error| format!("cannot publish artifact: {error}"))
|
||||
}
|
||||
|
||||
fn run_check(args: &Args) -> ExitCode {
|
||||
match design_load(args) {
|
||||
Ok(design) => {
|
||||
println!(
|
||||
"design {} definitions={} instances={} sources={}",
|
||||
design.root,
|
||||
design.definitions.len(),
|
||||
design.instances.len(),
|
||||
design.sources.len()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
ExitCode::from(code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_preview(args: &Args) -> ExitCode {
|
||||
let Some(out) = &args.out else {
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let design = match design_load(args) {
|
||||
Ok(design) => design,
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
return ExitCode::from(code);
|
||||
}
|
||||
};
|
||||
let html = match render(&design, &args.theme) {
|
||||
Ok(html) => html,
|
||||
Err(error) => {
|
||||
eprintln!("web preview: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if html.len() > 4 * 1024 * 1024 {
|
||||
eprintln!("web preview: error: rendered HTML exceeds the 4 MiB budget");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let out = PathBuf::from(out);
|
||||
let staging = match staging_for(&out) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("web preview: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if let Err(error) = fs::write(staging.join("index.html"), html) {
|
||||
eprintln!("web preview: error: cannot write index.html: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Err(error) = publish(&staging, &out) {
|
||||
eprintln!("web preview: error: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
println!("preview {} (theme {})", out.display(), args.theme);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_handoff(args: &Args) -> ExitCode {
|
||||
let Some(out) = &args.out else {
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let design = match design_load(args) {
|
||||
Ok(design) => design,
|
||||
Err((code, text)) => {
|
||||
eprint!("{text}");
|
||||
return ExitCode::from(code);
|
||||
}
|
||||
};
|
||||
let text = handoff(&design);
|
||||
if text.len() > 4 * 1024 * 1024 {
|
||||
eprintln!("web handoff: error: handoff exceeds the 4 MiB budget");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let out = PathBuf::from(out);
|
||||
if let Some(parent) = out.parent() {
|
||||
if !parent.as_os_str().is_empty() && !parent.is_dir() {
|
||||
eprintln!("web handoff: error: output parent is not a directory");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
if out.exists() {
|
||||
eprintln!(
|
||||
"web handoff: error: output already exists: {}",
|
||||
out.display()
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let staging = match staging_for(&out) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("web handoff: error: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let staging_file = staging.join("handoff.md");
|
||||
if let Err(error) = fs::write(&staging_file, text) {
|
||||
eprintln!("web handoff: error: cannot write handoff: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Err(error) = fs::rename(&staging_file, &out) {
|
||||
eprintln!("web handoff: error: cannot publish handoff: {error}");
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
println!("handoff {}", out.display());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args = match parse_args() {
|
||||
Ok(args) => args,
|
||||
Err(error) => {
|
||||
eprintln!("web: {error}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match args.command.as_str() {
|
||||
"check" => run_check(&args),
|
||||
"preview" => run_preview(&args),
|
||||
"handoff" => run_handoff(&args),
|
||||
_ => ExitCode::from(2),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn _scenario_state(scenario: &Scenario) -> String {
|
||||
scenario.state.clone()
|
||||
}
|
||||
Reference in new issue
Block a user