archive.json and sequence.json with source-generated JSON, forward-compatible reading (unknown fields kept, unknown enum names tolerated) and atomic writes; lease files with expiry and stale takeover; thumbs.pack with index, crash-safe append and random access; folder scanning, in-place adoption, reconcile, verify, index snapshot, rename planning and thumbnail/proxy rendering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
45 lines
2.0 KiB
C#
45 lines
2.0 KiB
C#
using System.Security.Cryptography;
|
|
|
|
namespace Titano.Core.Archiving;
|
|
|
|
/// <summary>SHA-256 of files, streamed (originals can be hundreds of megabytes).</summary>
|
|
public static class ContentHash
|
|
{
|
|
internal const int BufferSize = 1 << 20;
|
|
|
|
/// <summary>Lower-case hex SHA-256 of the file.</summary>
|
|
/// <param name="progress">Receives the number of bytes read since the previous call.</param>
|
|
public static async Task<string> Sha256Async(string path, Action<long>? progress = null, CancellationToken cancellationToken = default)
|
|
{
|
|
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize,
|
|
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
|
return await Sha256Async(stream, progress, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
public static async Task<string> Sha256Async(Stream stream, Action<long>? progress = null, CancellationToken cancellationToken = default)
|
|
{
|
|
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
|
var buffer = new byte[BufferSize];
|
|
int read;
|
|
while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
|
{
|
|
hash.AppendData(buffer, 0, read);
|
|
progress?.Invoke(read);
|
|
}
|
|
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
|
}
|
|
}
|
|
|
|
/// <summary>Size and modification time of a file, the cheap change detector of incremental scans (BRIEF §7).</summary>
|
|
public readonly record struct FileStamp(long Size, DateTime ModifiedUtc)
|
|
{
|
|
/// <summary>The stamp of a file or directory, or null when it does not exist.</summary>
|
|
public static FileStamp? Of(string path)
|
|
{
|
|
var file = new FileInfo(path);
|
|
if (file.Exists) return new FileStamp(file.Length, file.LastWriteTimeUtc);
|
|
var directory = new DirectoryInfo(path);
|
|
return directory.Exists ? new FileStamp(0, directory.LastWriteTimeUtc) : null;
|
|
}
|
|
}
|