From 51b18edb1c0aee0952888668dfa34faae1e14d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Saparelli?= Date: Sat, 20 Apr 2024 23:19:06 +1200 Subject: [PATCH] Don't initially create a tmpfile until it's needed --- crates/cli/src/filterer/proglib/file.rs | 4 ++-- crates/cli/src/lib.rs | 2 +- crates/cli/src/state.rs | 32 +++++++++++-------------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/crates/cli/src/filterer/proglib/file.rs b/crates/cli/src/filterer/proglib/file.rs index fe94315..b92077d 100644 --- a/crates/cli/src/filterer/proglib/file.rs +++ b/crates/cli/src/filterer/proglib/file.rs @@ -5,14 +5,14 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; -use jaq_interpret::{ParseCtx, Error, Native, Val}; +use jaq_interpret::{Error, Native, ParseCtx, Val}; use serde_json::{json, Value}; use tracing::{debug, error, trace}; use super::macros::*; pub fn load(jaq: &mut ParseCtx) { - trace!("jaq: add file_read filter"); + trace!("jaq: add file_read filter"); jaq.insert_native( "file_read".into(), 1, diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42bda7e..bd50cea 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -101,7 +101,7 @@ async fn init() -> Result { async fn run_watchexec(args: Args) -> Result<()> { info!(version=%env!("CARGO_PKG_VERSION"), "constructing Watchexec from CLI"); - let state = state::State::new()?; + let state = state::State::default(); let config = config::make_config(&args, &state)?; config.filterer(WatchexecFilterer::new(&args).await?); diff --git a/crates/cli/src/state.rs b/crates/cli/src/state.rs index 4c3ed05..5a56c1b 100644 --- a/crates/cli/src/state.rs +++ b/crates/cli/src/state.rs @@ -7,38 +7,34 @@ use std::{ use miette::{IntoDiagnostic, Result}; use tempfile::NamedTempFile; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct State { pub emit_file: RotatingTempFile, } -impl State { - pub fn new() -> Result { - let emit_file = RotatingTempFile::new()?; - Ok(Self { emit_file }) - } -} - -#[derive(Clone, Debug)] -pub struct RotatingTempFile(Arc>); +#[derive(Clone, Debug, Default)] +pub struct RotatingTempFile(Arc>>); impl RotatingTempFile { - pub fn new() -> Result { - let file = Arc::new(Mutex::new(NamedTempFile::new().into_diagnostic()?)); - Ok(Self(file)) - } - pub fn rotate(&self) -> Result<()> { // implicitly drops the old file - *self.0.lock().unwrap() = NamedTempFile::new().into_diagnostic()?; + *self.0.lock().unwrap() = Some(NamedTempFile::new().into_diagnostic()?); Ok(()) } pub fn write(&self, data: &[u8]) -> Result<()> { - self.0.lock().unwrap().write_all(data).into_diagnostic() + if let Some(file) = self.0.lock().unwrap().as_mut() { + file.write_all(data).into_diagnostic()?; + } + + Ok(()) } pub fn path(&self) -> PathBuf { - self.0.lock().unwrap().path().to_owned() + if let Some(file) = self.0.lock().unwrap().as_ref() { + file.path().to_owned() + } else { + PathBuf::new() + } } }