build.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. use std::fs::{self, File};
  2. use std::io::Write;
  3. use std::path::{Path, PathBuf};
  4. fn main() {
  5. // Step 1: Find `migrations/` folder recursively
  6. let root = Path::new("src");
  7. for migration_path in find_migrations_dirs(root) {
  8. // Step 2: Collect all files inside the migrations dir
  9. let mut files = Vec::new();
  10. visit_dirs(&migration_path, &mut files).expect("Failed to read migrations directory");
  11. files.sort();
  12. // Step 3: Output file path (e.g., `src/db/migrations.rs`)
  13. let parent = migration_path.parent().unwrap();
  14. let skip_path = parent.to_str().unwrap_or_default().len();
  15. let dest_path = parent.join("migrations.rs");
  16. let mut out_file = File::create(&dest_path).expect("Failed to create migrations.rs");
  17. let skip_name = migration_path.to_str().unwrap_or_default().len();
  18. writeln!(out_file, "/// @generated").unwrap();
  19. writeln!(out_file, "/// Auto-generated by build.rs").unwrap();
  20. writeln!(
  21. out_file,
  22. "pub static MIGRATIONS: &[(&str, &str, &str)] = &["
  23. )
  24. .unwrap();
  25. for path in &files {
  26. let parts = path.to_str().unwrap().replace("\\", "/")[skip_name + 1..]
  27. .split("/")
  28. .map(|x| x.to_owned())
  29. .collect::<Vec<_>>();
  30. let prefix = if parts.len() == 2 {
  31. parts.first().map(|x| x.to_owned()).unwrap_or_default()
  32. } else {
  33. "".to_owned()
  34. };
  35. let rel_name = &path.file_name().unwrap().to_str().unwrap();
  36. let rel_path = &path.to_str().unwrap().replace("\\", "/")[skip_path..]; // for Windows
  37. writeln!(
  38. out_file,
  39. " (\"{prefix}\", \"{rel_name}\", include_str!(r#\".{rel_path}\"#)),"
  40. )
  41. .unwrap();
  42. println!("cargo:rerun-if-changed={}", path.display());
  43. }
  44. writeln!(out_file, "];").unwrap();
  45. println!("cargo:rerun-if-changed={}", migration_path.display());
  46. }
  47. }
  48. fn find_migrations_dirs(root: &Path) -> Vec<PathBuf> {
  49. let mut found = Vec::new();
  50. find_migrations_dirs_rec(root, &mut found);
  51. found
  52. }
  53. fn find_migrations_dirs_rec(dir: &Path, found: &mut Vec<PathBuf>) {
  54. if let Ok(entries) = fs::read_dir(dir) {
  55. for entry in entries.flatten() {
  56. let path = entry.path();
  57. if path.is_dir() {
  58. if path.file_name().unwrap_or_default() == "migrations" {
  59. found.push(path.clone());
  60. }
  61. find_migrations_dirs_rec(&path, found);
  62. }
  63. }
  64. }
  65. }
  66. fn visit_dirs(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
  67. for entry in fs::read_dir(dir)? {
  68. let entry = entry?;
  69. let path = entry.path();
  70. if path.is_dir() {
  71. visit_dirs(&path, files)?;
  72. } else if path.is_file() {
  73. files.push(path);
  74. }
  75. }
  76. Ok(())
  77. }