fix(prepare): store temporary query files inside the workspace

This commit is contained in:
Austin Schey
2023-03-11 14:23:17 -06:00
committed by Austin Bonander
parent 70934d7cd2
commit cf3ce13d27
4 changed files with 39 additions and 4 deletions

View File

@@ -157,10 +157,17 @@ where
}
}
pub(super) fn save_in(&self, dir: impl AsRef<Path>) -> crate::Result<()> {
pub(super) fn save_in(
&self,
dir: impl AsRef<Path>,
tmp_dir: impl AsRef<Path>,
) -> crate::Result<()> {
// Output to a temporary file first, then move it atomically to avoid clobbering
// other invocations trying to write to the same path.
let mut tmp_file = tempfile::NamedTempFile::new()
// Use a temp directory inside the workspace to avoid potential issues
// with persisting the file across filesystems.
let mut tmp_file = tempfile::NamedTempFile::new_in(tmp_dir)
.map_err(|err| format!("failed to create query file: {:?}", err))?;
serde_json::to_writer_pretty(tmp_file.as_file_mut(), self)
.map_err(|err| format!("failed to serialize query data to file: {:?}", err))?;

View File

@@ -357,6 +357,19 @@ where
if let Ok(dir) = env("SQLX_OFFLINE_DIR") {
let path = PathBuf::from(&dir);
// Prefer SQLX_TMP if set explicitly.
// Otherwise fallback to CARGO_TARGET_DIR and then the standard target directory.
let tmp_dir = if let Ok(tmp_dir) = env("SQLX_TMP") {
PathBuf::from(tmp_dir)
} else if let Ok(target_dir) = env("CARGO_TARGET_DIR") {
PathBuf::from(target_dir)
} else {
let tmp_target = PathBuf::from("./target/sqlx");
fs::create_dir_all(&tmp_target)
.map_err(|e| format!("Error creating cache directory: {e:?}"))?;
tmp_target
};
match fs::metadata(&path) {
Err(e) => {
if e.kind() != io::ErrorKind::NotFound {
@@ -376,7 +389,7 @@ where
}
// .sqlx exists and is a directory, store data.
data.save_in(path)?;
data.save_in(path, tmp_dir)?;
}
}
}