4
0

build.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use std::{
  2. env,
  3. fs::{read_dir, read_to_string, File},
  4. io::Write,
  5. path::PathBuf,
  6. };
  7. use regex::Regex;
  8. const COMMAND_REGEX: &str = r"pub fn (.*)\(app: &mut Application\) -> Result<\(\)>";
  9. fn main() {
  10. generate_handler();
  11. }
  12. fn generate_handler() {
  13. let out_dir = env::var("OUT_DIR").unwrap();
  14. let out_file_pathbuf = PathBuf::new().join(out_dir).join("handle_map");
  15. let mut out_file = File::create(out_file_pathbuf).unwrap();
  16. out_file
  17. .write(
  18. r"{
  19. let mut handles: HashMap<&'static str, fn(&mut Application) -> Result<()>> = HashMap::new();
  20. "
  21. .as_bytes(),
  22. )
  23. .unwrap();
  24. let expression = Regex::new(COMMAND_REGEX).expect("Failed to compile command matching regex");
  25. let readdir = read_dir("./src/application/handler/").unwrap();
  26. for entry in readdir {
  27. if let Ok(entry) = entry {
  28. let path = entry.path();
  29. let module_name = entry
  30. .file_name()
  31. .into_string()
  32. .unwrap()
  33. .split('.')
  34. .next()
  35. .unwrap()
  36. .to_owned();
  37. let content = read_to_string(path).unwrap();
  38. for captures in expression.captures_iter(&content) {
  39. let function_name = captures.get(1).unwrap().as_str();
  40. write(&mut out_file, &module_name, function_name);
  41. }
  42. }
  43. }
  44. out_file
  45. .write(
  46. r"
  47. handles
  48. }"
  49. .as_bytes(),
  50. )
  51. .unwrap();
  52. }
  53. fn write(output: &mut File, module_name: &str, function_name: &str) {
  54. output
  55. .write(
  56. format!(
  57. " handles.insert(\"{}::{}\", {}::{});\n",
  58. module_name, function_name, module_name, function_name
  59. )
  60. .as_bytes(),
  61. )
  62. .unwrap();
  63. }