Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,12 @@ Each is covered by regression tests. Do not reintroduce them.
`ProcessDirectoryTests.InputsSharingABaseNameDoNotOverwriteEachOther` and
`ArgumentsTests.ValidateRejectsAnOutputThatIsTheInputDirectory`.

- **A failed save destroyed the earlier output.** `SaveAsPng(path)` truncates the destination before
encoding, so a save that failed part-way (a full disk, say) left a truncated or 0-byte PNG under
the output name, replacing the good icon from an earlier run. `WriteReplacing` now encodes to a
`<name>.png.<random>.tmp` file beside the output and moves it into place, and deletes it on
failure. Pinned by `ProcessDirectoryTests.ASaveThatFailsPartWayLeavesTheEarlierOutputUntouched`.

## Testing

`IconHelper.Test` is an MSTest project (`MSTest.Sdk`, Microsoft Testing Platform). Both it and the
Expand Down
53 changes: 53 additions & 0 deletions IconHelper.Test/ProcessDirectoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,4 +420,57 @@ public void SmallArtworkWithValidatedPaddingDoesNotFailTheBatch()
Assert.AreEqual(1, result.Written);
Assert.AreEqual(IconHelper.ExitSuccess, IconHelper.ExitCodeFor(result));
}

[TestMethod]
public void ASaveThatFailsPartWayLeavesTheEarlierOutputUntouched()
{
using TempDirectory temp = new();
string output = temp.Combine("icon.png");
byte[] earlier = [1, 2, 3, 4, 5];
File.WriteAllBytes(output, earlier);

Assert.ThrowsExactly<IOException>(() => IconHelper.WriteReplacing(output, stream =>
{
stream.Write(new byte[4096]);
stream.Flush();
throw new IOException("No space left on device");
}));

CollectionAssert.AreEqual(earlier, File.ReadAllBytes(output), "A failed save must not truncate the earlier output.");
CollectionAssert.AreEqual(new[] { output }, Directory.GetFiles(temp.FullPath), "A failed save must leave no partial or temporary file behind.");
}

[TestMethod]
public void ASaveThatFailsPartWayLeavesNothingWhenThereWasNoEarlierOutput()
{
using TempDirectory temp = new();
string output = temp.Combine("icon.png");

Assert.ThrowsExactly<IOException>(() => IconHelper.WriteReplacing(output, stream =>
{
stream.Write(new byte[4096]);
throw new IOException("No space left on device");
}));

Assert.IsEmpty(Directory.GetFiles(temp.FullPath), "A failed save must leave no partial file under the output name.");
}

[TestMethod]
public void ARerunReplacesTheEarlierOutputAndLeavesNoTemporaryFiles()
{
using TempDirectory temp = new();
string input = temp.Combine("in");
string output = temp.Combine("out");
Directory.CreateDirectory(input);
Directory.CreateDirectory(output);
WritePng(Path.Join(input, "icon.png"), 64);
File.WriteAllBytes(Path.Join(output, "icon.png"), [1, 2, 3]);

BatchResult result = IconHelper.ProcessDirectory(ArgumentsFor(input, output), NamedColors.White);

Assert.AreEqual(1, result.Written);
CollectionAssert.AreEqual(new[] { Path.Join(output, "icon.png") }, Directory.GetFiles(output));
using Image<Rgba32> written = Image.Load<Rgba32>(Path.Join(output, "icon.png"));
Assert.AreEqual(32, written.Width);
}
}
33 changes: 32 additions & 1 deletion IconHelper/IconHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ internal static BatchResult ProcessDirectory(Arguments args, Color color)
FileName outputFileName = FileName.Create<FileName>(outputName);
AbsoluteFilePath outputFilePath = outputDirectory / outputFileName;

image.SaveAsPng(outputFilePath, Encoder);
WriteReplacing(outputFilePath, stream => image.SaveAsPng(stream, Encoder));
written.Add(outputName, file);
processed++;
}
Expand All @@ -188,6 +188,37 @@ internal static BatchResult ProcessDirectory(Arguments args, Color color)
return new BatchResult(processed, failed);
}

/// <summary>
/// Writes <paramref name="outputFilePath"/> through a temporary file beside it, then moves that
/// file over the destination. A save that fails part-way, for example on a full disk, leaves no
/// partial file under the output name and keeps the output an earlier run wrote there.
/// </summary>
/// <remarks>
/// The temporary file is not a .png, and Validate rejects an output folder that is the input
/// folder, so a file left behind by a crash is never picked up as an input.
/// </remarks>
internal static void WriteReplacing(string outputFilePath, Action<Stream> write)
{
Ensure.NotNull(outputFilePath);
Ensure.NotNull(write);

string temporaryPath = $"{outputFilePath}.{Path.GetRandomFileName()}.tmp";
try
{
using (FileStream stream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
write(stream);
}

File.Move(temporaryPath, outputFilePath, overwrite: true);
}
catch
{
File.Delete(temporaryPath);
throw;
}
}

/// <summary>
/// Names that Finder and Explorer drop into any folder they open: dot-files such as .DS_Store and
/// ._ AppleDouble files, plus Thumbs.db, ehthumbs.db and desktop.ini. They are not icons, so they
Expand Down
Loading