A fork of Eusth's IPA
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.

74 lines
2.0KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. namespace IPA.Patcher
  8. {
  9. public class BackupManager
  10. {
  11. public static void MakeBackup(string file)
  12. {
  13. File.Copy(file, GetBackupName(file));
  14. }
  15. private static string GetBackupName(string file)
  16. {
  17. string backup = file + ".Original";
  18. if (File.Exists(backup))
  19. {
  20. int i = 1;
  21. string backupBase = backup;
  22. while (File.Exists(backup))
  23. {
  24. backup = backupBase + i++;
  25. }
  26. }
  27. return backup;
  28. }
  29. public static string FindLatestBackup(string file)
  30. {
  31. var directory = Path.GetDirectoryName(file);
  32. var filename = Path.GetFileName(file);
  33. var regex = new Regex(String.Format(@"^{0}\.Original\d*$", Regex.Escape(filename)));
  34. var extractNumRegex = new Regex(@"\d+$");
  35. string latestFile = null;
  36. int latestNum = -1;
  37. foreach(var f in Directory.GetFiles(directory))
  38. {
  39. if(regex.IsMatch(Path.GetFileName(f)))
  40. {
  41. var match = extractNumRegex.Match(f);
  42. int number = match.Success ? int.Parse(match.Value) : 0;
  43. if(number > latestNum)
  44. {
  45. latestNum = number;
  46. latestFile = f;
  47. }
  48. }
  49. }
  50. return latestFile;
  51. }
  52. public static bool Restore(string file)
  53. {
  54. var backup = FindLatestBackup(file);
  55. if(backup != null)
  56. {
  57. File.Delete(file);
  58. File.Move(backup, file);
  59. return true;
  60. }
  61. return false;
  62. }
  63. }
  64. }