//! The dry-run report — the port of `packages/import-core/src/report.ts`.//!//! The rule is report-before-mutate, and this is the surface that honours it://! the caller parses everything, prints exactly what it WOULD write, and//! stops. `--execute` is the only thing that turns the parse into rows.//!//! The report is written to be read by someone deciding whether to press the//! button, so every number that could mean "this import is wrong" gets its own//! line: date spans (the only visible symptom of WhatsApp's silent//! truncation), direction splits (a wrong owner name inverts them),//! unresolvable reply refs, and skip counts.//!//! ## Where the types are//!//! `ChatReport` and `SkippedChatReport` are `normalize`'s already — the//! normalizer is what fills them in, and a second declaration here would be a//! second opinion about the shape it returns. `mediaPlan`'s counts are//! `media_plan::MediaUploadCounts`, for the same reason: the TypeScript writes//! that object literal twice and the port writes it once.//!//! ## The renderer is not "printing"//!//! [`format_report`] returns a `String`. Nothing in this crate writes to a//! terminal — the caller does — so the report stays a value, which is also//! what makes every line of it testable against Node.//!//! ## Two grammar bugs are kept on purpose//!//! `1 message were unusable and dropped.` and a same-day span that reads//! `(1 day)` (16 hours rounds up) are the TypeScript's output, byte for byte.//! A port that quietly fixed them would make the two implementations disagree//! on a line a person reads, which is exactly the class of drift these vectors//! exist to catch. Fix them in the TypeScript first, if they are worth fixing.use serde::{Deserialize, Serialize};usecrate::import::media_plan::MediaUploadCounts;usecrate::import::normalize::{ChatReport, SkippedChatReport};usecrate::js_number::math_round;use cotton_store::protocol::js;/// What the operator pointed us at —/// `packages/import-core/src/sourceTypes.ts`.////// The platform-neutral vocabulary for the four input shapes: the node/// package's `source.ts` (fs auto-detection) and the app's picker flow both/// speak these, and only the LOADING differs per platform. Its other half,/// `SourceMediaEntry`, lands with `media_plan`, its only reader.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pubenumSourceKind { #[serde(rename = "wce-json")]WceJson, #[serde(rename = "chat-txt")]ChatTxt, #[serde(rename = "chat-zip")]ChatZip, #[serde(rename = "chat-dir")]ChatDir,}implSourceKind {pubconstfn as_str(self) -> &'static str {matchself {SourceKind::WceJson => "wce-json",SourceKind::ChatTxt => "chat-txt",SourceKind::ChatZip => "chat-zip",SourceKind::ChatDir => "chat-dir", } }/// In the TypeScript union's declared order.pubconst ALL: [SourceKind; 4] = [SourceKind::WceJson,SourceKind::ChatTxt,SourceKind::ChatZip,SourceKind::ChatDir, ];pubfn parse(value: &str) -> Option<Self> {Self::ALL.into_iter().find(|kind| kind.as_str() == value) }}impl std::fmt::DisplayforSourceKind {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructReportSource {pub kind: SourceKind,pub path: String,}/// Cell + workspace the run is aimed at, echoed so a wrong target is visible.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructReportTarget {pub cell: String,pub workspace_id: String,pub endpoint: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructImportReport {pub source: ReportSource,pub target: ReportTarget,pub chats: Vec<ChatReport>,pub skipped_chats: Vec<SkippedChatReport>,/// Address-book shells with no messages (WCE only) — expected, not a/// problem.pub empty_chats: i64,pub dropped_messages: i64,/// Notes about what this SOURCE structurally cannot carry.pub limitations: Vec<String>,pub warnings: Vec<String>,pub media_manifest_path: Option<String>,pub media_files: i64,/// How the referenced files classified against the caller's limits.////// The TypeScript spells this `mediaPlan?: {…} | null` and the renderer/// tests BOTH halves; here one `None` covers "never planned" and/// "explicitly nothing", because the renderer treats them alike. #[serde(default, skip_serializing_if = "Option::is_none")]pub media_plan: Option<MediaUploadCounts>,/// `--media upload --execute`: what actually landed / failed. #[serde(default, skip_serializing_if = "Option::is_none")]pub media_uploaded: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")]pub media_upload_failed: Option<f64>,}pubfn total_messages(report: &ImportReport) -> i64 { report.chats.iter().map(|chat| chat.messages).sum()}/// `String.prototype.slice(0, end)` — UTF-16 code units, as JavaScript counts/// them. Every instant here is ASCII, so the two agree; the unit is written/// out anyway because a truncation that counts bytes is the bug this repo/// keeps finding.fn slice_utf16(text: &str, end: usize) -> String {let units: Vec<u16> = text.encode_utf16().take(end).collect();String::from_utf16_lossy(&units)}/// The day part of an instant, or an em dash when there is none.fn day(iso: Option<&str>) -> String {match iso {None => "\u{2014}".to_string(),Some(value) => slice_utf16(value, 10), }}/// Whole days between two instants, rounded, never negative.////// `None` is the TypeScript's `null` — one end was missing, so there is no/// span to state. An instant that will not PARSE gives `NaN` on both sides/// (`new Date("x").getTime()` is `NaN`, and arithmetic on it stays `NaN`), and/// the renderer then prints `NaN days` rather than hiding the problem.fn span_days(from: Option<&str>, to: Option<&str>) -> Option<f64> {let (from, to) = (from?, to?);let (Some(from_ms), Some(to_ms)) = (js::parse_date_ms(from), js::parse_date_ms(to)) else {returnSome(f64::NAN); };let ms = (to_ms - from_ms) as f64;// JS `Math.max(0, x)` answers `NaN` when x is `NaN`; the branch above is// the only way one gets here, and `f64::max` would swallow it, so the NaN// is carried explicitly.let rounded = math_round(ms / 86_400_000.0);Some(if rounded.is_nan() { rounded } else { rounded.max(0.0) })}fn indent(lines: implIntoIterator<Item = String>) -> Vec<String> { lines .into_iter() .map(|line| format!(" {line}")) .collect()}/// `3 messages` / `1 message`. The report is read by a person, not a parser.fn count_with(n: f64, singular: &str, plural: &str) -> String {let noun = if n == 1.0 { singular } else { plural }; format!("{} {noun}", js::number_to_string(n))}/// The TypeScript's default plural — `${singular}s`.fn count(n: f64, singular: &str) -> String { count_with(n, singular, &format!("{singular}s"))}/// Plain-text render for the terminal.pubfn format_report(report: &ImportReport) -> String {letmut out: Vec<String> = Vec::new(); out.push(format!("Source {} ({})", report.source.path, report.source.kind )); out.push(format!("Target cell {} \u{b7} workspace {}", report.target.cell, report.target.workspace_id )); out.push(format!(" {}", report.target.endpoint)); out.push(String::new());if report.chats.is_empty() { out.push("No importable conversations were found.".to_string()); }for chat in &report.chats {let is_group = chat.kind.as_deref() == Some("group");let who = if is_group {let title = chat .title .clone() .or_else(|| chat.display_name.clone()) .unwrap_or_else(|| "(untitled)".to_string()); format!("Group {}", js::json_stringify(&serde_json::Value::String(title)) ) } else {// `[displayName, phone && `+${phone}`].filter(Boolean)` — an EMPTY// display name is falsy in JavaScript and drops out too.letmut halves: Vec<&str> = Vec::new();ifletSome(name) = chat.display_name.as_deref() {if !name.is_empty() { halves.push(name); } }let plus;ifletSome(phone) = chat.phone.as_deref() {if !phone.is_empty() { plus = format!("+{phone}"); halves.push(&plus); } } halves.join(" ") }; out.push(if who.is_empty() {"(unidentified contact)".to_string() } else { who });if is_group {ifletSome(participants) = chat.participants.as_ref() {if !participants.is_empty() { out.extend(indent(participants.iter().map(|participant| {match participant.phone.as_deref() {None => format!("{} (to identify)", participant.display_name),Some(phone) => format!("{} +{phone}", participant.display_name), } }))); } } }let span = span_days(chat.first_sent_at.as_deref(), chat.last_sent_at.as_deref());letmut details: Vec<String> = Vec::new();let events = match chat.system_imported {Some(imported) if imported > 0 => { format!(" / {}", count(imported as f64, "group event")) } _ => String::new(), }; details.push(format!("{} {} in / {} out{events}", count(chat.messages as f64, "message"), chat.inbound, chat.outbound )); details.push(format!("{} \u{2192} {}{}", day(chat.first_sent_at.as_deref()), day(chat.last_sent_at.as_deref()),match span {None => String::new(),Some(span) => format!(" ({})", count(span, "day")), } ));if chat.reply_refs > 0 { details.push(format!("{}{}", count_with(chat.reply_refs as f64, "reply", "replies"),if chat.unresolved_reply_refs > 0 { format!(" ({} quoting a message outside this import)", chat.unresolved_reply_refs ) } else {String::new() } )); }if chat.reactions > 0 { details.push(count(chat.reactions as f64, "reaction")); }if chat.attachments > 0 { details.push(format!("{}{}", count(chat.attachments as f64, "attachment"),if chat.omitted_media > 0 { format!(" ({} not present in the export)", chat.omitted_media) } else {String::new() } )); }if chat.system_skipped > 0 { details.push(format!("{} skipped", count(chat.system_skipped as f64, "system line") )); }if chat.album_containers_dropped > 0 { details.push(format!("{} \u{2014} the export's blank line before each one was dropped", count_with(chat.album_containers_dropped as f64, "album", "albums") )); } out.extend(indent(details));if !chat.warnings.is_empty() { out.extend(indent( chat.warnings.iter().map(|warning| format!("! {warning}")), )); } out.push(String::new()); }if !report.skipped_chats.is_empty() { out.push(format!("Skipped ({}):", report.skipped_chats.len()));for skipped in &report.skipped_chats { out.push(format!(" {} {} \u{2014} {}", skipped.label, count(skipped.messages as f64, "message"), skipped.reason )); } out.push(String::new()); }if report.empty_chats > 0 { out.push(format!("{} with no messages (the exporter creates one per saved contact). Ignored.", count_with( report.empty_chats as f64,"address-book entry","address-book entries" ) )); }if report.dropped_messages > 0 {// The TypeScript's own sentence, subject/verb disagreement included —// a port that fixed it would make the two disagree on a line a person// reads. out.push(format!("{} were unusable and dropped.", count(report.dropped_messages as f64, "message") )); }if report.empty_chats > 0 || report.dropped_messages > 0 { out.push(String::new()); }if report.media_files > 0 {let referenced = format!("{} referenced", count(report.media_files as f64, "media file") );match report.media_plan.as_ref() {Some(plan) => {letmut parts = vec![format!("{} uploadable", plan.uploadable)];if plan.unsupported_type > 0 { parts.push(format!("{} unsupported type", plan.unsupported_type)); }if plan.oversize > 0 { parts.push(format!("{} over the Worker's size cap", plan.oversize)); }if plan.missing > 0 { parts.push(format!("{} referenced but not in the archive", plan.missing )); }if plan.omitted > 0 { parts.push(format!("{} omitted by the export", plan.omitted)); } out.push(format!("{referenced} \u{2014} {}", parts.join(" \u{b7} ")));ifletSome(uploaded) = report.media_uploaded {// `report.mediaUploadFailed ? …` is a TRUTHY test: a zero// and an absent count both stay silent.let failed = match report.media_upload_failed {Some(failed) if failed != 0.0 && !failed.is_nan() => { format!(" \u{b7} {} FAILED", js::number_to_string(failed)) } _ => String::new(), }; out.push(format!(" {} uploaded{failed}", count(uploaded, "file") )); } }None => out.push(match report.media_manifest_path.as_deref() {None => format!("{referenced}. Pass --media manifest to write the manifest, or --media upload to upload." ),Some(path) => format!("{referenced} \u{2014} manifest written to {path}"), }), } out.push(String::new()); }if !report.limitations.is_empty() { out.push("This source cannot carry:".to_string()); out.extend(indent( report .limitations .iter() .map(|line| format!("\u{b7} {line}")), )); out.push(String::new()); }if !report.warnings.is_empty() { out.push("Warnings:".to_string()); out.extend(indent( report.warnings.iter().map(|line| format!("! {line}")), )); out.push(String::new()); } out.push(format!("TOTAL {} across {}", count(total_messages(report) as f64, "message"), count(report.chats.len() as f64, "conversation") )); out.join("\n")}#[cfg(test)]#[path = "report_tests.rs"]mod tests;