| 210 | } |
| 211 | |
| 212 | fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box<dyn Error>> { |
| 213 | let migrator_filepath = get_migrator_filepath(migration_dir); |
| 214 | println!( |
| 215 | "Adding migration `{}` to `{}`", |
| 216 | migration_name, |
| 217 | migrator_filepath.display() |
| 218 | ); |
| 219 | let migrator_content = fs::read_to_string(&migrator_filepath)?; |
| 220 | let mut updated_migrator_content = migrator_content.clone(); |
| 221 | |
| 222 | // create a backup of the migrator file in case something goes wrong |
| 223 | let migrator_backup_filepath = migrator_filepath.with_extension("rs.bak"); |
| 224 | fs::copy(&migrator_filepath, &migrator_backup_filepath)?; |
| 225 | let mut migrator_file = fs::File::create(&migrator_filepath)?; |
| 226 | |
| 227 | // find existing mod declarations, add new line |
| 228 | let mod_regex = Regex::new(r"mod\s+(?P<name>m\d{8}_\d{6}_\w+);")?; |
| 229 | let mods: Vec<_> = mod_regex.captures_iter(&migrator_content).collect(); |
| 230 | let mods_end = if let Some(last_match) = mods.last() { |
| 231 | last_match.get(0).unwrap().end() + 1 |
| 232 | } else { |
| 233 | migrator_content.len() |
| 234 | }; |
| 235 | updated_migrator_content.insert_str(mods_end, format!("mod {migration_name};\n").as_str()); |
| 236 | |
| 237 | // build new vector from declared migration modules |
| 238 | let mut migrations: Vec<&str> = mods |
| 239 | .iter() |
| 240 | .map(|cap| cap.name("name").unwrap().as_str()) |
| 241 | .collect(); |
| 242 | migrations.push(migration_name); |
| 243 | let mut boxed_migrations = migrations |
| 244 | .iter() |
| 245 | .map(|migration| format!(" Box::new({migration}::Migration),")) |
| 246 | .collect::<Vec<String>>() |
| 247 | .join("\n"); |
| 248 | boxed_migrations.push('\n'); |
| 249 | let boxed_migrations = format!("vec![\n{boxed_migrations} ]\n"); |
| 250 | let vec_regex = Regex::new(r"vec!\[[\s\S]+\]\n")?; |
| 251 | let updated_migrator_content = vec_regex.replace(&updated_migrator_content, &boxed_migrations); |
| 252 | |
| 253 | migrator_file.write_all(updated_migrator_content.as_bytes())?; |
| 254 | fs::remove_file(&migrator_backup_filepath)?; |
| 255 | Ok(()) |
| 256 | } |
| 257 | |
| 258 | #[derive(Debug)] |
| 259 | enum MigrationCommandError { |