ファイル

277 行
8.5 KiB
C#

using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using YukkuriMovieMaker.Commons;
namespace UndoTree;
internal sealed class UndoTreeRecordStore(string directory)
{
const string Extension = ".json";
const string TemporaryExtension = ".tmp";
const string IndexName = "hashes.index";
const int NameLength = 32;
public const long BytesPerKilobyte = 1024;
public const long BytesPerMegabyte = BytesPerKilobyte * BytesPerKilobyte;
static readonly Lazy<UndoTreeRecordStore> DefaultStore = new(() => new UndoTreeRecordStore(Path.Combine(AppDirectories.UserResourceDirectory, "cache", UndoTreeToolPlugin.Id)));
static readonly JsonSerializerOptions Options = new() { WriteIndented = false };
readonly object gate = new();
public static UndoTreeRecordStore Default => DefaultStore.Value;
public string Directory { get; } = directory;
public string FileOf(string projectPath)
{
var normalized = Path.GetFullPath(projectPath).ToUpperInvariant();
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized)));
return Path.Combine(Directory, hash[..NameLength] + Extension);
}
public bool Exists(string projectPath)
{
try
{
return File.Exists(FileOf(projectPath));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return false;
}
}
public UndoTreeRecordFile? Load(string projectPath)
{
lock (gate)
{
try
{
return LoadFile(FileOf(projectPath));
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException)
{
return null;
}
}
}
public UndoTreeRecordFile? FindByHash(string projectHash, string excludePath)
{
lock (gate)
{
var index = ReadIndex() ?? RebuildIndex();
if (!index.TryGetValue(projectHash, out var names))
return null;
return names
.Select(name => new FileInfo(Path.Combine(Directory, name)))
.OrderByDescending(file => file.LastWriteTimeUtc)
.Select(file => LoadFile(file.FullName))
.FirstOrDefault(loaded => loaded is not null && !string.Equals(loaded.ProjectPath, excludePath, StringComparison.OrdinalIgnoreCase) && HashesOf(loaded).Contains(projectHash));
}
}
public bool Save(string projectPath, UndoTreeRecordFile record)
{
lock (gate)
{
try
{
System.IO.Directory.CreateDirectory(Directory);
var file = FileOf(projectPath);
var temporary = file + TemporaryExtension;
File.WriteAllText(temporary, JsonSerializer.Serialize(record, Options), new UTF8Encoding(false));
File.Move(temporary, file, overwrite: true);
UpdateIndex(Path.GetFileName(file), record);
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return false;
}
}
}
public UndoTreeRecordUsage Usage()
{
lock (gate)
{
var files = RecordFiles();
return new UndoTreeRecordUsage(files.Count, files.Sum(file => file.Length));
}
}
public int Clear()
{
lock (gate)
{
var removed = 0;
foreach (var file in RecordFiles())
{
if (TryDelete(file))
removed++;
}
DeleteIndex();
return removed;
}
}
public int Prune(int retentionDays, long maxBytes, DateTime now)
{
lock (gate)
{
var removed = 0;
var files = RecordFiles().OrderByDescending(file => file.LastWriteTime).ToList();
foreach (var file in files.Where(file => now - file.LastWriteTime > TimeSpan.FromDays(retentionDays)).ToArray())
{
if (TryDelete(file))
removed++;
files.Remove(file);
}
var total = 0L;
foreach (var file in files)
{
total += file.Length;
if (total > maxBytes && TryDelete(file))
removed++;
}
if (removed > 0)
DeleteIndex();
return removed;
}
}
static IEnumerable<string> HashesOf(UndoTreeRecordFile file)
=> new[] { file.Previous, file.Current }
.OfType<UndoTreeRecord>()
.SelectMany(record => record.Nodes)
.Select(node => node.ProjectHash)
.Where(hash => !string.IsNullOrEmpty(hash))
.Distinct();
UndoTreeRecordFile? LoadFile(string file)
{
try
{
if (!File.Exists(file))
return null;
var loaded = JsonSerializer.Deserialize<UndoTreeRecordFile>(File.ReadAllText(file, Encoding.UTF8), Options);
return loaded is { Version: UndoTreeRecordFile.CurrentVersion } ? loaded : null;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or ArgumentException or NotSupportedException)
{
return null;
}
}
Dictionary<string, string[]>? ReadIndex()
{
try
{
var file = Path.Combine(Directory, IndexName);
return File.Exists(file) ? JsonSerializer.Deserialize<Dictionary<string, string[]>>(File.ReadAllText(file, Encoding.UTF8), Options) : null;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or ArgumentException or NotSupportedException)
{
return null;
}
}
Dictionary<string, string[]> RebuildIndex()
{
var index = new Dictionary<string, string[]>();
foreach (var file in RecordFiles())
{
if (LoadFile(file.FullName) is { } loaded)
Index(index, file.Name, loaded);
}
WriteIndex(index);
return index;
}
void UpdateIndex(string name, UndoTreeRecordFile record)
{
var index = ReadIndex() ?? RebuildIndex();
foreach (var key in index.Keys.ToArray())
{
var rest = index[key].Where(existing => existing != name).ToArray();
if (rest.Length == 0)
index.Remove(key);
else
index[key] = rest;
}
Index(index, name, record);
WriteIndex(index);
}
static void Index(Dictionary<string, string[]> index, string name, UndoTreeRecordFile record)
{
foreach (var hash in HashesOf(record))
index[hash] = index.TryGetValue(hash, out var names) ? [.. names, name] : [name];
}
void WriteIndex(Dictionary<string, string[]> index)
{
try
{
var file = Path.Combine(Directory, IndexName);
var temporary = file + TemporaryExtension;
File.WriteAllText(temporary, JsonSerializer.Serialize(index, Options), new UTF8Encoding(false));
File.Move(temporary, file, overwrite: true);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
}
}
void DeleteIndex()
{
try
{
File.Delete(Path.Combine(Directory, IndexName));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
}
}
List<FileInfo> RecordFiles()
{
try
{
return System.IO.Directory.Exists(Directory)
? new DirectoryInfo(Directory).GetFiles("*" + Extension).ToList()
: [];
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return [];
}
}
static bool TryDelete(FileInfo file)
{
try
{
file.Delete();
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
}
}