build.rs 5.5 KB

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