use std::collections::BTreeMap;
use std::fmt;
use std::ops::Deref;
use serde_json::{Map, Value};
fn int(v: Option<&Value>) -> Option<u64> {
v.and_then(Value::as_u64)
}
fn text(v: Option<&Value>) -> Option<String> {
v.and_then(Value::as_str).map(str::to_owned)
}
fn label(v: Option<&Value>) -> Option<String> {
match v? {
Value::String(s) => Some(s.clone()),
Value::Null => None,
other => Some(other.to_string()),
}
}
fn object(v: Option<&Value>) -> Option<Map<String, Value>> {
v.and_then(Value::as_object).cloned()
}
fn objects(v: Option<&Value>) -> Vec<Map<String, Value>> {
v.and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_object().cloned()).collect()).unwrap_or_default()
}
fn strings(v: Option<&Value>) -> Vec<String> {
v.and_then(Value::as_array)
.map(|a| a.iter().map(|x| label(Some(x)).unwrap_or_default()).collect())
.unwrap_or_default()
}
#[derive(Debug, Clone, PartialEq)]
pub struct Diagnostic {
pub kind: String,
pub message: String,
pub severity: String,
pub at: Option<String>,
pub page: Option<String>,
pub data: Option<Map<String, Value>>,
}
impl Diagnostic {
pub fn is_error(&self) -> bool {
self.severity == "error"
}
fn from_json(d: &Map<String, Value>) -> Self {
Diagnostic {
kind: text(d.get("kind")).unwrap_or_default(),
message: text(d.get("message")).unwrap_or_default(),
severity: text(d.get("severity")).unwrap_or_else(|| "warning".to_owned()),
at: text(d.get("at")),
page: label(d.get("page")),
data: object(d.get("data")),
}
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let page = self.page.as_ref().map(|p| format!("page {p}"));
let place: Vec<&str> = [self.at.as_deref(), page.as_deref()].into_iter().flatten().collect();
write!(f, "{} {}", self.severity, self.kind)?;
if !place.is_empty() {
write!(f, " ({})", place.join(", "))?;
}
write!(f, ": {}", self.message)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output {
pub kind: String,
pub path: String,
pub size: Option<u64>,
pub pages: Option<u64>,
}
impl Output {
fn from_json(d: &Map<String, Value>) -> Self {
Output {
kind: text(d.get("kind")).unwrap_or_default(),
path: text(d.get("path")).unwrap_or_default(),
size: int(d.get("bytes")),
pages: int(d.get("pages")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BookSummary {
pub name: String,
pub id: String,
pub locale: Option<String>,
pub kind: Option<String>,
pub chapters: Option<u64>,
pub description: Option<String>,
pub locales: Option<Vec<String>>,
pub page_size: Option<String>,
}
impl BookSummary {
fn from_json(d: &Map<String, Value>) -> Self {
BookSummary {
name: text(d.get("name")).unwrap_or_default(),
id: text(d.get("id")).unwrap_or_default(),
locale: text(d.get("locale")),
kind: text(d.get("kind")),
chapters: int(d.get("chapters")),
description: text(d.get("description")),
locales: d.get("locales").and_then(Value::as_array).map(|_| strings(d.get("locales"))),
page_size: text(d.get("pageSize")),
}
}
}
#[derive(Clone, PartialEq)]
pub struct Report {
pub ok: bool,
pub command: String,
pub version: String,
pub exit_code: i32,
pub outputs: Vec<Output>,
pub warnings: Vec<Diagnostic>,
pub timings: BTreeMap<String, f64>,
pub error: Option<String>,
pub pages: Option<u64>,
pub book: Option<BookSummary>,
pub raw: Value,
pub content: Option<Vec<u8>>,
pub stderr: String,
}
impl Report {
pub fn output(&self) -> Option<&Output> {
self.outputs.first()
}
pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
self.warnings.iter().filter(|w| w.is_error())
}
pub fn from_json(raw: Value, content: Option<Vec<u8>>, stderr: String) -> Self {
let empty = Map::new();
let d = raw.as_object().unwrap_or(&empty);
let timings = d
.get("timings")
.and_then(Value::as_object)
.map(|t| t.iter().filter_map(|(k, v)| Some((k.clone(), v.as_f64()?))).collect())
.unwrap_or_default();
Report {
ok: d.get("ok").and_then(Value::as_bool).unwrap_or(false),
command: text(d.get("command")).unwrap_or_default(),
version: text(d.get("version")).unwrap_or_default(),
exit_code: d.get("exitCode").and_then(Value::as_i64).unwrap_or(0) as i32,
outputs: objects(d.get("outputs")).iter().map(Output::from_json).collect(),
warnings: objects(d.get("warnings")).iter().map(Diagnostic::from_json).collect(),
timings,
error: text(d.get("error")),
pages: int(d.get("pages")),
book: object(d.get("book")).as_ref().map(BookSummary::from_json),
content,
stderr,
raw,
}
}
fn get(&self, key: &str) -> Option<&Value> {
self.raw.get(key)
}
}
impl fmt::Debug for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Report")
.field("ok", &self.ok)
.field("command", &self.command)
.field("version", &self.version)
.field("exit_code", &self.exit_code)
.field("outputs", &self.outputs)
.field("warnings", &self.warnings)
.field("timings", &self.timings)
.field("error", &self.error)
.field("pages", &self.pages)
.field("book", &self.book)
.field("content", &self.content.as_ref().map(|c| format!("{} bytes", c.len())))
.finish_non_exhaustive()
}
}
pub trait FromReport: Sized {
fn from_report(report: Report) -> Self;
}
impl FromReport for Report {
fn from_report(report: Report) -> Self {
report
}
}
macro_rules! detailed {
($(#[$m:meta])* $name:ident { $($(#[$fm:meta])* $field:ident: $ty:ty = |$r:ident| $e:expr,)* }) => {
$(#[$m])*
#[derive(Debug, Clone, PartialEq)]
pub struct $name {
/// What every command reports.
pub report: Report,
$($(#[$fm])* pub $field: $ty,)*
}
impl FromReport for $name {
fn from_report(report: Report) -> Self {
$(let $field = { let $r = &report; $e };)*
$name { report, $($field,)* }
}
}
impl Deref for $name {
type Target = Report;
fn deref(&self) -> &Report {
&self.report
}
}
impl From<$name> for Report {
fn from(r: $name) -> Report {
r.report
}
}
};
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChapterInfo {
pub index: u64,
pub title: String,
pub words: u64,
pub file: Option<String>,
pub pages: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontInfo {
pub family: String,
pub source: String,
pub variants: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageRef {
pub label: String,
pub position: u64,
pub chapter: Option<u64>,
}
detailed! {
InfoReport {
chapters: Vec<ChapterInfo> = |r| objects(r.get("chapters")).iter().map(|c| ChapterInfo {
index: int(c.get("index")).unwrap_or(0),
title: text(c.get("title")).unwrap_or_default(),
words: int(c.get("words")).unwrap_or(0),
file: text(c.get("file")),
pages: int(c.get("pages")),
}).collect(),
resources: BTreeMap<String, u64> = |r| r.get("resources").and_then(Value::as_object)
.map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_u64()?))).collect())
.unwrap_or_default(),
fonts: Vec<FontInfo> = |r| objects(r.get("fonts")).iter().map(|f| FontInfo {
family: text(f.get("family")).unwrap_or_default(),
source: text(f.get("source")).unwrap_or_default(),
variants: strings(f.get("variants")),
}).collect(),
files: Option<u64> = |r| int(r.get("files")),
}
}
detailed! {
CheckReport {
passed: bool = |r| r.get("check").and_then(|c| c.get("passed")).and_then(Value::as_bool).unwrap_or(r.ok),
error_count: u64 = |r| int(r.get("check").and_then(|c| c.get("errors"))).unwrap_or(0),
warning_count: u64 = |r| int(r.get("check").and_then(|c| c.get("warnings"))).unwrap_or(0),
contrast: Option<Map<String, Value>> = |r| object(r.get("contrast")),
reflow: Vec<Value> = |r| r.get("reflow").and_then(Value::as_array).cloned().unwrap_or_default(),
preflight: Option<Map<String, Value>> = |r| object(r.get("preflight")),
}
}
detailed! {
ImageReport {
page: Option<PageRef> = |r| object(r.get("page")).map(|p| PageRef {
label: label(p.get("label")).unwrap_or_default(),
position: int(p.get("position")).unwrap_or(0),
chapter: int(p.get("chapter")),
}),
}
}
detailed! {
ImportDocxReport {
chapters: Option<u64> = |r| int(r.get("chapters")),
variant: Option<String> = |r| text(r.get("variant")),
export_id: Option<String> = |r| text(r.get("exportId")),
edits: Vec<Map<String, Value>> = |r| objects(r.get("edits")),
comments: Vec<Map<String, Value>> = |r| objects(r.get("comments")),
files: Vec<Value> = |r| r.get("files").and_then(Value::as_array).cloned().unwrap_or_default(),
diff: Option<String> = |r| text(r.get("diff")),
quality: Option<Map<String, Value>> = |r| object(r.get("report")),
}
}
detailed! {
UnpackReport {
files: Option<u64> = |r| int(r.get("files")),
}
}
detailed! {
DesignReport {
name: Option<String> = |r| text(r.get("design").and_then(|d| d.get("name"))),
parts: Vec<String> = |r| strings(r.get("design").and_then(|d| d.get("parts"))),
}
}
detailed! {
ImportIdmlReport {
layout: Option<String> = |r| text(r.get("layout")),
reason: Option<String> = |r| text(r.get("reason")),
chapters: Option<u64> = |r| int(r.get("chapters")),
quality: Option<Map<String, Value>> = |r| object(r.get("report")),
fonts: Vec<Map<String, Value>> = |r| objects(r.get("fonts")),
missing_links: Vec<Map<String, Value>> = |r| objects(r.get("missingLinks")),
package: Option<Map<String, Value>> = |r| object(r.get("package")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn reads_a_report() {
let raw = json!({
"ok": true, "command": "pdf", "version": "1.87.0", "exitCode": 0, "pages": 3,
"outputs": [{"kind": "pdf", "path": "b.pdf", "bytes": 1234, "pages": 3}, "junk"],
"warnings": [{"kind": "unknownConfigKey", "message": "nonsense", "at": "config.json", "page": 2}],
"timings": {"total": 812.5, "layout": 400, "bad": "x"},
"book": {"name": "B", "id": "b", "chapters": 2, "locales": ["en", "es"], "pageSize": "A5"},
"future": {"kept": true}
});
let r = Report::from_json(raw, None, String::new());
assert!(r.ok && r.command == "pdf" && r.pages == Some(3));
assert_eq!(
r.output().unwrap(),
&Output { kind: "pdf".into(), path: "b.pdf".into(), size: Some(1234), pages: Some(3) }
);
let w = &r.warnings[0];
assert_eq!(w.severity, "warning");
assert_eq!(w.to_string(), "warning unknownConfigKey (config.json, page 2): nonsense");
assert_eq!(r.timings.len(), 2);
let book = r.book.as_ref().unwrap();
assert_eq!((book.chapters, book.locales.as_deref()), (Some(2), Some(&["en".to_owned(), "es".to_owned()][..])));
assert_eq!(r.raw["future"]["kept"], true);
assert_eq!(r.errors().count(), 0);
}
#[test]
fn detailed_reports() {
let r = Report::from_json(
json!({"ok": false, "check": {"passed": false, "errors": 1, "warnings": 2}, "reflow": [1]}),
None,
String::new(),
);
let c = CheckReport::from_report(r);
assert!(!c.passed && c.error_count == 1 && c.warning_count == 2 && c.reflow.len() == 1);
assert!(!c.ok); let d = DesignReport::from_report(Report::from_json(
json!({"design": {"name": "Large", "parts": ["page", "text"]}}),
None,
String::new(),
));
assert_eq!((d.name.as_deref(), d.parts.clone()), (Some("Large"), vec!["page".to_owned(), "text".to_owned()]));
let i = ImageReport::from_report(Report::from_json(
json!({"page": {"label": "iv", "position": 4, "chapter": 1}}),
None,
String::new(),
));
assert_eq!(i.page, Some(PageRef { label: "iv".into(), position: 4, chapter: Some(1) }));
}
}