Compare commits
3
Commits
c815a7d49f
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6d16fd108 | ||
|
|
996c0a9515 | ||
|
|
34a588864f |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
using SongTidy.Models;
|
||||
|
||||
namespace SongTidy.Tests;
|
||||
namespace SongTidy.Tests.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="RenameFormats"/>.
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using SongTidy.Services;
|
||||
using SongTidy.Tests.TestUtilities;
|
||||
|
||||
namespace SongTidy.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="AudioFileScanner"/>.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class AudioFileScannerTests {
|
||||
private readonly TempDirectory _tempDirectory = new();
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the current test.
|
||||
/// </summary>
|
||||
[TestCleanup]
|
||||
public void Cleanup() {
|
||||
_tempDirectory.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that supported extensions are matched case-insensitively and others are ignored.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ScansSupportedExtensionsCaseInsensitively() {
|
||||
CreateFile("a.mp3");
|
||||
CreateFile("b.FLAC");
|
||||
CreateFile("c.txt");
|
||||
|
||||
IReadOnlyList<string> files = AudioFileScanner.Scan(_tempDirectory.FullPath);
|
||||
|
||||
Assert.HasCount(2, files);
|
||||
Assert.IsTrue(files.Any(file => file.EndsWith("a.mp3", StringComparison.OrdinalIgnoreCase)));
|
||||
Assert.IsTrue(files.Any(file => file.EndsWith("b.FLAC", StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that subdirectories are not scanned.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void DoesNotScanSubdirectories() {
|
||||
CreateFile("root.mp3");
|
||||
CreateFile(Path.Combine("sub", "nested.wav"));
|
||||
|
||||
IReadOnlyList<string> files = AudioFileScanner.Scan(_tempDirectory.FullPath);
|
||||
|
||||
Assert.HasCount(1, files);
|
||||
Assert.IsTrue(files[0].EndsWith("root.mp3", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an empty file inside the test directory.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The relative file name, which may include a subdirectory.</param>
|
||||
private void CreateFile(string fileName) {
|
||||
string path = Path.Combine(_tempDirectory.FullPath, fileName);
|
||||
string directory = Path.GetDirectoryName(path) ?? _tempDirectory.FullPath;
|
||||
|
||||
Directory.CreateDirectory(directory);
|
||||
File.WriteAllText(path, string.Empty);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
using SongTidy.Services;
|
||||
|
||||
namespace SongTidy.Tests;
|
||||
namespace SongTidy.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="FilenameParser"/>.
|
||||
@@ -6,8 +6,9 @@ using System.Xml.Linq;
|
||||
|
||||
using SongTidy.Models;
|
||||
using SongTidy.Services;
|
||||
using SongTidy.Tests.TestUtilities;
|
||||
|
||||
namespace SongTidy.Tests;
|
||||
namespace SongTidy.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="PlanXmlIO"/>.
|
||||
@@ -210,32 +211,27 @@ public sealed class PlanXmlIOTests {
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void SavesAndLoadsFileWithSpacesInPath() {
|
||||
string directory = Path.Combine(Path.GetTempPath(), $"SongTidy Plan Test {Guid.NewGuid():N}");
|
||||
string filePath = Path.Combine(directory, "plan with spaces.xml");
|
||||
Directory.CreateDirectory(directory);
|
||||
using TempDirectory tempDirectory = new();
|
||||
string filePath = Path.Combine(tempDirectory.FullPath, "plan with spaces.xml");
|
||||
|
||||
try {
|
||||
SongPlan plan = CreateSamplePlan();
|
||||
SongPlan plan = CreateSamplePlan();
|
||||
|
||||
PlanXmlIO.Save(plan, filePath);
|
||||
PlanXmlIO.Save(plan, filePath);
|
||||
|
||||
Assert.IsTrue(File.Exists(filePath));
|
||||
Assert.IsTrue(File.Exists(filePath));
|
||||
|
||||
byte[] bytes = File.ReadAllBytes(filePath);
|
||||
Assert.AreEqual((byte)'<', bytes[0]);
|
||||
byte[] bytes = File.ReadAllBytes(filePath);
|
||||
Assert.AreEqual((byte)'<', bytes[0]);
|
||||
|
||||
string xml = Encoding.UTF8.GetString(bytes);
|
||||
Assert.IsTrue(
|
||||
xml.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>", StringComparison.Ordinal),
|
||||
"The file should be written as UTF-8 without a BOM.");
|
||||
string xml = Encoding.UTF8.GetString(bytes);
|
||||
Assert.IsTrue(
|
||||
xml.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>", StringComparison.Ordinal),
|
||||
"The file should be written as UTF-8 without a BOM.");
|
||||
|
||||
SongPlan loaded = PlanXmlIO.Load(filePath);
|
||||
Assert.AreEqual(plan.Format, loaded.Format);
|
||||
Assert.HasCount(plan.Items.Count, loaded.Items);
|
||||
AssertPlanItem(plan.Items[0], loaded.Items[0]);
|
||||
} finally {
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
SongPlan loaded = PlanXmlIO.Load(filePath);
|
||||
Assert.AreEqual(plan.Format, loaded.Format);
|
||||
Assert.HasCount(plan.Items.Count, loaded.Items);
|
||||
AssertPlanItem(plan.Items[0], loaded.Items[0]);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -0,0 +1,362 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using SongTidy.Models;
|
||||
using SongTidy.Services;
|
||||
using SongTidy.Tests.TestUtilities;
|
||||
|
||||
namespace SongTidy.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="RenameValidator"/>.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RenameValidatorTests {
|
||||
private readonly TempDirectory _tempDirectory = new();
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the current test.
|
||||
/// </summary>
|
||||
[TestCleanup]
|
||||
public void Cleanup() {
|
||||
_tempDirectory.Dispose();
|
||||
}
|
||||
|
||||
#region Per-entry validation
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that empty and whitespace-only titles are rejected.
|
||||
/// </summary>
|
||||
/// <param name="title">The title to validate.</param>
|
||||
[TestMethod]
|
||||
[DataRow("")]
|
||||
[DataRow(" ")]
|
||||
public void ReportsEmptyTitle(string title) {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, title));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.EmptyTitle, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that every forbidden file name character is detected in the title.
|
||||
/// </summary>
|
||||
/// <param name="invalidCharacter">The character to insert into the title.</param>
|
||||
[TestMethod]
|
||||
[DataRow("\\")]
|
||||
[DataRow("/")]
|
||||
[DataRow(":")]
|
||||
[DataRow("*")]
|
||||
[DataRow("?")]
|
||||
[DataRow("\"")]
|
||||
[DataRow("<")]
|
||||
[DataRow(">")]
|
||||
[DataRow("|")]
|
||||
[DataRow("\t")]
|
||||
public void ReportsInvalidCharacterInTitle(string invalidCharacter) {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "A" + invalidCharacter + "B"));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.InvalidFieldCharacter, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that invalid characters are detected in the artist and comment fields.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsInvalidCharactersInArtistAndComment() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(sourcePath, "Title", artist: "A\\B", comment: "C:D"));
|
||||
|
||||
Assert.HasCount(
|
||||
2,
|
||||
result.Issues.Where(issue => issue.Problem == RenameValidationProblem.InvalidFieldCharacter));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that target names ending with a dot or a space are rejected.
|
||||
/// </summary>
|
||||
/// <param name="title">The title that produces the invalid target ending.</param>
|
||||
[TestMethod]
|
||||
[DataRow("Title.")]
|
||||
[DataRow("Title ")]
|
||||
public void ReportsInvalidTargetEnding(string title) {
|
||||
string sourcePath = CreateFile("Source");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, title));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.InvalidTargetEnding, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that missing source files are detected.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsMissingSourceFile() {
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "Missing.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "Title"));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.MissingSourceFile, 1));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Source path validation
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that duplicate source paths are reported for every affected row.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsDuplicateSourcePaths() {
|
||||
string sourcePath = CreateFile("Dup.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(sourcePath, "One"),
|
||||
CreateItem(sourcePath, "Two"));
|
||||
|
||||
Assert.HasCount(
|
||||
2,
|
||||
result.Issues.Where(issue => issue.Problem == RenameValidationProblem.DuplicateSourcePath));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateSourcePath, 1));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateSourcePath, 2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that source path comparison is case-sensitive.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void TreatsSourcePathsAsCaseSensitive() {
|
||||
CreateFile("Case.mp3");
|
||||
PlanItem first = CreateItem(Path.Combine(_tempDirectory.FullPath, "Case.mp3"), "One");
|
||||
PlanItem second = CreateItem(Path.Combine(_tempDirectory.FullPath, "case.mp3"), "Two");
|
||||
|
||||
RenameValidationResult result = Validate(first, second);
|
||||
|
||||
Assert.IsFalse(
|
||||
result.Issues.Any(issue => issue.Problem == RenameValidationProblem.DuplicateSourcePath));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Target conflict validation
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that duplicate target paths are detected case-insensitively.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsDuplicateTargetNamesCaseInsensitively() {
|
||||
string firstPath = CreateFile("A.mp3");
|
||||
string secondPath = CreateFile("B.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(firstPath, "Same"),
|
||||
CreateItem(secondPath, "same"));
|
||||
|
||||
Assert.HasCount(
|
||||
2,
|
||||
result.Issues.Where(issue => issue.Problem == RenameValidationProblem.DuplicateTargetName));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateTargetName, 1));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateTargetName, 2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that equal target names in different directories do not conflict.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AllowsSameTargetNameInDifferentDirectories() {
|
||||
string firstPath = CreateFile(Path.Combine("dir1", "A.mp3"));
|
||||
string secondPath = CreateFile(Path.Combine("dir2", "B.mp3"));
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(firstPath, "Same"),
|
||||
CreateItem(secondPath, "Same"));
|
||||
|
||||
Assert.IsTrue(result.IsValid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that an existing target file is reported as a conflict.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsTargetFileConflict() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
CreateFile("Existing.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "Existing"));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.TargetFileConflict, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a target equal to the entry's own source is not a conflict.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AllowsTargetEqualToOwnSource() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "A"));
|
||||
|
||||
Assert.IsTrue(result.IsValid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that casing-only changes to the entry's own source are not conflicts.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AllowsTargetEqualToOwnSourceIgnoringCase() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "a"));
|
||||
|
||||
Assert.IsTrue(result.IsValid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a renaming chain such as A to B and B to A is blocked.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void BlocksConflictChain() {
|
||||
string aPath = CreateFile("A.mp3");
|
||||
string bPath = CreateFile("B.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(aPath, "B"),
|
||||
CreateItem(bPath, "A"));
|
||||
|
||||
Assert.HasCount(
|
||||
2,
|
||||
result.Issues.Where(issue => issue.Problem == RenameValidationProblem.TargetFileConflict));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.TargetFileConflict, 1));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.TargetFileConflict, 2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the original file extension is preserved when checking conflicts.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void UsesOriginalExtensionForTargetNames() {
|
||||
string sourcePath = CreateFile("Source.flac");
|
||||
CreateFile("Title.flac");
|
||||
|
||||
RenameValidationResult result = Validate(CreateItem(sourcePath, "Title"));
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.TargetFileConflict, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the selected naming format controls the generated target name.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void UsesSelectedFormatForTargetNames() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
CreateFile("Title - Artist.mp3");
|
||||
PlanItem item = CreateItem(sourcePath, "Title", artist: "Artist");
|
||||
|
||||
RenameValidationResult result = RenameValidator.Validate(
|
||||
new[] { item },
|
||||
RenameFormat.TitleFirst);
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.TargetFileConflict, 1));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Combined validation
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that validation collects problems from multiple rules in one pass.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReportsAllProblemKinds() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
PlanItem emptyTitle = CreateItem(sourcePath, "");
|
||||
PlanItem missingSource = CreateItem(Path.Combine(_tempDirectory.FullPath, "Missing.mp3"), "Title");
|
||||
PlanItem invalidCharacter = CreateItem(sourcePath, "Bad/Title");
|
||||
|
||||
RenameValidationResult result = Validate(emptyTitle, missingSource, invalidCharacter);
|
||||
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.EmptyTitle, 1));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.MissingSourceFile, 2));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.InvalidFieldCharacter, 3));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateSourcePath, 1));
|
||||
Assert.IsTrue(HasProblem(result, RenameValidationProblem.DuplicateSourcePath, 3));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that a clean set of entries produces no issues.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ReturnsValidResultForRenameableEntries() {
|
||||
string firstPath = CreateFile("A.mp3");
|
||||
string secondPath = CreateFile("B.mp3");
|
||||
|
||||
RenameValidationResult result = Validate(
|
||||
CreateItem(firstPath, "One"),
|
||||
CreateItem(secondPath, "Two"));
|
||||
|
||||
Assert.IsTrue(result.IsValid);
|
||||
Assert.HasCount(0, result.Issues);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Creates an empty file inside the test directory.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The relative file name, which may include a subdirectory.</param>
|
||||
/// <returns>The full path of the created file.</returns>
|
||||
private string CreateFile(string fileName) {
|
||||
string path = Path.Combine(_tempDirectory.FullPath, fileName);
|
||||
string directory = Path.GetDirectoryName(path) ?? _tempDirectory.FullPath;
|
||||
|
||||
Directory.CreateDirectory(directory);
|
||||
File.WriteAllText(path, string.Empty);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a plan item with the supplied field values.
|
||||
/// </summary>
|
||||
/// <param name="path">The source file path.</param>
|
||||
/// <param name="title">The title value.</param>
|
||||
/// <param name="artist">The artist value.</param>
|
||||
/// <param name="comment">The comment value.</param>
|
||||
/// <returns>The created plan item.</returns>
|
||||
private static PlanItem CreateItem(string path, string title, string artist = "", string comment = "") {
|
||||
return new PlanItem {
|
||||
Path = path,
|
||||
Artist = artist,
|
||||
Title = title,
|
||||
Comment = comment,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates entries with the artist-first format.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to validate.</param>
|
||||
/// <returns>The validation result.</returns>
|
||||
private static RenameValidationResult Validate(params PlanItem[] items) {
|
||||
return RenameValidator.Validate(items, RenameFormat.ArtistFirst);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the result contains a specific problem for a row.
|
||||
/// </summary>
|
||||
/// <param name="result">The validation result to inspect.</param>
|
||||
/// <param name="problem">The problem category to find.</param>
|
||||
/// <param name="rowNumber">The one-based row number to match.</param>
|
||||
/// <returns><see langword="true"/> when the problem is present.</returns>
|
||||
private static bool HasProblem(
|
||||
RenameValidationResult result,
|
||||
RenameValidationProblem problem,
|
||||
int rowNumber) {
|
||||
return result.Issues.Any(issue => issue.Problem == problem && issue.RowNumber == rowNumber);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SongTidy.Tests.TestUtilities;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique temporary directory per test instance and removes it on disposal.
|
||||
/// </summary>
|
||||
public sealed class TempDirectory : IDisposable {
|
||||
/// <summary>
|
||||
/// Gets the unique directory path managed by this instance.
|
||||
/// </summary>
|
||||
public string FullPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique temporary directory.
|
||||
/// </summary>
|
||||
public TempDirectory() {
|
||||
FullPath = Path.Combine(Path.GetTempPath(), "songtidy-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(FullPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the directory tree, retrying once after a short delay.
|
||||
/// </summary>
|
||||
public void Dispose() {
|
||||
try {
|
||||
// SAFETY: Recursive deletion is confined to the GUID-named directory
|
||||
// created by this instance under the OS temp folder.
|
||||
Directory.Delete(FullPath, recursive: true);
|
||||
} catch (IOException) {
|
||||
// A file handle may still be closing; retry once before giving up.
|
||||
Thread.Sleep(100);
|
||||
|
||||
try {
|
||||
// SAFETY: The retry targets the same instance-owned temp directory.
|
||||
Directory.Delete(FullPath, recursive: true);
|
||||
} catch (IOException) {
|
||||
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using SongTidy.Models;
|
||||
using SongTidy.Services;
|
||||
using SongTidy.Tests.TestUtilities;
|
||||
using SongTidy.ViewModels;
|
||||
|
||||
namespace SongTidy.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="MainWindowViewModel"/>.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class MainWindowViewModelTests {
|
||||
private readonly TempDirectory _tempDirectory = new();
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the current test.
|
||||
/// </summary>
|
||||
[TestCleanup]
|
||||
public void Cleanup() {
|
||||
_tempDirectory.Dispose();
|
||||
}
|
||||
|
||||
#region Input and merge rules
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that added files are parsed and appended.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AddFilesParsesAndAppendsEntries() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A - B (Live).mp3");
|
||||
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
|
||||
Assert.HasCount(1, viewModel.Entries);
|
||||
Assert.AreEqual(1, viewModel.EntryCount);
|
||||
Assert.IsTrue(viewModel.IsDirty);
|
||||
|
||||
SongEntryViewModel entry = viewModel.Entries[0];
|
||||
Assert.AreEqual(sourcePath, entry.FilePath);
|
||||
Assert.AreEqual("A", entry.Artist);
|
||||
Assert.AreEqual("B", entry.Title);
|
||||
Assert.AreEqual("Live", entry.Comment);
|
||||
Assert.AreEqual("A - B (Live).mp3", entry.OriginalFileName);
|
||||
Assert.AreEqual("A - B (Live).mp3", entry.TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that duplicate paths keep the existing entry and its edits.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AddFilesSkipsDuplicatesAndPreservesEdits() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A - B.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.Entries[0].Artist = "Edited";
|
||||
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
|
||||
Assert.HasCount(1, viewModel.Entries);
|
||||
Assert.AreEqual("Edited", viewModel.Entries[0].Artist);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that duplicate detection compares full path strings case-sensitively.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AddFilesTreatsPathsAsCaseSensitive() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
|
||||
viewModel.AddFiles(new[] {
|
||||
Path.Combine(_tempDirectory.FullPath, "a.mp3"),
|
||||
Path.Combine(_tempDirectory.FullPath, "A.mp3"),
|
||||
});
|
||||
|
||||
Assert.HasCount(2, viewModel.Entries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that adding only duplicates does not change the dirty state.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AddFilesWithOnlyDuplicatesDoesNotDirty() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that folder input uses the audio extension filter.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void AddFilesFromFolderAddsOnlyAudioFiles() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
CreateFile("A.mp3");
|
||||
CreateFile("B.FLAC");
|
||||
CreateFile("C.txt");
|
||||
CreateFile(Path.Combine("sub", "D.wav"));
|
||||
|
||||
viewModel.AddFilesFromFolder(_tempDirectory.FullPath);
|
||||
|
||||
Assert.HasCount(2, viewModel.Entries);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dirty tracking
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that field edits mark the document dirty and reverting does not clear it.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void EntryEditMarksDirtyAndRevertingDoesNotClear() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
SongEntryViewModel entry = viewModel.Entries[0];
|
||||
string originalArtist = entry.Artist;
|
||||
|
||||
entry.Artist = "Changed";
|
||||
Assert.IsTrue(viewModel.IsDirty);
|
||||
|
||||
entry.Artist = originalArtist;
|
||||
Assert.IsTrue(viewModel.IsDirty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that changing the format updates previews and marks the document dirty.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void FormatChangeUpdatesPreviewsAndMarksDirty() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A - B (Live).mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
|
||||
viewModel.SelectedFormat = RenameFormat.TitleFirst;
|
||||
|
||||
Assert.IsTrue(viewModel.IsDirty);
|
||||
Assert.AreEqual("B (Live) - A.mp3", viewModel.Entries[0].TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that selecting the current format does not mark the document dirty.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void SettingSameFormatDoesNotDirty() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
|
||||
viewModel.SelectedFormat = RenameFormat.ArtistFirst;
|
||||
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Plan operations
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that starting a new plan clears entries, path, and dirty state.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void NewPlanClearsDocument() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
|
||||
viewModel.NewPlan();
|
||||
|
||||
Assert.HasCount(0, viewModel.Entries);
|
||||
Assert.AreEqual(0, viewModel.EntryCount);
|
||||
Assert.IsNull(viewModel.PlanPath);
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that closing a plan clears entries, path, and dirty state.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ClosePlanClearsDocument() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A.mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SavePlan(Path.Combine(_tempDirectory.FullPath, "plan.xml"));
|
||||
|
||||
viewModel.ClosePlan();
|
||||
|
||||
Assert.HasCount(0, viewModel.Entries);
|
||||
Assert.AreEqual(0, viewModel.EntryCount);
|
||||
Assert.IsNull(viewModel.PlanPath);
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that loading a plan restores its format, entries, and path.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void LoadPlanRestoresDocument() {
|
||||
string planPath = Path.Combine(_tempDirectory.FullPath, "plan.xml");
|
||||
SongPlan plan = new() {
|
||||
Format = RenameFormat.TitleFirst,
|
||||
Items = new List<PlanItem> {
|
||||
new PlanItem {
|
||||
Path = Path.Combine(_tempDirectory.FullPath, "A - B.mp3"),
|
||||
Artist = "A",
|
||||
Title = "B",
|
||||
},
|
||||
new PlanItem {
|
||||
Path = Path.Combine(_tempDirectory.FullPath, "C.mp3"),
|
||||
Title = "C",
|
||||
Comment = "Live",
|
||||
},
|
||||
},
|
||||
};
|
||||
PlanXmlIO.Save(plan, planPath);
|
||||
|
||||
MainWindowViewModel viewModel = new();
|
||||
viewModel.LoadPlan(planPath);
|
||||
|
||||
Assert.AreEqual(RenameFormat.TitleFirst, viewModel.SelectedFormat);
|
||||
Assert.HasCount(2, viewModel.Entries);
|
||||
Assert.AreEqual(2, viewModel.EntryCount);
|
||||
Assert.AreEqual(planPath, viewModel.PlanPath);
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
Assert.AreEqual("B - A.mp3", viewModel.Entries[0].TargetFileName);
|
||||
Assert.AreEqual("C (Live).mp3", viewModel.Entries[1].TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies saving to a path and then using the existing-path save overload.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void SavePlanWritesDocumentAndClearsDirty() {
|
||||
MainWindowViewModel viewModel = new();
|
||||
string sourcePath = Path.Combine(_tempDirectory.FullPath, "A - B (Live).mp3");
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.SelectedFormat = RenameFormat.TitleFirst;
|
||||
string planPath = Path.Combine(_tempDirectory.FullPath, "saved.xml");
|
||||
|
||||
viewModel.SavePlan(planPath);
|
||||
|
||||
Assert.AreEqual(planPath, viewModel.PlanPath);
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
|
||||
SongPlan saved = PlanXmlIO.Load(planPath);
|
||||
Assert.AreEqual(RenameFormat.TitleFirst, saved.Format);
|
||||
Assert.HasCount(1, saved.Items);
|
||||
Assert.AreEqual("A", saved.Items[0].Artist);
|
||||
Assert.AreEqual("B", saved.Items[0].Title);
|
||||
Assert.AreEqual("Live", saved.Items[0].Comment);
|
||||
|
||||
viewModel.Entries[0].Comment = "Changed";
|
||||
Assert.IsTrue(viewModel.IsDirty);
|
||||
Assert.IsTrue(viewModel.SavePlan());
|
||||
Assert.IsFalse(viewModel.IsDirty);
|
||||
|
||||
SongPlan reloaded = PlanXmlIO.Load(planPath);
|
||||
Assert.AreEqual("Changed", reloaded.Items[0].Comment);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Validation
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that validation uses the current entries.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ValidateRenameUsesCurrentDocument() {
|
||||
string sourcePath = CreateFile("A.mp3");
|
||||
MainWindowViewModel viewModel = new();
|
||||
viewModel.AddFiles(new[] { sourcePath });
|
||||
viewModel.Entries[0].Title = string.Empty;
|
||||
|
||||
RenameValidationResult result = viewModel.ValidateRename();
|
||||
|
||||
Assert.IsTrue(result.Issues.Any(issue => issue.Problem == RenameValidationProblem.EmptyTitle));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Creates an empty file inside the test directory.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The relative file name, which may include a subdirectory.</param>
|
||||
/// <returns>The full path of the created file.</returns>
|
||||
private string CreateFile(string fileName) {
|
||||
string path = Path.Combine(_tempDirectory.FullPath, fileName);
|
||||
string directory = Path.GetDirectoryName(path) ?? _tempDirectory.FullPath;
|
||||
|
||||
Directory.CreateDirectory(directory);
|
||||
File.WriteAllText(path, string.Empty);
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.IO;
|
||||
|
||||
using SongTidy.Models;
|
||||
using SongTidy.ViewModels;
|
||||
|
||||
namespace SongTidy.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Contains tests for <see cref="SongEntryViewModel"/>.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SongEntryViewModelTests {
|
||||
#region Preview
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the initial fields and target preview.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void InitializesFieldsAndTargetPreview() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
|
||||
Assert.AreEqual("Artist", entry.Artist);
|
||||
Assert.AreEqual("Title", entry.Title);
|
||||
Assert.AreEqual("Live", entry.Comment);
|
||||
Assert.AreEqual(RenameFormat.ArtistFirst, entry.Format);
|
||||
Assert.AreEqual("A.mp3", entry.OriginalFileName);
|
||||
Assert.AreEqual("Artist - Title (Live).mp3", entry.TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that changing a field immediately updates the target preview.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void UpdatesTargetPreviewWhenFieldChanges() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
|
||||
entry.Artist = "New Artist";
|
||||
|
||||
Assert.AreEqual("New Artist - Title (Live).mp3", entry.TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that changing the format updates the target preview.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void UpdatesTargetPreviewWhenFormatChanges() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
|
||||
entry.Format = RenameFormat.TitleFirst;
|
||||
|
||||
Assert.AreEqual("Title (Live) - Artist.mp3", entry.TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the original extension is preserved for other file types.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void PreservesOriginalExtension() {
|
||||
SongEntryViewModel entry = new(
|
||||
Path.Combine("Music", "A.flac"),
|
||||
string.Empty,
|
||||
"Title",
|
||||
string.Empty,
|
||||
RenameFormat.ArtistFirst);
|
||||
|
||||
Assert.AreEqual("Title.flac", entry.TargetFileName);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dirty notifications
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that editing any field raises the edited event.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void RaisesEditedWhenFieldChanges() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
int editCount = 0;
|
||||
entry.Edited += (_, _) => editCount++;
|
||||
|
||||
entry.Artist = "New Artist";
|
||||
entry.Title = "New Title";
|
||||
entry.Comment = "New Comment";
|
||||
|
||||
Assert.AreEqual(3, editCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that assigning the current value does not raise the edited event.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void DoesNotRaiseEditedWhenFieldValueIsUnchanged() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
int editCount = 0;
|
||||
entry.Edited += (_, _) => editCount++;
|
||||
|
||||
entry.Artist = entry.Artist;
|
||||
|
||||
Assert.AreEqual(0, editCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that changing the format does not itself count as a field edit.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ChangingFormatDoesNotRaiseEdited() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
int editCount = 0;
|
||||
entry.Edited += (_, _) => editCount++;
|
||||
|
||||
entry.Format = RenameFormat.TitleFirst;
|
||||
|
||||
Assert.AreEqual(0, editCount);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Swap
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that swapping exchanges the artist and title values.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void SwapsArtistAndTitle() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
|
||||
entry.SwapArtistAndTitle();
|
||||
|
||||
Assert.AreEqual("Title", entry.Artist);
|
||||
Assert.AreEqual("Artist", entry.Title);
|
||||
Assert.AreEqual("Title - Artist (Live).mp3", entry.TargetFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that swapping raises edited notifications for both changed fields.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void SwapRaisesEditedForBothFields() {
|
||||
SongEntryViewModel entry = CreateEntry();
|
||||
int editCount = 0;
|
||||
entry.Edited += (_, _) => editCount++;
|
||||
|
||||
entry.SwapArtistAndTitle();
|
||||
|
||||
Assert.AreEqual(2, editCount);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Creates a standard test entry.
|
||||
/// </summary>
|
||||
/// <returns>The created entry.</returns>
|
||||
private static SongEntryViewModel CreateEntry() {
|
||||
return new SongEntryViewModel(
|
||||
Path.Combine("Music", "A.mp3"),
|
||||
"Artist",
|
||||
"Title",
|
||||
"Live",
|
||||
RenameFormat.ArtistFirst);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace SongTidy.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Finds supported audio files in a single folder.
|
||||
/// </summary>
|
||||
public static class AudioFileScanner {
|
||||
private static readonly HashSet<string> s_audioExtensions = new(StringComparer.OrdinalIgnoreCase) {
|
||||
".mp3",
|
||||
".flac",
|
||||
".wav",
|
||||
".ogg",
|
||||
".m4a",
|
||||
".aac",
|
||||
".wma",
|
||||
".opus",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Scans one folder without searching its subfolders.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The folder to scan.</param>
|
||||
/// <returns>The full paths of matching audio files, sorted by path.</returns>
|
||||
public static IReadOnlyList<string> Scan(string folderPath) {
|
||||
string fullFolderPath = Path.GetFullPath(folderPath);
|
||||
|
||||
return Directory
|
||||
.EnumerateFiles(fullFolderPath, "*", SearchOption.TopDirectoryOnly)
|
||||
.Where(filePath => s_audioExtensions.Contains(Path.GetExtension(filePath)))
|
||||
.OrderBy(filePath => filePath, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
using SongTidy.Models;
|
||||
|
||||
namespace SongTidy.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Identifies the category of a rename validation problem.
|
||||
/// </summary>
|
||||
public enum RenameValidationProblem {
|
||||
/// <summary>
|
||||
/// The title is empty or contains only whitespace.
|
||||
/// </summary>
|
||||
EmptyTitle,
|
||||
|
||||
/// <summary>
|
||||
/// An editable field contains a character that cannot appear in a file name.
|
||||
/// </summary>
|
||||
InvalidFieldCharacter,
|
||||
|
||||
/// <summary>
|
||||
/// The generated target name ends with a dot or a space.
|
||||
/// </summary>
|
||||
InvalidTargetEnding,
|
||||
|
||||
/// <summary>
|
||||
/// The source file no longer exists.
|
||||
/// </summary>
|
||||
MissingSourceFile,
|
||||
|
||||
/// <summary>
|
||||
/// The same source path appears more than once.
|
||||
/// </summary>
|
||||
DuplicateSourcePath,
|
||||
|
||||
/// <summary>
|
||||
/// Multiple entries generate the same target path.
|
||||
/// </summary>
|
||||
DuplicateTargetName,
|
||||
|
||||
/// <summary>
|
||||
/// The target path already exists on disk under a different source path.
|
||||
/// </summary>
|
||||
TargetFileConflict,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents one validation problem associated with a plan row.
|
||||
/// </summary>
|
||||
/// <param name="RowNumber">The one-based row number of the affected entry.</param>
|
||||
/// <param name="Problem">The problem category.</param>
|
||||
/// <param name="Message">The user-facing reason for the problem.</param>
|
||||
public sealed record RenameValidationIssue(int RowNumber, RenameValidationProblem Problem, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// Contains the complete result of a rename validation pass.
|
||||
/// </summary>
|
||||
/// <param name="Issues">All problems found during validation.</param>
|
||||
public sealed record RenameValidationResult(IReadOnlyList<RenameValidationIssue> Issues) {
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether validation found no problems.
|
||||
/// </summary>
|
||||
public bool IsValid => Issues.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates that a set of plan entries can be renamed without conflicts.
|
||||
/// </summary>
|
||||
public static class RenameValidator {
|
||||
#region Public API
|
||||
|
||||
/// <summary>
|
||||
/// Validates all entries and returns every problem found.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to validate.</param>
|
||||
/// <param name="format">The naming format used to generate target names.</param>
|
||||
/// <returns>All validation problems, or an empty result when renaming can proceed.</returns>
|
||||
public static RenameValidationResult Validate(IReadOnlyList<PlanItem> items, RenameFormat format) {
|
||||
List<RenameValidationIssue> issues = new();
|
||||
List<EntryTarget> targets = CreateTargets(items, format);
|
||||
|
||||
// Check rules that apply to each entry independently.
|
||||
AddEntryIssues(items, targets, issues);
|
||||
|
||||
// Check rules that require comparing entries with each other or with the file system.
|
||||
AddDuplicateSourceIssues(items, issues);
|
||||
AddDuplicateTargetIssues(targets, issues);
|
||||
AddDiskConflictIssues(items, targets, issues);
|
||||
|
||||
// Present problems in row order so the report reads naturally.
|
||||
issues.Sort(static (left, right) => left.RowNumber.CompareTo(right.RowNumber));
|
||||
|
||||
return new RenameValidationResult(issues);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Target generation
|
||||
|
||||
/// <summary>
|
||||
/// Generates target names and full target paths for every entry.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to process.</param>
|
||||
/// <param name="format">The naming format to apply.</param>
|
||||
/// <returns>The generated targets in entry order.</returns>
|
||||
private static List<EntryTarget> CreateTargets(IReadOnlyList<PlanItem> items, RenameFormat format) {
|
||||
List<EntryTarget> targets = new(items.Count);
|
||||
|
||||
for (int index = 0; index < items.Count; index++) {
|
||||
PlanItem item = items[index];
|
||||
string fileName = RenameFormats.GenerateStem(format, item.Artist, item.Title, item.Comment)
|
||||
+ Path.GetExtension(item.Path);
|
||||
string directory = Path.GetDirectoryName(item.Path) ?? string.Empty;
|
||||
string path = Path.Combine(directory, fileName);
|
||||
|
||||
targets.Add(new EntryTarget(index + 1, fileName, path));
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Per-entry validation
|
||||
|
||||
/// <summary>
|
||||
/// Checks the rules that can be evaluated for one entry at a time.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to validate.</param>
|
||||
/// <param name="targets">The generated targets in entry order.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddEntryIssues(
|
||||
IReadOnlyList<PlanItem> items,
|
||||
List<EntryTarget> targets,
|
||||
List<RenameValidationIssue> issues) {
|
||||
for (int index = 0; index < items.Count; index++) {
|
||||
PlanItem item = items[index];
|
||||
EntryTarget target = targets[index];
|
||||
int rowNumber = target.RowNumber;
|
||||
|
||||
// The title is mandatory.
|
||||
if (string.IsNullOrWhiteSpace(item.Title)) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
rowNumber,
|
||||
RenameValidationProblem.EmptyTitle,
|
||||
"The title is empty."));
|
||||
}
|
||||
|
||||
AddInvalidCharacterIssues(item, rowNumber, issues);
|
||||
|
||||
// Windows cannot create names that end with a dot or a space.
|
||||
if (target.FileName.EndsWith('.') || target.FileName.EndsWith(' ')) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
rowNumber,
|
||||
RenameValidationProblem.InvalidTargetEnding,
|
||||
"The target file name cannot end with a dot or a space."));
|
||||
}
|
||||
|
||||
// The source file must still exist when the user confirms renaming.
|
||||
if (!File.Exists(item.Path)) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
rowNumber,
|
||||
RenameValidationProblem.MissingSourceFile,
|
||||
"The source file does not exist."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks all editable fields for characters that cannot appear in a file name.
|
||||
/// </summary>
|
||||
/// <param name="item">The entry to inspect.</param>
|
||||
/// <param name="rowNumber">The one-based row number.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddInvalidCharacterIssues(
|
||||
PlanItem item,
|
||||
int rowNumber,
|
||||
List<RenameValidationIssue> issues) {
|
||||
AddFieldCharacterIssue(item.Artist, "Artist", rowNumber, issues);
|
||||
AddFieldCharacterIssue(item.Title, "Title", rowNumber, issues);
|
||||
AddFieldCharacterIssue(item.Comment, "Comment", rowNumber, issues);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds one issue when a field contains an invalid file name character.
|
||||
/// </summary>
|
||||
/// <param name="value">The field value to inspect.</param>
|
||||
/// <param name="fieldName">The localized field name used in the message.</param>
|
||||
/// <param name="rowNumber">The one-based row number.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddFieldCharacterIssue(
|
||||
string value,
|
||||
string fieldName,
|
||||
int rowNumber,
|
||||
List<RenameValidationIssue> issues) {
|
||||
foreach (char character in value) {
|
||||
if (IsInvalidFileNameCharacter(character)) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
rowNumber,
|
||||
RenameValidationProblem.InvalidFieldCharacter,
|
||||
$"{fieldName} contains a character that is not allowed in a file name."));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a character is forbidden in a Windows file name.
|
||||
/// </summary>
|
||||
/// <param name="character">The character to inspect.</param>
|
||||
/// <returns><see langword="true"/> when the character is invalid.</returns>
|
||||
private static bool IsInvalidFileNameCharacter(char character) {
|
||||
return char.IsControl(character)
|
||||
|| character is '\\' or '/' or ':' or '*' or '?' or '"' or '<' or '>' or '|';
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Conflict validation
|
||||
|
||||
/// <summary>
|
||||
/// Adds issues for source paths that appear more than once.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to inspect.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddDuplicateSourceIssues(
|
||||
IReadOnlyList<PlanItem> items,
|
||||
List<RenameValidationIssue> issues) {
|
||||
Dictionary<string, List<int>> rowsByPath = new(StringComparer.Ordinal);
|
||||
|
||||
// Group rows by exact source path; comparison is intentionally case-sensitive.
|
||||
for (int index = 0; index < items.Count; index++) {
|
||||
string path = items[index].Path;
|
||||
|
||||
if (!rowsByPath.TryGetValue(path, out List<int>? rows)) {
|
||||
rows = new List<int>();
|
||||
rowsByPath.Add(path, rows);
|
||||
}
|
||||
|
||||
rows.Add(index + 1);
|
||||
}
|
||||
|
||||
// Report every row that participates in a duplicate group.
|
||||
foreach (List<int> rows in rowsByPath.Values) {
|
||||
if (rows.Count < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (int rowNumber in rows) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
rowNumber,
|
||||
RenameValidationProblem.DuplicateSourcePath,
|
||||
"The source path duplicates another entry in the list."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds issues for entries that generate the same target path.
|
||||
/// </summary>
|
||||
/// <param name="targets">The generated targets to inspect.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddDuplicateTargetIssues(
|
||||
List<EntryTarget> targets,
|
||||
List<RenameValidationIssue> issues) {
|
||||
Dictionary<string, List<EntryTarget>> groups = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// Group entries by full target path; file systems treat casing as equivalent.
|
||||
foreach (EntryTarget target in targets) {
|
||||
if (!groups.TryGetValue(target.Path, out List<EntryTarget>? group)) {
|
||||
group = new List<EntryTarget>();
|
||||
groups.Add(target.Path, group);
|
||||
}
|
||||
|
||||
group.Add(target);
|
||||
}
|
||||
|
||||
// Report every entry that participates in a duplicate target group.
|
||||
foreach (List<EntryTarget> group in groups.Values) {
|
||||
if (group.Count < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (EntryTarget target in group) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
target.RowNumber,
|
||||
RenameValidationProblem.DuplicateTargetName,
|
||||
$"The target file name duplicates another entry: {target.FileName}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds issues for targets that already exist under a different source path.
|
||||
/// </summary>
|
||||
/// <param name="items">The entries to inspect.</param>
|
||||
/// <param name="targets">The generated targets in entry order.</param>
|
||||
/// <param name="issues">The issue collection to append to.</param>
|
||||
private static void AddDiskConflictIssues(
|
||||
IReadOnlyList<PlanItem> items,
|
||||
List<EntryTarget> targets,
|
||||
List<RenameValidationIssue> issues) {
|
||||
for (int index = 0; index < items.Count; index++) {
|
||||
PlanItem item = items[index];
|
||||
EntryTarget target = targets[index];
|
||||
|
||||
// Renaming a file to itself is not a conflict, even when only casing changes.
|
||||
if (string.Equals(target.Path, item.Path, StringComparison.OrdinalIgnoreCase)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Any other existing target would be overwritten or would block the rename.
|
||||
if (File.Exists(target.Path)) {
|
||||
issues.Add(new RenameValidationIssue(
|
||||
target.RowNumber,
|
||||
RenameValidationProblem.TargetFileConflict,
|
||||
$"The target file already exists: {target.FileName}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Nested types
|
||||
|
||||
/// <summary>
|
||||
/// Represents a generated target name for one plan entry.
|
||||
/// </summary>
|
||||
/// <param name="RowNumber">The one-based row number of the entry.</param>
|
||||
/// <param name="FileName">The target file name including its original extension.</param>
|
||||
/// <param name="Path">The full target path in the source directory.</param>
|
||||
private sealed record EntryTarget(int RowNumber, string FileName, string Path);
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,11 +1,381 @@
|
||||
namespace SongTidy.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
using System.IO;
|
||||
using System.Reactive;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
using ReactiveUI;
|
||||
|
||||
using SongTidy.Models;
|
||||
using SongTidy.Services;
|
||||
|
||||
namespace SongTidy.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the state and commands of the main application window.
|
||||
/// Represents the state and operations of the main application window.
|
||||
/// </summary>
|
||||
public class MainWindowViewModel : ViewModelBase {
|
||||
public sealed class MainWindowViewModel : ViewModelBase {
|
||||
#region Fields
|
||||
|
||||
private readonly ObservableCollection<SongEntryViewModel> _entries = new();
|
||||
private readonly HashSet<string> _paths = new(StringComparer.Ordinal);
|
||||
private readonly ObservableAsPropertyHelper<int> _entryCount;
|
||||
private RenameFormat _selectedFormat = RenameFormat.ArtistFirst;
|
||||
private string? _planPath;
|
||||
private bool _isDirty;
|
||||
private bool _suppressDirty;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Gets a temporary greeting displayed by the template view.
|
||||
/// Creates the main window view model.
|
||||
/// </summary>
|
||||
public string Greeting { get; } = "Welcome to Avalonia!";
|
||||
public MainWindowViewModel() {
|
||||
Entries = new ReadOnlyObservableCollection<SongEntryViewModel>(_entries);
|
||||
|
||||
// Keep the information-bar count synchronized with the entry collection.
|
||||
_entryCount = Observable
|
||||
.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
|
||||
handler => _entries.CollectionChanged += handler,
|
||||
handler => _entries.CollectionChanged -= handler)
|
||||
.Select(_ => _entries.Count)
|
||||
.StartWith(_entries.Count)
|
||||
.ToProperty(this, x => x.EntryCount);
|
||||
|
||||
_entries.CollectionChanged += OnEntriesCollectionChanged;
|
||||
|
||||
AddFilesCommand = ReactiveCommand.Create<IReadOnlyList<string>>(paths => AddFiles(paths));
|
||||
ScanFolderCommand = ReactiveCommand.Create<string>(AddFilesFromFolder);
|
||||
LoadPlanCommand = ReactiveCommand.Create<string>(LoadPlan);
|
||||
SavePlanCommand = ReactiveCommand.Create<string>(filePath => SavePlan(filePath));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Document state
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only collection of song entries.
|
||||
/// </summary>
|
||||
public ReadOnlyObservableCollection<SongEntryViewModel> Entries { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of entries in the current plan.
|
||||
/// </summary>
|
||||
public int EntryCount => _entryCount.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the naming format used for target previews and saving.
|
||||
/// </summary>
|
||||
public RenameFormat SelectedFormat {
|
||||
get => _selectedFormat;
|
||||
set {
|
||||
if (_selectedFormat == value) {
|
||||
return;
|
||||
}
|
||||
|
||||
_selectedFormat = value;
|
||||
this.RaisePropertyChanged(nameof(SelectedFormat));
|
||||
|
||||
// Refresh every row preview when the format changes.
|
||||
foreach (SongEntryViewModel entry in _entries) {
|
||||
entry.Format = value;
|
||||
}
|
||||
|
||||
MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the current plan file, or <see langword="null"/> when the plan has not been saved.
|
||||
/// </summary>
|
||||
public string? PlanPath {
|
||||
get => _planPath;
|
||||
private set {
|
||||
if (_planPath == value) {
|
||||
return;
|
||||
}
|
||||
|
||||
_planPath = value;
|
||||
this.RaisePropertyChanged(nameof(PlanPath));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the current plan has unsaved changes.
|
||||
/// </summary>
|
||||
public bool IsDirty {
|
||||
get => _isDirty;
|
||||
private set {
|
||||
if (_isDirty == value) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isDirty = value;
|
||||
this.RaisePropertyChanged(nameof(IsDirty));
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Commands
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command that adds selected file paths to the plan.
|
||||
/// </summary>
|
||||
public ReactiveCommand<IReadOnlyList<string>, Unit> AddFilesCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command that scans a folder and adds its audio files.
|
||||
/// </summary>
|
||||
public ReactiveCommand<string, Unit> ScanFolderCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command that loads a plan from the supplied path.
|
||||
/// </summary>
|
||||
public ReactiveCommand<string, Unit> LoadPlanCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command that saves the plan to the supplied path.
|
||||
/// </summary>
|
||||
public ReactiveCommand<string, Unit> SavePlanCommand { get; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Input
|
||||
|
||||
/// <summary>
|
||||
/// Parses and appends files that are not already present in the plan.
|
||||
/// </summary>
|
||||
/// <param name="filePaths">The source file paths to add.</param>
|
||||
public void AddFiles(IEnumerable<string> filePaths) {
|
||||
foreach (string filePath in filePaths) {
|
||||
// Duplicate paths keep the existing row and all of its edits.
|
||||
if (ContainsPath(filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
|
||||
FilenameParseResult parsed = FilenameParser.Parse(fileNameWithoutExtension);
|
||||
AddEntry(filePath, parsed.Artist, parsed.Title, parsed.Comment, SelectedFormat);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans one folder and appends its supported audio files.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The folder to scan.</param>
|
||||
public void AddFilesFromFolder(string folderPath) {
|
||||
AddFiles(AudioFileScanner.Scan(folderPath));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Plan operations
|
||||
|
||||
/// <summary>
|
||||
/// Saves the plan to its current path when one exists.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the plan had a path and was saved.</returns>
|
||||
public bool SavePlan() {
|
||||
if (PlanPath is null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
SavePlan(PlanPath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the plan to the supplied path and clears the dirty state.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The destination plan file path.</param>
|
||||
public void SavePlan(string filePath) {
|
||||
SongPlan plan = CreatePlan();
|
||||
PlanXmlIO.Save(plan, filePath);
|
||||
|
||||
PlanPath = filePath;
|
||||
MarkClean();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a plan from the supplied path and replaces the current document.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The source plan file path.</param>
|
||||
public void LoadPlan(string filePath) {
|
||||
SongPlan plan = PlanXmlIO.Load(filePath);
|
||||
|
||||
// Replace the document without treating the replacement as user edits.
|
||||
_suppressDirty = true;
|
||||
try {
|
||||
ClearEntries();
|
||||
SelectedFormat = plan.Format;
|
||||
|
||||
foreach (PlanItem item in plan.Items) {
|
||||
AddEntry(item.Path, item.Artist, item.Title, item.Comment, plan.Format);
|
||||
}
|
||||
|
||||
PlanPath = filePath;
|
||||
} finally {
|
||||
_suppressDirty = false;
|
||||
}
|
||||
|
||||
MarkClean();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the current document and starts a new empty plan.
|
||||
/// </summary>
|
||||
public void NewPlan() {
|
||||
ClearDocument();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the current document and leaves an empty plan.
|
||||
/// </summary>
|
||||
public void ClosePlan() {
|
||||
ClearDocument();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a serializable plan from the current document state.
|
||||
/// </summary>
|
||||
/// <returns>The current plan.</returns>
|
||||
public SongPlan CreatePlan() {
|
||||
return new SongPlan {
|
||||
Version = SongPlan.CurrentVersion,
|
||||
Format = SelectedFormat,
|
||||
Items = CreatePlanItems(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates model entries from the current document state.
|
||||
/// </summary>
|
||||
/// <returns>The current entries as plan items.</returns>
|
||||
public List<PlanItem> CreatePlanItems() {
|
||||
List<PlanItem> items = new(_entries.Count);
|
||||
|
||||
foreach (SongEntryViewModel entry in _entries) {
|
||||
items.Add(new PlanItem {
|
||||
Path = entry.FilePath,
|
||||
Artist = entry.Artist,
|
||||
Title = entry.Title,
|
||||
Comment = entry.Comment,
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Validation
|
||||
|
||||
/// <summary>
|
||||
/// Validates the current document for renaming.
|
||||
/// </summary>
|
||||
/// <returns>All validation problems found.</returns>
|
||||
public RenameValidationResult ValidateRename() {
|
||||
return RenameValidator.Validate(CreatePlanItems(), SelectedFormat);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dirty tracking
|
||||
|
||||
/// <summary>
|
||||
/// Marks the document as dirty unless changes are currently suppressed.
|
||||
/// </summary>
|
||||
private void MarkDirty() {
|
||||
if (!_suppressDirty) {
|
||||
IsDirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the dirty state after loading, saving, or clearing the document.
|
||||
/// </summary>
|
||||
private void MarkClean() {
|
||||
IsDirty = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the document dirty when an entry field changes.
|
||||
/// </summary>
|
||||
/// <param name="sender">The entry that changed.</param>
|
||||
/// <param name="e">The event arguments.</param>
|
||||
private void OnEntryEdited(object? sender, EventArgs e) {
|
||||
MarkDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the document dirty when the entry collection changes.
|
||||
/// </summary>
|
||||
/// <param name="sender">The collection that changed.</param>
|
||||
/// <param name="e">The collection change arguments.</param>
|
||||
private void OnEntriesCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) {
|
||||
MarkDirty();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the supplied path is already present in the plan.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path to search for.</param>
|
||||
/// <returns><see langword="true"/> when an entry has the exact same path.</returns>
|
||||
private bool ContainsPath(string filePath) {
|
||||
return _paths.Contains(filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a row view model, subscribes to its edits, and appends it to the collection.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The source file path.</param>
|
||||
/// <param name="artist">The artist value.</param>
|
||||
/// <param name="title">The title value.</param>
|
||||
/// <param name="comment">The comment value.</param>
|
||||
/// <param name="format">The naming format used for the target preview.</param>
|
||||
private void AddEntry(string filePath, string artist, string title, string comment, RenameFormat format) {
|
||||
SongEntryViewModel entry = new(filePath, artist, title, comment, format);
|
||||
entry.Edited += OnEntryEdited;
|
||||
_entries.Add(entry);
|
||||
_paths.Add(filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes all entries and unsubscribes from their edit notifications.
|
||||
/// </summary>
|
||||
private void ClearEntries() {
|
||||
foreach (SongEntryViewModel entry in _entries) {
|
||||
entry.Edited -= OnEntryEdited;
|
||||
}
|
||||
|
||||
_entries.Clear();
|
||||
_paths.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the document state and resets the dirty flag.
|
||||
/// </summary>
|
||||
private void ClearDocument() {
|
||||
_suppressDirty = true;
|
||||
try {
|
||||
ClearEntries();
|
||||
PlanPath = null;
|
||||
} finally {
|
||||
_suppressDirty = false;
|
||||
}
|
||||
|
||||
MarkClean();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reactive;
|
||||
|
||||
using ReactiveUI;
|
||||
|
||||
using SongTidy.Models;
|
||||
|
||||
namespace SongTidy.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents one editable song entry row in the main window.
|
||||
/// </summary>
|
||||
public sealed class SongEntryViewModel : ViewModelBase {
|
||||
private readonly ObservableAsPropertyHelper<string> _targetFileName;
|
||||
private string _artist;
|
||||
private string _title;
|
||||
private string _comment;
|
||||
private RenameFormat _format;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a row view model for one source file.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The absolute source file path.</param>
|
||||
/// <param name="artist">The initial artist value.</param>
|
||||
/// <param name="title">The initial title value.</param>
|
||||
/// <param name="comment">The initial comment value.</param>
|
||||
/// <param name="format">The naming format used for the target preview.</param>
|
||||
public SongEntryViewModel(string filePath, string artist, string title, string comment, RenameFormat format) {
|
||||
FilePath = filePath;
|
||||
OriginalFileName = Path.GetFileName(filePath);
|
||||
_artist = artist;
|
||||
_title = title;
|
||||
_comment = comment;
|
||||
_format = format;
|
||||
|
||||
// Keep the target preview synchronized with every field that affects it.
|
||||
_targetFileName = this.WhenAnyValue(
|
||||
x => x.Artist,
|
||||
x => x.Title,
|
||||
x => x.Comment,
|
||||
x => x.Format,
|
||||
(artist, title, comment, format) => BuildTargetFileName(artist, title, comment, format))
|
||||
.ToProperty(this, x => x.TargetFileName);
|
||||
|
||||
SwapArtistAndTitleCommand = ReactiveCommand.Create(SwapArtistAndTitle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised when an editable field changes.
|
||||
/// </summary>
|
||||
public event EventHandler? Edited;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the absolute source file path.
|
||||
/// </summary>
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the original file name without its directory.
|
||||
/// </summary>
|
||||
public string OriginalFileName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the artist value.
|
||||
/// </summary>
|
||||
public string Artist {
|
||||
get => _artist;
|
||||
set {
|
||||
if (string.Equals(_artist, value, StringComparison.Ordinal)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.RaiseAndSetIfChanged(ref _artist, value);
|
||||
OnEdited();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the title value.
|
||||
/// </summary>
|
||||
public string Title {
|
||||
get => _title;
|
||||
set {
|
||||
if (string.Equals(_title, value, StringComparison.Ordinal)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.RaiseAndSetIfChanged(ref _title, value);
|
||||
OnEdited();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the comment value.
|
||||
/// </summary>
|
||||
public string Comment {
|
||||
get => _comment;
|
||||
set {
|
||||
if (string.Equals(_comment, value, StringComparison.Ordinal)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.RaiseAndSetIfChanged(ref _comment, value);
|
||||
OnEdited();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the naming format used for the target preview.
|
||||
/// </summary>
|
||||
public RenameFormat Format {
|
||||
get => _format;
|
||||
set => this.RaiseAndSetIfChanged(ref _format, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the target file name preview, including the original extension.
|
||||
/// </summary>
|
||||
public string TargetFileName => _targetFileName.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command that swaps the artist and title values.
|
||||
/// </summary>
|
||||
public ReactiveCommand<Unit, Unit> SwapArtistAndTitleCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Swaps the artist and title values.
|
||||
/// </summary>
|
||||
public void SwapArtistAndTitle() {
|
||||
string artist = Artist;
|
||||
Artist = Title;
|
||||
Title = artist;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the target file name preview from the supplied field values.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist value.</param>
|
||||
/// <param name="title">The title value.</param>
|
||||
/// <param name="comment">The comment value.</param>
|
||||
/// <param name="format">The naming format to apply.</param>
|
||||
/// <returns>The target file name, including the original extension.</returns>
|
||||
private string BuildTargetFileName(string artist, string title, string comment, RenameFormat format) {
|
||||
string stem = RenameFormats.GenerateStem(format, artist, title, comment);
|
||||
return stem + Path.GetExtension(FilePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the <see cref="Edited"/> event.
|
||||
/// </summary>
|
||||
private void OnEdited() {
|
||||
Edited?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,6 @@
|
||||
<vm:MainWindowViewModel/>
|
||||
</Design.DataContext>
|
||||
|
||||
<TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
<Grid />
|
||||
|
||||
</Window>
|
||||
Reference in new issue
Block a user