build.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. use std::cmp::Ordering;
  2. use std::env;
  3. use std::fs::{self, File};
  4. use std::io::Write;
  5. use std::path::{Path, PathBuf};
  6. fn main() {
  7. // Step 1: Find `migrations/` folder recursively
  8. let root = Path::new("src");
  9. // Get the OUT_DIR from Cargo - this is writable
  10. let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by Cargo"));
  11. for migration_path in find_migrations_dirs(root) {
  12. // Step 3: Output file path to OUT_DIR instead of source directory
  13. let parent = migration_path.parent().unwrap();
  14. // Create a unique filename based on the migration path to avoid conflicts
  15. let migration_name = parent
  16. .strip_prefix("src")
  17. .unwrap_or(parent)
  18. .to_str()
  19. .unwrap_or("default")
  20. .replace("/", "_")
  21. .replace("\\", "_");
  22. let dest_path = out_dir.join(format!("migrations_{}.rs", migration_name));
  23. let mut out_file = File::create(&dest_path).expect("Failed to create migrations.rs");
  24. let skip_name = migration_path.to_str().unwrap_or_default().len();
  25. // Step 2: Collect all files inside the migrations dir
  26. let mut files = Vec::new();
  27. visit_dirs(&migration_path, &mut files).expect("Failed to read migrations directory");
  28. files.sort_by(|path_a, path_b| {
  29. let parts_a = path_a.to_str().unwrap().replace("\\", "/")[skip_name + 1..]
  30. .split("/")
  31. .map(|x| x.to_owned())
  32. .collect::<Vec<_>>();
  33. let parts_b = path_b.to_str().unwrap().replace("\\", "/")[skip_name + 1..]
  34. .split("/")
  35. .map(|x| x.to_owned())
  36. .collect::<Vec<_>>();
  37. let prefix_a = if parts_a.len() == 2 {
  38. parts_a.first().map(|x| x.to_owned()).unwrap_or_default()
  39. } else {
  40. "".to_owned()
  41. };
  42. let prefix_b = if parts_a.len() == 2 {
  43. parts_b.first().map(|x| x.to_owned()).unwrap_or_default()
  44. } else {
  45. "".to_owned()
  46. };
  47. let prefix_cmp = prefix_a.cmp(&prefix_b);
  48. if prefix_cmp != Ordering::Equal {
  49. return prefix_cmp;
  50. }
  51. let path_a = path_a.file_name().unwrap().to_str().unwrap();
  52. let path_b = path_b.file_name().unwrap().to_str().unwrap();
  53. let prefix_a = path_a
  54. .split("_")
  55. .next()
  56. .and_then(|prefix| prefix.parse::<usize>().ok())
  57. .unwrap_or_default();
  58. let prefix_b = path_b
  59. .split("_")
  60. .next()
  61. .and_then(|prefix| prefix.parse::<usize>().ok())
  62. .unwrap_or_default();
  63. if prefix_a != 0 && prefix_b != 0 {
  64. prefix_a.cmp(&prefix_b)
  65. } else {
  66. path_a.cmp(path_b)
  67. }
  68. });
  69. writeln!(out_file, "/// @generated").unwrap();
  70. writeln!(out_file, "/// Auto-generated by build.rs").unwrap();
  71. writeln!(
  72. out_file,
  73. "pub static MIGRATIONS: &[(&str, &str, &str)] = &["
  74. )
  75. .unwrap();
  76. for path in &files {
  77. let parts = path.to_str().unwrap().replace("\\", "/")[skip_name + 1..]
  78. .split("/")
  79. .map(|x| x.to_owned())
  80. .collect::<Vec<_>>();
  81. let prefix = if parts.len() == 2 {
  82. parts.first().map(|x| x.to_owned()).unwrap_or_default()
  83. } else {
  84. "".to_owned()
  85. };
  86. let rel_name = &path.file_name().unwrap().to_str().unwrap();
  87. // Copy migration file to OUT_DIR
  88. let relative_path = path.strip_prefix(root).unwrap();
  89. let dest_migration_file = out_dir.join(relative_path);
  90. if let Some(parent) = dest_migration_file.parent() {
  91. fs::create_dir_all(parent)
  92. .expect("Failed to create migration directory in OUT_DIR");
  93. }
  94. fs::copy(path, &dest_migration_file).expect("Failed to copy migration file to OUT_DIR");
  95. // Use path relative to OUT_DIR for include_str
  96. let relative_to_out_dir = relative_path.to_str().unwrap().replace("\\", "/");
  97. writeln!(
  98. out_file,
  99. " (\"{prefix}\", \"{rel_name}\", include_str!(r#\"{}\"#)),",
  100. relative_to_out_dir
  101. )
  102. .unwrap();
  103. println!("cargo:rerun-if-changed={}", path.display());
  104. }
  105. writeln!(out_file, "];").unwrap();
  106. println!("cargo:rerun-if-changed={}", migration_path.display());
  107. }
  108. }
  109. fn find_migrations_dirs(root: &Path) -> Vec<PathBuf> {
  110. let mut found = Vec::new();
  111. find_migrations_dirs_rec(root, &mut found);
  112. found
  113. }
  114. fn find_migrations_dirs_rec(dir: &Path, found: &mut Vec<PathBuf>) {
  115. if let Ok(entries) = fs::read_dir(dir) {
  116. for entry in entries.flatten() {
  117. let path = entry.path();
  118. if path.is_dir() {
  119. if path.file_name().unwrap_or_default() == "migrations" {
  120. found.push(path.clone());
  121. }
  122. find_migrations_dirs_rec(&path, found);
  123. }
  124. }
  125. }
  126. }
  127. fn visit_dirs(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
  128. for entry in fs::read_dir(dir)? {
  129. let entry = entry?;
  130. let path = entry.path();
  131. if path.is_dir() {
  132. visit_dirs(&path, files)?;
  133. } else if path.is_file() {
  134. files.push(path);
  135. }
  136. }
  137. Ok(())
  138. }