-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathStorageManager.cs
More file actions
354 lines (305 loc) · 13 KB
/
Copy pathStorageManager.cs
File metadata and controls
354 lines (305 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using GeneralUpdate.Core.HashAlgorithms;
namespace GeneralUpdate.Core.FileSystem
{
public sealed class StorageManager
{
private long _fileCount = 0;
public const string DirectoryName = "app-";
/// <summary>Optional blacklist matcher. When set, takes precedence over BlackListManager.</summary>
public static IBlackListMatcher? BlackListMatcher { get; set; }
private ComparisonResult ComparisonResult { get; set; }
#region Public Methods
/// <summary>
/// Using the list on the left as a baseline, find the set of differences between the two file lists.
/// </summary>
public IEnumerable<FileNode>? Except(string leftPath, string rightPath)
{
var leftFileNodes = ReadFileNode(leftPath);
var rightFileNodes = ReadFileNode(rightPath);
var rightNodeDic = rightFileNodes.ToDictionary(x => x.RelativePath);
return leftFileNodes.Where(f => !rightNodeDic.ContainsKey(f.RelativePath)).ToList();
}
/// <summary>
/// Compare two directories.
/// </summary>
/// <param name="leftDir"></param>
/// <param name="rightDir"></param>
public ComparisonResult Compare(string leftDir, string rightDir)
{
ResetId();
ComparisonResult = new ComparisonResult();
var leftFileNodes = ReadFileNode(leftDir);
var rightFileNodes = ReadFileNode(rightDir);
var leftTree = new FileTree(leftFileNodes);
var rightTree = new FileTree(rightFileNodes);
var differentTreeNode = new List<FileNode>();
leftTree.Compare(leftTree.GetRoot(), rightTree.GetRoot(), ref differentTreeNode);
ComparisonResult.AddToLeft(leftFileNodes);
ComparisonResult.AddToRight(rightFileNodes);
ComparisonResult.AddDifferent(differentTreeNode);
return ComparisonResult;
}
public static void CreateJson<T>(string targetPath, T obj, JsonTypeInfo<T>? typeInfo = null) where T : class
{
var folderPath = Path.GetDirectoryName(targetPath) ??
throw new ArgumentException("invalid path", nameof(targetPath));
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
var jsonString = typeInfo != null ? JsonSerializer.Serialize(obj, typeInfo) : JsonSerializer.Serialize(obj);
File.WriteAllText(targetPath, jsonString);
}
public static T? GetJson<T>(string path, JsonTypeInfo<T>? typeInfo = null) where T : class
{
if (File.Exists(path))
{
var json = File.ReadAllText(path);
if (typeInfo != null)
{
return JsonSerializer.Deserialize(json, typeInfo);
}
return JsonSerializer.Deserialize<T>(json);
}
return default;
}
public static string GetTempDirectory(string name)
{
var path = $"generalupdate_{DateTime.Now:yyyy-MM-dd}_{name}";
var tempDir = Path.Combine(Path.GetTempPath(), path);
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
return tempDir;
}
public static void DeleteDirectory(string targetDir)
{
foreach (var file in Directory.GetFiles(targetDir))
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (var dir in Directory.GetDirectories(targetDir))
{
DeleteDirectory(dir);
}
Directory.Delete(targetDir, false);
}
public static List<FileInfo> GetAllFiles(string path, List<string> skipDirectorys)
{
try
{
var files = new List<FileInfo>();
files.AddRange(new DirectoryInfo(path).GetFiles());
var tmpDir = new DirectoryInfo(path).GetDirectories();
foreach (var dic in tmpDir)
{
bool shouldSkip = false;
foreach (var notBackup in skipDirectorys)
{
if (dic.FullName.Contains(notBackup))
{
shouldSkip = true;
break;
}
}
if (!shouldSkip)
files.AddRange(GetAllfiles(dic.FullName));
}
return files;
}
catch
{
return new List<FileInfo>();
}
}
private static List<FileInfo> GetAllfiles(string path)
{
try
{
var files = new List<FileInfo>();
files.AddRange(new DirectoryInfo(path).GetFiles());
var tmpDir = new DirectoryInfo(path).GetDirectories();
foreach (var dic in tmpDir)
{
files.AddRange(GetAllfiles(dic.FullName));
}
return files;
}
catch (Exception)
{
return new List<FileInfo>();
}
}
public static bool HashEquals(string leftPath, string rightPath)
{
var hashAlgorithm = new Sha256HashAlgorithm();
var hashLeft = hashAlgorithm.ComputeHash(leftPath);
var hashRight = hashAlgorithm.ComputeHash(rightPath);
return hashLeft.SequenceEqual(hashRight);
}
/// <summary>
/// Backup the all program.
/// </summary>
/// <param name="backupPath"></param>
/// <param name="sourcePath"></param>
/// <param name="directoryName"></param>
public static void Backup(string sourcePath, string backupPath, IReadOnlyList<string> directoryNames)
{
if (Directory.Exists(backupPath))
{
DeleteDirectory(backupPath);
}
Directory.CreateDirectory(backupPath);
CopyDirectory(sourcePath, backupPath, directoryNames);
}
private static void CopyDirectory(string sourceDir, string targetDir, IReadOnlyList<string> directoryNames)
{
foreach (string dirPath in Directory.GetDirectories(sourceDir, "*", SearchOption.TopDirectoryOnly))
{
if (!directoryNames.Any(name => Path.GetFileName(dirPath).Contains(name)))
{
string newTargetDir = Path.Combine(targetDir, Path.GetFileName(dirPath));
Directory.CreateDirectory(newTargetDir);
CopyDirectory(dirPath, newTargetDir, directoryNames);
}
}
foreach (string filePath in Directory.GetFiles(sourceDir, "*.*", SearchOption.TopDirectoryOnly))
{
string newFilePath = Path.Combine(targetDir, Path.GetFileName(filePath));
File.Copy(filePath, newFilePath, true);
}
}
/// <summary>
/// Restore the all program.
/// </summary>
/// <param name="backupPath"></param>
/// <param name="sourcePath"></param>
public static void Restore(string backupPath, string sourcePath)
{
if (!Directory.Exists(sourcePath))
{
Directory.CreateDirectory(sourcePath);
}
CopyDirectory(backupPath, sourcePath);
}
private static void CopyDirectory(string sourceDir, string targetDir)
{
foreach (string dirPath in Directory.GetDirectories(sourceDir, "*", SearchOption.TopDirectoryOnly))
{
string newTargetDir = Path.Combine(targetDir, Path.GetFileName(dirPath));
Directory.CreateDirectory(newTargetDir);
CopyDirectory(dirPath, newTargetDir);
}
foreach (string filePath in Directory.GetFiles(sourceDir, "*.*", SearchOption.TopDirectoryOnly))
{
string newFilePath = Path.Combine(targetDir, Path.GetFileName(filePath));
File.Copy(filePath, newFilePath, true);
}
}
public static async System.Threading.Tasks.Task BackupAsync(string sourcePath, string backupPath, System.Collections.Generic.IReadOnlyList<string> directoryNames)
{
await System.Threading.Tasks.Task.Run(() => Backup(sourcePath, backupPath, directoryNames)).ConfigureAwait(false);
}
public static async System.Threading.Tasks.Task RestoreAsync(string backupPath, string sourcePath)
{
await System.Threading.Tasks.Task.Run(() => Restore(backupPath, sourcePath)).ConfigureAwait(false);
}
public static async System.Threading.Tasks.Task CleanBackupAsync(string installPath, int keepVersions = 3)
{
await System.Threading.Tasks.Task.Run(() => CleanBackup(installPath, keepVersions)).ConfigureAwait(false);
}
#endregion
#region Private Methods
/// <summary>
/// Recursively read all files in the folder path.
/// </summary>
private IEnumerable<FileNode> ReadFileNode(string path, string rootPath = null)
{
var resultFiles = new List<FileNode>();
rootPath ??= path;
if (!rootPath.EndsWith("/"))
{
rootPath += "/";
}
var rootUri = new Uri(rootPath);
foreach (var subPath in Directory.EnumerateFiles(path))
{
#pragma warning disable CS0618 // Obsolete fallback
if ((BlackListMatcher ?? BlackListManager.Instance).IsBlacklisted(subPath)) continue;
#pragma warning restore CS0618
var hashAlgorithm = new Sha256HashAlgorithm();
var hash = hashAlgorithm.ComputeHash(subPath);
var subFileInfo = new FileInfo(subPath);
var subUri = new Uri(subFileInfo.FullName);
resultFiles.Add(new FileNode
{
Id = GetId(),
Path = path,
Name = subFileInfo.Name,
Hash = hash,
FullName = subFileInfo.FullName,
RelativePath = rootUri.MakeRelativeUri(subUri).ToString()
});
}
foreach (var subPath in Directory.EnumerateDirectories(path))
{
#pragma warning disable CS0618 // Obsolete fallback
if ((BlackListMatcher ?? BlackListManager.Instance).ShouldSkipDirectory(subPath)) continue;
#pragma warning restore CS0618
resultFiles.AddRange(ReadFileNode(subPath, rootPath));
}
return resultFiles;
}
/// <summary>
/// Self-growing file tree node ID.
/// </summary>
private long GetId() => Interlocked.Increment(ref _fileCount);
private void ResetId() => Interlocked.Exchange(ref _fileCount, 0);
/// <summary>Clean old backups, keeping only the N most recent versions.</summary>
public static void CleanBackup(string installPath, int keepVersions = 3)
{
var backupRoot = Path.Combine(installPath, "__backups");
if (!Directory.Exists(backupRoot)) return;
var dirs = Directory.GetDirectories(backupRoot)
.Select(d => new DirectoryInfo(d))
.OrderByDescending(d =>
{
var name = d.Name;
return Version.TryParse(name, out var v) ? v : new Version(0, 0);
})
.Skip(keepVersions);
foreach (var dir in dirs)
dir.Delete(true);
}
/// <summary>List backup versions with metadata.</summary>
public static IReadOnlyList<BackupInfo> ListBackups(string installPath)
{
var backupRoot = Path.Combine(installPath, "__backups");
if (!Directory.Exists(backupRoot)) return Array.Empty<BackupInfo>();
return Directory.GetDirectories(backupRoot)
.Select(d => new DirectoryInfo(d))
.Select(d => new BackupInfo(
d.Name, d.FullName, d.CreationTime,
d.GetFiles("*", SearchOption.AllDirectories).Sum(f => f.Length)))
.ToList();
}
#endregion
}
/// <summary>Backup configuration.</summary>
public sealed class BackupConfig
{
public int KeepVersions { get; set; } = 3;
public string? BackupRoot { get; set; }
public List<string> SkipDirectories { get; set; } = new();
public bool Enabled { get; set; } = true;
}
/// <summary>Backup metadata.</summary>
public record BackupInfo(string Version, string Path, DateTime CreatedAt, long SizeBytes);
}