proto_gen.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #![allow(unused_attributes)]
  2. #![allow(dead_code)]
  3. #![allow(unused_imports)]
  4. #![allow(unused_results)]
  5. use crate::code_gen::protobuf_file::ast::parse_protobuf_context_from;
  6. use crate::code_gen::protobuf_file::proto_info::ProtobufCrateContext;
  7. use crate::code_gen::protobuf_file::ProtoFile;
  8. use crate::code_gen::util::*;
  9. use crate::code_gen::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. .map(|ctx| {
  49. ctx.files
  50. .iter()
  51. .map(|file| {
  52. (
  53. file.file_path.clone(),
  54. ProtoFileSymbol {
  55. file_name: file.file_name.clone(),
  56. symbols: file.symbols(),
  57. },
  58. )
  59. })
  60. .collect::<HashMap<String, ProtoFileSymbol>>()
  61. })
  62. .flatten()
  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(current_file: &ProtoFile, file_path_symbols_map: &HashMap<String, ProtoFileSymbol>) -> String {
  80. let mut import_files: Vec<String> = vec![];
  81. file_path_symbols_map
  82. .iter()
  83. .for_each(|(file_path, proto_file_symbols)| {
  84. if file_path != &current_file.file_path {
  85. current_file.ref_types.iter().for_each(|ref_type| {
  86. if proto_file_symbols.symbols.contains(ref_type) {
  87. let import_file = format!("import \"{}.proto\";", proto_file_symbols.file_name);
  88. if !import_files.contains(&import_file) {
  89. import_files.push(import_file);
  90. }
  91. }
  92. });
  93. }
  94. });
  95. if import_files.len() == 1 {
  96. format!("{}\n", import_files.pop().unwrap())
  97. } else {
  98. import_files.join("\n")
  99. }
  100. }
  101. struct ProtoFileSymbol {
  102. file_name: String,
  103. symbols: Vec<String>,
  104. }
  105. fn write_rust_crate_mod_file(crate_contexts: &[ProtobufCrateContext]) {
  106. for context in crate_contexts {
  107. let mod_path = context.protobuf_crate.proto_model_mod_file();
  108. match OpenOptions::new()
  109. .create(true)
  110. .write(true)
  111. .append(false)
  112. .truncate(true)
  113. .open(&mod_path)
  114. {
  115. Ok(ref mut file) => {
  116. let mut mod_file_content = String::new();
  117. mod_file_content.push_str("#![cfg_attr(rustfmt, rustfmt::skip)]\n");
  118. mod_file_content.push_str("// Auto-generated, do not edit\n");
  119. walk_dir(
  120. context.protobuf_crate.proto_output_path(),
  121. |e| !e.file_type().is_dir(),
  122. |_, name| {
  123. let c = format!("\nmod {};\npub use {}::*;\n", &name, &name);
  124. mod_file_content.push_str(c.as_ref());
  125. },
  126. );
  127. file.write_all(mod_file_content.as_bytes()).unwrap();
  128. }
  129. Err(err) => {
  130. panic!("Failed to open file: {}", err);
  131. }
  132. }
  133. }
  134. }
  135. impl ProtoCache {
  136. fn from_crate_contexts(crate_contexts: &[ProtobufCrateContext]) -> Self {
  137. let proto_files = crate_contexts
  138. .iter()
  139. .map(|crate_info| &crate_info.files)
  140. .flatten()
  141. .collect::<Vec<&ProtoFile>>();
  142. let structs: Vec<String> = proto_files.iter().map(|info| info.structs.clone()).flatten().collect();
  143. let enums: Vec<String> = proto_files.iter().map(|info| info.enums.clone()).flatten().collect();
  144. Self { structs, enums }
  145. }
  146. }