Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JetBrains Rider code cleanup #73

Merged
merged 8 commits into from
Nov 22, 2024
Merged
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
43 changes: 21 additions & 22 deletions src/CCVTAC.Console.Tests/ExtensionMethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ public sealed class ExtensionMethodTests
{
public sealed class ReplaceInvalidPathCharsTests
{
private const string _validBaseFileName = @"filename123あいうえお漢字!@#$%^()_+ ";
private const char _defaultReplaceWithChar = '_';
private const string ValidBaseFileName = "filename123あいうえお漢字!@#$%^()_+ ";
private const char DefaultReplaceWithChar = '_';

private static readonly char[] _pathInvalidChars = [
private static readonly char[] PathInvalidChars = [
Path.PathSeparator,
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar,
Expand All @@ -21,44 +21,43 @@ public sealed class ReplaceInvalidPathCharsTests
[Fact]
public void ReplaceInvalidPathChars_StringContainsInvalidPathChars_Fixes()
{
string badFileName = _validBaseFileName + new string(_pathInvalidChars);
string fixedPathName = badFileName.ReplaceInvalidPathChars(_defaultReplaceWithChar);
string expected = _validBaseFileName + new string(_defaultReplaceWithChar, _pathInvalidChars.Length);
string badFileName = ValidBaseFileName + new string(PathInvalidChars);
string fixedPathName = badFileName.ReplaceInvalidPathChars(DefaultReplaceWithChar);
string expected = ValidBaseFileName + new string(DefaultReplaceWithChar, PathInvalidChars.Length);
Assert.Equal(expected, fixedPathName);
}

[Fact]
public void ReplaceInvalidPathChars_StringContainsNoInvalidPathChars_DoesNotChange()
{
string goodFileName = _validBaseFileName;
string result = goodFileName.ReplaceInvalidPathChars(_defaultReplaceWithChar);
Assert.Equal(goodFileName, result);
string result = ValidBaseFileName.ReplaceInvalidPathChars(DefaultReplaceWithChar);
Assert.Equal(ValidBaseFileName, result);
}

[Fact]
public void ReplaceInvalidPathCharsIncludingCustom_StringContainsInvalidPathChars_Fixes()
{
char[] customInvalidChars = ['&', '&'];
string badFileName = _validBaseFileName + new string(customInvalidChars);
string fixedPathName = badFileName.ReplaceInvalidPathChars(_defaultReplaceWithChar, customInvalidChars);
string expected = _validBaseFileName + new string(_defaultReplaceWithChar, customInvalidChars.Length);
Assert.Equal(expected, fixedPathName);
var badFileName = ValidBaseFileName + new string(customInvalidChars);
var fixedPathName = badFileName.ReplaceInvalidPathChars(DefaultReplaceWithChar, customInvalidChars);
var expectedName = ValidBaseFileName + new string(DefaultReplaceWithChar, customInvalidChars.Length);
Assert.Equal(expectedName, fixedPathName);
}

[Fact]
public void ReplaceInvalidPathCharsIncludingCustom_StringContainsNoInvalidPathChars_DoesNotChange()
{
char[] customInvalidChars = ['&', '&'];
const string goodFileName = _validBaseFileName + "++";
string result = goodFileName.ReplaceInvalidPathChars(_defaultReplaceWithChar, customInvalidChars);
const string goodFileName = ValidBaseFileName + "++";
string result = goodFileName.ReplaceInvalidPathChars(DefaultReplaceWithChar, customInvalidChars);
Assert.Equal(goodFileName, result);
}

[Fact]
public void ReplaceInvalidPathChars_InvalidReplaceChar_ThrowsException()
{
const char knownInvalidChar = '/';
Assert.Throws<ArgumentException>(() => _validBaseFileName.ReplaceInvalidPathChars(knownInvalidChar));
Assert.Throws<ArgumentException>(() => ValidBaseFileName.ReplaceInvalidPathChars(knownInvalidChar));
}
}

Expand Down Expand Up @@ -153,7 +152,7 @@ public void HasText_WithText_ReturnsTrue()

public sealed class CaseInsensitiveContainsTests
{
private static readonly List<string> _celestialBodies =
private static readonly List<string> CelestialBodies =
["Moon", "Mercury", "Mars", "Jupiter", "Venus"];

[Fact]
Expand All @@ -167,39 +166,39 @@ public void CaseInsensitiveContains_EmptyCollection_ReturnsFalse()
[Fact]
public void CaseInsensitiveContains_SearchAllCapsInPopulatedCollection_ReturnsTrue()
{
List<string> collection = _celestialBodies;
List<string> collection = CelestialBodies;
var actual = collection.CaseInsensitiveContains("MOON");
Assert.True(actual);
}

[Fact]
public void CaseInsensitiveContains_SearchAllLowercaseInPopulatedCollection_ReturnsTrue()
{
List<string> collection = _celestialBodies;
List<string> collection = CelestialBodies;
var actual = collection.CaseInsensitiveContains("moon");
Assert.True(actual);
}

[Fact]
public void CaseInsensitiveContains_SearchExactInPopulatedCollection_ReturnsTrue()
{
List<string> collection = _celestialBodies;
List<string> collection = CelestialBodies;
var actual = collection.CaseInsensitiveContains("Moon");
Assert.True(actual);
}

[Fact]
public void CaseInsensitiveContains_SearchPartialInPopulatedCollection_ReturnsFalse()
{
List<string> collection = _celestialBodies;
List<string> collection = CelestialBodies;
var actual = collection.CaseInsensitiveContains("Mo");
Assert.False(actual);
}

[Fact]
public void CaseInsensitiveContains_SearchExactButDoubleWidthInPopulatedCollection_ReturnsFalse()
{
List<string> collection = _celestialBodies;
List<string> collection = CelestialBodies;
var actual = collection.CaseInsensitiveContains("Moon");
Assert.False(actual);
}
Expand Down
10 changes: 4 additions & 6 deletions src/CCVTAC.Console.Tests/InputHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void SingleCommandEntered_CorrectlyParsed()
[Fact]
public void MultipleDuplicateCommandsAndUrlsEntered_CorrectlyParsed()
{
const string combinedInput = "\\imageshttps://youtu.be/5OpuZHsPBhQ https://youtu.be/NT22EGxTuNw\\images https://youtu.be/5OpuZHsPBhQ";
const string combinedInput = @"\imageshttps://youtu.be/5OpuZHsPBhQ https://youtu.be/NT22EGxTuNw\images https://youtu.be/5OpuZHsPBhQ";
List<string> expected = ["\\images", "https://youtu.be/5OpuZHsPBhQ", "https://youtu.be/NT22EGxTuNw"];
var actual = InputHelper.SplitInput(combinedInput);
Assert.Equal(expected.Count, actual.Length);
Expand All @@ -62,18 +62,16 @@ public void MultipleDuplicateCommandsAndUrlsEntered_CorrectlyParsed()
[Fact]
public void EmptyInput_CorrectlyParsed()
{
string combinedInput = string.Empty;
List<string> expected = [];
var combinedInput = string.Empty;
var actual = InputHelper.SplitInput(combinedInput);
Assert.Equal(expected.Count, actual.Length);
Assert.Empty(actual);
}

[Fact]
public void InvalidInput_CorrectlyParsed()
{
const string combinedInput = "invalid";
List<string> expected = [];
var actual = InputHelper.SplitInput(combinedInput);
Assert.Equal(expected.Count, actual.Length);
Assert.Empty(actual);
}
}
2 changes: 1 addition & 1 deletion src/CCVTAC.Console/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal static class Commands
{ QuietModeToggles[0], "Toggles quiet mode for the current session only" },
{ UpdateAudioFormatPrefix, $"Followed by a supported audio format (e.g., {UpdateAudioFormatPrefix}m4a), changes the audio format for the current session only" },
{ UpdateAudioQualityPrefix, $"Followed by a supported audio quality (e.g., {UpdateAudioQualityPrefix}0), changes the audio quality for the current session only" },
{ $"{QuitOptions[0]} or {QuitOptions[1]}", "Quit the application" },
{ $"{QuitOptions[0]} or {QuitOptions[1]}", "Quit the application" }
};

private static string MakeCommand(string text)
Expand Down
4 changes: 2 additions & 2 deletions src/CCVTAC.Console/Downloading/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ internal static Result<MediaTypeWithUrls> WrapUrlInMediaType(string url)
var (exitCode, warnings) = downloadResult.Value;
if (exitCode != 0)
{
printer.Warning($"Downloading completed with minor issues.");
printer.Warning("Downloading completed with minor issues.");
if (warnings.HasText())
{
printer.Warning(warnings);
Expand Down Expand Up @@ -153,7 +153,7 @@ private static string GenerateDownloadArgs(
"--write-thumbnail --convert-thumbnails jpg", // For album art
writeJson, // Contains metadata
trimFileNames,
"--retries 2", // Default is 10, which seems like overkill
"--retries 2" // Default is 10, which seems like overkill
]
};

Expand Down
7 changes: 4 additions & 3 deletions src/CCVTAC.Console/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,12 @@ public static string ReplaceInvalidPathChars(
{
var invalidChars = Path.GetInvalidFileNameChars()
.Concat(Path.GetInvalidPathChars())
.Concat(new [] {
.Concat([
Path.PathSeparator,
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar,
Path.VolumeSeparatorChar })
Path.VolumeSeparatorChar
])
.Concat(customInvalidChars ?? Enumerable.Empty<char>())
.ToFrozenSet();

Expand All @@ -62,7 +63,7 @@ public static string ReplaceInvalidPathChars(
return invalidChars.Aggregate(
new StringBuilder(sourceText),
(workingText, ch) => workingText.Replace(ch, replaceWith),
(workingText) => workingText.ToString()
workingText => workingText.ToString()
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/CCVTAC.Console/ExternalTools/ExternalTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ internal Result ProgramExists()
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
CreateNoWindow = true
};

try
{
using Process? process = Process.Start(processStartInfo);
using var process = Process.Start(processStartInfo);

if (process is null)
{
Expand Down
8 changes: 4 additions & 4 deletions src/CCVTAC.Console/History.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ namespace CCVTAC.Console;
public class History
{
private const char Separator = ';';
private string FilePath { get; init; }
private byte DisplayCount { get; init; }
private string FilePath { get; }
private byte DisplayCount { get; }

public History(string filePath, byte displayCount)
{
Expand All @@ -34,7 +34,7 @@ public void Append(string url, DateTime entryTime, Printer printer)
}
catch (Exception ex)
{
printer.Error($"Could not append URL(s) to history log: " + ex.Message);
printer.Error("Could not append URL(s) to history log: " + ex.Message);
}
}

Expand Down Expand Up @@ -62,7 +62,7 @@ public void ShowRecent(Printer printer)
table.AddRow(formattedTime, urls);
}

printer.PrintTable(table);
Printer.PrintTable(table);
}
catch (Exception ex)
{
Expand Down
8 changes: 4 additions & 4 deletions src/CCVTAC.Console/Orchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal static void Start(UserSettings settings, Printer printer)
else
{
printer.FirstError(deleteResult);
printer.Info($"Aborting...");
printer.Info("Aborting...");
return;
}
}
Expand Down Expand Up @@ -206,7 +206,7 @@ private static Result<NextAction> ProcessCommand(
table.AddRow(cmd, description);
}

printer.PrintTable(table);
Printer.PrintTable(table);
return Result.Ok(NextAction.Continue);
}

Expand Down Expand Up @@ -334,7 +334,7 @@ private static void SummarizeInput(
{
printer.Info($" • {input.Text}");
}
printer.EmptyLines(1);
Printer.EmptyLines(1);
}
}

Expand Down Expand Up @@ -375,6 +375,6 @@ private enum NextAction : byte
/// <summary>
/// Program execution should end due to an inability to continue.
/// </summary>
QuitDueToErrors,
QuitDueToErrors
}
}
8 changes: 4 additions & 4 deletions src/CCVTAC.Console/PostProcessing/Mover.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ namespace CCVTAC.Console.PostProcessing;

internal static class Mover
{
private static readonly Regex _playlistImageRegex = new(@"\[[OP]L[\w\d_-]{12,}\]");
private const string _imageFileWildcard = "*.jp*";
private static readonly Regex PlaylistImageRegex = new(@"\[[OP]L[\w\d_-]{12,}\]");
private const string ImageFileWildcard = "*.jp*";

internal static void Run(
IEnumerable<TaggingSet> taggingSets,
Expand Down Expand Up @@ -69,12 +69,12 @@ internal static void Run(

private static bool IsPlaylistImage(string fileName)
{
return _playlistImageRegex.IsMatch(fileName);
return PlaylistImageRegex.IsMatch(fileName);
}

private static FileInfo? GetCoverImage(DirectoryInfo workingDirInfo, int audioFileCount)
{
var images = workingDirInfo.EnumerateFiles(_imageFileWildcard).ToImmutableArray();
var images = workingDirInfo.EnumerateFiles(ImageFileWildcard).ToImmutableArray();
if (images.IsEmpty)
{
return null;
Expand Down
2 changes: 1 addition & 1 deletion src/CCVTAC.Console/PostProcessing/Tagging/TagDetector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace CCVTAC.Console.PostProcessing.Tagging;
/// </summary>
internal sealed class TagDetector
{
private TagDetectionPatterns Patterns { get; init;}
private TagDetectionPatterns Patterns { get; }

internal TagDetector(TagDetectionPatterns tagDetectionPatterns)
{
Expand Down
4 changes: 2 additions & 2 deletions src/CCVTAC.Console/PostProcessing/Tagging/Tagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ private static void ProcessSingleTaggingSet(
}
}

static void TagSingleFile(
private static void TagSingleFile(
UserSettings settings,
VideoMetadata videoData,
string audioFilePath,
string? imageFilePath,
CollectionMetadata? collectionData,
Printer printer)
{
string audioFileName = Path.GetFileName(audioFilePath);
var audioFileName = Path.GetFileName(audioFilePath);

printer.Debug($"Current audio file: \"{audioFileName}\"");

Expand Down
6 changes: 3 additions & 3 deletions src/CCVTAC.Console/PostProcessing/Tagging/TaggingSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal readonly record struct TaggingSet
/// The ID of a single video and perhaps its child videos (if "split chapters" was used).
/// Used to locate all the related files (whose filenames will contain the same ID).
/// </summary>
internal string ResourceId { get; init; }
internal string ResourceId { get; }

/// <summary>
/// All audio files for the associated resource ID. Several files with identical IDs indicates
Expand All @@ -28,12 +28,12 @@ internal readonly record struct TaggingSet
/// <summary>
/// The path to the JSON file containing metadata related to the source video.
/// </summary>
internal string JsonFilePath { get; init; }
internal string JsonFilePath { get; }

/// <summary>
/// The path to the image file containing the thumbnail related to the source video.
/// </summary>
internal string ImageFilePath { get; init; }
internal string ImageFilePath { get; }

internal IReadOnlyList<string> AllFiles => [..AudioFilePaths, JsonFilePath, ImageFilePath];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ private static string UploaderSummary(this VideoMetadata videoData)
/// </summary>
private static string FormattedUploadDate(this VideoMetadata videoData)
{
return $"{videoData.UploadDate[4..6]}/{videoData.UploadDate[6..8]}/{videoData.UploadDate[0..4]}";
return $"{videoData.UploadDate[4..6]}/{videoData.UploadDate[6..8]}/{videoData.UploadDate[..4]}";
}

/// <summary>
Expand Down
6 changes: 3 additions & 3 deletions src/CCVTAC.Console/Printer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void Print(
EmptyLines(appendLines);
}

public void PrintTable(Table table)
public static void PrintTable(Table table)
{
AnsiConsole.Write(table);
}
Expand Down Expand Up @@ -203,7 +203,7 @@ public void Debug(
/// Prints the requested number of blank lines.
/// </summary>
/// <param name="count"></param>
public void EmptyLines(byte count)
public static void EmptyLines(byte count)
{
if (count == 0)
return;
Expand All @@ -219,7 +219,7 @@ public string GetInput(string prompt)
return AnsiConsole.Ask<string>($"[skyblue1]{prompt}[/]");
}

private string Ask(string title, string[] options)
private static string Ask(string title, string[] options)
{
return AnsiConsole.Prompt(
new SelectionPrompt<string>()
Expand Down
Loading
Loading