proto_gen.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #![allow(unused_attributes)]
  2. #![allow(dead_code)]
  3. #![allow(unused_imports)]
  4. #![allow(unused_results)]
  5. use crate::protobuf_file::ast::parse_protobuf_context_from;
  6. use crate::protobuf_file::proto_info::ProtobufCrateContext;
  7. use crate::protobuf_file::ProtoFile;
  8. use crate::util::*;
  9. use crate::ProtoCache;
  10. use std::collections::HashMap;
  11. use std::fs::File;
  12. use std::path::Path;
  13. use std::{fs::OpenOptions, io::Write};
  14. pub struct ProtoGenerator();
  15. impl ProtoGenerator {
  16. pub fn gen(crate_name: &str, crate_path: &str) -> Vec<ProtobufCrateContext> {
  17. let crate_contexts = parse_protobuf_context_from(vec![crate_path.to_owned()]);
  18. write_proto_files(&crate_contexts);
  19. write_rust_crate_mod_file(&crate_contexts);
  20. let proto_cache = ProtoCache::from_crate_contexts(&crate_contexts);
  21. let proto_cache_str = serde_json::to_string(&proto_cache).unwrap();
  22. let crate_cache_dir = path_buf_with_component(&cache_dir(), vec![crate_name]);
  23. if !crate_cache_dir.as_path().exists() {
  24. std::fs::create_dir_all(&crate_cache_dir).unwrap();
  25. }
  26. let protobuf_cache_path = path_string_with_component(&crate_cache_dir, vec!["proto_cache"]);
  27. match std::fs::OpenOptions::new()
  28. .create(true)
  29. .write(true)
  30. .append(false)
  31. .truncate(true)
  32. .open(&protobuf_cache_path)
  33. {
  34. Ok(ref mut file) => {
  35. file.write_all(proto_cache_str.as_bytes()).unwrap();
  36. File::flush(file).unwrap();
  37. },
  38. Err(_err) => {
  39. panic!("Failed to open file: {}", protobuf_cache_path);
  40. },
  41. }
  42. crate_contexts
  43. }
  44. }
  45. fn write_proto_files(crate_contexts: &[ProtobufCrateContext]) {
  46. let file_path_content_map = crate_contexts
  47. .iter()
  48. .flat_map(|ctx| {
  49. ctx
  50. .files
  51. .iter()
  52. .map(|file| {
  53. (
  54. file.file_path.clone(),
  55. ProtoFileSymbol {
  56. file_name: file.file_name.clone(),
  57. symbols: file.symbols(),
  58. },
  59. )
  60. })
  61. .collect::<HashMap<String, ProtoFileSymbol>>()
  62. })
  63. .collect::<HashMap<String, ProtoFileSymbol>>();
  64. for context in crate_contexts {
  65. let dir = context.protobuf_crate.proto_output_path();
  66. context.files.iter().for_each(|file| {
  67. // syntax
  68. let mut file_content = file.syntax.clone();
  69. // import
  70. file_content.push_str(&gen_import_content(file, &file_path_content_map));
  71. // content
  72. file_content.push_str(&file.content);
  73. let proto_file = format!("{}.proto", &file.file_name);
  74. let proto_file_path = path_string_with_component(&dir, vec![&proto_file]);
  75. save_content_to_file_with_diff_prompt(&file_content, proto_file_path.as_ref());
  76. });
  77. }
  78. }
  79. fn gen_import_content(
  80. current_file: &ProtoFile,
  81. file_path_symbols_map: &HashMap<String, ProtoFileSymbol>,
  82. ) -> String {
  83. let mut import_files: Vec<String> = vec![];
  84. file_path_symbols_map
  85. .iter()
  86. .for_each(|(file_path, proto_file_symbols)| {
  87. if file_path != &current_file.file_path {
  88. current_file.ref_types.iter().for_each(|ref_type| {
  89. if proto_file_symbols.symbols.contains(ref_type) {
  90. let import_file = format!("import \"{}.proto\";", proto_file_symbols.file_name);
  91. if !import_files.contains(&import_file) {
  92. import_files.push(import_file);
  93. }
  94. }
  95. });
  96. }
  97. });
  98. if import_files.len() == 1 {
  99. format!("{}\n", import_files.pop().unwrap())
  100. } else {
  101. import_files.join("\n")
  102. }
  103. }
  104. struct ProtoFileSymbol {
  105. file_name: String,
  106. symbols: Vec<String>,
  107. }
  108. fn write_rust_crate_mod_file(crate_contexts: &[ProtobufCrateContext]) {
  109. for context in crate_contexts {
  110. let mod_path = context.protobuf_crate.proto_model_mod_file();
  111. match OpenOptions::new()
  112. .create(true)
  113. .write(true)
  114. .append(false)
  115. .truncate(true)
  116. .open(&mod_path)
  117. {
  118. Ok(ref mut file) => {
  119. let mut mod_file_content = String::new();
  120. mod_file_content.push_str("#![cfg_attr(rustfmt, rustfmt::skip)]\n");
  121. mod_file_content.push_str(" #![allow(ambiguous_glob_reexports)]\n");
  122. mod_file_content.push_str("// Auto-generated, do not edit\n");
  123. walk_dir(
  124. context.protobuf_crate.proto_output_path(),
  125. |e| !e.file_type().is_dir(),
  126. |_, name| {
  127. let c = format!("\nmod {};\npub use {}::*;\n", &name, &name);
  128. mod_file_content.push_str(c.as_ref());
  129. },
  130. );
  131. file.write_all(mod_file_content.as_bytes()).unwrap();
  132. },
  133. Err(err) => {
  134. panic!("Failed to open file: {}", err);
  135. },
  136. }
  137. }
  138. }
  139. impl ProtoCache {
  140. fn from_crate_contexts(crate_contexts: &[ProtobufCrateContext]) -> Self {
  141. let proto_files = crate_contexts
  142. .iter()
  143. .flat_map(|crate_info| &crate_info.files)
  144. .collect::<Vec<&ProtoFile>>();
  145. let structs: Vec<String> = proto_files
  146. .iter()
  147. .flat_map(|info| info.structs.clone())
  148. .collect();
  149. let enums: Vec<String> = proto_files
  150. .iter()
  151. .flat_map(|info| info.enums.clone())
  152. .collect();
  153. Self { structs, enums }
  154. }
  155. }