proto_gen.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use crate::proto_gen::ast::parse_crate_protobuf;
  2. use crate::proto_gen::proto_info::ProtobufCrateContext;
  3. use crate::proto_gen::template::write_derive_meta;
  4. use crate::proto_gen::util::*;
  5. use std::{fs::OpenOptions, io::Write};
  6. pub(crate) struct ProtoGenerator();
  7. impl ProtoGenerator {
  8. pub(crate) fn gen(root: &str) -> Vec<ProtobufCrateContext> {
  9. let crate_contexts = parse_crate_protobuf(vec![root.to_owned()]);
  10. write_proto_files(&crate_contexts);
  11. write_rust_crate_mod_file(&crate_contexts);
  12. for crate_info in &crate_contexts {
  13. let _ = crate_info.protobuf_crate.create_output_dir();
  14. let _ = crate_info.protobuf_crate.proto_output_dir();
  15. crate_info.create_crate_mod_file();
  16. }
  17. crate_contexts
  18. }
  19. }
  20. fn write_proto_files(crate_contexts: &[ProtobufCrateContext]) {
  21. for context in crate_contexts {
  22. let dir = context.protobuf_crate.proto_output_dir();
  23. context.files.iter().for_each(|info| {
  24. let proto_file_path = format!("{}/{}.proto", dir, &info.file_name);
  25. save_content_to_file_with_diff_prompt(&info.generated_content, proto_file_path.as_ref());
  26. });
  27. }
  28. }
  29. fn write_rust_crate_mod_file(crate_contexts: &[ProtobufCrateContext]) {
  30. for context in crate_contexts {
  31. let mod_path = context.protobuf_crate.proto_model_mod_file();
  32. match OpenOptions::new()
  33. .create(true)
  34. .write(true)
  35. .append(false)
  36. .truncate(true)
  37. .open(&mod_path)
  38. {
  39. Ok(ref mut file) => {
  40. let mut mod_file_content = String::new();
  41. mod_file_content.push_str("#![cfg_attr(rustfmt, rustfmt::skip)]\n");
  42. mod_file_content.push_str("// Auto-generated, do not edit\n");
  43. walk_dir(
  44. context.protobuf_crate.proto_output_dir().as_ref(),
  45. |e| !e.file_type().is_dir(),
  46. |_, name| {
  47. let c = format!("\nmod {};\npub use {}::*;\n", &name, &name);
  48. mod_file_content.push_str(c.as_ref());
  49. },
  50. );
  51. file.write_all(mod_file_content.as_bytes()).unwrap();
  52. }
  53. Err(err) => {
  54. panic!("Failed to open file: {}", err);
  55. }
  56. }
  57. }
  58. }