wabbajack/Wabbajack.CLI/Services/ArchiveMaintainer.cs

64 lines
1.7 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Wabbajack.Hashing.xxHash64;
using Wabbajack.Paths;
using Wabbajack.Paths.IO;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.CLI.Services;
/// <summary>
/// Maintains a concurrent cache of all the files we've downloaded, indexed by Hash.
/// </summary>
public class ArchiveManager
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
private readonly AbsolutePath _location;
private ILogger _logger;
public ArchiveManager(ILogger logger, AbsolutePath location)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
_logger = logger;
_location = location;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
private AbsolutePath ArchivePath(Hash hash)
{
return _location.Combine(hash.ToHex());
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async Task Ingest(AbsolutePath file, CancellationToken token)
{
await using var tempPath = new TemporaryPath(_location.Combine("___" + Guid.NewGuid()));
await using var fOut = tempPath.Path.Open(FileMode.Create, FileAccess.Write);
await using var fIn = file.Open(FileMode.Open);
var hash = await fIn.HashingCopy(fOut, token);
fIn.Close();
fOut.Close();
if (hash == default) return;
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
var newPath = ArchivePath(hash);
if (HaveArchive(hash)) return;
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
await tempPath.Path.MoveToAsync(newPath, false, token);
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public bool HaveArchive(Hash hash)
{
return ArchivePath(hash).FileExists();
}
public bool TryGetPath(Hash hash, out AbsolutePath path)
{
path = ArchivePath(hash);
return path.FileExists();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public AbsolutePath GetPath(Hash hash)
{
if (!TryGetPath(hash, out var path))
throw new FileNotFoundException($"Cannot find file for hash {hash}");
return path;
2021-09-27 12:42:46 +00:00
}
2021-10-23 16:51:17 +00:00
}