summaryrefslogtreecommitdiff
path: root/src/fs.rs
diff options
context:
space:
mode:
authorBert Belder <bertbelder@gmail.com>2018-08-24 00:36:45 +0200
committerBert Belder <bertbelder@gmail.com>2018-08-29 22:40:05 +0200
commitceaf82268282d16b97101c00c75612745de416bb (patch)
tree6294eeeb063ca2196ef285ad7f125437cbc3bd45 /src/fs.rs
parenta836c493f30323e7b40e988140ed2603f0e3d10f (diff)
Implement makeTempDirSync()
Diffstat (limited to 'src/fs.rs')
-rw-r--r--src/fs.rs32
1 files changed, 30 insertions, 2 deletions
diff --git a/src/fs.rs b/src/fs.rs
index 50c99c593..786c35691 100644
--- a/src/fs.rs
+++ b/src/fs.rs
@@ -1,13 +1,41 @@
use std;
-use std::fs::File;
+use std::fs::{create_dir, File};
+use std::io::ErrorKind;
use std::io::Write;
-use std::path::Path;
+use std::path::{Path, PathBuf};
+
+use rand;
+use rand::RngCore;
pub fn write_file_sync(path: &Path, content: &[u8]) -> std::io::Result<()> {
let mut f = File::create(path)?;
f.write_all(content)
}
+pub fn make_temp_dir(
+ dir: Option<&Path>,
+ prefix: Option<&str>,
+ suffix: Option<&str>,
+) -> std::io::Result<PathBuf> {
+ let prefix_ = prefix.unwrap_or("");
+ let suffix_ = suffix.unwrap_or("");
+ let mut buf: PathBuf = match dir {
+ Some(ref p) => p.to_path_buf(),
+ None => std::env::temp_dir(),
+ }.join("_");
+ loop {
+ let unique = rand::thread_rng().next_u32();
+ buf.set_file_name(format!("{}{:08x}{}", prefix_, unique, suffix_));
+ // TODO: on posix, set mode flags to 0o700.
+ let r = create_dir(buf.as_path());
+ match r {
+ Err(ref e) if e.kind() == ErrorKind::AlreadyExists => continue,
+ Ok(_) => return Ok(buf),
+ Err(e) => return Err(e),
+ }
+ }
+}
+
pub fn mkdir(path: &Path) -> std::io::Result<()> {
debug!("mkdir -p {}", path.display());
assert!(path.has_root(), "non-has_root not yet implemented");