refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,222 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Core.Tests.Import.ImportTestKit;
|
||||
|
||||
namespace Chronos.Core.Tests.Import;
|
||||
|
||||
[Category("import")]
|
||||
public sealed class ImportExecutorTests(TestContext context)
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
|
||||
|
||||
private string Card(int frames = 70)
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, frames, Interval);
|
||||
return card;
|
||||
}
|
||||
|
||||
private static Task<ImportProgress> RunAsync(ImportPlan plan, IImportSink sink, int startAt = 0, Func<ImportBatch, ValueTask>? committed = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
new ImportExecutor(plan, sink).RunAsync(startAt, verify: true, committed ?? (_ => ValueTask.CompletedTask), null, cancellationToken);
|
||||
|
||||
[Test]
|
||||
public async Task VerifiedCopyHashesPreservesTheTimeAndNeverOverwrites()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
var source = TestPhotos.Write(Path.Combine(dir, "a.jpg"), Start, 1);
|
||||
File.SetLastWriteTimeUtc(source, new DateTime(2026, 9, 28, 16, 0, 0, DateTimeKind.Utc));
|
||||
var target = Path.Combine(dir, "copy", "a.jpg");
|
||||
var sha = await VerifiedCopy.CopyAsync(source, target, verify: true);
|
||||
Assert.Equal(await ContentHash.Sha256Async(source), sha);
|
||||
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
|
||||
Assert.Equal(File.GetLastWriteTimeUtc(source), File.GetLastWriteTimeUtc(target));
|
||||
|
||||
var other = TestPhotos.Write(Path.Combine(dir, "b.jpg"), Start, 2);
|
||||
await Assert.ThrowsAsync<IOException>(() => VerifiedCopy.CopyAsync(other, target, verify: true));
|
||||
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
|
||||
await Assert.ThrowsAsync<FileNotFoundException>(() => VerifiedCopy.CopyAsync(Path.Combine(dir, "gone.jpg"), Path.Combine(dir, "c.jpg"), true));
|
||||
Assert.FileMissing(Path.Combine(dir, "c.jpg"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APlanIsCopiedExactlyIntoAFolder()
|
||||
{
|
||||
var card = Card();
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
var batches = new List<ImportBatch>();
|
||||
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
|
||||
{
|
||||
batches.Add(b);
|
||||
return ValueTask.CompletedTask;
|
||||
});
|
||||
Assert.Equal(70, final.Copied);
|
||||
Assert.Equal(plan.CopyBytes, final.BytesDone);
|
||||
Assert.SequenceEqual(plan.Items.Select(i => plan.Sessions[0].Folder + "/" + i.FileName).Order(StringComparer.Ordinal), Files(destination));
|
||||
Assert.Equal(70, batches[^1].NextItem);
|
||||
Assert.True(batches.Count >= 3);
|
||||
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
|
||||
foreach (var item in plan.Items)
|
||||
{
|
||||
Assert.BytesEqual(File.ReadAllBytes(Path.Combine(card, item.SourcePath)),
|
||||
File.ReadAllBytes(Path.Combine(destination, plan.Sessions[0].Folder, item.FileName)));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnInterruptedImportResumesFromItsLastBatch()
|
||||
{
|
||||
var card = Card();
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
using var cts = new CancellationTokenSource();
|
||||
var checkpoint = 0;
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
|
||||
{
|
||||
checkpoint = b.NextItem;
|
||||
cts.Cancel();
|
||||
return ValueTask.CompletedTask;
|
||||
}, cancellationToken: cts.Token));
|
||||
Assert.True(checkpoint is > 0 and < 70);
|
||||
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
|
||||
Assert.Equal(70 - checkpoint, final.Copied);
|
||||
|
||||
var reference = context.CreateTempDirectory("reference");
|
||||
await RunAsync(await PlanAsync(card, reference), new FolderImportSink(reference));
|
||||
Assert.SequenceEqual(Files(reference), Files(destination));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RepeatingCommittedItemsYieldsDuplicatesNotSecondCopies()
|
||||
{
|
||||
var card = Card(20);
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
await RunAsync(plan, new FolderImportSink(destination));
|
||||
var again = await RunAsync(plan, new FolderImportSink(destination), startAt: 10);
|
||||
Assert.Equal(0, again.Copied);
|
||||
Assert.Equal(10, again.Skipped);
|
||||
Assert.Equal(20, Files(destination).Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARemovedCardStopsTheImportWhichResumesOnReinsertion()
|
||||
{
|
||||
var card = Card();
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
var aside = card + "-removed";
|
||||
var checkpoint = 0;
|
||||
await Assert.ThrowsAsync<ImportSourceUnavailableException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
|
||||
{
|
||||
checkpoint = b.NextItem;
|
||||
if (Directory.Exists(card)) Directory.Move(card, aside); // the card is pulled after the first batch
|
||||
return ValueTask.CompletedTask;
|
||||
}));
|
||||
Assert.Equal(checkpoint, Files(destination).Count);
|
||||
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
|
||||
|
||||
Directory.Move(aside, card);
|
||||
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
|
||||
Assert.Equal(70 - checkpoint, final.Copied);
|
||||
Assert.Equal(70, Files(destination).Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFileThatChangedSinceThePlanFailsAloneAndTheRestIsCopied()
|
||||
{
|
||||
var card = Card(20);
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
File.AppendAllText(Path.Combine(card, plan.Sessions[0].Items[5].SourcePath), "edited");
|
||||
var failed = new List<ImportItemResult>();
|
||||
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
|
||||
{
|
||||
failed.AddRange(b.Results.Where(r => r.Status == ImportItemStatus.Failed));
|
||||
return ValueTask.CompletedTask;
|
||||
});
|
||||
Assert.Equal(19, final.Copied);
|
||||
Assert.Equal(1, final.Failed);
|
||||
Assert.Equal(plan.Sessions[0].Items[5].SourcePath, failed.Single().Item.SourcePath);
|
||||
Assert.Equal(Loc.L("Archive.Error.SourceChanged", plan.Sessions[0].Items[5].SourcePath), failed.Single().Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyTheSystemRefusesFailsAloneWithACatalogSentence()
|
||||
{
|
||||
var card = Card(10);
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination);
|
||||
var sink = new FolderImportSink(destination);
|
||||
// A folder squats the staging name of the fourth copy: creating that copy fails with the system's own text.
|
||||
var item = plan.Sessions[0].Items[3];
|
||||
Directory.CreateDirectory(Path.Combine(sink.StagingDirectory, $"{plan.Id:N}-{3:D6}{Path.GetExtension(item.FileName)}"));
|
||||
var failed = new List<ImportItemResult>();
|
||||
var final = await RunAsync(plan, sink, committed: b =>
|
||||
{
|
||||
failed.AddRange(b.Results.Where(r => r.Status == ImportItemStatus.Failed));
|
||||
return ValueTask.CompletedTask;
|
||||
});
|
||||
Assert.Equal(9, final.Copied);
|
||||
Assert.Equal(item.SourcePath, failed.Single().Item.SourcePath);
|
||||
Assert.Contains(failed.Single().Error, new[] { Loc.L("Import.Failed.Photo"), Loc.L("Import.Failed.PhotoAccess") });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFailedCopySaysWhyInOneLocalizedSentence()
|
||||
{
|
||||
Assert.Equal(Loc.L("Import.Failed.Full"), ImportExecutor.FailureText(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070))));
|
||||
Assert.Equal(Loc.L("Import.Failed.Full"), ImportExecutor.FailureText(new IOException("The disk is full.", unchecked((int)0x80070027))));
|
||||
Assert.Equal(Loc.L("Import.Failed.PhotoAccess"), ImportExecutor.FailureText(new UnauthorizedAccessException(@"Access to the path 'E:\DCIM\IMG_0001.CR3' is denied.")));
|
||||
Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new IOException("The semaphore timeout period has expired.")));
|
||||
Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new FileNotFoundException(@"Could not find file 'E:\DCIM\IMG_0001.CR3'.")));
|
||||
// A sink that stages its copies on this PC (a server import, in the cache folder): a full disk there is this PC's.
|
||||
Assert.Equal(Loc.L("Import.Failed.CacheFull"),
|
||||
ImportExecutor.FailureText(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), stagesOnThisPc: true));
|
||||
Assert.Equal(Loc.L("Import.Failed.CacheFull"), ImportExecutor.FailureText(new IOException("The disk is full.", unchecked((int)0x80070027)), stagesOnThisPc: true));
|
||||
Assert.Equal(Loc.L("Import.Failed.PhotoAccess"), ImportExecutor.FailureText(new UnauthorizedAccessException("Access denied."), stagesOnThisPc: true));
|
||||
Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new IOException("The semaphore timeout period has expired."), stagesOnThisPc: true));
|
||||
Assert.False(((IImportSink)new FolderImportSink(Path.GetTempPath())).StagesOnThisPc, "a folder import stages inside the destination");
|
||||
// The executor's own checks are one sentence each already.
|
||||
Assert.Equal(Loc.L("Archive.Error.CopyMismatch", "IMG_0001.CR3"), ImportExecutor.FailureText(new CopyVerificationException("/staging/IMG_0001.CR3")));
|
||||
Assert.Equal(Loc.L("Archive.Error.SourceChanged", "DCIM/IMG_0001.CR3"), ImportExecutor.FailureText(new ImportSourceChangedException("DCIM/IMG_0001.CR3")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ErasingDeletesOnlyFilesWhoseCardAndCopyStillMatch()
|
||||
{
|
||||
var card = Card(6);
|
||||
var destination = context.CreateTempDirectory("dest");
|
||||
var plan = await PlanAsync(card, destination, new ImportOptions { MinimumSessionFrames = 1 });
|
||||
var results = new List<ImportItemResult>();
|
||||
await RunAsync(plan, new FolderImportSink(destination), committed: b =>
|
||||
{
|
||||
results.AddRange(b.Results);
|
||||
return ValueTask.CompletedTask;
|
||||
});
|
||||
var candidates = results.Select(r => new EraseCandidate(r.Item.SourcePath, r.Item.Size, r.Sha256!, Path.Combine(destination, r.Commit!.RelativePath)))
|
||||
.ToList();
|
||||
// Copy of item 1 damaged after import, card file of item 2 edited, copy of item 3 deleted.
|
||||
var damaged = File.ReadAllBytes(candidates[1].CopyPath);
|
||||
damaged[^10] ^= 0xFF;
|
||||
File.WriteAllBytes(candidates[1].CopyPath, damaged);
|
||||
File.AppendAllText(Path.Combine(card, candidates[2].SourcePath), "x");
|
||||
File.Delete(candidates[3].CopyPath);
|
||||
|
||||
var erase = await CardEraser.PlanAsync(card, candidates);
|
||||
Assert.SequenceEqual(
|
||||
[EraseVerdict.Delete, EraseVerdict.CopyMismatch, EraseVerdict.SourceChanged, EraseVerdict.CopyMissing, EraseVerdict.Delete, EraseVerdict.Delete],
|
||||
erase.Items.Select(i => i.Verdict));
|
||||
Assert.Equal(6, Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Count());
|
||||
|
||||
var done = CardEraser.Execute(erase);
|
||||
Assert.Equal(3, done.Deleted);
|
||||
Assert.Equal(3, done.Kept.Count);
|
||||
var left = Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(card, f).Replace('\\', '/')).Order();
|
||||
Assert.SequenceEqual(candidates.Skip(1).Take(3).Select(c => c.SourcePath).Order(), left);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Core.Tests.Import.ImportTestKit;
|
||||
|
||||
namespace Chronos.Core.Tests.Import;
|
||||
|
||||
[Category("import")]
|
||||
public sealed class ImportPlannerTests(TestContext context)
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
|
||||
|
||||
[Test]
|
||||
public async Task ADcimCardIsPlannedWithTheDefaultTemplates()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 10, Interval);
|
||||
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "._IMG_0001.JPG"), [0, 5, 22]);
|
||||
File.WriteAllText(Path.Combine(card, "DCIM", "100CANON", "notes.txt"), "x");
|
||||
TestPhotos.Write(Path.Combine(card, "MISC", "IMG_9999.JPG"), Start, 99);
|
||||
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
|
||||
var session = plan.Sessions.Single();
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5", session.Folder);
|
||||
Assert.Equal(10, plan.FileCount);
|
||||
Assert.Equal(10, plan.CopyCount);
|
||||
Assert.SequenceEqual(
|
||||
["2026-09-28_18-00-00_0001.JPG", "2026-09-28_18-00-10_0002.JPG", "2026-09-28_18-00-20_0003.JPG"],
|
||||
session.Items.Take(3).Select(i => i.FileName));
|
||||
Assert.Equal("DCIM/100CANON/IMG_0001.JPG", session.Items[0].SourcePath);
|
||||
Assert.Equal(plan.Items.Sum(i => i.Size), plan.CopyBytes);
|
||||
Assert.NotNull(plan.AvailableBytes);
|
||||
Assert.True(plan.HasEnoughSpace);
|
||||
Assert.Empty(plan.Problems);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFileThatCannotBeReadIsAProblemWithOneLocalizedSentence()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 3, Interval);
|
||||
var files = CardScanner.Find(card, includeSubfolders: true);
|
||||
// A photo leaves the card between listing and reading; another name is a folder the system refuses to read as a file.
|
||||
File.Delete(Path.Combine(card, files[1].RelativePath));
|
||||
Directory.CreateDirectory(Path.Combine(card, "DCIM", "100CANON", "IMG_9999.JPG"));
|
||||
var problems = new List<ImportProblem>();
|
||||
|
||||
var photos = CardScanner.ReadMetadata(card, [.. files, new CardFile("DCIM/100CANON/IMG_9999.JPG", 0, Start)], problems);
|
||||
Assert.Equal(2, photos.Count);
|
||||
Assert.SequenceEqual([files[1].RelativePath, "DCIM/100CANON/IMG_9999.JPG"], problems.Select(p => p.RelativePath));
|
||||
Assert.Equal(Loc.L("Import.Failed.Photo"), problems[0].Message);
|
||||
Assert.Contains(problems[1].Message, new[] { Loc.L("Import.Failed.Photo"), Loc.L("Import.Failed.PhotoAccess") });
|
||||
Assert.False(problems.Any(p => p.Message.Contains(card, StringComparison.Ordinal)), "the system's text, with the card's path, stays in the log");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(card, Start, 8, Interval);
|
||||
TestPhotos.WriteSeries(Path.Combine(card, "more"), Start.AddSeconds(80), 8, Interval, firstSeed: 50, firstNumber: 9);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
Assert.Equal(16, (await PlanAsync(card, destination)).FileCount);
|
||||
Assert.Equal(8, (await PlanAsync(card, destination, new ImportOptions { IncludeSubfolders = false })).FileCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SessionsAreSplitPerCameraBodyAndNumberedFromOne()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
var dcim = Path.Combine(card, "DCIM", "100MEDIA");
|
||||
TestPhotos.WriteSeries(dcim, Start, 10, Interval, prefix: "CAN_");
|
||||
TestPhotos.WriteSeries(dcim, Start.AddHours(2), 10, Interval, firstSeed: 20, prefix: "CAN_", firstNumber: 11);
|
||||
TestPhotos.WriteSeries(dcim, Start.AddSeconds(5), 9, Interval, firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
|
||||
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
|
||||
Assert.SequenceEqual(
|
||||
["2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Nikon Z 8", "2026/2026-09-28 Canon EOS R5 (2)"],
|
||||
plan.Sessions.Select(s => s.Folder));
|
||||
Assert.SequenceEqual([1, 2, 3], plan.Sessions.Select(s => s.Number));
|
||||
Assert.Equal("2026-09-28_20-00-00_0001.JPG", plan.Sessions[2].Items[0].FileName);
|
||||
Assert.Equal(3, plan.Sessions.Select(s => s.SessionKey).Distinct().Count());
|
||||
Assert.True(plan.Sessions.All(s => s.Items.All(i => i.SourcePath.Contains(s.CameraModel == "NIKON Z 8" ? "NIK_" : "CAN_"))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NamesTakenTwiceGetASuffix()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(card, Start, 3, Interval);
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = "{date}", MinimumSessionFrames = 1 });
|
||||
Assert.SequenceEqual(["2026-09-28.JPG", "2026-09-28_2.JPG", "2026-09-28_3.JPG"], plan.Sessions[0].Items.Select(i => i.FileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ImportedAndArchivedPhotosAreSkippedAfterAHashMatch()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
var files = TestPhotos.WriteSeries(card, Start, 10, Interval);
|
||||
var lookup = new FakeLookup();
|
||||
lookup.Imported.Add("IMG_0001.JPG");
|
||||
var archived = await ContentHash.Sha256Async(files[1]);
|
||||
lookup.Archive.Add((new FileInfo(files[1]).Length, Start + Interval, new ArchiveMatch(Guid.NewGuid(), archived)));
|
||||
lookup.Archive.Add((new FileInfo(files[2]).Length, Start + 2 * Interval, new ArchiveMatch(Guid.NewGuid(), new string('0', 64))));
|
||||
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), lookup: lookup);
|
||||
var items = plan.Sessions[0].Items;
|
||||
Assert.Equal(ImportAction.SkipImported, items[0].Action);
|
||||
Assert.Equal(ImportAction.SkipInArchive, items[1].Action);
|
||||
Assert.Equal(lookup.Archive[0].Match.FrameId, items[1].ExistingFrameId);
|
||||
Assert.Equal(ImportAction.Copy, items[2].Action);
|
||||
Assert.Equal(await ContentHash.Sha256Async(files[2]), items[2].Sha256);
|
||||
Assert.Null(items[3].Sha256);
|
||||
Assert.Equal(8, plan.CopyCount);
|
||||
Assert.Equal("2026-09-28_18-00-10_0002.JPG", items[1].FileName);
|
||||
|
||||
var again = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { Duplicates = DuplicatePolicy.ImportAgain }, lookup);
|
||||
Assert.Equal(ImportAction.Copy, again.Sessions[0].Items[1].Action);
|
||||
Assert.Equal(lookup.Archive[0].Match.FrameId, again.Sessions[0].Items[1].ExistingFrameId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReplanningGivesStableKeysThatTitlesAndEarlierFoldersAttachTo()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(card, Start, 10, Interval);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
var first = await PlanAsync(card, destination);
|
||||
var key = first.Sessions[0].SessionKey;
|
||||
Assert.Equal(key, (await PlanAsync(card, destination)).Sessions[0].SessionKey);
|
||||
|
||||
var titled = await PlanAsync(card, destination, new ImportOptions
|
||||
{
|
||||
FolderTemplate = "{year}/{date} {title}",
|
||||
Titles = new Dictionary<string, string> { [key] = "Harbour sunset" },
|
||||
});
|
||||
Assert.Equal("2026/2026-09-28 Harbour sunset", titled.Sessions[0].Folder);
|
||||
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
|
||||
|
||||
var lookup = new FakeLookup();
|
||||
lookup.SessionFolders[key] = "2026/earlier import";
|
||||
Assert.Equal("2026/earlier import", (await PlanAsync(card, destination, lookup: lookup)).Sessions[0].Folder);
|
||||
|
||||
var taken = new FakeLookup();
|
||||
taken.TakenFolders.Add("2026/2026-09-28 Canon EOS R5");
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5 (2)", (await PlanAsync(card, destination, lookup: taken)).Sessions[0].Folder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UserMergeAndSplitReshapeSessions()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(card, Start, 10, Interval);
|
||||
TestPhotos.WriteSeries(card, Start.AddHours(3), 10, Interval, firstSeed: 30, firstNumber: 11);
|
||||
var destination = context.CreateTempDirectory("archive");
|
||||
Assert.Equal(2, (await PlanAsync(card, destination)).Sessions.Count);
|
||||
var merged = await PlanAsync(card, destination, new ImportOptions { MergeAt = new HashSet<string> { "IMG_0011.JPG" } });
|
||||
Assert.Equal(20, merged.Sessions.Single().Items.Count);
|
||||
Assert.Equal("2026-09-28_21-00-00_0011.JPG", merged.Sessions[0].Items[10].FileName);
|
||||
var split = await PlanAsync(card, destination, new ImportOptions { SplitBefore = new HashSet<string> { "IMG_0006.JPG" } });
|
||||
Assert.SequenceEqual([5, 5, 10], split.Sessions.Select(s => s.Items.Count));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoWithoutExifIsPlannedAtItsFileTime()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(card, Start, 8, Interval);
|
||||
var bare = Path.Combine(card, "BARE.JPG");
|
||||
File.WriteAllBytes(bare, [0xFF, 0xD8, 0xFF, 0xD9]);
|
||||
File.SetLastWriteTime(bare, Start.AddSeconds(85));
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
|
||||
var item = plan.Items.Single(i => i.SourcePath == "BARE.JPG");
|
||||
Assert.Equal(Start.AddSeconds(85), item.CapturedAt);
|
||||
// No camera identity: it forms its own body group rather than joining the Canon session.
|
||||
Assert.SequenceEqual([8, 1], plan.Sessions.Select(s => s.Items.Count));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Chronos.Core.Import;
|
||||
|
||||
namespace Chronos.Core.Tests.Import;
|
||||
|
||||
/// <summary>An <see cref="IImportLookup"/> answered from in-memory sets.</summary>
|
||||
internal sealed class FakeLookup : IImportLookup
|
||||
{
|
||||
public HashSet<string> Imported { get; } = [];
|
||||
public List<(long Size, DateTime Captured, ArchiveMatch Match)> Archive { get; } = [];
|
||||
public Dictionary<string, string> SessionFolders { get; } = [];
|
||||
public HashSet<string> TakenFolders { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
public int CandidateQueries { get; private set; }
|
||||
|
||||
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(Imported.Contains(file.RelativePath));
|
||||
|
||||
public Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken)
|
||||
{
|
||||
CandidateQueries++;
|
||||
return Task.FromResult<IReadOnlyList<ArchiveMatch>>(Archive.Where(a => a.Size == size && a.Captured == capturedAt).Select(a => a.Match).ToList());
|
||||
}
|
||||
|
||||
public Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(SessionFolders.GetValueOrDefault(sessionKey));
|
||||
|
||||
public bool IsFolderTaken(string folder) => TakenFolders.Contains(folder);
|
||||
}
|
||||
|
||||
internal static class ImportTestKit
|
||||
{
|
||||
public static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
|
||||
|
||||
/// <summary>Plans an import of <paramref name="card"/> into <paramref name="destination"/>.</summary>
|
||||
public static async Task<ImportPlan> PlanAsync(string card, string destination, ImportOptions? options = null, FakeLookup? lookup = null)
|
||||
{
|
||||
options ??= new ImportOptions();
|
||||
var problems = new List<ImportProblem>();
|
||||
var photos = CardScanner.ReadMetadata(card, CardScanner.Find(card, options.IncludeSubfolders), problems);
|
||||
return await ImportPlanner.PlanAsync(card, destination, photos, problems, options, lookup ?? new FakeLookup());
|
||||
}
|
||||
|
||||
/// <summary>Every file below <paramref name="root"/> (relative, forward slashes), excluding Chronos's metadata folders.</summary>
|
||||
public static List<string> Files(string root) =>
|
||||
Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
|
||||
.Select(f => Path.GetRelativePath(root, f).Replace('\\', '/'))
|
||||
.Where(f => !f.StartsWith(".chronos/", StringComparison.Ordinal))
|
||||
.Order(StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Core.Tests.Import;
|
||||
|
||||
[Category("import")]
|
||||
public sealed class SessionSplitterTests
|
||||
{
|
||||
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
|
||||
private static readonly TimeSpan Gap = TimeSpan.FromMinutes(45);
|
||||
|
||||
/// <summary>Capture times from a compact description: runs of frames 10 s apart, separated by pauses in minutes.</summary>
|
||||
private static List<DateTime> Times(params (int Frames, int PauseBeforeMinutes)[] runs)
|
||||
{
|
||||
var times = new List<DateTime>();
|
||||
var t = Start;
|
||||
foreach (var (frames, pause) in runs)
|
||||
{
|
||||
t = t.AddMinutes(pause);
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
times.Add(t);
|
||||
t = t.AddSeconds(10);
|
||||
}
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
private static string Describe(IReadOnlyList<SessionRange> ranges) => string.Join(",", ranges.Select(r => r.Count));
|
||||
|
||||
[Theory]
|
||||
[Case(new[] { 30 }, new[] { 0 }, "30", Name = "one session")]
|
||||
[Case(new[] { 30, 40 }, new[] { 0, 60 }, "30,40", Name = "pause longer than the gap splits")]
|
||||
[Case(new[] { 30, 40 }, new[] { 0, 44 }, "70", Name = "pause shorter than the gap does not")]
|
||||
[Case(new[] { 3, 30 }, new[] { 0, 90 }, "33", Name = "leading test shots join the next session")]
|
||||
[Case(new[] { 30, 3 }, new[] { 0, 90 }, "33", Name = "trailing test shots join the previous session")]
|
||||
[Case(new[] { 30, 2, 30 }, new[] { 0, 90, 90 }, "32,30", Name = "small middle group joins the previous session")]
|
||||
[Case(new[] { 2, 3 }, new[] { 0, 90 }, "5", Name = "only small groups make one session")]
|
||||
public void AutomaticSessions(int[] frames, int[] pauses, string expected)
|
||||
{
|
||||
var times = Times(frames.Zip(pauses).ToArray());
|
||||
Assert.Equal(expected, Describe(SessionSplitter.Split(times, Gap, 8)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APauseOfExactlyTheGapDoesNotSplit()
|
||||
{
|
||||
var times = new List<DateTime> { Start };
|
||||
for (var i = 1; i < 10; i++) times.Add(Start.AddSeconds(i));
|
||||
for (var i = 0; i < 10; i++) times.Add(times[9] + Gap + TimeSpan.FromSeconds(i));
|
||||
Assert.Equal("20", Describe(SessionSplitter.Split(times, Gap, 8)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UserSplitsAndMergesOverrideTheRules()
|
||||
{
|
||||
var times = Times((30, 0), (40, 60));
|
||||
// Split before frame 25 (a 5-frame group the user wants on its own) and merge the automatic break at 30.
|
||||
var ranges = SessionSplitter.Split(times, Gap, 8, i => i == 25 ? true : i == 30 ? false : null);
|
||||
Assert.Equal("25,45", Describe(ranges));
|
||||
Assert.Equal(25, ranges[1].Start);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AForcedSmallSessionIsNotMergedAway()
|
||||
{
|
||||
var times = Times((30, 0));
|
||||
Assert.Equal("28,2", Describe(SessionSplitter.Split(times, Gap, 8, i => i == 28 ? true : null)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NoFramesNoSessions() => Assert.Empty(SessionSplitter.Split([], Gap, 8));
|
||||
}
|
||||
Reference in new issue
Block a user