use std::{
env,
io::Write,
path::{Path, PathBuf},
};
use crate::{Error, TOKEN_ENV, protocol};
pub struct Reporter {
token: String,
last_report: Option<ResumeCommand>,
}
#[derive(PartialEq, Eq)]
struct ResumeCommand {
argv: Vec<String>,
cwd: Option<PathBuf>,
}
impl Reporter {
pub fn from_env() -> Result<Option<Self>, Error> {
let Some(token) = env::var_os(TOKEN_ENV) else {
return Ok(None);
};
let token = token.to_str().ok_or(Error::InvalidToken)?;
Self::new(token).map(Some)
}
pub fn new(token: impl Into<String>) -> Result<Self, Error> {
let token = token.into();
protocol::validate_token(&token)?;
Ok(Self {
token,
last_report: None,
})
}
pub fn report(&mut self, argv: &[String], cwd: Option<&Path>) -> Result<(), Error> {
let mut terminal = terminal_writer()?;
self.report_to(&mut terminal, argv, cwd)
}
pub fn refresh(&self) -> Result<(), Error> {
if self.last_report.is_none() {
return Ok(());
}
let mut terminal = terminal_writer()?;
self.refresh_to(&mut terminal)
}
pub fn clear(&mut self) -> Result<(), Error> {
let mut terminal = terminal_writer()?;
self.clear_to(&mut terminal)
}
pub fn report_to<W: Write>(
&mut self,
writer: &mut W,
argv: &[String],
cwd: Option<&Path>,
) -> Result<(), Error> {
let command = ResumeCommand {
argv: argv.to_vec(),
cwd: cwd.map(Path::to_path_buf),
};
if self.last_report.as_ref() == Some(&command) {
return Ok(());
}
let mut report = Vec::new();
if let Err(error) = protocol::write_report(&mut report, argv, cwd, &self.token) {
if matches!(&error, Error::InvalidReport(_)) {
self.clear_to(writer)?;
}
return Err(error);
}
writer.write_all(&report)?;
writer.flush()?;
self.last_report = Some(command);
Ok(())
}
pub fn refresh_to<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
let Some(command) = self.last_report.as_ref() else {
return Ok(());
};
let argv = command.argv.clone();
let cwd = command.cwd.clone();
protocol::write_report(writer, &argv, cwd.as_deref(), &self.token)
}
pub fn clear_to<W: Write>(&mut self, writer: &mut W) -> Result<(), Error> {
protocol::write_clear(writer, &self.token)?;
self.last_report = None;
Ok(())
}
}
#[cfg(unix)]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
use std::fs::OpenOptions;
Ok(Box::new(OpenOptions::new().write(true).open("/dev/tty")?))
}
#[cfg(windows)]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
Ok(Box::new(std::io::stdout()))
}
#[cfg(not(any(unix, windows)))]
fn terminal_writer() -> Result<Box<dyn Write>, Error> {
Err(Error::UnsupportedPlatform)
}