build.rs 2.5 KB

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