build.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. writeln!(out_file, "// @generated").unwrap();
  18. writeln!(out_file, "// Auto-generated by build.rs").unwrap();
  19. writeln!(out_file, "pub static MIGRATIONS: &[(&str, &str)] = &[").unwrap();
  20. for path in &files {
  21. let name = path.file_name().unwrap().to_string_lossy();
  22. let rel_path = &path.to_str().unwrap().replace("\\", "/")[skip_path..]; // for Windows
  23. writeln!(
  24. out_file,
  25. " (\"{name}\", include_str!(r#\".{rel_path}\"#)),"
  26. )
  27. .unwrap();
  28. }
  29. writeln!(out_file, "];").unwrap();
  30. println!("cargo:rerun-if-changed={}", migration_path.display());
  31. }
  32. }
  33. fn find_migrations_dirs(root: &Path) -> Vec<PathBuf> {
  34. let mut found = Vec::new();
  35. find_migrations_dirs_rec(root, &mut found);
  36. found
  37. }
  38. fn find_migrations_dirs_rec(dir: &Path, found: &mut Vec<PathBuf>) {
  39. if let Ok(entries) = fs::read_dir(dir) {
  40. for entry in entries.flatten() {
  41. let path = entry.path();
  42. if path.is_dir() {
  43. if path.file_name().unwrap_or_default() == "migrations" {
  44. found.push(path.clone());
  45. }
  46. find_migrations_dirs_rec(&path, found);
  47. }
  48. }
  49. }
  50. }
  51. fn visit_dirs(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
  52. for entry in fs::read_dir(dir)? {
  53. let entry = entry?;
  54. let path = entry.path();
  55. if path.is_dir() {
  56. visit_dirs(&path, files)?;
  57. } else if path.is_file() {
  58. files.push(path);
  59. }
  60. }
  61. Ok(())
  62. }