You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.9 KiB

  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace IPA.Patcher
  5. {
  6. public static class BackupManager
  7. {
  8. public static BackupUnit FindLatestBackup(PatchContext context)
  9. {
  10. new DirectoryInfo(context.BackupPath).Create();
  11. return new DirectoryInfo(context.BackupPath)
  12. .GetDirectories()
  13. .OrderByDescending(p => p.Name)
  14. .Select(p => BackupUnit.FromDirectory(p, context))
  15. .FirstOrDefault();
  16. }
  17. public static bool HasBackup(PatchContext context)
  18. {
  19. return FindLatestBackup(context) != null;
  20. }
  21. public static bool Restore(PatchContext context)
  22. {
  23. var backup = FindLatestBackup(context);
  24. if(backup != null)
  25. {
  26. backup.Restore();
  27. backup.Delete();
  28. DeleteEmptyDirs(context.ProjectRoot);
  29. return true;
  30. }
  31. return false;
  32. }
  33. public static void DeleteEmptyDirs(string dir)
  34. {
  35. if (string.IsNullOrEmpty(dir))
  36. throw new ArgumentException(
  37. "Starting directory is a null reference or an empty string",
  38. nameof(dir));
  39. try
  40. {
  41. foreach (var d in Directory.EnumerateDirectories(dir))
  42. {
  43. DeleteEmptyDirs(d);
  44. }
  45. var entries = Directory.EnumerateFileSystemEntries(dir);
  46. if (entries.Any()) return;
  47. try
  48. {
  49. Directory.Delete(dir);
  50. }
  51. catch (UnauthorizedAccessException) { }
  52. catch (DirectoryNotFoundException) { }
  53. }
  54. catch (UnauthorizedAccessException) { }
  55. }
  56. }
  57. }