openai_client_cli/program/loaders/
output.rs

1use crate::{Entry, Result, traits::*};
2use std::{fs::File, path::Path, io::{stdout, Write}};
3use tracing::{debug, info};
4
5/// The output writer.
6pub struct Output(Box<dyn Write>, bool);
7
8impl Output {
9  /// Check if the output writer is a file; otherwise, it is the standard output.
10  pub fn is_file(&self) -> bool {
11    self.1
12  }
13
14  fn post_fetch_ok(self, target: &str) -> Result<Self> {
15    info!("Successfully fetched the output writer to {target}");
16    Ok(self)
17  }
18}
19
20impl FromFile for Output {
21  fn from_file<P>(path: P) -> Result<Self>
22  where
23    P: AsRef<Path>,
24  {
25    Ok(Self(Box::new(File::create(path)?), true))
26  }
27}
28
29impl Loader<Box<dyn Write>> for Output {
30  fn fetch(entry: &Entry) -> Result<Self> {
31    if let Some(path) = entry.output_file.as_ref() {
32      let target = &format!("the file {path:?}");
33      match Output::from_file(path) {
34        Ok(output) => return output.post_fetch_ok(target),
35        Err(err) => debug!("Failed to create the output writer to {target}: {err:?}"),
36      }
37    }
38    Self(Box::new(stdout()), false).post_fetch_ok("the standard output")
39  }
40  fn value(self) -> Box<dyn Write> {
41    self.0
42  }
43  fn value_ref(&self) -> &Box<dyn Write> {
44    &self.0
45  }
46}