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.

99 lines
3.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace IPA.Injector.Backups
  5. {
  6. /// <summary>
  7. /// A unit for backup. WIP.
  8. /// </summary>
  9. public class BackupUnit
  10. {
  11. public string Name { get; private set; }
  12. private readonly DirectoryInfo _backupPath;
  13. private readonly HashSet<string> _files = new HashSet<string>();
  14. private readonly FileInfo _manifestFile;
  15. private const string ManifestFileName = "$manifest$.txt";
  16. public BackupUnit(string dir) : this(dir, DateTime.Now.ToString("yyyy-MM-dd_h-mm-ss"))
  17. {
  18. }
  19. private BackupUnit(string dir, string name)
  20. {
  21. Name = name;
  22. _backupPath = new DirectoryInfo(Path.Combine(dir, Name));
  23. _manifestFile = new FileInfo(Path.Combine(_backupPath.FullName, ManifestFileName));
  24. }
  25. public static BackupUnit FromDirectory(DirectoryInfo directory, string dir)
  26. {
  27. var unit = new BackupUnit(dir, directory.Name);
  28. // Read Manifest
  29. if (unit._manifestFile.Exists)
  30. {
  31. var manifest = File.ReadAllText(unit._manifestFile.FullName);
  32. foreach (var line in manifest.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
  33. unit._files.Add(line);
  34. }
  35. else
  36. {
  37. foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories))
  38. {
  39. if (file.Name == ManifestFileName) continue;
  40. var relativePath = file.FullName.Substring(directory.FullName.Length + 1);
  41. unit._files.Add(relativePath);
  42. }
  43. }
  44. return unit;
  45. }
  46. public void Add(string file)
  47. {
  48. Add(new FileInfo(file));
  49. }
  50. internal void Delete()
  51. {
  52. _backupPath.Delete(true);
  53. }
  54. /// <summary>
  55. /// Adds a file to the list of changed files and backups it.
  56. /// </summary>
  57. /// <param name="file"></param>
  58. public void Add(FileInfo file)
  59. {
  60. var relativePath = Utilities.Utils.GetRelativePath(file.FullName, Environment.CurrentDirectory);
  61. var backupPath = new FileInfo(Path.Combine(_backupPath.FullName, relativePath));
  62. // Copy over
  63. backupPath.Directory?.Create();
  64. if (file.Exists)
  65. {
  66. if (File.Exists(backupPath.FullName))
  67. File.Delete(backupPath.FullName);
  68. file.CopyTo(backupPath.FullName);
  69. }
  70. else
  71. {
  72. // Make empty file
  73. backupPath.Create().Close();
  74. }
  75. if (_files.Contains(relativePath)) return;
  76. if (!File.Exists(_manifestFile.FullName))
  77. _manifestFile.Create().Close();
  78. var stream = _manifestFile.AppendText();
  79. stream.WriteLine(relativePath);
  80. stream.Close();
  81. // Add to list
  82. _files.Add(relativePath);
  83. }
  84. }
  85. }