1use std::io::Write as _;
4use std::path::{Path, PathBuf};
5
6use rig_core::error::BoxError;
7use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
8
9use crate::Report;
10
11pub trait Sink: WasmCompatSend + WasmCompatSync {
13 fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>>;
15}
16
17#[derive(Debug, thiserror::Error)]
19#[non_exhaustive]
20pub enum SinkError {
21 #[error("cannot write {path}: {source}")]
23 Write {
24 path: PathBuf,
26 source: std::io::Error,
28 },
29 #[error("cannot write to stdout: {0}")]
31 Stdout(std::io::Error),
32 #[error("cannot serialize the report: {0}")]
34 Serialize(#[from] serde_json::Error),
35 #[error(transparent)]
37 Other(BoxError),
38}
39
40fn write(path: &Path, contents: &str) -> Result<(), SinkError> {
42 let written = match path.parent() {
43 Some(dir) if !dir.as_os_str().is_empty() => std::fs::create_dir_all(dir),
44 _ => Ok(()),
45 }
46 .and_then(|()| std::fs::write(path, contents));
47 written.map_err(|source| SinkError::Write {
48 path: path.to_owned(),
49 source,
50 })
51}
52
53#[derive(Debug, Clone)]
55pub struct JsonFile(PathBuf);
56
57impl JsonFile {
58 pub fn new(path: impl Into<PathBuf>) -> Self {
60 Self(path.into())
61 }
62}
63
64impl Sink for JsonFile {
65 fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
66 Box::pin(async move { write(&self.0, &report.to_json()?) })
67 }
68}
69
70#[derive(Debug, Clone)]
73pub struct JunitFile(PathBuf);
74
75impl JunitFile {
76 pub fn new(path: impl Into<PathBuf>) -> Self {
78 Self(path.into())
79 }
80}
81
82impl Sink for JunitFile {
83 fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
84 Box::pin(async move { write(&self.0, &report.to_junit()) })
85 }
86}
87
88#[derive(Debug, Clone)]
91pub struct Markdown(Option<PathBuf>);
92
93impl Markdown {
94 pub fn file(path: impl Into<PathBuf>) -> Self {
96 Self(Some(path.into()))
97 }
98
99 pub fn stdout() -> Self {
101 Self(None)
102 }
103}
104
105impl Sink for Markdown {
106 fn record<'a>(&'a self, report: &'a Report) -> WasmBoxedFuture<'a, Result<(), SinkError>> {
107 Box::pin(async move {
108 let markdown = report.to_markdown();
109 match &self.0 {
110 Some(path) => write(path, &markdown),
111 None => std::io::stdout()
112 .lock()
113 .write_all(markdown.as_bytes())
114 .map_err(SinkError::Stdout),
115 }
116 })
117 }
118}