Don't create a tmpfile until one is needed (#820)

This commit is contained in:
Félix Saparelli 2024-04-20 23:52:28 +12:00 committed by GitHub
parent ec316a7279
commit f81aed1260
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 25 additions and 21 deletions

View File

@ -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,

View File

@ -101,7 +101,7 @@ async fn init() -> Result<Args> {
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?);

View File

@ -1,4 +1,5 @@
use std::{
env::var_os,
io::Write,
path::PathBuf,
sync::{Arc, Mutex},
@ -7,38 +8,41 @@ 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<Self> {
let emit_file = RotatingTempFile::new()?;
Ok(Self { emit_file })
}
}
#[derive(Clone, Debug)]
pub struct RotatingTempFile(Arc<Mutex<NamedTempFile>>);
#[derive(Clone, Debug, Default)]
pub struct RotatingTempFile(Arc<Mutex<Option<NamedTempFile>>>);
impl RotatingTempFile {
pub fn new() -> Result<Self> {
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(
if let Some(dir) = var_os("WATCHEXEC_TMPDIR") {
NamedTempFile::new_in(dir)
} else {
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()
}
}
}