Skip to main content

DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/RPC/CocoonService/FileSystem/
WriteFile.rs

1//! Write bytes to disk, creating any missing parent directories.
2
3use tonic::{Response, Status};
4
5use crate::{
6	RPC::CocoonService::CocoonServiceImpl,
7	Vine::Generated::{Empty, WriteFileRequest},
8	dev_log,
9};
10
11pub async fn Fn(_Service:&CocoonServiceImpl, Request:WriteFileRequest) -> Result<Response<Empty>, Status> {
12	let Path = CocoonServiceImpl::UriToPath(Request.uri.as_ref())
13		.ok_or_else(|| Status::invalid_argument("write_file: missing or empty URI"))?;
14
15	dev_log!(
16		"cocoon",
17		"[CocoonService] Writing file: {:?} ({} bytes)",
18		Path,
19		Request.content.len()
20	);
21
22	if let Some(Parent) = Path.parent() {
23		if !Parent.as_os_str().is_empty() {
24			tokio::fs::create_dir_all(Parent)
25				.await
26				.map_err(|Error| Status::internal(format!("write_file: create_dir_all {:?}: {}", Parent, Error)))?;
27		}
28	}
29
30	tokio::fs::write(&Path, &Request.content).await.map_err(|Error| {
31		dev_log!("cocoon", "warn: [CocoonService] write_file failed for {:?}: {}", Path, Error);
32		Status::internal(format!("write_file: {}: {}", Path.display(), Error))
33	})?;
34
35	Ok(Response::new(Empty {}))
36}