util.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use nanoid::nanoid;
  2. use std::fs::{create_dir_all, File};
  3. use std::io::copy;
  4. use std::path::{Path, PathBuf};
  5. use zip::ZipArchive;
  6. pub fn unzip_history_user_db(folder_name: &str) -> std::io::Result<(Cleaner, PathBuf)> {
  7. // Open the zip file
  8. let zip_file_path = format!(
  9. "./tests/user/migration_test/history_user_db/{}.zip",
  10. folder_name
  11. );
  12. let reader = File::open(zip_file_path)?;
  13. let output_folder_path = format!(
  14. "./tests/user/migration_test/history_user_db/unit_test_{}",
  15. nanoid!(6)
  16. );
  17. // Create a ZipArchive from the file
  18. let mut archive = ZipArchive::new(reader)?;
  19. // Iterate through each file in the zip
  20. for i in 0..archive.len() {
  21. let mut file = archive.by_index(i)?;
  22. let output_path = Path::new(&output_folder_path).join(file.mangled_name());
  23. if file.name().ends_with('/') {
  24. // Create directory
  25. create_dir_all(&output_path)?;
  26. } else {
  27. // Write file
  28. if let Some(p) = output_path.parent() {
  29. if !p.exists() {
  30. create_dir_all(p)?;
  31. }
  32. }
  33. let mut outfile = File::create(&output_path)?;
  34. copy(&mut file, &mut outfile)?;
  35. }
  36. }
  37. let path = format!("{}/{}", output_folder_path, folder_name);
  38. Ok((
  39. Cleaner::new(PathBuf::from(output_folder_path)),
  40. PathBuf::from(path),
  41. ))
  42. }
  43. pub struct Cleaner(PathBuf);
  44. impl Cleaner {
  45. pub fn new(dir: PathBuf) -> Self {
  46. Cleaner(dir)
  47. }
  48. fn cleanup(dir: &PathBuf) {
  49. let _ = std::fs::remove_dir_all(dir);
  50. }
  51. }
  52. impl Drop for Cleaner {
  53. fn drop(&mut self) {
  54. Self::cleanup(&self.0)
  55. }
  56. }