From 7d7263c48f4280f8da5496273e85fb1a8fb79547 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 22 Aug 2018 13:19:32 -0400 Subject: Implement writeFileSync In collaboration with Tommy Savaria --- src/fs.rs | 6 ++++++ src/handlers.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) (limited to 'src') diff --git a/src/fs.rs b/src/fs.rs index 0aaf2a93d..9191d5373 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -1,6 +1,7 @@ use std; use std::fs::File; use std::io::Read; +use std::io::Write; use std::path::Path; pub fn read_file_sync(path: &Path) -> std::io::Result> { @@ -17,6 +18,11 @@ pub fn read_file_sync_string(path: &Path) -> std::io::Result { .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err)) } +pub fn write_file_sync(path: &Path, content: &[u8]) -> std::io::Result<()> { + let mut f = File::create(path)?; + f.write_all(content) +} + pub fn mkdir(path: &Path) -> std::io::Result<()> { debug!("mkdir -p {}", path.display()); assert!(path.has_root(), "non-has_root not yet implemented"); diff --git a/src/handlers.rs b/src/handlers.rs index 853fbbc77..1b8a59173 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -70,6 +70,14 @@ pub extern "C" fn msg_from_js(d: *const DenoC, buf: deno_buf) { let filename = msg.filename().unwrap(); handle_read_file_sync(d, &mut builder, filename) } + msg::Any::WriteFileSync => { + // TODO base.msg_as_WriteFileSync(); + let msg = msg::WriteFileSync::init_from_table(base.msg().unwrap()); + let filename = msg.filename().unwrap(); + let data = msg.data().unwrap(); + let perm = msg.perm(); + handle_write_file_sync(d, &mut builder, filename, data, perm) + } _ => panic!(format!( "Unhandled message {}", msg::enum_name_any(msg_type) @@ -413,6 +421,28 @@ fn handle_read_file_sync( )) } +fn handle_write_file_sync( + d: *const DenoC, + builder: &mut FlatBufferBuilder, + filename: &str, + data: &[u8], + perm: u32, +) -> HandlerResult { + debug!("handle_write_file_sync {}", filename); + let deno = from_c(d); + if deno.flags.allow_write { + // TODO(ry) Use perm. + fs::write_file_sync(Path::new(filename), data)?; + Ok(null_buf()) + } else { + let err = std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "allow_write is off.", + ); + Err(err.into()) + } +} + // TODO(ry) Use Deno instead of DenoC as first arg. fn remove_timer(d: *const DenoC, timer_id: u32) { let deno = from_c(d); -- cgit v1.2.3