1 #![doc(hidden)]
2
3 use std::fs;
4 use std::io;
5 use std::path::Path;
6
7 use protobuf::descriptor::FileDescriptorProto;
8 use protobuf_parse::ProtoPathBuf;
9
10 use crate::customize::CustomizeCallback;
11 use crate::gen::all::gen_all;
12 use crate::Customize;
13
14 #[derive(Debug, thiserror::Error)]
15 enum Error {
16 #[error("output path `{0}` is not a directory")]
17 OutputIsNotDirectory(String),
18 #[error("output path `{0}` does not exist or not accessible")]
19 OutputDoesNotExistOrNotAccssible(String, #[source] io::Error),
20 #[error("failed to create file `{0}`: {1}")]
21 FailedToWriteFile(String, #[source] io::Error),
22 }
23
24 #[doc(hidden)]
gen_and_write( file_descriptors: &[FileDescriptorProto], parser: &str, files_to_generate: &[ProtoPathBuf], out_dir: &Path, customize: &Customize, customize_callback: &dyn CustomizeCallback, ) -> anyhow::Result<()>25 pub fn gen_and_write(
26 file_descriptors: &[FileDescriptorProto],
27 parser: &str,
28 files_to_generate: &[ProtoPathBuf],
29 out_dir: &Path,
30 customize: &Customize,
31 customize_callback: &dyn CustomizeCallback,
32 ) -> anyhow::Result<()> {
33 match out_dir.metadata() {
34 Ok(m) => {
35 if !m.is_dir() {
36 return Err(Error::OutputIsNotDirectory(out_dir.display().to_string()).into());
37 }
38 }
39 Err(e) => {
40 return Err(
41 Error::OutputDoesNotExistOrNotAccssible(out_dir.display().to_string(), e).into(),
42 );
43 }
44 }
45
46 let results = gen_all(
47 file_descriptors,
48 parser,
49 files_to_generate,
50 customize,
51 customize_callback,
52 )?;
53
54 for r in &results {
55 let mut file_path = out_dir.to_owned();
56 file_path.push(&r.name);
57 fs::write(&file_path, r.content.as_slice())
58 .map_err(|e| Error::FailedToWriteFile(file_path.display().to_string(), e))?;
59 }
60
61 Ok(())
62 }
63