From f7f40aa490c829692ba7ae11df771956756ac62e Mon Sep 17 00:00:00 2001 From: Paul Hebble <pjhebble@gmail.com> Date: Sun, 12 Nov 2023 17:55:04 -0600 Subject: [PATCH] More vscode suggestions --- .editorconfig | 51 ++++++++++ AutoUpdate/Main.cs | 4 +- AutoUpdate/SingleAssemblyResourceManager.cs | 7 +- Cmdline/Action/Available.cs | 1 - Cmdline/Action/Cache.cs | 13 +-- Cmdline/Action/Compat.cs | 2 + Cmdline/Action/Filter.cs | 2 + Cmdline/Action/GameInstance.cs | 6 +- Cmdline/Action/Install.cs | 2 +- Cmdline/Action/Mark.cs | 2 + Cmdline/Action/Remove.cs | 2 + Cmdline/Action/Repair.cs | 2 + Cmdline/Action/Replace.cs | 3 +- Cmdline/Action/Repo.cs | 6 +- Cmdline/Action/Search.cs | 36 +++---- Cmdline/ConsoleUser.cs | 10 +- Cmdline/Main.cs | 16 +-- Cmdline/Options.cs | 15 +-- Cmdline/ProgressReporter.cs | 1 - Cmdline/SingleAssemblyResourceManager.cs | 7 +- ConsoleUI/CompatibleVersionDialog.cs | 2 - ConsoleUI/DownloadImportDialog.cs | 1 - ConsoleUI/ExitScreen.cs | 6 +- ConsoleUI/GameInstanceAddScreen.cs | 11 +-- ConsoleUI/GameInstanceEditScreen.cs | 20 +--- ConsoleUI/InstallFilterAddDialog.cs | 7 -- ConsoleUI/ModInfoScreen.cs | 16 ++- ConsoleUI/ModListHelpDialog.cs | 4 +- ConsoleUI/ModListScreen.cs | 14 ++- ConsoleUI/Program.cs | 2 + ConsoleUI/RepoAddScreen.cs | 7 +- ConsoleUI/RepoEditScreen.cs | 13 +-- ConsoleUI/SingleAssemblyResourceManager.cs | 26 ++++- ConsoleUI/Toolkit/ConsoleButton.cs | 12 +-- ConsoleUI/Toolkit/ConsoleChoiceDialog.cs | 6 +- ConsoleUI/Toolkit/ConsoleDialog.cs | 1 - ConsoleUI/Toolkit/ConsoleDoubleFrame.cs | 10 +- ConsoleUI/Toolkit/ConsoleField.cs | 23 ++--- .../Toolkit/ConsoleFileMultiSelectDialog.cs | 67 ++++++------- ConsoleUI/Toolkit/ConsoleFrame.cs | 6 +- ConsoleUI/Toolkit/ConsoleLabel.cs | 18 +--- ConsoleUI/Toolkit/ConsoleListBox.cs | 85 ++++++---------- ConsoleUI/Toolkit/ConsoleMessageDialog.cs | 6 +- ConsoleUI/Toolkit/ConsolePopupMenu.cs | 33 +++---- ConsoleUI/Toolkit/ConsoleProgressBar.cs | 4 +- ConsoleUI/Toolkit/ConsoleScreen.cs | 6 +- ConsoleUI/Toolkit/ConsoleTextBox.cs | 30 +++--- ConsoleUI/Toolkit/Formatting.cs | 1 - ConsoleUI/Toolkit/Keys.cs | 68 ++++++------- ConsoleUI/Toolkit/ScreenContainer.cs | 37 +++---- ConsoleUI/Toolkit/ScreenObject.cs | 14 ++- Core/CKANPathUtils.cs | 12 +-- Core/CompatibleGameVersions.cs | 2 +- Core/Configuration/JsonConfiguration.cs | 23 +---- .../Win32RegistryConfiguration.cs | 19 ++-- Core/Converters/JsonIgnoreBadUrlConverter.cs | 7 +- .../Converters/JsonOldResourceUrlConverter.cs | 6 +- .../JsonPropertyNamesChangedConverter.cs | 12 +-- Core/Converters/JsonRelationshipConverter.cs | 8 +- .../DelimeterSeparatedValueExporter.cs | 74 ++++---------- Core/Extensions/CryptoExtensions.cs | 2 +- Core/Extensions/DictionaryExtensions.cs | 2 +- Core/Extensions/EnumerableExtensions.cs | 27 ++--- Core/Extensions/IOExtensions.cs | 2 +- Core/FileIdentifier.cs | 25 +---- Core/GameInstance.cs | 10 +- Core/GameInstanceManager.cs | 43 ++++---- Core/Games/KerbalSpaceProgram.cs | 12 +-- .../DLC/BreakingGroundDlcDetector.cs | 4 - .../KerbalSpaceProgram/DLC/IDlcDetector.cs | 1 - .../DLC/MakingHistoryDlcDetector.cs | 2 - .../DLC/StandardDlcDetectorBase.cs | 9 +- .../KspBuildIdVersionProvider.cs | 4 +- .../GameVersionProviders/KspBuildMap.cs | 29 +++--- .../KspReadmeVersionProvider.cs | 2 +- Core/Games/KerbalSpaceProgram2.cs | 8 +- Core/ModuleInstaller.cs | 7 +- Core/Net/AutoUpdate.cs | 11 +-- Core/Net/Net.cs | 10 +- Core/Net/NetAsyncDownloader.cs | 21 ++-- Core/Net/NetAsyncModulesDownloader.cs | 2 +- Core/Net/NetFileCache.cs | 60 +++++------- Core/Net/NetModuleCache.cs | 19 ++-- Core/Net/RedirectingTimeoutWebClient.cs | 9 +- Core/Platform.cs | 2 + Core/Registry/CompatibilitySorter.cs | 4 +- Core/Registry/IRegistryQuerier.cs | 10 +- Core/Registry/InstalledModule.cs | 4 +- Core/Registry/Registry.cs | 14 ++- Core/Registry/RegistryManager.cs | 20 ++-- Core/Relationships/RelationshipResolver.cs | 14 ++- Core/Relationships/SanityChecker.cs | 2 - Core/Repositories/AvailableModule.cs | 4 + Core/Repositories/ReadProgressStream.cs | 4 + Core/Repositories/Repository.cs | 2 +- Core/Repositories/RepositoryData.cs | 2 +- Core/Repositories/RepositoryDataManager.cs | 10 +- Core/Repositories/RepositoryList.cs | 2 +- Core/ServiceLocator.cs | 2 + Core/SingleAssemblyResourceManager.cs | 6 +- Core/SuppressedCompatWarningIdentifiers.cs | 2 +- Core/Types/CkanModule.cs | 58 +++++++---- .../GameComparator/GrasGameComparator.cs | 20 ++-- Core/Types/Kraken.cs | 9 +- Core/Types/License.cs | 6 +- Core/Types/ModuleInstallDescriptor.cs | 62 +++++++++--- Core/Types/ReleaseStatus.cs | 3 +- Core/Types/TimeLog.cs | 10 +- Core/User.cs | 5 +- Core/Versioning/GameVersion.cs | 98 ++++++++++++++++--- Core/Versioning/GameVersionBound.cs | 44 +++++++-- Core/Versioning/GameVersionCriteria.cs | 19 ++-- Core/Versioning/GameVersionRange.cs | 46 +++++++-- Core/Versioning/ModuleVersion.cs | 36 ++++++- Core/Versioning/ProvidesModuleVersion.cs | 4 +- Core/Versioning/UnmanagedModuleVersion.cs | 4 +- GUI/Controls/ChooseProvidedMods.cs | 8 +- GUI/Controls/ChooseRecommendedMods.cs | 3 +- GUI/Controls/DeleteDirectories.cs | 4 +- GUI/Controls/DropdownMenuButton.cs | 2 +- GUI/Controls/EditModSearch.cs | 4 +- GUI/Controls/EditModpack.cs | 28 +++--- GUI/Controls/InstallationHistory.cs | 8 +- GUI/Controls/LeftRightRowPanel.cs | 2 + GUI/Controls/ManageMods.cs | 84 +++++++++++----- GUI/Controls/ModInfo.cs | 8 +- GUI/Controls/ModInfoTabs/Metadata.cs | 2 +- GUI/Controls/ModInfoTabs/Relationships.cs | 2 +- GUI/Controls/TriStateToggle.cs | 15 ++- GUI/Controls/UnmanagedFiles.cs | 2 +- GUI/Controls/Wait.cs | 4 + GUI/Dialogs/CloneGameInstanceDialog.cs | 6 +- GUI/Dialogs/CompatibleGameVersionsDialog.cs | 6 +- GUI/Dialogs/DownloadsFailedDialog.cs | 6 +- GUI/Dialogs/EditLabelsDialog.cs | 6 +- GUI/Dialogs/ManageGameInstancesDialog.cs | 10 ++ GUI/Dialogs/SelectionDialog.cs | 8 +- GUI/Dialogs/SettingsDialog.cs | 20 ++-- GUI/Dialogs/YesNoDialog.cs | 2 +- GUI/Labels/ModuleLabel.cs | 1 - GUI/Labels/ModuleLabelList.cs | 1 - GUI/Main/Main.cs | 25 ++++- GUI/Main/MainDialogs.cs | 4 +- GUI/Main/MainDownload.cs | 2 + GUI/Main/MainHistory.cs | 2 - GUI/Main/MainRecommendations.cs | 1 - GUI/Model/GUIConfiguration.cs | 10 +- GUI/Model/GUIMod.cs | 29 ++++-- GUI/Model/ModChange.cs | 22 ++++- GUI/NavigationHistory.cs | 24 ++--- GUI/Plugins/PluginController.cs | 2 +- GUI/Program.cs | 2 +- GUI/SingleAssemblyComponentResourceManager.cs | 4 +- GUI/SingleAssemblyResourceManager.cs | 6 +- GUI/Util.cs | 26 +++-- GUI/X11.cs | 18 ++-- Netkan/ConsoleUser.cs | 14 +-- Netkan/Extensions/JObjectExtensions.cs | 4 +- Netkan/Extensions/VersionExtensions.cs | 13 +-- Netkan/Services/CachingHttpService.cs | 2 +- Netkan/Services/ModuleService.cs | 11 ++- Netkan/Sources/Avc/JsonAvcToGameVersion.cs | 18 ++-- Netkan/Sources/Curse/CurseApi.cs | 5 +- Netkan/Sources/Curse/CurseFile.cs | 12 ++- Netkan/Sources/Curse/CurseMod.cs | 16 +-- Netkan/Sources/Github/GithubReleaseAsset.cs | 6 +- Netkan/Sources/Jenkins/JenkinsApi.cs | 2 + Netkan/Sources/Jenkins/JenkinsOptions.cs | 4 +- .../Spacedock/JsonConvertFromRelativeSdUri.cs | 3 + Netkan/Sources/Spacedock/SDVersion.cs | 2 + Netkan/Transformers/AvcKrefTransformer.cs | 7 +- Netkan/Transformers/AvcTransformer.cs | 4 +- Netkan/Transformers/CurseTransformer.cs | 22 ++++- .../DownloadAttributeTransformer.cs | 2 +- Netkan/Transformers/EpochTransformer.cs | 4 +- Netkan/Transformers/ForcedVTransformer.cs | 2 +- Netkan/Transformers/GeneratedByTransformer.cs | 2 +- Netkan/Transformers/GithubTransformer.cs | 22 ++++- Netkan/Transformers/HttpTransformer.cs | 2 +- Netkan/Transformers/InstallSizeTransformer.cs | 2 +- .../Transformers/InternalCkanTransformer.cs | 2 +- Netkan/Transformers/JenkinsTransformer.cs | 2 +- .../Transformers/LocalizationsTransformer.cs | 2 +- Netkan/Transformers/MetaNetkanTransformer.cs | 7 +- Netkan/Transformers/NetkanTransformer.cs | 4 +- .../Transformers/OptimusPrimeTransformer.cs | 2 +- .../Transformers/PropertySortTransformer.cs | 2 +- .../Transformers/SpaceWarpInfoTransformer.cs | 1 - Netkan/Transformers/SpacedockTransformer.cs | 10 +- .../Transformers/StagingLinksTransformer.cs | 2 +- Netkan/Transformers/StagingTransformer.cs | 2 +- .../StripNetkanMetadataTransformer.cs | 25 ++--- Netkan/Transformers/VersionEditTransformer.cs | 2 +- .../VersionedOverrideTransformer.cs | 16 ++- Netkan/Validators/InstallValidator.cs | 4 +- Netkan/Validators/InstallsFilesValidator.cs | 2 +- Netkan/Validators/LicensesValidator.cs | 19 ++-- Netkan/Validators/PluginsValidator.cs | 1 - Tests/AutoUpdate/ResourcesTests.cs | 2 +- Tests/CapturingUser.cs | 4 +- Tests/CmdLine/ResourcesTests.cs | 2 +- Tests/ConsoleUI/ResourcesTests.cs | 2 +- Tests/Core/CKANPathUtils.cs | 88 ++++++++--------- Tests/Core/Cache.cs | 2 +- Tests/Core/Configuration/FakeConfiguration.cs | 2 + Tests/Core/Configuration/JsonConfiguration.cs | 66 ++++++------- Tests/Core/GameInstance.cs | 15 ++- Tests/Core/GameInstanceManager.cs | 8 +- Tests/Core/ModuleInstallerDirTest.cs | 36 +++---- Tests/Core/ModuleInstallerTests.cs | 98 +++++++++---------- Tests/Core/Net/AutoUpdateTests.cs | 6 +- Tests/Core/Net/Net.cs | 2 +- .../Net/NetAsyncModulesDownloaderTests.cs | 14 +-- Tests/Core/Registry/CompatibilitySorter.cs | 2 +- Tests/Core/Registry/Registry.cs | 10 +- Tests/Core/Registry/RegistryManager.cs | 5 +- .../Relationships/RelationshipResolver.cs | 4 +- Tests/Core/Relationships/SanityChecker.cs | 6 +- .../RepositoryDataManagerTests.cs | 4 +- Tests/Core/ResourcesTests.cs | 2 +- Tests/Core/Types/GameComparator.cs | 44 ++++----- Tests/Core/Types/RelationshipDescriptor.cs | 3 +- Tests/Core/Types/ReleaseStatus.cs | 5 +- Tests/Core/Utilities.cs | 4 +- Tests/Core/Versioning/KspVersionBoundTests.cs | 2 + Tests/Core/Versioning/KspVersionRangeTests.cs | 2 + Tests/Core/Versioning/KspVersionTests.cs | 8 +- Tests/Data/TestData.cs | 6 +- Tests/GUI/GUIConfiguration.cs | 2 +- Tests/GUI/Model/ModList.cs | 6 +- Tests/GUI/NavigationHistoryTests.cs | 7 +- Tests/GUI/ResourcesTests.cs | 2 +- Tests/GUI/ThreadSafetyTests.cs | 11 +-- Tests/NetKAN/MainClass.cs | 6 +- Tests/NetKAN/NetkanOverride.cs | 14 ++- .../Transformers/AvcKrefTransformerTests.cs | 2 +- .../Transformers/AvcTransformerTests.cs | 16 ++- .../Transformers/CurseTransformerTests.cs | 7 +- .../DownloadAttributeTransformerTests.cs | 3 +- .../GeneratedByTransformerTests.cs | 2 +- .../Transformers/HttpTransformerTests.cs | 2 +- .../InstallSizeTransformerTests.cs | 2 +- .../InternalCkanTransformerTests.cs | 2 +- .../MetaNetkanTransformerTests.cs | 2 +- .../Transformers/SpacedockTransformerTests.cs | 2 +- .../StripNetkanMetadataTransformerTests.cs | 4 +- .../VersionEditTransformerTests.cs | 2 +- Tests/Util.cs | 20 +++- 248 files changed, 1647 insertions(+), 1382 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..f7a664c935 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,51 @@ +[*.cs] +dotnet_analyzer_diagnostic.category-Style.severity = warning +dotnet_analyzer_diagnostic.category-CodeQuality.severity = warning + +# Using `var` is good +dotnet_diagnostic.IDE0008.severity = none + +# Don't need to enumerate every case for `switch` with `default` +dotnet_diagnostic.IDE0010.severity = none + +# Don't "simplify" if statements that throw +dotnet_diagnostic.IDE0016.severity = none + +# Expression bodies are good for methods +dotnet_diagnostic.IDE0022.severity = none + +# Expression bodies are fine for operators +dotnet_diagnostic.IDE0024.severity = none + +# Collection initialization simplification affects JObject, which is dumb +dotnet_diagnostic.IDE0028.severity = none + +# "auto" properties seem pretty useless +dotnet_diagnostic.IDE0032.severity = none + +# "local functions" are just weird, no thank you +dotnet_diagnostic.IDE0039.severity = none + +# "if" statements should only be "simplified" if they're pure functional, +# and these checks don't know that +dotnet_diagnostic.IDE0045.severity = none +dotnet_diagnostic.IDE0046.severity = none +dotnet_diagnostic.IDE0270.severity = none + +# We use "unnecessary" parentheses for clarity +dotnet_diagnostic.IDE0047.severity = none + +# Let me keep my extra spaces for aligning things +dotnet_diagnostic.IDE0055.severity = none + +# OK to call functions that return values and not use them +dotnet_diagnostic.IDE0058.severity = none + +# A `using` inside a namespace is useful as a typedef +dotnet_diagnostic.IDE0065.severity = none + +# Allow namespaces to be independent of folder names +dotnet_diagnostic.IDE0130.severity = none + +# Who cares if it's a JSON formatted string, in a test? +dotnet_diagnostic.JSON002.severity = none diff --git a/AutoUpdate/Main.cs b/AutoUpdate/Main.cs index 56e5b4667e..2d32697b02 100644 --- a/AutoUpdate/Main.cs +++ b/AutoUpdate/Main.cs @@ -123,7 +123,7 @@ private static void StartCKAN(string path) // Start CKAN if (IsOnMono()) { - Process.Start("mono", String.Format("\"{0}\"", path)); + Process.Start("mono", string.Format("\"{0}\"", path)); } else { @@ -171,7 +171,7 @@ private static bool IsOnWindows() /// </summary> /// <param name="sender">Source of unhandled exception</param> /// <param name="e">Info about the exception</param> - private static void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e) + private static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { ReportError(Properties.Resources.UnhandledException, e.ExceptionObject); } diff --git a/AutoUpdate/SingleAssemblyResourceManager.cs b/AutoUpdate/SingleAssemblyResourceManager.cs index 48f266d341..3ee0990a59 100644 --- a/AutoUpdate/SingleAssemblyResourceManager.cs +++ b/AutoUpdate/SingleAssemblyResourceManager.cs @@ -1,7 +1,6 @@ using System.IO; using System.Globalization; using System.Resources; -using System.Collections; using System.Reflection; using System.Collections.Generic; @@ -9,7 +8,7 @@ namespace CKAN.AutoUpdateHelper { // Thanks and credit to this guy: https://stackoverflow.com/q/1952638/2422988 - class SingleAssemblyResourceManager : ResourceManager + public class SingleAssemblyResourceManager : ResourceManager { public SingleAssemblyResourceManager(string basename, Assembly assembly) : base(basename, assembly) { @@ -23,7 +22,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -34,7 +33,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/Cmdline/Action/Available.cs b/Cmdline/Action/Available.cs index 969fccb449..5fdab4d305 100644 --- a/Cmdline/Action/Available.cs +++ b/Cmdline/Action/Available.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Collections.Generic; namespace CKAN.CmdLine { diff --git a/Cmdline/Action/Cache.cs b/Cmdline/Action/Cache.cs index a928222985..50332e5bf1 100644 --- a/Cmdline/Action/Cache.cs +++ b/Cmdline/Action/Cache.cs @@ -106,7 +106,9 @@ public int RunSubCommand(GameInstanceManager mgr, CommonOptions opts, SubCommand manager = mgr ?? new GameInstanceManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) + { return; + } switch (option) { @@ -214,14 +216,9 @@ private int ShowCacheSizeLimit() private int SetCacheSizeLimit(SetLimitOptions options) { IConfiguration cfg = ServiceLocator.Container.Resolve<IConfiguration>(); - if (options.Megabytes < 0) - { - cfg.CacheSizeLimit = null; - } - else - { - cfg.CacheSizeLimit = options.Megabytes * (long)1024 * (long)1024; - } + cfg.CacheSizeLimit = options.Megabytes < 0 + ? null : + (long?)(options.Megabytes * 1024 * 1024); return ShowCacheSizeLimit(); } diff --git a/Cmdline/Action/Compat.cs b/Cmdline/Action/Compat.cs index 7be08bc06e..734c3310f9 100644 --- a/Cmdline/Action/Compat.cs +++ b/Cmdline/Action/Compat.cs @@ -82,7 +82,9 @@ public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCom _kspManager = manager ?? new GameInstanceManager(_user); exitCode = comOpts.Handle(_kspManager, _user); if (exitCode != Exit.OK) + { return; + } switch (option) { diff --git a/Cmdline/Action/Filter.cs b/Cmdline/Action/Filter.cs index 9cab436414..3c8ed92688 100644 --- a/Cmdline/Action/Filter.cs +++ b/Cmdline/Action/Filter.cs @@ -42,7 +42,9 @@ public int RunSubCommand(GameInstanceManager mgr, CommonOptions opts, SubCommand manager = mgr ?? new GameInstanceManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) + { return; + } switch (option) { diff --git a/Cmdline/Action/GameInstance.cs b/Cmdline/Action/GameInstance.cs index 328abfb408..849d954703 100644 --- a/Cmdline/Action/GameInstance.cs +++ b/Cmdline/Action/GameInstance.cs @@ -179,7 +179,9 @@ public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCom Manager = manager ?? new GameInstanceManager(User); exitCode = options.Handle(Manager, User); if (exitCode != Exit.OK) + { return; + } switch (option) { @@ -461,7 +463,7 @@ private int SetDefaultInstall(DefaultOptions options) string defaultInstance = Manager.Configuration.AutoStartInstance; int defaultInstancePresent = 0; - if (!String.IsNullOrWhiteSpace(defaultInstance)) + if (!string.IsNullOrWhiteSpace(defaultInstance)) { defaultInstancePresent = 1; } @@ -477,7 +479,7 @@ private int SetDefaultInstall(DefaultOptions options) } // Mark the default instance for the user. - if (!String.IsNullOrWhiteSpace(defaultInstance)) + if (!string.IsNullOrWhiteSpace(defaultInstance)) { keys[0] = Manager.Instances.IndexOfKey(defaultInstance); } diff --git a/Cmdline/Action/Install.cs b/Cmdline/Action/Install.cs index 6338bb9440..81b76ef5ef 100644 --- a/Cmdline/Action/Install.cs +++ b/Cmdline/Action/Install.cs @@ -61,7 +61,7 @@ public int RunCommand(CKAN.GameInstance instance, object raw_options) ckan_uri = new Uri(ckan_file); } - string filename = String.Empty; + string filename = string.Empty; // If it is a local file, we already know the filename. If it is remote, create a temporary file and download the remote resource. if (ckan_uri.IsFile) diff --git a/Cmdline/Action/Mark.cs b/Cmdline/Action/Mark.cs index aff716bce4..ead13ffc37 100644 --- a/Cmdline/Action/Mark.cs +++ b/Cmdline/Action/Mark.cs @@ -44,7 +44,9 @@ public int RunSubCommand(GameInstanceManager mgr, CommonOptions opts, SubCommand manager = mgr ?? new GameInstanceManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) + { return; + } switch (option) { diff --git a/Cmdline/Action/Remove.cs b/Cmdline/Action/Remove.cs index f28a430fe1..e0634f3136 100644 --- a/Cmdline/Action/Remove.cs +++ b/Cmdline/Action/Remove.cs @@ -50,7 +50,9 @@ public int RunCommand(CKAN.GameInstance instance, object raw_options) foreach (string mod in regMgr.registry.InstalledModules.Select(mod => mod.identifier)) { if (justins.Any(re => re.IsMatch(mod))) + { selectedModules.Add(mod); + } } // Replace the regular expressions with the selected modules diff --git a/Cmdline/Action/Repair.cs b/Cmdline/Action/Repair.cs index 5eaaf32267..198f4dec6e 100644 --- a/Cmdline/Action/Repair.cs +++ b/Cmdline/Action/Repair.cs @@ -60,7 +60,9 @@ public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCom } exitCode = options.Handle(manager, User); if (exitCode != Exit.OK) + { return; + } switch (option) { diff --git a/Cmdline/Action/Replace.cs b/Cmdline/Action/Replace.cs index 5f89e7ffee..7032baa756 100644 --- a/Cmdline/Action/Replace.cs +++ b/Cmdline/Action/Replace.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; using log4net; using CKAN.Versioning; @@ -9,7 +8,7 @@ namespace CKAN.CmdLine { public class Replace : ICommand { - public Replace(CKAN.GameInstanceManager mgr, RepositoryDataManager repoData, IUser user) + public Replace(GameInstanceManager mgr, RepositoryDataManager repoData, IUser user) { manager = mgr; this.repoData = repoData; diff --git a/Cmdline/Action/Repo.cs b/Cmdline/Action/Repo.cs index 074a93d0f7..48dc18d075 100644 --- a/Cmdline/Action/Repo.cs +++ b/Cmdline/Action/Repo.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Net; using Newtonsoft.Json; using CommandLine; @@ -139,7 +137,9 @@ public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCom Manager = manager ?? new GameInstanceManager(User); exitCode = options.Handle(Manager, User); if (exitCode != Exit.OK) + { return; + } switch (option) { @@ -282,7 +282,7 @@ private int AddRepository(RepoAddOptions options) foreach (Repository candidate in repositoryList.repositories) { - if (String.Equals(candidate.name, options.name, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(candidate.name, options.name, StringComparison.OrdinalIgnoreCase)) { options.name = candidate.name; options.uri = candidate.uri.ToString(); diff --git a/Cmdline/Action/Search.cs b/Cmdline/Action/Search.cs index c71b96821e..59edd9912c 100644 --- a/Cmdline/Action/Search.cs +++ b/Cmdline/Action/Search.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using CKAN.Games; namespace CKAN.CmdLine { @@ -19,7 +18,7 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) SearchOptions options = (SearchOptions)raw_options; // Check the input. - if (String.IsNullOrWhiteSpace(options.search_term) && String.IsNullOrWhiteSpace(options.author_term)) + if (string.IsNullOrWhiteSpace(options.search_term) && string.IsNullOrWhiteSpace(options.author_term)) { user.RaiseError(Properties.Resources.SearchNoTerm); return Exit.BADOPT; @@ -33,7 +32,7 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) } // Show how many matches we have. - if (options.all && !String.IsNullOrWhiteSpace(options.author_term)) + if (options.all && !string.IsNullOrWhiteSpace(options.author_term)) { user.RaiseMessage(Properties.Resources.SearchFoundByAuthorWithIncompat, matching_compatible.Count().ToString(), @@ -41,21 +40,21 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) options.search_term, options.author_term); } - else if (options.all && String.IsNullOrWhiteSpace(options.author_term)) + else if (options.all && string.IsNullOrWhiteSpace(options.author_term)) { user.RaiseMessage(Properties.Resources.SearchFoundWithIncompat, matching_compatible.Count().ToString(), matching_incompatible.Count().ToString(), options.search_term); } - else if (!options.all && !String.IsNullOrWhiteSpace(options.author_term)) + else if (!options.all && !string.IsNullOrWhiteSpace(options.author_term)) { user.RaiseMessage(Properties.Resources.SearchFoundByAuthor, matching_compatible.Count().ToString(), options.search_term, options.author_term); } - else if (!options.all && String.IsNullOrWhiteSpace(options.author_term)) + else if (!options.all && string.IsNullOrWhiteSpace(options.author_term)) { user.RaiseMessage(Properties.Resources.SearchFound, matching_compatible.Count().ToString(), @@ -77,7 +76,7 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) mod.identifier, mod.version, mod.name, - mod.author == null ? "N/A" : String.Join(", ", mod.author), + mod.author == null ? "N/A" : string.Join(", ", mod.author), mod.@abstract); } @@ -94,7 +93,7 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) mod.version, GameVersion, mod.name, - mod.author == null ? "N/A" : String.Join(", ", mod.author), + mod.author == null ? "N/A" : string.Join(", ", mod.author), mod.@abstract); } } @@ -125,27 +124,23 @@ public int RunCommand(CKAN.GameInstance ksp, object raw_options) public List<CkanModule> PerformSearch(CKAN.GameInstance ksp, string term, string author = null, bool searchIncompatible = false) { // Remove spaces and special characters from the search term. - term = String.IsNullOrWhiteSpace(term) ? string.Empty : CkanModule.nonAlphaNums.Replace(term, ""); - author = String.IsNullOrWhiteSpace(author) ? string.Empty : CkanModule.nonAlphaNums.Replace(author, ""); + term = string.IsNullOrWhiteSpace(term) ? string.Empty : CkanModule.nonAlphaNums.Replace(term, ""); + author = string.IsNullOrWhiteSpace(author) ? string.Empty : CkanModule.nonAlphaNums.Replace(author, ""); var registry = RegistryManager.Instance(ksp, repoData).registry; - if (!searchIncompatible) - { - return registry - .CompatibleModules(ksp.VersionCriteria()) + return searchIncompatible + ? registry + .IncompatibleModules(ksp.VersionCriteria()) // Look for a match in each string. .Where(module => (module.SearchableName.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1 || module.SearchableIdentifier.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1 || module.SearchableAbstract.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1 || module.SearchableDescription.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) && module.SearchableAuthors.Any((auth) => auth.IndexOf(author, StringComparison.OrdinalIgnoreCase) > -1)) - .ToList(); - } - else - { - return registry - .IncompatibleModules(ksp.VersionCriteria()) + .ToList() + : registry + .CompatibleModules(ksp.VersionCriteria()) // Look for a match in each string. .Where(module => (module.SearchableName.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1 || module.SearchableIdentifier.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1 @@ -153,7 +148,6 @@ public List<CkanModule> PerformSearch(CKAN.GameInstance ksp, string term, string || module.SearchableDescription.IndexOf(term, StringComparison.OrdinalIgnoreCase) > -1) && module.SearchableAuthors.Any((auth) => auth.IndexOf(author, StringComparison.OrdinalIgnoreCase) > -1)) .ToList(); - } } /// <summary> diff --git a/Cmdline/ConsoleUser.cs b/Cmdline/ConsoleUser.cs index 8f2725b837..99373bdd06 100644 --- a/Cmdline/ConsoleUser.cs +++ b/Cmdline/ConsoleUser.cs @@ -93,7 +93,7 @@ public int RaiseSelectionDialog(string message, params object[] args) } // Validate input. - if (String.IsNullOrWhiteSpace(message)) + if (string.IsNullOrWhiteSpace(message)) { throw new Kraken("Passed message string must be non-empty."); } @@ -130,7 +130,7 @@ public int RaiseSelectionDialog(string message, params object[] args) // Further data validation. foreach (object argument in args) { - if (String.IsNullOrWhiteSpace(argument.ToString())) + if (string.IsNullOrWhiteSpace(argument.ToString())) { throw new Kraken("Candidate may not be empty."); } @@ -142,14 +142,14 @@ public int RaiseSelectionDialog(string message, params object[] args) // List options. for (int i = 0; i < args.Length; i++) { - string CurrentRow = String.Format("{0}", i + 1); + string CurrentRow = string.Format("{0}", i + 1); if (i == defaultSelection) { CurrentRow += "*"; } - CurrentRow += String.Format(") {0}", args[i]); + CurrentRow += string.Format(") {0}", args[i]); RaiseMessage(CurrentRow); } @@ -176,7 +176,7 @@ public int RaiseSelectionDialog(string message, params object[] args) input = input.Trim().ToLower(); // Check for default selection. - if (String.IsNullOrEmpty(input) && defaultSelection >= 0) + if (string.IsNullOrEmpty(input) && defaultSelection >= 0) { return defaultSelection; } diff --git a/Cmdline/Main.cs b/Cmdline/Main.cs index 22593eff5b..4767f8a7d0 100644 --- a/Cmdline/Main.cs +++ b/Cmdline/Main.cs @@ -6,11 +6,8 @@ using System; using System.Net; using System.Diagnostics; -using System.IO; using System.Linq; -using System.Reflection; using System.Runtime.InteropServices; -using System.Text.RegularExpressions; using Autofac; using log4net; @@ -154,7 +151,9 @@ public static int Execute(GameInstanceManager manager, CommonOptions opts, strin { int exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) + { return exitCode; + } // Don't bother with instances or registries yet because some commands don't need them. return RunSimpleAction(cmdline, options, args, user, manager); } @@ -293,7 +292,7 @@ private static int ConsoleUi(GameInstanceManager manager, ConsoleUIOptions opts) { // Debug/verbose output just messes up the screen LogManager.GetRepository().Threshold = Level.Warn; - return CKAN.ConsoleUI.ConsoleUI.Main_(manager, + return ConsoleUI.ConsoleUI.Main_(manager, opts.Theme ?? Environment.GetEnvironmentVariable("CKAN_CONSOLEUI_THEME") ?? "default", opts.Debug); } @@ -352,14 +351,7 @@ public NoGameInstanceKraken() { } public class CmdLineUtil { public static uint GetUID() - { - if (Platform.IsUnix || Platform.IsMac) - { - return getuid(); - } - - return 1; - } + => Platform.IsUnix || Platform.IsMac ? getuid() : 1; [DllImport("libc")] private static extern uint getuid(); diff --git a/Cmdline/Options.cs b/Cmdline/Options.cs index 11e89f0a52..6f676ee0ed 100644 --- a/Cmdline/Options.cs +++ b/Cmdline/Options.cs @@ -289,7 +289,10 @@ private static void CheckMonoVersion(IUser user, int rec_major, int rec_minor, i try { Type type = Type.GetType("Mono.Runtime"); - if (type == null) return; + if (type == null) + { + return; + } MethodInfo display_name = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (display_name != null) @@ -299,15 +302,15 @@ private static void CheckMonoVersion(IUser user, int rec_major, int rec_minor, i if (match.Success) { - int major = Int32.Parse(match.Groups["major"].Value); - int minor = Int32.Parse(match.Groups["minor"].Value); - int patch = Int32.Parse(match.Groups["revision"].Value); + int major = int.Parse(match.Groups["major"].Value); + int minor = int.Parse(match.Groups["minor"].Value); + int patch = int.Parse(match.Groups["revision"].Value); if (major < rec_major || (major == rec_major && minor < rec_minor)) { user.RaiseMessage(Properties.Resources.OptionsMonoWarning, - String.Join(".", major, minor, patch), - String.Join(".", rec_major, rec_minor, rec_patch)); + string.Join(".", major, minor, patch), + string.Join(".", rec_major, rec_minor, rec_patch)); } } } diff --git a/Cmdline/ProgressReporter.cs b/Cmdline/ProgressReporter.cs index 02989d0cfe..333ba656c2 100644 --- a/Cmdline/ProgressReporter.cs +++ b/Cmdline/ProgressReporter.cs @@ -1,4 +1,3 @@ -using System; using System.Text.RegularExpressions; namespace CKAN.CmdLine diff --git a/Cmdline/SingleAssemblyResourceManager.cs b/Cmdline/SingleAssemblyResourceManager.cs index 25f1e19f90..e13699cd00 100644 --- a/Cmdline/SingleAssemblyResourceManager.cs +++ b/Cmdline/SingleAssemblyResourceManager.cs @@ -1,7 +1,6 @@ using System.IO; using System.Globalization; using System.Resources; -using System.Collections; using System.Reflection; using System.Collections.Generic; @@ -9,7 +8,7 @@ namespace CKAN.CmdLine { // Thanks and credit to this guy: https://stackoverflow.com/q/1952638/2422988 - class SingleAssemblyResourceManager : ResourceManager + public class SingleAssemblyResourceManager : ResourceManager { public SingleAssemblyResourceManager(string basename, Assembly assembly) : base(basename, assembly) { @@ -23,7 +22,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -34,7 +33,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/ConsoleUI/CompatibleVersionDialog.cs b/ConsoleUI/CompatibleVersionDialog.cs index a3d016812b..50afd03808 100644 --- a/ConsoleUI/CompatibleVersionDialog.cs +++ b/ConsoleUI/CompatibleVersionDialog.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; -using Autofac; - using CKAN.Versioning; using CKAN.Games; using CKAN.ConsoleUI.Toolkit; diff --git a/ConsoleUI/DownloadImportDialog.cs b/ConsoleUI/DownloadImportDialog.cs index 3bc4e7c5f2..116a96b420 100644 --- a/ConsoleUI/DownloadImportDialog.cs +++ b/ConsoleUI/DownloadImportDialog.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Collections.Generic; -using System.ComponentModel; using CKAN.ConsoleUI.Toolkit; namespace CKAN.ConsoleUI { diff --git a/ConsoleUI/ExitScreen.cs b/ConsoleUI/ExitScreen.cs index 86562f89d1..ad74be0125 100644 --- a/ConsoleUI/ExitScreen.cs +++ b/ConsoleUI/ExitScreen.cs @@ -59,7 +59,7 @@ private void Draw(ConsoleTheme theme) .Replace("{0}", ckanPiece).ToArray(), new FancyLinePiece[] { new FancyLinePiece( - new string(Symbols.horizLine, Console.WindowWidth - 2 -2 * horizMargin), + new string(Symbols.horizLine, Console.WindowWidth - 2 -(2 * horizMargin)), theme.ExitInnerBg, theme.ExitNormalFg) }, }.Concat( @@ -90,7 +90,7 @@ private void drawLine(ConsoleTheme theme, int y, FancyLinePiece[] pieces) foreach (FancyLinePiece p in pieces) { textLen += p.Text.Length; } - int boxW = Console.WindowWidth - 2 * horizMargin; + int boxW = Console.WindowWidth - (2 * horizMargin); int leftPad = (boxW - textLen) / 2; if (leftPad < 0) { leftPad = 0; @@ -157,7 +157,7 @@ IEnumerable<FancyLinePiece> InjectReplacement(string p, int i) var pieces = Text.Split(tokens, StringSplitOptions.None); return pieces.Length <= 1 // Stop making new objects if no tokens found - ? Enumerable.Repeat<FancyLinePiece>(this, 1) + ? Enumerable.Repeat(this, 1) : pieces.SelectMany(InjectReplacement); } diff --git a/ConsoleUI/GameInstanceAddScreen.cs b/ConsoleUI/GameInstanceAddScreen.cs index b882e40cec..59e7f51ba6 100644 --- a/ConsoleUI/GameInstanceAddScreen.cs +++ b/ConsoleUI/GameInstanceAddScreen.cs @@ -27,20 +27,13 @@ public GameInstanceAddScreen(GameInstanceManager mgr) : base(mgr) /// The basic non-empty and unique checks are good enough for adding. /// </summary> protected override bool Valid() - { - if (!nameValid() || !pathValid()) { - return false; - } - return true; - } + => nameValid() && pathValid(); /// <summary> /// Put description in top center /// </summary> protected override string CenterHeader() - { - return Properties.Resources.InstanceAddTitle; - } + => Properties.Resources.InstanceAddTitle; /// <summary> /// Add the instance diff --git a/ConsoleUI/GameInstanceEditScreen.cs b/ConsoleUI/GameInstanceEditScreen.cs index 53b4adfc69..ecf923f9e6 100644 --- a/ConsoleUI/GameInstanceEditScreen.cs +++ b/ConsoleUI/GameInstanceEditScreen.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using CKAN.Versioning; -using CKAN.Games; using CKAN.ConsoleUI.Toolkit; namespace CKAN.ConsoleUI { @@ -174,33 +173,22 @@ private static V SortedDictFind<K, V>(SortedDictionary<K, V> dict, Func<V, bool> return kvp.Value; } } - return default(V); + return default; } /// <summary> /// Put description in top center /// </summary> protected override string CenterHeader() - { - return Properties.Resources.InstanceEditTitle; - } + => Properties.Resources.InstanceEditTitle; /// <summary> /// Return whether the fields are valid. /// Similar to adding, except leaving the fields unchanged is allowed. /// </summary> protected override bool Valid() - { - if (name.Value != ksp.Name - && !nameValid()) { - return false; - } - if (path.Value != ksp.GameDir() - && !pathValid()) { - return false; - } - return true; - } + => (name.Value == ksp.Name || nameValid()) + && (path.Value == ksp.GameDir() || pathValid()); /// <summary> /// Save the changes. diff --git a/ConsoleUI/InstallFilterAddDialog.cs b/ConsoleUI/InstallFilterAddDialog.cs index dbb953c2eb..de2ea97265 100644 --- a/ConsoleUI/InstallFilterAddDialog.cs +++ b/ConsoleUI/InstallFilterAddDialog.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; - -using Autofac; - -using CKAN.Versioning; -using CKAN.Games; using CKAN.ConsoleUI.Toolkit; namespace CKAN.ConsoleUI { diff --git a/ConsoleUI/ModInfoScreen.cs b/ConsoleUI/ModInfoScreen.cs index a3ecea46d8..3e55db34df 100644 --- a/ConsoleUI/ModInfoScreen.cs +++ b/ConsoleUI/ModInfoScreen.cs @@ -1,7 +1,5 @@ using System; -using System.Diagnostics; using System.Collections.Generic; -using System.Text.RegularExpressions; using System.Linq; using System.Threading; @@ -31,7 +29,7 @@ public ModInfoScreen(GameInstanceManager mgr, Registry registry, ChangePlan cp, plan = cp; this.registry = registry; - int midL = Console.WindowWidth / 2 - 1; + int midL = (Console.WindowWidth / 2) - 1; AddObject(new ConsoleLabel( 1, 1, -1, @@ -58,8 +56,8 @@ public ModInfoScreen(GameInstanceManager mgr, Registry registry, ChangePlan cp, )); AddObject(new ConsoleLabel( 13, 4, midL - 2, - () => string.Join(", ", Array.ConvertAll<License, string>( - mod.license.ToArray(), (l => l.ToString()))) + () => string.Join(", ", Array.ConvertAll( + mod.license.ToArray(), l => l.ToString())) )); AddObject(new ConsoleLabel( 3, 5, 12, @@ -74,13 +72,13 @@ public ModInfoScreen(GameInstanceManager mgr, Registry registry, ChangePlan cp, if (mod.install_size > 0) { AddObject(new ConsoleLabel( - midL / 2, 5, midL / 2 + 9, + midL / 2, 5, (midL / 2) + 9, () => "Install:", null, th => th.DimLabelFg )); AddObject(new ConsoleLabel( - midL / 2 + 9, 5, midL - 2, + (midL / 2) + 9, 5, midL - 2, () => CkanModule.FmtSize(mod.install_size) )); } @@ -263,7 +261,7 @@ private int addDependencies(int top = 8) int numConfs = mod.conflicts?.Count ?? 0; if (numDeps + numConfs > 0) { - int midL = Console.WindowWidth / 2 - 1; + int midL = (Console.WindowWidth / 2) - 1; int h = Math.Min(11, numDeps + numConfs + 2); const int lblW = 16; int nameW = midL - 2 - lblW - 2 - 1; @@ -336,7 +334,7 @@ private int addDependencies(int top = 8) private int addVersionDisplay() { - int boxLeft = Console.WindowWidth / 2 + 1, + int boxLeft = (Console.WindowWidth / 2) + 1, boxTop = 3; const int boxRight = -1, boxH = 5; diff --git a/ConsoleUI/ModListHelpDialog.cs b/ConsoleUI/ModListHelpDialog.cs index 5f110337ff..747c0562af 100644 --- a/ConsoleUI/ModListHelpDialog.cs +++ b/ConsoleUI/ModListHelpDialog.cs @@ -22,7 +22,7 @@ public ModListHelpDialog() : base() int btnL = (Console.WindowWidth - btnW) / 2; ConsoleTextBox symbolTb = new ConsoleTextBox( - GetLeft() + 2, GetTop() + 2, Console.WindowWidth / 2 - 1, GetBottom() - 4, + GetLeft() + 2, GetTop() + 2, (Console.WindowWidth / 2) - 1, GetBottom() - 4, false, TextAlign.Center, th => th.PopupBg, @@ -51,7 +51,7 @@ public ModListHelpDialog() : base() )); ConsoleTextBox searchTb = new ConsoleTextBox( - Console.WindowWidth / 2 + 1, GetTop() + 3, GetRight() - 2, GetBottom() - 4, + (Console.WindowWidth / 2) + 1, GetTop() + 3, GetRight() - 2, GetBottom() - 4, false, TextAlign.Center, th => th.PopupBg, diff --git a/ConsoleUI/ModListScreen.cs b/ConsoleUI/ModListScreen.cs index 6c98c0baa6..60bcac5bd9 100644 --- a/ConsoleUI/ModListScreen.cs +++ b/ConsoleUI/ModListScreen.cs @@ -31,7 +31,7 @@ public ModListScreen(GameInstanceManager mgr, RepositoryDataManager repoData, Re debug = dbg; manager = mgr; this.regMgr = regMgr; - this.registry = regMgr.registry; + registry = regMgr.registry; this.repoData = repoData; moduleList = new ConsoleListBox<CkanModule>( @@ -75,7 +75,9 @@ public ModListScreen(GameInstanceManager mgr, RepositoryDataManager repoData, Re if (filter.Length <= 1) { // Don't blank the list for just "~" by itself return true; - } else switch (filter.Substring(1, 1)) { + } else + { + switch (filter.Substring(1, 1)) { case "i": return registry.IsInstalled(m.identifier, false); case "u": @@ -106,6 +108,8 @@ public ModListScreen(GameInstanceManager mgr, RepositoryDataManager repoData, Re } return false; } + } + return false; } else { filter = CkanModule.nonAlphaNums.Replace(filter, ""); @@ -347,7 +351,7 @@ private bool ImportDownloads(ConsoleTheme theme) private bool CaptureKey(ConsoleTheme theme) { - ConsoleKeyInfo k = default(ConsoleKeyInfo); + ConsoleKeyInfo k = default; ConsoleMessageDialog keyprompt = new ConsoleMessageDialog(Properties.Resources.ModListPressAKey, new List<string>()); keyprompt.Run(theme, (ConsoleTheme th) => { k = Console.ReadKey(true); @@ -435,11 +439,11 @@ private bool UpdateRegistry(ConsoleTheme theme, bool showNewModsPrompt = true) ); LaunchSubScreen(theme, ps, (ConsoleTheme th) => { HashSet<string> availBefore = new HashSet<string>( - Array.ConvertAll<CkanModule, string>( + Array.ConvertAll( registry.CompatibleModules( manager.CurrentInstance.VersionCriteria() ).ToArray(), - (l => l.identifier) + l => l.identifier ) ); recent.Clear(); diff --git a/ConsoleUI/Program.cs b/ConsoleUI/Program.cs index 2f6e6f299b..da14b854ed 100644 --- a/ConsoleUI/Program.cs +++ b/ConsoleUI/Program.cs @@ -14,7 +14,9 @@ public static class ConsoleUI /// </summary> /// <param name="args">Command line arguments</param> [STAThread] + #pragma warning disable IDE0060 public static void Main(string[] args) + #pragma warning restore IDE0060 { Main_(null, null); } diff --git a/ConsoleUI/RepoAddScreen.cs b/ConsoleUI/RepoAddScreen.cs index 0e3629f406..99e972a45c 100644 --- a/ConsoleUI/RepoAddScreen.cs +++ b/ConsoleUI/RepoAddScreen.cs @@ -23,12 +23,7 @@ public RepoAddScreen(IGame game, SortedDictionary<string, Repository> reps) /// True if name and URL are valid, false otherwise. /// </returns> protected override bool Valid() - { - if (!nameValid() || !urlValid()) { - return false; - } - return true; - } + => nameValid() && urlValid(); /// <summary> /// Save the new Repository diff --git a/ConsoleUI/RepoEditScreen.cs b/ConsoleUI/RepoEditScreen.cs index 1807aab1ea..32349fab2d 100644 --- a/ConsoleUI/RepoEditScreen.cs +++ b/ConsoleUI/RepoEditScreen.cs @@ -28,17 +28,8 @@ public RepoEditScreen(IGame game, SortedDictionary<string, Repository> reps, Rep /// True if valid, false otherwise /// </returns> protected override bool Valid() - { - if (name.Value != repository.name - && !nameValid()) { - return false; - } - if (url.Value != repository.uri.ToString() - && !urlValid()) { - return false; - } - return true; - } + => (name.Value == repository.name || nameValid()) + && (url.Value == repository.uri.ToString() || urlValid()); /// <summary> /// Save changes diff --git a/ConsoleUI/SingleAssemblyResourceManager.cs b/ConsoleUI/SingleAssemblyResourceManager.cs index 994305ec28..ecdf62c50d 100644 --- a/ConsoleUI/SingleAssemblyResourceManager.cs +++ b/ConsoleUI/SingleAssemblyResourceManager.cs @@ -1,7 +1,6 @@ using System.IO; using System.Globalization; using System.Resources; -using System.Collections; using System.Reflection; using System.Collections.Generic; @@ -9,12 +8,29 @@ namespace CKAN.ConsoleUI { // Thanks and credit to this guy: https://stackoverflow.com/q/1952638/2422988 - class SingleAssemblyResourceManager : ResourceManager + /// <summary> + /// Wrapper around ResourceManager that retrieves strings from the assembly + /// rather than external files + /// </summary> + public class SingleAssemblyResourceManager : ResourceManager { - public SingleAssemblyResourceManager(string basename, Assembly assembly) : base(basename, assembly) + /// <summary> + /// Initialize the resource manager + /// </summary> + /// <param name="basename">To be passed to ResourceManager</param> + /// <param name="assembly">To be passed to ResourceManager</param> + public SingleAssemblyResourceManager(string basename, Assembly assembly) + : base(basename, assembly) { } + /// <summary> + /// Provides resources from the assembly to ResourceManager + /// </summary> + /// <param name="culture">The language to get</param> + /// <param name="createIfNotExists">Set to false to avoid loading if not already cached</param> + /// <param name="tryParents">Just gets passed to base class implementation</param> + /// <returns></returns> protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { @@ -23,7 +39,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -34,7 +50,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/ConsoleUI/Toolkit/ConsoleButton.cs b/ConsoleUI/Toolkit/ConsoleButton.cs index 98aea54123..010d95a369 100644 --- a/ConsoleUI/Toolkit/ConsoleButton.cs +++ b/ConsoleUI/Toolkit/ConsoleButton.cs @@ -35,12 +35,8 @@ public override void Draw(ConsoleTheme theme, bool focused) // Main button text Console.SetCursorPosition(GetLeft(), GetTop()); Console.BackgroundColor = theme.PopupButtonBg; - if (focused) { - Console.ForegroundColor = theme.PopupButtonSelectedFg; - } else { - Console.ForegroundColor = theme.PopupButtonFg; - } - Console.Write(ScreenObject.PadCenter(caption, w)); + Console.ForegroundColor = focused ? theme.PopupButtonSelectedFg : theme.PopupButtonFg; + Console.Write(PadCenter(caption, w)); // Right shadow if (theme.PopupButtonShadow.HasValue) @@ -93,8 +89,8 @@ public override void OnKeyPress(ConsoleKeyInfo k) } } - private string caption; - private Action choiceEvent; + private readonly string caption; + private readonly Action choiceEvent; private readonly string shadowStrip; } } diff --git a/ConsoleUI/Toolkit/ConsoleChoiceDialog.cs b/ConsoleUI/Toolkit/ConsoleChoiceDialog.cs index a9f493629b..50d4d19ab6 100644 --- a/ConsoleUI/Toolkit/ConsoleChoiceDialog.cs +++ b/ConsoleUI/Toolkit/ConsoleChoiceDialog.cs @@ -84,11 +84,11 @@ public ConsoleChoiceDialog(string m, string hdr, List<ChoiceT> c, Func<ChoiceT, public new ChoiceT Run(ConsoleTheme theme, Action<ConsoleTheme> process = null) { base.Run(theme, process); - return cancelled ? default(ChoiceT) : choices.Selection; + return cancelled ? default : choices.Selection; } - private ConsoleListBox<ChoiceT> choices; - private bool cancelled; + private readonly ConsoleListBox<ChoiceT> choices; + private bool cancelled; } } diff --git a/ConsoleUI/Toolkit/ConsoleDialog.cs b/ConsoleUI/Toolkit/ConsoleDialog.cs index 3a73809040..6bbd02b539 100644 --- a/ConsoleUI/Toolkit/ConsoleDialog.cs +++ b/ConsoleUI/Toolkit/ConsoleDialog.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; namespace CKAN.ConsoleUI.Toolkit { diff --git a/ConsoleUI/Toolkit/ConsoleDoubleFrame.cs b/ConsoleUI/Toolkit/ConsoleDoubleFrame.cs index d27a35db54..f77d3e8e94 100644 --- a/ConsoleUI/Toolkit/ConsoleDoubleFrame.cs +++ b/ConsoleUI/Toolkit/ConsoleDoubleFrame.cs @@ -91,11 +91,11 @@ private void writeTitleRow(string title, int w) /// </summary> public override bool Focusable() { return false; } - private Func<string> getTopTitle; - private Func<string> getMidTitle; - private Func<ConsoleTheme, ConsoleColor> getColor; - private bool doubleBorder; - private int middleRow; + private readonly Func<string> getTopTitle; + private readonly Func<string> getMidTitle; + private readonly Func<ConsoleTheme, ConsoleColor> getColor; + private readonly bool doubleBorder; + private readonly int middleRow; } } diff --git a/ConsoleUI/Toolkit/ConsoleField.cs b/ConsoleUI/Toolkit/ConsoleField.cs index 9e13ab1cf3..5aaf25fe3b 100644 --- a/ConsoleUI/Toolkit/ConsoleField.cs +++ b/ConsoleUI/Toolkit/ConsoleField.cs @@ -1,5 +1,4 @@ using System; -using CKAN.ConsoleUI.Toolkit; namespace CKAN.ConsoleUI.Toolkit { @@ -49,9 +48,7 @@ public ConsoleField(int l, int t, int r, string val = "") public event ChangeListener OnChange; private void Changed() { - if (OnChange != null) { - OnChange(this, Value); - } + OnChange?.Invoke(this, Value); } /// <summary> @@ -89,11 +86,9 @@ public override void Draw(ConsoleTheme theme, bool focused) Console.ForegroundColor = theme.FieldGhostFg; Console.Write(GhostText().PadRight(w)); } else { - if (focused) { - Console.ForegroundColor = theme.FieldFocusedFg; - } else { - Console.ForegroundColor = theme.FieldBlurredFg; - } + Console.ForegroundColor = focused + ? theme.FieldFocusedFg + : theme.FieldBlurredFg; Console.Write(FormatExactWidth(Value.Substring(leftPos), w)); } } @@ -126,11 +121,9 @@ public override void OnKeyPress(ConsoleKeyInfo k) break; case ConsoleKey.Delete: if (Position < Value.Length) { - if ((k.Modifiers & ConsoleModifiers.Control) == 0) { - Value = Value.Substring(0, Position) + Value.Substring(Position + 1); - } else { - Value = Value.Substring(0, Position); - } + Value = (k.Modifiers & ConsoleModifiers.Control) == 0 + ? Value.Substring(0, Position) + Value.Substring(Position + 1) + : Value.Substring(0, Position); Changed(); } break; @@ -160,7 +153,7 @@ public override void OnKeyPress(ConsoleKeyInfo k) Blur((k.Modifiers & ConsoleModifiers.Shift) == 0); break; default: - if (!Char.IsControl(k.KeyChar)) { + if (!char.IsControl(k.KeyChar)) { if (Position < Value.Length) { Value = Value.Substring(0, Position) + k.KeyChar + Value.Substring(Position); } else { diff --git a/ConsoleUI/Toolkit/ConsoleFileMultiSelectDialog.cs b/ConsoleUI/Toolkit/ConsoleFileMultiSelectDialog.cs index 1597e2eec9..36919347d0 100644 --- a/ConsoleUI/Toolkit/ConsoleFileMultiSelectDialog.cs +++ b/ConsoleUI/Toolkit/ConsoleFileMultiSelectDialog.cs @@ -24,9 +24,9 @@ public ConsoleFileMultiSelectDialog(string title, string startPath, string filPa curDir = new DirectoryInfo(startPath); filePattern = filPat; - int w = (Console.WindowWidth > idealW + 2 * hPad) + int w = (Console.WindowWidth > idealW + (2 * hPad)) ? idealW - : Console.WindowWidth - 2 * hPad; + : Console.WindowWidth - (2 * hPad); int left = (Console.WindowWidth - w) / 2; int right = -left; @@ -73,8 +73,8 @@ public ConsoleFileMultiSelectDialog(string title, string startPath, string filPa Width = 9, Renderer = (FileSystemInfo fi) => getLength(fi), Comparer = (a, b) => { - FileInfo fa = a as FileInfo, fb = b as FileInfo; - return fa == null + FileInfo fb = b as FileInfo; + return !(a is FileInfo fa) ? (fb == null ? 0 : -1) : (fb == null ? 1 : fa.Length.CompareTo(fb.Length)); } @@ -111,8 +111,8 @@ public ConsoleFileMultiSelectDialog(string title, string startPath, string filPa AddBinding(Keys.CtrlA, (object sender, ConsoleTheme theme) => { foreach (FileSystemInfo fi in contents) { if (!isDir(fi)) { - FileInfo file = fi as FileInfo; - if (file != null) { + if (fi is FileInfo file) + { chosenFiles.Add(file); } } @@ -137,18 +137,21 @@ public ConsoleFileMultiSelectDialog(string title, string startPath, string filPa private bool selectRow() { if (isDir(fileList.Selection)) { - DirectoryInfo di = fileList.Selection as DirectoryInfo; - if (di != null) { + if (fileList.Selection is DirectoryInfo di) + { curDir = di; pathField.Value = curDir.FullName; fileList.SetData(getFileList()); } } else { - FileInfo fi = fileList.Selection as FileInfo; - if (fi != null) { - if (chosenFiles.Contains(fi)) { + if (fileList.Selection is FileInfo fi) + { + if (chosenFiles.Contains(fi)) + { chosenFiles.Remove(fi); - } else { + } + else + { chosenFiles.Add(fi); } } @@ -226,18 +229,11 @@ private static bool pathEquals(FileSystemInfo a, FileSystemInfo b) } private string getLength(FileSystemInfo fi) - { - if (isDir(fi)) { - return Properties.Resources.FileSelectDirSize; - } else { - FileInfo file = fi as FileInfo; - if (file != null) { - return CkanModule.FmtSize(file.Length); - } else { - return Properties.Resources.FileSelectDirSize; - } - } - } + => isDir(fi) + ? Properties.Resources.FileSelectDirSize + : fi is FileInfo file + ? CkanModule.FmtSize(file.Length) + : Properties.Resources.FileSelectDirSize; private long totalChosenSize() { @@ -250,12 +246,9 @@ private long totalChosenSize() } private string getRowSymbol(FileSystemInfo fi) - { - if (!isDir(fi) && chosenFiles.Contains(fi as FileInfo)) { - return chosen; - } - return ""; - } + => !isDir(fi) && chosenFiles.Contains(fi as FileInfo) + ? chosen + : ""; private string getRowName(FileSystemInfo fi) { @@ -298,19 +291,19 @@ private int compareNames(FileSystemInfo a, FileSystemInfo b) } } - private List<FileSystemInfo> contents; - private ConsoleField pathField; - private ConsoleListBox<FileSystemInfo> fileList; - private DirectoryInfo curDir; + private List<FileSystemInfo> contents; + private readonly ConsoleField pathField; + private readonly ConsoleListBox<FileSystemInfo> fileList; + private DirectoryInfo curDir; - private HashSet<FileInfo> chosenFiles = new HashSet<FileInfo>(); + private readonly HashSet<FileInfo> chosenFiles = new HashSet<FileInfo>(); - private string filePattern; + private readonly string filePattern; private static readonly string chosen = Symbols.checkmark; private const int idealW = 76; - private int labelW => Properties.Resources.FileSelectDirectory.Length; + private int labelW => Properties.Resources.FileSelectDirectory.Length; private const int hPad = 2; private const int top = 2; private const int bottom = -2; diff --git a/ConsoleUI/Toolkit/ConsoleFrame.cs b/ConsoleUI/Toolkit/ConsoleFrame.cs index 1d9bc859b1..15a9c15c02 100644 --- a/ConsoleUI/Toolkit/ConsoleFrame.cs +++ b/ConsoleUI/Toolkit/ConsoleFrame.cs @@ -75,9 +75,9 @@ public override void Draw(ConsoleTheme theme, bool focused) /// </summary> public override bool Focusable() { return false; } - private Func<string> getTitle; - private Func<ConsoleTheme, ConsoleColor> getColor; - private bool doubleBorder; + private readonly Func<string> getTitle; + private readonly Func<ConsoleTheme, ConsoleColor> getColor; + private readonly bool doubleBorder; } } diff --git a/ConsoleUI/Toolkit/ConsoleLabel.cs b/ConsoleUI/Toolkit/ConsoleLabel.cs index a59f8678a0..ebbb9e95ac 100644 --- a/ConsoleUI/Toolkit/ConsoleLabel.cs +++ b/ConsoleUI/Toolkit/ConsoleLabel.cs @@ -33,16 +33,8 @@ public override void Draw(ConsoleTheme theme, bool focused) { int w = GetRight() - GetLeft() + 1; Console.SetCursorPosition(GetLeft(), GetTop()); - if (getBgColor == null) { - Console.BackgroundColor = theme.LabelBg; - } else { - Console.BackgroundColor = getBgColor(theme); - } - if (getFgColor == null) { - Console.ForegroundColor = theme.LabelFg; - } else { - Console.ForegroundColor = getFgColor(theme); - } + Console.BackgroundColor = getBgColor == null ? theme.LabelBg : getBgColor(theme); + Console.ForegroundColor = getFgColor == null ? theme.LabelFg : getFgColor(theme); try { Console.Write(FormatExactWidth(labelFunc(), w)); } catch (Exception ex) { @@ -55,9 +47,9 @@ public override void Draw(ConsoleTheme theme, bool focused) /// </summary> public override bool Focusable() { return false; } - private Func<string> labelFunc; - private Func<ConsoleTheme, ConsoleColor> getBgColor; - private Func<ConsoleTheme, ConsoleColor> getFgColor; + private readonly Func<string> labelFunc; + private readonly Func<ConsoleTheme, ConsoleColor> getBgColor; + private readonly Func<ConsoleTheme, ConsoleColor> getFgColor; } } diff --git a/ConsoleUI/Toolkit/ConsoleListBox.cs b/ConsoleUI/Toolkit/ConsoleListBox.cs index 38c4b6d44c..ba6581afed 100644 --- a/ConsoleUI/Toolkit/ConsoleListBox.cs +++ b/ConsoleUI/Toolkit/ConsoleListBox.cs @@ -82,15 +82,10 @@ public string FilterString { /// <summary> /// Currently selected row's object /// </summary> - public RowT Selection { - get { - if (selectedRow >= 0 && selectedRow < (sortedFilteredData?.Count ?? 0)) { - return sortedFilteredData[selectedRow]; - } else { - return default (RowT); - } - } - } + public RowT Selection + => selectedRow >= 0 && selectedRow < (sortedFilteredData?.Count ?? 0) + ? sortedFilteredData[selectedRow] + : default; /// <returns> /// Return the number of rows shown in the box @@ -201,7 +196,7 @@ public override void Draw(ConsoleTheme theme, bool focused) theme, r, t + scrollTop, b, sortedFilteredData.Count > 0 - ? t + 1 + scrollTop + (h - 2 - scrollTop) * selectedRow / sortedFilteredData.Count + ? t + 1 + scrollTop + ((h - 2 - scrollTop) * selectedRow / sortedFilteredData.Count) : -1 ); } @@ -251,7 +246,7 @@ public override void OnKeyPress(ConsoleKeyInfo k) break; default: // Go backwards if (k.Modifiers & ConsoleModifiers.Shift) - if (!Char.IsControl(k.KeyChar) + if (!char.IsControl(k.KeyChar) && (k.Modifiers | ConsoleModifiers.Shift) == ConsoleModifiers.Shift) { bool forward = (k.Modifiers & ConsoleModifiers.Shift) == 0; @@ -350,30 +345,21 @@ public void SetData(IList<RowT> newData) } private string FmtHdr(int colIndex, int w) - { - ConsoleListBoxColumn<RowT> col = columns[colIndex]; - if (colIndex == sortColIndex) { - return FormatExactWidth( - col.Header + " " + (sortDir == ListSortDirection.Ascending ? sortUp : sortDown), - w - ); - } else { - return FormatExactWidth(col.Header, w); - } - } + => colIndex == sortColIndex + ? FormatExactWidth( + columns[colIndex].Header + " " + + (sortDir == ListSortDirection.Ascending ? sortUp : sortDown), + w) + : FormatExactWidth(columns[colIndex].Header, w); private void filterAndSort() { // Keep the same row highlighted when the number of rows changes RowT oldSelect = Selection; - if (string.IsNullOrEmpty(filterStr) || filterCheck == null) { - sortedFilteredData = new List<RowT>(data); - } else { - sortedFilteredData = new List<RowT>(data).FindAll( - r => filterCheck(r, filterStr) - ); - } + sortedFilteredData = string.IsNullOrEmpty(filterStr) || filterCheck == null + ? new List<RowT>(data) + : new List<RowT>(data).FindAll(r => filterCheck(r, filterStr)); // Semantic sort for versions rather than lexicographical if (sortColIndex >= 0 && sortColIndex < columns.Count) { @@ -395,40 +381,31 @@ private void filterAndSort() } private Comparison<RowT> getComparer(ConsoleListBoxColumn<RowT> col, bool ascending) - { - if (ascending) { - return col.Comparer - ?? ((a, b) => col.Renderer(a).Trim().CompareTo(col.Renderer(b).Trim())); - - } else if (col.Comparer != null) { - return (a, b) => col.Comparer(b, a); - } else { - return (a, b) => col.Renderer(b).Trim().CompareTo(col.Renderer(a).Trim()); - } - } + => ascending + ? col.Comparer + ?? ((a, b) => col.Renderer(a).Trim().CompareTo(col.Renderer(b).Trim())) + : col.Comparer != null + ? (Comparison<RowT>)((RowT a, RowT b) => col.Comparer(b, a)) + : ((RowT a, RowT b) => col.Renderer(b).Trim().CompareTo(col.Renderer(a).Trim())); // Sometimes type safety can be a minor hindrance; // this would just be "first || second" in C private int IntOr(Func<int> first, Func<int> second) { int a = first(); - if (a != 0) { - return a; - } else { - return second(); - } + return a != 0 ? a : second(); } - private List<RowT> sortedFilteredData; - private IList<RowT> data; - private IList<ConsoleListBoxColumn<RowT>> columns; - private Func<RowT, string, bool> filterCheck; - private ConsolePopupMenu sortMenu; + private List<RowT> sortedFilteredData; + private IList<RowT> data; + private readonly IList<ConsoleListBoxColumn<RowT>> columns; + private readonly Func<RowT, string, bool> filterCheck; + private ConsolePopupMenu sortMenu; - private int defaultSortColumn = 0; - private int sortColIndex; - private ListSortDirection sortDir; - private string filterStr = ""; + private readonly int defaultSortColumn = 0; + private int sortColIndex; + private ListSortDirection sortDir; + private string filterStr = ""; private int topRow = 0; private int selectedRow = 0; diff --git a/ConsoleUI/Toolkit/ConsoleMessageDialog.cs b/ConsoleUI/Toolkit/ConsoleMessageDialog.cs index ef8126ce06..7f34d14a8e 100644 --- a/ConsoleUI/Toolkit/ConsoleMessageDialog.cs +++ b/ConsoleUI/Toolkit/ConsoleMessageDialog.cs @@ -27,7 +27,7 @@ public ConsoleMessageDialog(string m, List<string> btns, Func<string> hdr = null CenterHeader = hdr; } - int btnW = btns.Count * buttonWidth + (btns.Count - 1) * buttonPadding; + int btnW = (btns.Count * buttonWidth) + ((btns.Count - 1) * buttonPadding); if (w < btnW + 4) { // Widen the window to fit the buttons // Buttons will NOT wrap - use ConsoleChoiceDialog @@ -46,13 +46,13 @@ public ConsoleMessageDialog(string m, List<string> btns, Func<string> hdr = null // Calculate vertical position including offset int t, b; if (vertOffset <= 0) { - t = (Console.WindowHeight - h) / 2 + vertOffset; + t = ((Console.WindowHeight - h) / 2) + vertOffset; if (t < 1) { t = 2; } b = t + h - 1; } else { - b = (Console.WindowHeight - h) / 2 + h - 1; + b = ((Console.WindowHeight - h) / 2) + h - 1; if (b >= Console.WindowHeight - 1) { b = Console.WindowHeight - 1; } diff --git a/ConsoleUI/Toolkit/ConsolePopupMenu.cs b/ConsoleUI/Toolkit/ConsolePopupMenu.cs index c1558d9fe5..3d8026d91e 100644 --- a/ConsoleUI/Toolkit/ConsolePopupMenu.cs +++ b/ConsoleUI/Toolkit/ConsolePopupMenu.cs @@ -66,13 +66,10 @@ public bool Run(ConsoleTheme theme, int right, int top) if (options[selectedOption].OnExec != null) { val = options[selectedOption].OnExec(theme); } - if (options[selectedOption].SubMenu != null) { - options[selectedOption].SubMenu.Run( + options[selectedOption].SubMenu?.Run( theme, right - 2, - top + selectedOption + 2 - ); - } + top + selectedOption + 2); break; case ConsoleKey.F10: case ConsoleKey.Escape: @@ -156,23 +153,17 @@ private void DrawFooter(ConsoleTheme theme) } private string AnnotatedCaption(ConsoleMenuOption opt) - { - if (opt.SubMenu != null) { - return opt.Caption.PadRight(longestLength - 1) + submenuIndicator; - } else if (opt.RadioActive != null) { - if (opt.RadioActive()) { - return $"({Symbols.dot}) {opt.Caption}".PadRight(longestLength); - } else { - return $"( ) {opt.Caption}".PadRight(longestLength); - } - } else { - return opt.Caption.PadRight(longestLength - opt.Key.Length) + opt.Key; - } - } + => opt.SubMenu != null + ? opt.Caption.PadRight(longestLength - 1) + submenuIndicator + : opt.RadioActive != null + ? opt.RadioActive() + ? $"({Symbols.dot}) {opt.Caption}".PadRight(longestLength) + : $"( ) {opt.Caption}".PadRight(longestLength) + : opt.Caption.PadRight(longestLength - opt.Key.Length) + opt.Key; - private List<ConsoleMenuOption> options; - private int longestLength; - private int selectedOption = 0; + private readonly List<ConsoleMenuOption> options; + private readonly int longestLength; + private int selectedOption = 0; private static readonly string submenuIndicator = ">"; } diff --git a/ConsoleUI/Toolkit/ConsoleProgressBar.cs b/ConsoleUI/Toolkit/ConsoleProgressBar.cs index 77f93b35a5..ac07f3579b 100644 --- a/ConsoleUI/Toolkit/ConsoleProgressBar.cs +++ b/ConsoleUI/Toolkit/ConsoleProgressBar.cs @@ -63,8 +63,8 @@ public override void Draw(ConsoleTheme theme, bool focused) /// </summary> public override bool Focusable() { return false; } - private Func<string> captionFunc; - private Func<double> percentFunc; + private readonly Func<string> captionFunc; + private readonly Func<double> percentFunc; } } diff --git a/ConsoleUI/Toolkit/ConsoleScreen.cs b/ConsoleUI/Toolkit/ConsoleScreen.cs index 7eeb1cf8e5..d51e48f4a1 100644 --- a/ConsoleUI/Toolkit/ConsoleScreen.cs +++ b/ConsoleUI/Toolkit/ConsoleScreen.cs @@ -78,7 +78,7 @@ protected virtual string MenuTip() /// <summary> /// Tell IUser clients that we have the ability to interact with the user /// </summary> - public bool Headless { get { return false; } } + public bool Headless => false; // These functions can be implemented the same on all screens, // so they are not virtual. @@ -128,7 +128,7 @@ public int RaiseSelectionDialog(string message, params object[] args) { ConsoleMessageDialog d = new ConsoleMessageDialog( string.Join("", messagePieces) + message, - new List<string>(Array.ConvertAll<object, string>(args, p => p.ToString())) + new List<string>(Array.ConvertAll(args, p => p.ToString())) ); messagePieces.Clear(); int val = d.Run(userTheme); @@ -191,7 +191,7 @@ protected virtual void Message(string message, params object[] args) // But there's nothing intrinsic to the API that tells us which strings // to combine. So we'll just save them all and then combine them // when a function is called that takes input. - private List<string> messagePieces = new List<string>(); + private readonly List<string> messagePieces = new List<string>(); /// <summary> /// Update a user visible progress bar diff --git a/ConsoleUI/Toolkit/ConsoleTextBox.cs b/ConsoleUI/Toolkit/ConsoleTextBox.cs index 8e9418c7fe..5a4c8466e4 100644 --- a/ConsoleUI/Toolkit/ConsoleTextBox.cs +++ b/ConsoleUI/Toolkit/ConsoleTextBox.cs @@ -68,7 +68,7 @@ private void rewrapLines() prevTextW = w; int h = GetBottom() - GetTop() + 1; float scrollFrac = displayLines.Count > h - ? (float)topLine / ((float)displayLines.Count - h) + ? topLine / ((float)displayLines.Count - h) : 0; displayLines.Clear(); foreach (string line in lines) { @@ -140,16 +140,8 @@ public override void Draw(ConsoleTheme theme, bool focused) rewrapLines(); } - if (getBgColor != null) { - Console.BackgroundColor = getBgColor(theme); - } else { - Console.BackgroundColor = theme.TextBoxBg; - } - if (getFgColor != null) { - Console.ForegroundColor = getFgColor(theme); - } else { - Console.ForegroundColor = theme.TextBoxFg; - } + Console.BackgroundColor = getBgColor != null ? getBgColor(theme) : theme.TextBoxBg; + Console.ForegroundColor = getFgColor != null ? getFgColor(theme) : theme.TextBoxFg; for (int y = GetTop(); y <= GetBottom(); ++y, ++index) { Console.SetCursorPosition(l, y); if (index < displayLines.Count) { @@ -158,7 +150,7 @@ public override void Draw(ConsoleTheme theme, bool focused) Console.Write(displayLines[index].PadRight(w)); break; case TextAlign.Center: - Console.Write(ScreenObject.PadCenter(displayLines[index], w)); + Console.Write(PadCenter(displayLines[index], w)); break; case TextAlign.Right: Console.Write(displayLines[index].PadLeft(w)); @@ -174,7 +166,7 @@ public override void Draw(ConsoleTheme theme, bool focused) DrawScrollbar( theme, GetRight(), GetTop(), GetBottom(), - GetTop() + 1 + (h - 3) * topLine / (displayLines.Count - h) + GetTop() + 1 + ((h - 3) * topLine / (displayLines.Count - h)) ); } } @@ -252,13 +244,13 @@ public void AddScrollBindings(ScreenContainer cont, bool drawMore = false) private bool needScroll = false; private int prevTextW; - private bool scrollToBottom; + private readonly bool scrollToBottom; private int topLine; - private TextAlign align; - private SynchronizedCollection<string> lines = new SynchronizedCollection<string>(); - private SynchronizedCollection<string> displayLines = new SynchronizedCollection<string>(); - private Func<ConsoleTheme, ConsoleColor> getBgColor; - private Func<ConsoleTheme, ConsoleColor> getFgColor; + private readonly TextAlign align; + private readonly SynchronizedCollection<string> lines = new SynchronizedCollection<string>(); + private readonly SynchronizedCollection<string> displayLines = new SynchronizedCollection<string>(); + private readonly Func<ConsoleTheme, ConsoleColor> getBgColor; + private readonly Func<ConsoleTheme, ConsoleColor> getFgColor; } /// <summary> diff --git a/ConsoleUI/Toolkit/Formatting.cs b/ConsoleUI/Toolkit/Formatting.cs index 390992914d..a23998c44d 100644 --- a/ConsoleUI/Toolkit/Formatting.cs +++ b/ConsoleUI/Toolkit/Formatting.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text.RegularExpressions; namespace CKAN.ConsoleUI.Toolkit { diff --git a/ConsoleUI/Toolkit/Keys.cs b/ConsoleUI/Toolkit/Keys.cs index 09bfcd3236..51976202a6 100644 --- a/ConsoleUI/Toolkit/Keys.cs +++ b/ConsoleUI/Toolkit/Keys.cs @@ -7,8 +7,8 @@ namespace CKAN.ConsoleUI.Toolkit { /// </summary> public static class Keys { - private const char LinuxEnter = (Char)10; - private const char WindowsEnter = (Char)13; + private const char LinuxEnter = (char)10; + private const char WindowsEnter = (char)13; /// <summary> /// Representation of enter key for key bindings @@ -29,98 +29,98 @@ public static class Keys { /// Representation of escape key for key bindings /// </summary> public static readonly ConsoleKeyInfo Escape = new ConsoleKeyInfo( - (Char)27, ConsoleKey.Escape, false, false, false + (char)27, ConsoleKey.Escape, false, false, false ); /// <summary> /// Representation of F1 for key bindings /// </summary> public static readonly ConsoleKeyInfo F1 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F1, false, false, false + (char)0, ConsoleKey.F1, false, false, false ); /// <summary> /// Representation of F2 for key bindings /// </summary> public static readonly ConsoleKeyInfo F2 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F2, false, false, false + (char)0, ConsoleKey.F2, false, false, false ); /// <summary> /// Representation of F5 for key bindings /// </summary> public static readonly ConsoleKeyInfo F5 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F5, false, false, false + (char)0, ConsoleKey.F5, false, false, false ); /// <summary> /// Representation of F8 for key bindings /// </summary> public static readonly ConsoleKeyInfo F8 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F8, false, false, false + (char)0, ConsoleKey.F8, false, false, false ); /// <summary> /// Representation of F9 for key bindings /// </summary> public static readonly ConsoleKeyInfo F9 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F9, false, false, false + (char)0, ConsoleKey.F9, false, false, false ); /// <summary> /// Representation of F10 for key bindings /// </summary> public static readonly ConsoleKeyInfo F10 = new ConsoleKeyInfo( - (Char)0, ConsoleKey.F10, false, false, false + (char)0, ConsoleKey.F10, false, false, false ); /// <summary> /// Representation of Apps for key bindings /// </summary> public static readonly ConsoleKeyInfo Apps = new ConsoleKeyInfo( - (Char)0, ConsoleKey.Applications, false, false, false + (char)0, ConsoleKey.Applications, false, false, false ); /// <summary> /// Representation of down arrow for key bindings /// </summary> public static readonly ConsoleKeyInfo DownArrow = new ConsoleKeyInfo( - (Char)0, ConsoleKey.DownArrow, false, false, false + (char)0, ConsoleKey.DownArrow, false, false, false ); /// <summary> /// Representation of up arrow for key bindings /// </summary> public static readonly ConsoleKeyInfo UpArrow = new ConsoleKeyInfo( - (Char)0, ConsoleKey.UpArrow, false, false, false + (char)0, ConsoleKey.UpArrow, false, false, false ); /// <summary> /// Representation of home for key bindings /// </summary> public static readonly ConsoleKeyInfo Home = new ConsoleKeyInfo( - (Char)0, ConsoleKey.Home, false, false, false + (char)0, ConsoleKey.Home, false, false, false ); /// <summary> /// Representation of end for key bindings /// </summary> public static readonly ConsoleKeyInfo End = new ConsoleKeyInfo( - (Char)0, ConsoleKey.End, false, false, false + (char)0, ConsoleKey.End, false, false, false ); /// <summary> /// Representation of page up for key bindings /// </summary> public static readonly ConsoleKeyInfo PageUp = new ConsoleKeyInfo( - (Char)0, ConsoleKey.PageUp, false, false, false + (char)0, ConsoleKey.PageUp, false, false, false ); /// <summary> /// Representation of page down for key bindings /// </summary> public static readonly ConsoleKeyInfo PageDown = new ConsoleKeyInfo( - (Char)0, ConsoleKey.PageDown, false, false, false + (char)0, ConsoleKey.PageDown, false, false, false ); /// <summary> @@ -129,11 +129,11 @@ public static class Keys { /// </summary> public static readonly ConsoleKeyInfo[] Plus = new ConsoleKeyInfo[] { new ConsoleKeyInfo( - (Char)'+', + '+', Platform.IsWindows ? ConsoleKey.OemPlus : ConsoleKey.Add, false, false, false ), new ConsoleKeyInfo( - (Char)'+', + '+', Platform.IsWindows ? ConsoleKey.OemPlus : ConsoleKey.Add, true, false, false ) @@ -143,7 +143,7 @@ public static class Keys { /// Representation of minus key for key bindings /// </summary> public static readonly ConsoleKeyInfo Minus = new ConsoleKeyInfo( - (Char)'-', + '-', Platform.IsWindows ? ConsoleKey.OemMinus : ConsoleKey.Subtract, false, false, false ); @@ -152,56 +152,56 @@ public static class Keys { /// Representation of Ctrl+A for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlA = new ConsoleKeyInfo( - (Char)1, ConsoleKey.A, false, false, true + (char)1, ConsoleKey.A, false, false, true ); /// <summary> /// Representation of Ctrl+D for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlD = new ConsoleKeyInfo( - (Char)4, ConsoleKey.D, false, false, true + (char)4, ConsoleKey.D, false, false, true ); /// <summary> /// Representation of Ctrl+F for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlF = new ConsoleKeyInfo( - (Char)6, ConsoleKey.F, false, false, true + (char)6, ConsoleKey.F, false, false, true ); /// <summary> /// Representation of Ctrl+L for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlL = new ConsoleKeyInfo( - (Char)12, ConsoleKey.Clear, false, false, false + (char)12, ConsoleKey.Clear, false, false, false ); /// <summary> /// Representation of Ctrl+Q for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlQ = new ConsoleKeyInfo( - (Char)17, ConsoleKey.Q, false, false, true + (char)17, ConsoleKey.Q, false, false, true ); /// <summary> /// Representation of Ctrl+R for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlR = new ConsoleKeyInfo( - (Char)18, ConsoleKey.R, false, false, true + (char)18, ConsoleKey.R, false, false, true ); /// <summary> /// Representation of Ctrl+U for key bindings /// </summary> public static readonly ConsoleKeyInfo CtrlU = new ConsoleKeyInfo( - (Char)21, ConsoleKey.U, false, false, true + (char)21, ConsoleKey.U, false, false, true ); /// <summary> /// Representation of Alt+H for key bindings /// </summary> public static readonly ConsoleKeyInfo AltH = new ConsoleKeyInfo( - (Char)'h', ConsoleKey.H, false, true, false + 'h', ConsoleKey.H, false, true, false ); /// <summary> @@ -209,49 +209,49 @@ public static class Keys { /// Does not work on MacOSX, so we /// </summary> public static readonly ConsoleKeyInfo AltX = new ConsoleKeyInfo( - (Char)'x', ConsoleKey.X, false, true, false + 'x', ConsoleKey.X, false, true, false ); /// <summary> /// Representation of letter 'a' for key bindings /// </summary> public static readonly ConsoleKeyInfo A = new ConsoleKeyInfo( - (Char)'a', ConsoleKey.A, false, false, false + 'a', ConsoleKey.A, false, false, false ); /// <summary> /// Representation of letter 'd' for key bindings /// </summary> public static readonly ConsoleKeyInfo D = new ConsoleKeyInfo( - (Char)'d', ConsoleKey.D, false, false, false + 'd', ConsoleKey.D, false, false, false ); /// <summary> /// Representation of letter 'e' for key bindings /// </summary> public static readonly ConsoleKeyInfo E = new ConsoleKeyInfo( - (Char)'e', ConsoleKey.E, false, false, false + 'e', ConsoleKey.E, false, false, false ); /// <summary> /// Representation of letter 'n' for key bindings /// </summary> public static readonly ConsoleKeyInfo N = new ConsoleKeyInfo( - (Char)'n', ConsoleKey.N, false, false, false + 'n', ConsoleKey.N, false, false, false ); /// <summary> /// Representation of letter 'r' for key bindings /// </summary> public static readonly ConsoleKeyInfo R = new ConsoleKeyInfo( - (Char)'r', ConsoleKey.R, false, false, false + 'r', ConsoleKey.R, false, false, false ); /// <summary> /// Representation of letter 'y' for key bindings /// </summary> public static readonly ConsoleKeyInfo Y = new ConsoleKeyInfo( - (Char)'y', ConsoleKey.Y, false, false, false + 'y', ConsoleKey.Y, false, false, false ); } diff --git a/ConsoleUI/Toolkit/ScreenContainer.cs b/ConsoleUI/Toolkit/ScreenContainer.cs index efb10c2e77..802b9e1530 100644 --- a/ConsoleUI/Toolkit/ScreenContainer.cs +++ b/ConsoleUI/Toolkit/ScreenContainer.cs @@ -176,13 +176,9 @@ protected void Interact(ConsoleTheme theme) /// Currently focused ScreenObject /// </returns> protected ScreenObject Focused() - { - if (focusIndex >= 0 && focusIndex < objects.Count) { - return objects[focusIndex]; - } else { - return null; - } - } + => focusIndex >= 0 && focusIndex < objects.Count + ? objects[focusIndex] + : null; /// <summary> /// Set the focus to a given ScreenObject @@ -222,12 +218,9 @@ private void DrawFooter(ConsoleTheme theme) Console.ForegroundColor = theme.FooterKeyFg; Console.Write(tipList[i].Key); Console.ForegroundColor = theme.FooterDescriptionFg; - string remainder; - if (tipList[i].Key == tipList[i].Description.Substring(0, 1)) { - remainder = tipList[i].Description.Substring(1); - } else { - remainder = $" - {tipList[i].Description}"; - } + string remainder = tipList[i].Key == tipList[i].Description.Substring(0, 1) + ? tipList[i].Description.Substring(1) + : $" - {tipList[i].Description}"; int maxW = Console.WindowWidth - Console.CursorLeft - 1; if (remainder.Length > maxW && maxW > 0) { Console.Write(remainder.Substring(0, maxW)); @@ -251,23 +244,21 @@ private void Blur(ScreenObject source, bool forward) focusIndex = 0; break; } - if (forward) { - focusIndex = (focusIndex + 1) % objects.Count; - } else { - focusIndex = (focusIndex + objects.Count - 1) % objects.Count; - } + focusIndex = forward + ? (focusIndex + 1) % objects.Count + : (focusIndex + objects.Count - 1) % objects.Count; } while (!objects[focusIndex].Focusable()); } } private bool done = false; - private List<ScreenObject> objects = new List<ScreenObject>(); + private readonly List<ScreenObject> objects = new List<ScreenObject>(); private int focusIndex = 0; - private Dictionary<ConsoleKeyInfo, KeyAction> bindings = new Dictionary<ConsoleKeyInfo, KeyAction>(); - private List<ScreenTip> tips = new List<ScreenTip>(); - private object screenLock = new object(); + private readonly Dictionary<ConsoleKeyInfo, KeyAction> bindings = new Dictionary<ConsoleKeyInfo, KeyAction>(); + private readonly List<ScreenTip> tips = new List<ScreenTip>(); + private readonly object screenLock = new object(); private static readonly string tipSeparator = $" {Symbols.vertLine} "; } @@ -287,7 +278,7 @@ public ScreenTip(string key, string descrip, Func<bool> dispIf = null) { Key = key; Description = descrip; - DisplayIf = dispIf != null ? dispIf : () => true; + DisplayIf = dispIf ?? (() => true); } /// <summary> diff --git a/ConsoleUI/Toolkit/ScreenObject.cs b/ConsoleUI/Toolkit/ScreenObject.cs index 169c7a0a9f..f13b6bf35c 100644 --- a/ConsoleUI/Toolkit/ScreenObject.cs +++ b/ConsoleUI/Toolkit/ScreenObject.cs @@ -69,15 +69,15 @@ public static string TruncateLength(string val, int w) /// <summary> /// Custom key bindings for this UI element /// </summary> - public Dictionary<ConsoleKeyInfo, ConsoleScreen.KeyAction> Bindings = - new Dictionary<ConsoleKeyInfo, ConsoleScreen.KeyAction>(); + public Dictionary<ConsoleKeyInfo, ScreenContainer.KeyAction> Bindings = + new Dictionary<ConsoleKeyInfo, ScreenContainer.KeyAction>(); /// <summary> /// Add a custom key binding /// </summary> /// <param name="k">Key to bind</param> /// <param name="a">Action to bind to key</param> - public void AddBinding(ConsoleKeyInfo k, ConsoleScreen.KeyAction a) + public void AddBinding(ConsoleKeyInfo k, ScreenContainer.KeyAction a) { Bindings.Add(k, a); } @@ -87,7 +87,7 @@ public void AddBinding(ConsoleKeyInfo k, ConsoleScreen.KeyAction a) /// </summary> /// <param name="keys">Keys to bind</param> /// <param name="a">Action to bind to key</param> - public void AddBinding(IEnumerable<ConsoleKeyInfo> keys, ConsoleScreen.KeyAction a) + public void AddBinding(IEnumerable<ConsoleKeyInfo> keys, ScreenContainer.KeyAction a) { foreach (ConsoleKeyInfo k in keys) { AddBinding(k, a); @@ -189,12 +189,10 @@ public virtual void OnKeyPress(ConsoleKeyInfo k) { } /// </summary> protected void Blur(bool forward) { - if (OnBlur != null) { - OnBlur(this, forward); - } + OnBlur?.Invoke(this, forward); } - private int left, top, right, bottom; + private readonly int left, top, right, bottom; private static readonly string scrollUp = "^"; private static readonly string scrollDown = "v"; diff --git a/Core/CKANPathUtils.cs b/Core/CKANPathUtils.cs index 1e8286347b..bbef46c3aa 100644 --- a/Core/CKANPathUtils.cs +++ b/Core/CKANPathUtils.cs @@ -126,11 +126,9 @@ public static string GetLeadingPathElements(string path) { path = NormalizePath(path); - if (Regex.IsMatch(path, "/")) - { - return Regex.Replace(path, @"(^.*)/.+", "$1"); - } - return String.Empty; + return Regex.IsMatch(path, "/") + ? Regex.Replace(path, @"(^.*)/.+", "$1") + : string.Empty; } /// <summary> @@ -188,7 +186,7 @@ public static string ToAbsolute(string path, string root) { throw new PathErrorKraken( path, - String.Format(Properties.Resources.PathUtilsAlreadyAbsolute, path) + string.Format(Properties.Resources.PathUtilsAlreadyAbsolute, path) ); } @@ -196,7 +194,7 @@ public static string ToAbsolute(string path, string root) { throw new PathErrorKraken( root, - String.Format(Properties.Resources.PathUtilsNotRoot, root) + string.Format(Properties.Resources.PathUtilsNotRoot, root) ); } diff --git a/Core/CompatibleGameVersions.cs b/Core/CompatibleGameVersions.cs index d03b516882..ec5c4ea4bb 100644 --- a/Core/CompatibleGameVersions.cs +++ b/Core/CompatibleGameVersions.cs @@ -5,7 +5,7 @@ namespace CKAN { [JsonConverter(typeof(CompatibleGameVersionsConverter))] - class CompatibleGameVersions + public class CompatibleGameVersions { public string GameVersionWhenWritten { get; set; } diff --git a/Core/Configuration/JsonConfiguration.cs b/Core/Configuration/JsonConfiguration.cs index 5478f20524..526f0e35f2 100644 --- a/Core/Configuration/JsonConfiguration.cs +++ b/Core/Configuration/JsonConfiguration.cs @@ -78,10 +78,7 @@ private class GameInstanceEntry // <summary> // Where the config file is located. // </summary> - public string ConfigFile - { - get => configFile; - } + public string ConfigFile => configFile; public string DownloadCacheDir { @@ -128,14 +125,7 @@ public long? CacheSizeLimit { lock (_lock) { - if (value < 0) - { - config.CacheSizeLimit = null; - } - else - { - config.CacheSizeLimit = value; - } + config.CacheSizeLimit = value < 0 ? null : value; SaveConfig(); } @@ -156,14 +146,7 @@ public int RefreshRate { lock (_lock) { - if (value <= 0) - { - config.RefreshRate = null; - } - else - { - config.RefreshRate = value; - } + config.RefreshRate = value <= 0 ? null : (int?)value; SaveConfig(); } diff --git a/Core/Configuration/Win32RegistryConfiguration.cs b/Core/Configuration/Win32RegistryConfiguration.cs index cf86f886e7..92dbbdffc5 100644 --- a/Core/Configuration/Win32RegistryConfiguration.cs +++ b/Core/Configuration/Win32RegistryConfiguration.cs @@ -22,7 +22,7 @@ public class Win32RegistryConfiguration : IConfiguration public string DownloadCacheDir { - get { return GetRegistryValue(@"DownloadCacheDir", defaultDownloadCacheDir); } + get => GetRegistryValue(@"DownloadCacheDir", defaultDownloadCacheDir); set { if (string.IsNullOrEmpty(value)) @@ -62,7 +62,7 @@ public long? CacheSizeLimit public int RefreshRate { - get { return GetRegistryValue(@"RefreshRate", 0); } + get => GetRegistryValue(@"RefreshRate", 0); set { if (value <= 0) @@ -76,24 +76,25 @@ public int RefreshRate } } - private int InstanceCount - { - get { return GetRegistryValue(@"KSPInstanceCount", 0); } - } + private int InstanceCount => GetRegistryValue(@"KSPInstanceCount", 0); public string AutoStartInstance { - get { return GetRegistryValue(@"KSPAutoStartInstance", ""); } - set { SetAutoStartInstance(value??String.Empty); } + get => GetRegistryValue(@"KSPAutoStartInstance", ""); + #pragma warning disable IDE0027 + set { SetAutoStartInstance(value ?? string.Empty); } + #pragma warning restore IDE0027 } public string Language { - get { return GetRegistryValue<string>("Language", null); } + get => GetRegistryValue<string>("Language", null); set { if (Utilities.AvailableLanguages.Contains(value)) + { SetRegistryValue("Language", value); + } } } diff --git a/Core/Converters/JsonIgnoreBadUrlConverter.cs b/Core/Converters/JsonIgnoreBadUrlConverter.cs index b34afb15f7..c68b9393f6 100644 --- a/Core/Converters/JsonIgnoreBadUrlConverter.cs +++ b/Core/Converters/JsonIgnoreBadUrlConverter.cs @@ -18,7 +18,9 @@ public override object ReadJson( string value = reader.Value?.ToString(); if (value == null) + { return null; + } try { @@ -43,10 +45,7 @@ public override bool CanConvert(Type object_type) /// Opt out of writing anything, otherwise things go horribly wrong when we try /// to write to the registry. /// </summary> - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { diff --git a/Core/Converters/JsonOldResourceUrlConverter.cs b/Core/Converters/JsonOldResourceUrlConverter.cs index 3f9345cef1..d68ae18ef7 100644 --- a/Core/Converters/JsonOldResourceUrlConverter.cs +++ b/Core/Converters/JsonOldResourceUrlConverter.cs @@ -32,10 +32,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return token.ToObject<Uri>(); } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -44,4 +41,3 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } } - diff --git a/Core/Converters/JsonPropertyNamesChangedConverter.cs b/Core/Converters/JsonPropertyNamesChangedConverter.cs index a9e125567b..1c169102d4 100644 --- a/Core/Converters/JsonPropertyNamesChangedConverter.cs +++ b/Core/Converters/JsonPropertyNamesChangedConverter.cs @@ -53,8 +53,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var changes = mapping; foreach (JProperty jp in jo.Properties()) { - string name; - if (!changes.TryGetValue(jp.Name, out name)) + if (!changes.TryGetValue(jp.Name, out string name)) { name = jp.Name; } @@ -72,12 +71,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist // No property, maybe there's a field FieldInfo field = objectType.GetTypeInfo().DeclaredFields.FirstOrDefault(fi => (fi.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? fi.Name) == name); - if (field != null) - { - field.SetValue(instance, - GetValue(field.GetCustomAttribute<JsonConverterAttribute>(), - jp.Value, field.FieldType, serializer)); - } + field?.SetValue(instance, + GetValue(field.GetCustomAttribute<JsonConverterAttribute>(), + jp.Value, field.FieldType, serializer)); } } return instance; diff --git a/Core/Converters/JsonRelationshipConverter.cs b/Core/Converters/JsonRelationshipConverter.cs index 058d1d0dca..7d5ca3a553 100644 --- a/Core/Converters/JsonRelationshipConverter.cs +++ b/Core/Converters/JsonRelationshipConverter.cs @@ -46,13 +46,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return null; } - public override bool CanWrite - { - get - { - return false; - } - } + public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { diff --git a/Core/Exporters/DelimeterSeparatedValueExporter.cs b/Core/Exporters/DelimeterSeparatedValueExporter.cs index 83edad6e22..fa9648082e 100644 --- a/Core/Exporters/DelimeterSeparatedValueExporter.cs +++ b/Core/Exporters/DelimeterSeparatedValueExporter.cs @@ -83,71 +83,39 @@ public void Export(IRegistryQuerier registry, Stream stream) } private string WriteUri(Uri uri) - { - return uri != null ? QuoteIfNecessary(uri.ToString()) : string.Empty; - } + => uri != null + ? QuoteIfNecessary(uri.ToString()) + : string.Empty; private string WriteRepository(ResourcesDescriptor resources) - { - if (resources != null && resources.repository != null) - { - return QuoteIfNecessary(resources.repository.ToString()); - } - - return string.Empty; - } + => resources != null && resources.repository != null + ? QuoteIfNecessary(resources.repository.ToString()) + : string.Empty; private string WriteHomepage(ResourcesDescriptor resources) - { - if (resources != null && resources.homepage != null) - { - return QuoteIfNecessary(resources.homepage.ToString()); - } - - return string.Empty; - } + => resources != null && resources.homepage != null + ? QuoteIfNecessary(resources.homepage.ToString()) + : string.Empty; private string WriteBugtracker(ResourcesDescriptor resources) - { - if (resources != null && resources.bugtracker != null) - { - return QuoteIfNecessary(resources.bugtracker.ToString()); - } - - return string.Empty; - } + => resources != null && resources.bugtracker != null + ? QuoteIfNecessary(resources.bugtracker.ToString()) + : string.Empty; private string WriteSpaceDock(ResourcesDescriptor resources) - { - if (resources != null && resources.spacedock != null) - { - return QuoteIfNecessary(resources.spacedock.ToString()); - } - - return string.Empty; - } + => resources != null && resources.spacedock != null + ? QuoteIfNecessary(resources.spacedock.ToString()) + : string.Empty; private string WriteCurse(ResourcesDescriptor resources) - { - if (resources != null && resources.curse != null) - { - return QuoteIfNecessary(resources.curse.ToString()); - } - - return string.Empty; - } + => resources != null && resources.curse != null + ? QuoteIfNecessary(resources.curse.ToString()) + : string.Empty; private string QuoteIfNecessary(string value) - { - if (value != null && value.IndexOf(_delimeter, StringComparison.Ordinal) >= 0) - { - return "\"" + value + "\""; - } - else - { - return value; - } - } + => value != null && value.IndexOf(_delimeter, StringComparison.Ordinal) >= 0 + ? "\"" + value + "\"" + : value; public enum Delimeter { diff --git a/Core/Extensions/CryptoExtensions.cs b/Core/Extensions/CryptoExtensions.cs index 9b08eb3b5a..2dc2d88cdf 100644 --- a/Core/Extensions/CryptoExtensions.cs +++ b/Core/Extensions/CryptoExtensions.cs @@ -21,7 +21,7 @@ public static class CryptoExtensions /// <param name="cancelToken">A cancellation token that can be used to abort the hash</param> /// <returns>The requested hash of the input stream</returns> public static byte[] ComputeHash(this HashAlgorithm hashAlgo, Stream stream, - IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + IProgress<long> progress, CancellationToken cancelToken = default) { const int bufSize = 1024 * 1024; var buffer = new byte[bufSize]; diff --git a/Core/Extensions/DictionaryExtensions.cs b/Core/Extensions/DictionaryExtensions.cs index 0f34b17944..2ab1ae94f1 100644 --- a/Core/Extensions/DictionaryExtensions.cs +++ b/Core/Extensions/DictionaryExtensions.cs @@ -14,7 +14,7 @@ public static bool DictionaryEquals<K, V>(this IDictionary<K, V> a, public static V GetOrDefault<K, V>(this Dictionary<K, V> dict, K key) { - V val = default(V); + V val = default; if (key != null) { dict.TryGetValue(key, out val); diff --git a/Core/Extensions/EnumerableExtensions.cs b/Core/Extensions/EnumerableExtensions.cs index 3a20f7dbee..a6d4aef63e 100644 --- a/Core/Extensions/EnumerableExtensions.cs +++ b/Core/Extensions/EnumerableExtensions.cs @@ -10,12 +10,9 @@ namespace CKAN.Extensions public static class EnumerableExtensions { public static ICollection<T> AsCollection<T>(this IEnumerable<T> source) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - return source is ICollection<T> collection ? collection : source.ToArray(); - } + => source == null + ? throw new ArgumentNullException(nameof(source)) + : source is ICollection<T> collection ? collection : source.ToArray(); #if NET45 @@ -249,19 +246,17 @@ public IEnumerator<T> GetEnumerator() } IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + => GetEnumerator(); private IEnumerator<T> GetMemoizingEnumerator() { - for (Int32 index = 0; TryGetItem(index, out T item); ++index) + for (int index = 0; TryGetItem(index, out T item); ++index) { yield return item; } } - private bool TryGetItem(Int32 index, out T item) + private bool TryGetItem(int index, out T item) { lock (gate) { @@ -270,12 +265,12 @@ private bool TryGetItem(Int32 index, out T item) // The iteration may have completed while waiting for the lock if (isCacheComplete) { - item = default(T); + item = default; return false; } if (!enumerator.MoveNext()) { - item = default(T); + item = default; isCacheComplete = true; enumerator.Dispose(); return false; @@ -287,10 +282,8 @@ private bool TryGetItem(Int32 index, out T item) } } - private bool IsItemInCache(Int32 index) - { - return index < cache.Count; - } + private bool IsItemInCache(int index) + => index < cache.Count; private readonly IEnumerable<T> source; private IEnumerator<T> enumerator; diff --git a/Core/Extensions/IOExtensions.cs b/Core/Extensions/IOExtensions.cs index ab597a8ba7..9178520be4 100644 --- a/Core/Extensions/IOExtensions.cs +++ b/Core/Extensions/IOExtensions.cs @@ -66,7 +66,7 @@ public static DriveInfo GetDrive(this DirectoryInfo dir) /// <param name="src">Stream from which to copy</param> /// <param name="dest">Stream to which to copy</param> /// <param name="progress">Callback to notify as we traverse the input, called with count of bytes received</param> - public static void CopyTo(this Stream src, Stream dest, IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + public static void CopyTo(this Stream src, Stream dest, IProgress<long> progress, CancellationToken cancelToken = default) { // CopyTo says its default buffer is 81920, but we want more than 1 update for a 100 KiB file const int bufSize = 16384; diff --git a/Core/FileIdentifier.cs b/Core/FileIdentifier.cs index 3eb7ede37e..626dfe8811 100644 --- a/Core/FileIdentifier.cs +++ b/Core/FileIdentifier.cs @@ -60,12 +60,7 @@ private static bool CheckGZip(Stream stream) } // Compare against the magic numbers. - if (buffer.SequenceEqual(gzip_identifier)) - { - return true; - } - - return false; + return buffer.SequenceEqual(gzip_identifier); } /// <summary> @@ -148,12 +143,9 @@ private static bool CheckZip(Stream stream) } // Compare against the magic numbers. - if (buffer.SequenceEqual(zip_identifier) || buffer.SequenceEqual(zip_identifier_empty) || buffer.SequenceEqual(zip_identifier_spanned)) - { - return true; - } - - return false; + return buffer.SequenceEqual(zip_identifier) + || buffer.SequenceEqual(zip_identifier_empty) + || buffer.SequenceEqual(zip_identifier_spanned); } /// <summary> @@ -184,14 +176,7 @@ public static FileType IdentifyFile(Stream stream) stream.Seek (0, SeekOrigin.Begin); using (ICSharpCode.SharpZipLib.GZip.GZipInputStream gz_stream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream (stream)) { - if (CheckTar(gz_stream)) - { - type = FileType.TarGz; - } - else - { - type = FileType.GZip; - } + type = CheckTar(gz_stream) ? FileType.TarGz : FileType.GZip; } } else if (CheckTar(stream)) diff --git a/Core/GameInstance.cs b/Core/GameInstance.cs index dbae00f7ad..01f8e191bc 100644 --- a/Core/GameInstance.cs +++ b/Core/GameInstance.cs @@ -125,7 +125,7 @@ private void SetupCkanDirectories() public void SetCompatibleVersions(List<GameVersion> compatibleVersions) { - this._compatibleVersions = compatibleVersions.Distinct().ToList(); + _compatibleVersions = compatibleVersions.Distinct().ToList(); SaveCompatibleVersions(); } @@ -144,7 +144,7 @@ private void SaveCompatibleVersions() private void LoadCompatibleVersions() { - String path = CompatibleGameVersionsFile(); + string path = CompatibleGameVersionsFile(); if (File.Exists(path)) { CompatibleGameVersions compatibleGameVersions = JsonConvert.DeserializeObject<CompatibleGameVersions>(File.ReadAllText(path)); @@ -162,7 +162,7 @@ private string CompatibleGameVersionsFile() => Path.Combine(CkanDir(), game.CompatibleVersionsFile); public List<GameVersion> GetCompatibleVersions() - => new List<GameVersion>(this._compatibleVersions); + => new List<GameVersion>(_compatibleVersions); public HashSet<string> GetSuppressedCompatWarningIdentifiers => SuppressedCompatWarningIdentifiers.LoadFrom(Version(), SuppressedCompatWarningIdentifiersFile).Identifiers; @@ -183,10 +183,12 @@ public string[] InstallFilters ? JsonConvert.DeserializeObject<string[]>(File.ReadAllText(InstallFiltersFile)) : new string[] { }; + #pragma warning disable IDE0027 set { File.WriteAllText(InstallFiltersFile, JsonConvert.SerializeObject(value)); } + #pragma warning restore IDE0027 } private string InstallFiltersFile => Path.Combine(CkanDir(), "install_filters.json"); @@ -367,7 +369,7 @@ public string ToAbsoluteGameDir(string path) /// </returns> public string DllPathToIdentifier(string relative_path) { - var paths = Enumerable.Repeat<string>(game.PrimaryModDirectoryRelative, 1) + var paths = Enumerable.Repeat(game.PrimaryModDirectoryRelative, 1) .Concat(game.AlternateModDirectoriesRelative); if (!paths.Any(p => relative_path.StartsWith($"{p}/", StringComparison.CurrentCultureIgnoreCase))) { diff --git a/Core/GameInstanceManager.cs b/Core/GameInstanceManager.cs index 46affb2c3f..e8cb2b3b8f 100644 --- a/Core/GameInstanceManager.cs +++ b/Core/GameInstanceManager.cs @@ -50,15 +50,12 @@ public class GameInstanceManager : IDisposable public string AutoStartInstance { - get - { - return HasInstance(Configuration.AutoStartInstance) - ? Configuration.AutoStartInstance - : null; - } + get => HasInstance(Configuration.AutoStartInstance) + ? Configuration.AutoStartInstance + : null; private set { - if (!String.IsNullOrEmpty(value) && !HasInstance(value)) + if (!string.IsNullOrEmpty(value) && !HasInstance(value)) { throw new InvalidKSPInstanceKraken(value); } @@ -66,10 +63,7 @@ private set } } - public SortedList<string, GameInstance> Instances - { - get { return new SortedList<string, GameInstance>(instances); } - } + public SortedList<string, GameInstance> Instances => new SortedList<string, GameInstance>(instances); public GameInstanceManager(IUser user, IConfiguration configuration = null) { @@ -212,10 +206,7 @@ public GameInstance AddInstance(GameInstance instance) public GameInstance AddInstance(string path, string name, IUser user) { var game = DetermineGame(new DirectoryInfo(path), user); - if (game == null) - return null; - - return AddInstance(new GameInstance(game, path, name, user)); + return game == null ? null : AddInstance(new GameInstance(game, path, name, user)); } /// <summary> @@ -294,12 +285,12 @@ public void FakeInstance(IGame game, string newName, string newPath, GameVersion { fileMgr.WriteAllText( Path.Combine(newPath, b), - String.Format("build id = {0}", version.Build)); + string.Format("build id = {0}", version.Build)); } } // Create the readme.txt WITHOUT build number. - fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), String.Format("Version {0}", new GameVersion(version.Major, version.Minor, version.Patch).ToString())); + fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), string.Format("Version {0}", new GameVersion(version.Major, version.Minor, version.Patch).ToString())); // Create the needed folder structure and the readme.txt for DLCs that should be simulated. if (dlcs != null) @@ -310,18 +301,20 @@ public void FakeInstance(IGame game, string newName, string newPath, GameVersion GameVersion dlcVersion = dlc.Value; if (!dlcDetector.AllowedOnBaseVersion(version)) + { throw new WrongGameVersionKraken( version, string.Format(Properties.Resources.GameInstanceFakeDLCNotAllowed, game.ShortName, dlcDetector.ReleaseGameVersion, dlcDetector.IdentifierBaseName)); + } string dlcDir = Path.Combine(newPath, dlcDetector.InstallPath()); fileMgr.CreateDirectory(dlcDir); fileMgr.WriteAllText( Path.Combine(dlcDir, "readme.txt"), - String.Format("Version {0}", dlcVersion)); + string.Format("Version {0}", dlcVersion)); } } @@ -337,7 +330,7 @@ public void FakeInstance(IGame game, string newName, string newPath, GameVersion /// </summary> /// <returns> A unused valid instance name.</returns> /// <param name="name">The name to use as a base.</param> - /// <exception cref="CKAN.Kraken">Could not find a valid name.</exception> + /// <exception cref="Kraken">Could not find a valid name.</exception> public string GetNextValidInstanceName(string name) { // Check if the current name is valid @@ -376,7 +369,7 @@ private bool InstanceNameIsValid(string name) { // Discard null, empty strings and white space only strings. // Look for the current name in the list of loaded instances. - return !String.IsNullOrWhiteSpace(name) && !HasInstance(name); + return !string.IsNullOrWhiteSpace(name) && !HasInstance(name); } /// <summary> @@ -595,12 +588,12 @@ public bool TrySetupCache(string path, out string failureReason) } /// <summary> - /// Releases all resource used by the <see cref="CKAN.GameInstance"/> object. + /// Releases all resource used by the <see cref="GameInstance"/> object. /// </summary> - /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="CKAN.GameInstance"/>. The <see cref="Dispose"/> - /// method leaves the <see cref="CKAN.GameInstance"/> in an unusable state. After calling <see cref="Dispose"/>, you must - /// release all references to the <see cref="CKAN.GameInstance"/> so the garbage collector can reclaim the memory that - /// the <see cref="CKAN.GameInstance"/> was occupying.</remarks> + /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="GameInstance"/>. The <see cref="Dispose"/> + /// method leaves the <see cref="GameInstance"/> in an unusable state. After calling <see cref="Dispose"/>, you must + /// release all references to the <see cref="GameInstance"/> so the garbage collector can reclaim the memory that + /// the <see cref="GameInstance"/> was occupying.</remarks> public void Dispose() { if (Cache != null) diff --git a/Core/Games/KerbalSpaceProgram.cs b/Core/Games/KerbalSpaceProgram.cs index 51c3ffcfad..216ad4d19e 100644 --- a/Core/Games/KerbalSpaceProgram.cs +++ b/Core/Games/KerbalSpaceProgram.cs @@ -167,7 +167,9 @@ public void RebuildSubdirectories(string absGameRoot) { string sAbsolutePath = Path.Combine(absGameRoot, Path.Combine(sRelativePath)); if (!Directory.Exists(sAbsolutePath)) + { Directory.CreateDirectory(sAbsolutePath); + } } } @@ -225,7 +227,7 @@ public List<GameVersion> KnownVersions } public GameVersion[] EmbeddedGameVersions - => JsonConvert.DeserializeObject<GameVersionProviders.JBuilds>( + => JsonConvert.DeserializeObject<JBuilds>( new StreamReader(Assembly.GetExecutingAssembly() .GetManifestResourceStream("CKAN.builds-ksp.json")) .ReadToEnd()) @@ -234,7 +236,7 @@ public GameVersion[] EmbeddedGameVersions .ToArray(); public GameVersion[] ParseBuildsJson(JToken json) - => json.ToObject<GameVersionProviders.JBuilds>() + => json.ToObject<JBuilds>() .Builds .Select(b => GameVersion.Parse(b.Value)) .ToArray(); @@ -325,11 +327,7 @@ private static string KSPDirectory(string steamPath) // Try with the lowercase version. installPath = Path.Combine(steamPath, "steamapps", "common", "Kerbal Space Program"); - if (Directory.Exists(installPath)) - { - return installPath; - } - return null; + return Directory.Exists(installPath) ? installPath : null; } /// <summary> diff --git a/Core/Games/KerbalSpaceProgram/DLC/BreakingGroundDlcDetector.cs b/Core/Games/KerbalSpaceProgram/DLC/BreakingGroundDlcDetector.cs index eff74221aa..4802af14f1 100644 --- a/Core/Games/KerbalSpaceProgram/DLC/BreakingGroundDlcDetector.cs +++ b/Core/Games/KerbalSpaceProgram/DLC/BreakingGroundDlcDetector.cs @@ -1,7 +1,3 @@ -using System.Collections.Generic; - -using CKAN.Games.KerbalSpaceProgram; - namespace CKAN.Games.KerbalSpaceProgram.DLC { /// <summary> diff --git a/Core/Games/KerbalSpaceProgram/DLC/IDlcDetector.cs b/Core/Games/KerbalSpaceProgram/DLC/IDlcDetector.cs index b442591380..54e11b1933 100644 --- a/Core/Games/KerbalSpaceProgram/DLC/IDlcDetector.cs +++ b/Core/Games/KerbalSpaceProgram/DLC/IDlcDetector.cs @@ -1,5 +1,4 @@ using CKAN.Versioning; -using CKAN.Games; namespace CKAN.DLC { diff --git a/Core/Games/KerbalSpaceProgram/DLC/MakingHistoryDlcDetector.cs b/Core/Games/KerbalSpaceProgram/DLC/MakingHistoryDlcDetector.cs index 84965b80da..ef946905e1 100644 --- a/Core/Games/KerbalSpaceProgram/DLC/MakingHistoryDlcDetector.cs +++ b/Core/Games/KerbalSpaceProgram/DLC/MakingHistoryDlcDetector.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; -using CKAN.Games.KerbalSpaceProgram; - namespace CKAN.Games.KerbalSpaceProgram.DLC { /// <summary> diff --git a/Core/Games/KerbalSpaceProgram/DLC/StandardDlcDetectorBase.cs b/Core/Games/KerbalSpaceProgram/DLC/StandardDlcDetectorBase.cs index 0e8eb946b9..a707d38245 100644 --- a/Core/Games/KerbalSpaceProgram/DLC/StandardDlcDetectorBase.cs +++ b/Core/Games/KerbalSpaceProgram/DLC/StandardDlcDetectorBase.cs @@ -5,7 +5,6 @@ using CKAN.DLC; using CKAN.Versioning; -using CKAN.Games; namespace CKAN.Games.KerbalSpaceProgram.DLC { @@ -25,7 +24,7 @@ public abstract class StandardDlcDetectorBase : IDlcDetector private readonly string DirectoryBaseName; private readonly Dictionary<string, string> CanonicalVersions; - private IGame game; + private readonly IGame game; private static readonly Regex VersionPattern = new Regex( @"^Version\s+(?<version>\S+)", @@ -38,10 +37,14 @@ protected StandardDlcDetectorBase(IGame game, string identifierBaseName, GameVer protected StandardDlcDetectorBase(IGame game, string identifierBaseName, string directoryBaseName, GameVersion releaseGameVersion, Dictionary<string, string> canonicalVersions = null) { if (string.IsNullOrWhiteSpace(identifierBaseName)) + { throw new ArgumentException("Value must be provided.", nameof(identifierBaseName)); + } if (string.IsNullOrWhiteSpace(directoryBaseName)) + { throw new ArgumentException("Value must be provided.", nameof(directoryBaseName)); + } this.game = game; IdentifierBaseName = identifierBaseName; @@ -71,7 +74,9 @@ public virtual bool IsInstalled(GameInstance ksp, out string identifier, out Unm var versionStr = match.Groups["version"].Value; if (CanonicalVersions.ContainsKey(versionStr)) + { versionStr = CanonicalVersions[versionStr]; + } version = new UnmanagedModuleVersion(versionStr); break; diff --git a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildIdVersionProvider.cs b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildIdVersionProvider.cs index c3bed58b8e..3983673b55 100644 --- a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildIdVersionProvider.cs +++ b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildIdVersionProvider.cs @@ -33,7 +33,7 @@ public bool TryGetVersion(string directory, out GameVersion result) if (foundVersions.Count < 1) { - result = default(GameVersion); + result = default; return false; } if (foundVersions.Count > 1) @@ -66,7 +66,7 @@ private bool TryGetVersionFromFile(string file, out GameVersion result) } } - result = default(GameVersion); + result = default; return false; } diff --git a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildMap.cs b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildMap.cs index 45aab06f7e..d528d59e18 100644 --- a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildMap.cs +++ b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspBuildMap.cs @@ -8,7 +8,6 @@ using Newtonsoft.Json; using CKAN.Versioning; -using CKAN.Configuration; namespace CKAN.Games.KerbalSpaceProgram.GameVersionProviders { @@ -39,7 +38,6 @@ public sealed class KspBuildMap : IKspBuildMap private static readonly ILog Log = LogManager.GetLogger(typeof(KspBuildMap)); private readonly object _buildMapLock = new object(); - private readonly IConfiguration _configuration; private JBuilds _jBuilds; public GameVersion this[string buildId] @@ -48,8 +46,7 @@ public GameVersion this[string buildId] { EnsureBuildMap(); - string version; - return _jBuilds.Builds.TryGetValue(buildId, out version) ? GameVersion.Parse(version) : null; + return _jBuilds.Builds.TryGetValue(buildId, out string version) ? GameVersion.Parse(version) : null; } } @@ -64,23 +61,29 @@ public List<GameVersion> KnownVersions } } - public KspBuildMap(IConfiguration configuration) + public KspBuildMap() { - _configuration = configuration; } private void EnsureBuildMap() { - if (ReferenceEquals(_jBuilds, null)) + if (_jBuilds is null) { lock (_buildMapLock) { - if (ReferenceEquals(_jBuilds, null)) + if (_jBuilds is null) { // Check for a cached copy of the remote build map - if (TrySetCachedBuildMap()) return; + if (TrySetCachedBuildMap()) + { + return; + } // If that doesn't exist, use the copy from when we were compiled - if (TrySetEmbeddedBuildMap()) return; + if (TrySetEmbeddedBuildMap()) + { + return; + } + Log.Warn("Could not load build map from cached or embedded copy"); } } @@ -93,7 +96,11 @@ private void EnsureBuildMap() public void Refresh() { Log.Debug("Refreshing build map from server"); - if (TrySetRemoteBuildMap()) return; + if (TrySetRemoteBuildMap()) + { + return; + } + Log.Warn("Could not refresh the build map from remote server"); } diff --git a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspReadmeVersionProvider.cs b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspReadmeVersionProvider.cs index e484a60d1b..c5453f483f 100644 --- a/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspReadmeVersionProvider.cs +++ b/Core/Games/KerbalSpaceProgram/GameVersionProviders/KspReadmeVersionProvider.cs @@ -31,7 +31,7 @@ public bool TryGetVersion(string directory, out GameVersion result) } } - result = default(GameVersion); + result = default; return false; } } diff --git a/Core/Games/KerbalSpaceProgram2.cs b/Core/Games/KerbalSpaceProgram2.cs index a8405a0883..580709d7a7 100644 --- a/Core/Games/KerbalSpaceProgram2.cs +++ b/Core/Games/KerbalSpaceProgram2.cs @@ -142,7 +142,9 @@ public void RebuildSubdirectories(string absGameRoot) const string dataDir = "KSP2_x64_Data"; var path = Path.Combine(absGameRoot, dataDir); if (!Directory.Exists(path)) + { Directory.CreateDirectory(path); + } } public string DefaultCommandLine => @@ -244,11 +246,7 @@ private static string GameDirectory(string steamPath) // Try with the lowercase version. installPath = Path.Combine(steamPath, "steamapps", "common", "Kerbal Space Program 2"); - if (Directory.Exists(installPath)) - { - return installPath; - } - return null; + return Directory.Exists(installPath) ? installPath : null; } private static readonly ILog log = LogManager.GetLogger(typeof(KerbalSpaceProgram2)); diff --git a/Core/ModuleInstaller.cs b/Core/ModuleInstaller.cs index 3e5b7a0d09..ed13591d6b 100644 --- a/Core/ModuleInstaller.cs +++ b/Core/ModuleInstaller.cs @@ -1496,10 +1496,9 @@ public static string StripV(string version) { Match match = Regex.Match(version, @"^(?<num>\d\:)?[vV]+(ersion)?[_.]*(?<ver>\d.*)$"); - if (match.Success) - return match.Groups["num"].Value + match.Groups["ver"].Value; - else - return version; + return match.Success + ? match.Groups["num"].Value + match.Groups["ver"].Value + : version; } /// <summary> diff --git a/Core/Net/AutoUpdate.cs b/Core/Net/AutoUpdate.cs index 628180a3b1..1eef7b8c79 100644 --- a/Core/Net/AutoUpdate.cs +++ b/Core/Net/AutoUpdate.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Reflection; -using log4net; using Newtonsoft.Json; using CKAN.Versioning; @@ -168,7 +167,7 @@ public void StartUpdateProcess(bool launchCKANAfterUpdate, IUser user = null) { Verb = "runas", FileName = updaterFilename, - Arguments = String.Format(@"{0} ""{1}"" ""{2}"" {3}", -pid, exePath, ckanFilename, launchCKANAfterUpdate ? "launch" : "nolaunch"), + Arguments = string.Format(@"{0} ""{1}"" ""{2}"" {3}", -pid, exePath, ckanFilename, launchCKANAfterUpdate ? "launch" : "nolaunch"), UseShellExecute = false, // Make child's stdin a pipe so it can tell when we exit RedirectStandardInput = true, @@ -188,13 +187,13 @@ public static void SetExecutable(string fileName) string command = string.Format("+x \"{0}\"", fileName); - ProcessStartInfo permsinfo = new ProcessStartInfo("chmod", command); - permsinfo.UseShellExecute = false; + ProcessStartInfo permsinfo = new ProcessStartInfo("chmod", command) + { + UseShellExecute = false + }; Process permsprocess = Process.Start(permsinfo); permsprocess.WaitForExit(); } } - - private static readonly ILog log = LogManager.GetLogger(typeof(AutoUpdate)); } } diff --git a/Core/Net/Net.cs b/Core/Net/Net.cs index db2cc6aa80..12d1f68294 100644 --- a/Core/Net/Net.cs +++ b/Core/Net/Net.cs @@ -66,10 +66,10 @@ public static string Download(Uri url, out string etag, string filename = null, => Download(url.OriginalString, out etag, filename, user); public static string Download(Uri url, string filename = null, IUser user = null) - => Download(url, out string etag, filename, user); + => Download(url, out _, filename, user); public static string Download(string url, string filename = null, IUser user = null) - => Download(url, out string etag, filename, user); + => Download(url, out _, filename, user); public static string Download(string url, out string etag, string filename = null, IUser user = null) { @@ -323,9 +323,9 @@ public static Uri GetRawUri(Uri remoteUri) log.InfoFormat("Remote GitHub URL is in raw format, using as is."); return remoteUri; } - if (segments.Count < 6 || - string.Compare(segments[3], "blob/", StringComparison.OrdinalIgnoreCase) != 0 && - string.Compare(segments[3], "tree/", StringComparison.OrdinalIgnoreCase) != 0) + if (segments.Count < 6 + || (string.Compare(segments[3], "blob/", StringComparison.OrdinalIgnoreCase) != 0 + && string.Compare(segments[3], "tree/", StringComparison.OrdinalIgnoreCase) != 0)) { log.WarnFormat("Remote non-raw GitHub URL is in an unknown format, using as is."); return remoteUri; diff --git a/Core/Net/NetAsyncDownloader.cs b/Core/Net/NetAsyncDownloader.cs index c32f77271f..ca9c7c4bb9 100644 --- a/Core/Net/NetAsyncDownloader.cs +++ b/Core/Net/NetAsyncDownloader.cs @@ -56,9 +56,8 @@ public void Download(Uri url, string path) { ResetAgent(); // Check whether to use an auth token for this host - string token; if (url.IsAbsoluteUri - && ServiceLocator.Container.Resolve<IConfiguration>().TryGetAuthToken(url.Host, out token) + && ServiceLocator.Container.Resolve<IConfiguration>().TryGetAuthToken(url.Host, out string token) && !string.IsNullOrEmpty(token)) { log.InfoFormat("Using auth token for {0}", url.Host); @@ -129,8 +128,8 @@ private void ResetAgent() private readonly object dlMutex = new object(); // NOTE: Never remove anything from this, because closures have indexes into it! // (Clearing completely after completion is OK) - private List<NetAsyncDownloaderDownloadPart> downloads = new List<NetAsyncDownloaderDownloadPart>(); - private List<NetAsyncDownloaderDownloadPart> queuedDownloads = new List<NetAsyncDownloaderDownloadPart>(); + private readonly List<NetAsyncDownloaderDownloadPart> downloads = new List<NetAsyncDownloaderDownloadPart>(); + private readonly List<NetAsyncDownloaderDownloadPart> queuedDownloads = new List<NetAsyncDownloaderDownloadPart>(); private int completed_downloads; // For inter-thread communication @@ -228,7 +227,9 @@ public void DownloadAndWait(IList<Net.DownloadTarget> targets) { throw new MissingCertificateKraken(); } + #pragma warning disable IDE0011 else switch ((wex.Response as HttpWebResponse)?.StatusCode) + #pragma warning restore IDE0011 { // Handle HTTP 403 used for throttling case HttpStatusCode.Forbidden: @@ -314,7 +315,7 @@ private void DownloadModule(NetAsyncDownloaderDownloadPart dl) // Schedule for us to get back progress reports. dl.Progress += (ProgressPercentage, BytesReceived, TotalBytesToReceive) => - FileProgressReport(index, ProgressPercentage, BytesReceived, TotalBytesToReceive); + FileProgressReport(index, BytesReceived, TotalBytesToReceive); // And schedule a notification if we're done (or if something goes wrong) dl.Done += (sender, args, etag) => @@ -364,7 +365,7 @@ private void triggerCompleted() /// <param name="percent">The percent complete</param> /// <param name="bytesDownloaded">The bytes downloaded</param> /// <param name="bytesToDownload">The total amount of bytes we expect to download</param> - private void FileProgressReport(int index, int percent, long bytesDownloaded, long bytesToDownload) + private void FileProgressReport(int index, long bytesDownloaded, long bytesToDownload) { NetAsyncDownloaderDownloadPart download = downloads[index]; @@ -390,7 +391,10 @@ private void FileProgressReport(int index, int percent, long bytesDownloaded, lo foreach (NetAsyncDownloaderDownloadPart t in downloads.ToList()) { if (t == null) + { continue; + } + if (t.bytesLeft > 0) { totalBytesPerSecond += t.bytesPerSecond; @@ -403,14 +407,17 @@ private void FileProgressReport(int index, int percent, long bytesDownloaded, lo { // Somehow managed to get a NullRef for t here if (dl == null) + { continue; + } + totalBytesLeft += dl.target.size; totalSize += dl.target.size; } int totalPercentage = (int)(((totalSize - totalBytesLeft) * 100) / (totalSize)); User.RaiseProgress( - String.Format(Properties.Resources.NetAsyncDownloaderProgress, + string.Format(Properties.Resources.NetAsyncDownloaderProgress, CkanModule.FmtSize(totalBytesPerSecond), CkanModule.FmtSize(totalBytesLeft)), totalPercentage); diff --git a/Core/Net/NetAsyncModulesDownloader.cs b/Core/Net/NetAsyncModulesDownloader.cs index fa28c9682d..280ab0fd47 100644 --- a/Core/Net/NetAsyncModulesDownloader.cs +++ b/Core/Net/NetAsyncModulesDownloader.cs @@ -117,7 +117,7 @@ public void CancelDownload() private const string defaultMimeType = "application/octet-stream"; - private List<CkanModule> modules; + private readonly List<CkanModule> modules; private readonly NetAsyncDownloader downloader; private IUser User => downloader.User; private readonly NetModuleCache cache; diff --git a/Core/Net/NetFileCache.cs b/Core/Net/NetFileCache.cs index d582619c52..46f56a262e 100644 --- a/Core/Net/NetFileCache.cs +++ b/Core/Net/NetFileCache.cs @@ -27,11 +27,11 @@ namespace CKAN [PermissionSet(SecurityAction.Demand, Name="FullTrust")] public class NetFileCache : IDisposable { - private FileSystemWatcher watcher; + private readonly FileSystemWatcher watcher; // hash => full file path private Dictionary<string, string> cachedFiles; - private string cachePath; - private GameInstanceManager manager; + private readonly string cachePath; + private readonly GameInstanceManager manager; private static readonly Regex cacheFileRegex = new Regex("^[0-9A-F]{8}-", RegexOptions.Compiled); private static readonly ILog log = LogManager.GetLogger(typeof (NetFileCache)); @@ -85,12 +85,12 @@ public NetFileCache(string path) } /// <summary> - /// Releases all resource used by the <see cref="CKAN.NetFileCache"/> object. + /// Releases all resource used by the <see cref="NetFileCache"/> object. /// </summary> - /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="CKAN.NetFileCache"/>. The - /// <see cref="Dispose"/> method leaves the <see cref="CKAN.NetFileCache"/> in an unusable state. After calling - /// <see cref="Dispose"/>, you must release all references to the <see cref="CKAN.NetFileCache"/> so the garbage - /// collector can reclaim the memory that the <see cref="CKAN.NetFileCache"/> was occupying.</remarks> + /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="NetFileCache"/>. The + /// <see cref="Dispose"/> method leaves the <see cref="NetFileCache"/> in an unusable state. After calling + /// <see cref="Dispose"/>, you must release all references to the <see cref="NetFileCache"/> so the garbage + /// collector can reclaim the memory that the <see cref="NetFileCache"/> was occupying.</remarks> public void Dispose() { // All we really need to do is clear our FileSystemWatcher. @@ -106,19 +106,18 @@ private string GetInProgressFileName(string hash, string description) { Directory.CreateDirectory(InProgressPath); return Directory.EnumerateFiles(InProgressPath) - .Where(path => new FileInfo(path).Name.StartsWith(hash)) - .FirstOrDefault() + .FirstOrDefault(path => new FileInfo(path).Name.StartsWith(hash)) // If not found, return the name to create ?? Path.Combine(InProgressPath, $"{hash}-{description}"); } public string GetInProgressFileName(Uri url, string description) - => GetInProgressFileName(NetFileCache.CreateURLHash(url), + => GetInProgressFileName(CreateURLHash(url), description); public string GetInProgressFileName(List<Uri> urls, string description) { - var filenames = urls?.Select(url => GetInProgressFileName(NetFileCache.CreateURLHash(url), description)) + var filenames = urls?.Select(url => GetInProgressFileName(CreateURLHash(url), description)) .ToArray(); return filenames?.FirstOrDefault(filename => File.Exists(filename)) ?? filenames?.FirstOrDefault(); @@ -204,18 +203,12 @@ public string GetCachedFilename(Uri url, DateTime? remoteTimestamp = null) // for. string found = scanDirectory(files, hash, remoteTimestamp); - if (!string.IsNullOrEmpty(found)) - { - return found; - } - - return null; + return string.IsNullOrEmpty(found) ? null : found; } private string scanDirectory(Dictionary<string, string> files, string findHash, DateTime? remoteTimestamp = null) { - string file; - if (files.TryGetValue(findHash, out file)) + if (files.TryGetValue(findHash, out string file)) { log.DebugFormat("Found file {0}", file); // Check local vs remote timestamps; if local is older, then it's invalid. @@ -315,7 +308,7 @@ public void EnforceSizeLimit(long bytes, Registry registry) // Now get all the files in all the caches, including in progress... List<FileInfo> files = allFiles(true); // ... and sort them by compatibility and timestamp... - files.Sort((a, b) => compareFiles(hashMap, aggregateCriteria, a, b)); + files.Sort((a, b) => compareFiles(hashMap, a, b)); // ... and delete them till we're under the limit foreach (FileInfo fi in files) @@ -336,16 +329,14 @@ public void EnforceSizeLimit(long bytes, Registry registry) } } - private int compareFiles(Dictionary<string, List<CkanModule>> hashMap, GameVersionCriteria crit, FileInfo a, FileInfo b) + private int compareFiles(Dictionary<string, List<CkanModule>> hashMap, FileInfo a, FileInfo b) { // Compatible modules for file A - List<CkanModule> modulesA; - hashMap.TryGetValue(a.Name.Substring(0, 8), out modulesA); + hashMap.TryGetValue(a.Name.Substring(0, 8), out List<CkanModule> modulesA); bool compatA = modulesA?.Any() ?? false; // Compatible modules for file B - List<CkanModule> modulesB; - hashMap.TryGetValue(b.Name.Substring(0, 8), out modulesB); + hashMap.TryGetValue(b.Name.Substring(0, 8), out List<CkanModule> modulesB); bool compatB = modulesB?.Any() ?? false; if (modulesA == null && modulesB != null) @@ -423,7 +414,7 @@ public string Store(Uri url, string path, string description = null, bool move = "description isn't as filesystem safe as we thought... (#1266)" ); - string fullName = String.Format("{0}-{1}", hash, Path.GetFileName(description)); + string fullName = string.Format("{0}-{1}", hash, Path.GetFileName(description)); string targetPath = Path.Combine(cachePath, fullName); // Purge hashes associated with the new file @@ -486,8 +477,8 @@ private void PurgeHashes(TxFileManager tx_file, string file) /// </summary> public void RemoveAll() { - var dirs = Enumerable.Repeat<string>(cachePath, 1) - .Concat(Enumerable.Repeat<string>(InProgressPath, 1)) + var dirs = Enumerable.Repeat(cachePath, 1) + .Concat(Enumerable.Repeat(InProgressPath, 1)) .Concat(legacyDirs()); foreach (string dir in dirs) { @@ -573,7 +564,7 @@ public static string CreateURLHash(Uri url) /// <returns> /// SHA1 hash, in all-caps hexadecimal format /// </returns> - public string GetFileHashSha1(string filePath, IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + public string GetFileHashSha1(string filePath, IProgress<long> progress, CancellationToken cancelToken = default) => GetFileHash<SHA1CryptoServiceProvider>(filePath, "sha1", sha1Cache, progress, cancelToken); /// <summary> @@ -584,7 +575,7 @@ public static string CreateURLHash(Uri url) /// <returns> /// SHA256 hash, in all-caps hexadecimal format /// </returns> - public string GetFileHashSha256(string filePath, IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + public string GetFileHashSha256(string filePath, IProgress<long> progress, CancellationToken cancelToken = default) => GetFileHash<SHA256CryptoServiceProvider>(filePath, "sha256", sha256Cache, progress, cancelToken); /// <summary> @@ -598,9 +589,8 @@ public static string CreateURLHash(Uri url) private string GetFileHash<T>(string filePath, string hashSuffix, Dictionary<string, string> cache, IProgress<long> progress, CancellationToken cancelToken) where T: HashAlgorithm, new() { - string hash = null; string hashFile = $"{filePath}.{hashSuffix}"; - if (cache.TryGetValue(filePath, out hash)) + if (cache.TryGetValue(filePath, out string hash)) { return hash; } @@ -627,7 +617,7 @@ private string GetFileHash<T>(string filePath, string hashSuffix, Dictionary<str } } - private Dictionary<string, string> sha1Cache = new Dictionary<string, string>(); - private Dictionary<string, string> sha256Cache = new Dictionary<string, string>(); + private readonly Dictionary<string, string> sha1Cache = new Dictionary<string, string>(); + private readonly Dictionary<string, string> sha256Cache = new Dictionary<string, string>(); } } diff --git a/Core/Net/NetModuleCache.cs b/Core/Net/NetModuleCache.cs index a8cc61ec9b..8ca3b271b5 100644 --- a/Core/Net/NetModuleCache.cs +++ b/Core/Net/NetModuleCache.cs @@ -78,8 +78,7 @@ public bool IsMaybeCachedZip(CkanModule m) ?? false; public string GetCachedFilename(CkanModule m) => m.download?.Select(dlUri => cache.GetCachedFilename(dlUri, m.release_date)) - .Where(filename => filename != null) - .FirstOrDefault(); + .FirstOrDefault(filename => filename != null); public void GetSizeInfo(out int numFiles, out long numBytes, out long bytesFree) { cache.GetSizeInfo(out numFiles, out numBytes, out bytesFree); @@ -124,7 +123,7 @@ public string DescribeAvailability(CkanModule m) /// <returns> /// SHA1 hash, in all-caps hexadecimal format /// </returns> - public string GetFileHashSha1(string filePath, IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + public string GetFileHashSha1(string filePath, IProgress<long> progress, CancellationToken cancelToken = default) => cache.GetFileHashSha1(filePath, progress, cancelToken); /// <summary> @@ -135,7 +134,7 @@ public string DescribeAvailability(CkanModule m) /// <returns> /// SHA256 hash, in all-caps hexadecimal format /// </returns> - public string GetFileHashSha256(string filePath, IProgress<long> progress, CancellationToken cancelToken = default(CancellationToken)) + public string GetFileHashSha256(string filePath, IProgress<long> progress, CancellationToken cancelToken = default) => cache.GetFileHashSha256(filePath, progress, cancelToken); /// <summary> @@ -150,7 +149,7 @@ public string DescribeAvailability(CkanModule m) /// <returns> /// Name of the new file in the cache /// </returns> - public string Store(CkanModule module, string path, IProgress<long> progress, string description = null, bool move = false, CancellationToken cancelToken = default(CancellationToken)) + public string Store(CkanModule module, string path, IProgress<long> progress, string description = null, bool move = false, CancellationToken cancelToken = default) { // ZipValid takes a lot longer than the hash steps, so scale them 60:20:20 const int zipValidPercent = 60; @@ -161,13 +160,17 @@ public string DescribeAvailability(CkanModule m) // Check file exists FileInfo fi = new FileInfo(path); if (!fi.Exists) + { throw new FileNotFoundKraken(path); + } // Check file size if (module.download_size > 0 && fi.Length != module.download_size) + { throw new InvalidModuleFileKraken(module, path, string.Format( Properties.Resources.NetModuleCacheBadLength, module, path, fi.Length, module.download_size)); + } cancelToken.ThrowIfCancellationRequested(); @@ -187,7 +190,7 @@ public string DescribeAvailability(CkanModule m) { // Check SHA1 match string sha1 = GetFileHashSha1(path, new Progress<long>(percent => - progress?.Report(zipValidPercent + percent * hashSha1Percent / 100)), cancelToken); + progress?.Report(zipValidPercent + (percent * hashSha1Percent / 100))), cancelToken); if (sha1 != module.download_hash.sha1) { throw new InvalidModuleFileKraken(module, path, string.Format( @@ -197,7 +200,7 @@ public string DescribeAvailability(CkanModule m) // Check SHA256 match string sha256 = GetFileHashSha256(path, new Progress<long>(percent => - progress?.Report(zipValidPercent + hashSha1Percent + percent * hashSha256Percent / 100)), cancelToken); + progress?.Report(zipValidPercent + hashSha1Percent + (percent * hashSha256Percent / 100))), cancelToken); if (sha256 != module.download_hash.sha256) { throw new InvalidModuleFileKraken(module, path, string.Format( @@ -318,6 +321,6 @@ public bool Purge(CkanModule module) return true; } - private NetFileCache cache; + private readonly NetFileCache cache; } } diff --git a/Core/Net/RedirectingTimeoutWebClient.cs b/Core/Net/RedirectingTimeoutWebClient.cs index bb87bb7072..000cc8b359 100644 --- a/Core/Net/RedirectingTimeoutWebClient.cs +++ b/Core/Net/RedirectingTimeoutWebClient.cs @@ -54,10 +54,15 @@ protected override WebRequest GetWebRequest(Uri address) protected override WebResponse GetWebResponse(WebRequest request) { if (request == null) + { return null; + } + var response = base.GetWebResponse(request); if (response == null) + { return null; + } if (response is HttpWebResponse hwr) { @@ -85,8 +90,8 @@ protected override WebResponse GetWebResponse(WebRequest request) return response; } - private int timeout; - private string mimeType; + private readonly int timeout; + private readonly string mimeType; private static readonly Dictionary<Uri, Uri> permanentRedirects = new Dictionary<Uri, Uri>(); private static readonly ILog log = LogManager.GetLogger(typeof(RedirectingTimeoutWebClient)); } diff --git a/Core/Platform.cs b/Core/Platform.cs index b9e683a65a..1754c58a30 100644 --- a/Core/Platform.cs +++ b/Core/Platform.cs @@ -59,7 +59,9 @@ static Platform() private static bool IsOnMonoFourOrLater() { if (!IsMono) + { return false; + } // Get Mono's display name and parse the version string display_name = diff --git a/Core/Registry/CompatibilitySorter.cs b/Core/Registry/CompatibilitySorter.cs index 00f85bd435..b956b0be2b 100644 --- a/Core/Registry/CompatibilitySorter.cs +++ b/Core/Registry/CompatibilitySorter.cs @@ -148,11 +148,11 @@ private Dictionary<string, HashSet<AvailableModule>> CompatibleProviders( .GroupBy(kvp => kvp.Value.AllAvailable() .All(m => !m.IsCompatible(CompatibleVersions)) // No versions compatible == incompatible - ? (bool?)false + ? false : kvp.Value.AllAvailable() .All(m => m.depends == null) // No dependencies == compatible - ? (bool?)true + ? true // Need to investigate this one more later : (bool?)null) .Select(grp => new Tuple<bool?, ConcurrentDictionary<string, AvailableModule>>( diff --git a/Core/Registry/IRegistryQuerier.cs b/Core/Registry/IRegistryQuerier.cs index 767c29c517..7d144b475d 100644 --- a/Core/Registry/IRegistryQuerier.cs +++ b/Core/Registry/IRegistryQuerier.cs @@ -6,7 +6,6 @@ using log4net; using CKAN.Versioning; -using CKAN.Extensions; using CKAN.Games; namespace CKAN @@ -286,10 +285,14 @@ public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, Ck { // Mod is not installed, so we don't care about replacements if (installedVersion == null) + { return null; + } // No replaced_by relationship if (installedVersion.replaced_by == null) + { return null; + } // Get the identifier from the replaced_by relationship, if it exists ModuleRelationshipDescriptor replacedBy = installedVersion.replaced_by; @@ -324,7 +327,10 @@ public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, Ck return replacement; } } - else return replacement; + else + { + return replacement; + } } } return null; diff --git a/Core/Registry/InstalledModule.cs b/Core/Registry/InstalledModule.cs index 61c501886a..25467a8c95 100644 --- a/Core/Registry/InstalledModule.cs +++ b/Core/Registry/InstalledModule.cs @@ -24,6 +24,7 @@ public class InstalledModuleFile public InstalledModuleFile(string path, GameInstance ksp) { string absolute_path = ksp.ToAbsoluteGameDir(path); + // TODO: What is the net performance cost of calculating this? Big files are not quick to hash! sha1_sum = Sha1Sum(absolute_path); } @@ -84,7 +85,8 @@ public class InstalledModule // TODO: Our InstalledModuleFile already knows its path, so this could just // be a list. However we've left it as a dictionary for now to maintain // registry format compatibility. - [JsonProperty] private Dictionary<string, InstalledModuleFile> installed_files; + [JsonProperty] + private Dictionary<string, InstalledModuleFile> installed_files; public IEnumerable<string> Files => installed_files.Keys; public string identifier => source_module.identifier; diff --git a/Core/Registry/Registry.cs b/Core/Registry/Registry.cs index 4e27ae0db7..3c5e0036c4 100644 --- a/Core/Registry/Registry.cs +++ b/Core/Registry/Registry.cs @@ -642,8 +642,7 @@ public CkanModule GetModuleByVersion(string ident, ModuleVersion version) try { return getAvail(ident)?.Select(am => am.ByVersion(version)) - .Where(m => m != null) - .FirstOrDefault(); + .FirstOrDefault(m => m != null); } catch { @@ -700,9 +699,13 @@ private void BuildProvidesIndexFor(AvailableModule am) foreach (string provided in m.ProvidesList) { if (providers.TryGetValue(provided, out HashSet<AvailableModule> provs)) + { provs.Add(am); + } else + { providers.Add(provided, new HashSet<AvailableModule>() { am }); + } } } } @@ -1082,7 +1085,10 @@ public ModuleVersion InstalledVersion(string modIdentifier, bool with_provides=t // Finally we have our provided checks. We'll skip these if // withProvides is false. - if (!with_provides) return null; + if (!with_provides) + { + return null; + } var provided = ProvidedByInstalled(); @@ -1315,6 +1321,7 @@ public IEnumerable<string> GetAllHosts() // Older clients expect these properties and can handle them being empty ("{}") but not null + #pragma warning disable IDE0052 [JsonProperty("available_modules", NullValueHandling = NullValueHandling.Include)] [JsonConverter(typeof(JsonAlwaysEmptyObjectConverter))] @@ -1324,6 +1331,7 @@ public IEnumerable<string> GetAllHosts() NullValueHandling = NullValueHandling.Include)] [JsonConverter(typeof(JsonAlwaysEmptyObjectConverter))] private readonly Dictionary<string, string> legacyDownloadCountsDoNotUse = new Dictionary<string, string>(); + #pragma warning restore IDE0052 } } diff --git a/Core/Registry/RegistryManager.cs b/Core/Registry/RegistryManager.cs index 483ce46979..5eb19de77a 100644 --- a/Core/Registry/RegistryManager.cs +++ b/Core/Registry/RegistryManager.cs @@ -52,7 +52,7 @@ public static bool IsInstanceMaybeLocked(string ckanDirPath) // enforce this being an instance (via Instance() above) private RegistryManager(string path, GameInstance inst, RepositoryDataManager repoData) { - this.gameInstance = inst; + gameInstance = inst; this.path = Path.Combine(path, "registry.json"); lockfilePath = InstanceRegistryLockPath(path); @@ -103,19 +103,21 @@ private RegistryManager(string path, GameInstance inst, RepositoryDataManager re // what's going on here. /// <summary> - /// Releases all resource used by the <see cref="CKAN.RegistryManager"/> object. + /// Releases all resource used by the <see cref="RegistryManager"/> object. /// </summary> - /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="CKAN.RegistryManager"/>. The - /// <see cref="Dispose"/> method leaves the <see cref="CKAN.RegistryManager"/> in an unusable state. After - /// calling <see cref="Dispose"/>, you must release all references to the <see cref="CKAN.RegistryManager"/> so - /// the garbage collector can reclaim the memory that the <see cref="CKAN.RegistryManager"/> was occupying.</remarks> + /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="RegistryManager"/>. The + /// <see cref="Dispose"/> method leaves the <see cref="RegistryManager"/> in an unusable state. After + /// calling <see cref="Dispose"/>, you must release all references to the <see cref="RegistryManager"/> so + /// the garbage collector can reclaim the memory that the <see cref="RegistryManager"/> was occupying.</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } + #pragma warning disable IDE0060 protected void Dispose(bool safeToAlsoFreeManagedObjects) + #pragma warning restore IDE0060 { // Right now we just release our lock, and leave everything else // to the GC, but if we were implementing the full pattern we'd also @@ -135,7 +137,7 @@ protected void Dispose(bool safeToAlsoFreeManagedObjects) /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the - /// <see cref="CKAN.RegistryManager"/> is reclaimed by garbage collection. + /// <see cref="RegistryManager"/> is reclaimed by garbage collection. /// </summary> ~RegistryManager() { @@ -175,7 +177,7 @@ private void CheckStaleLock() return; } log.DebugFormat("Lock file contents: {0}", contents); - if (Int32.TryParse(contents, out int pid)) + if (int.TryParse(contents, out int pid)) { // File contains a valid integer. try @@ -551,7 +553,7 @@ public bool ScanUnmanagedFiles() log.Info(Properties.Resources.GameInstanceScanning); using (var tx = CkanTransaction.CreateTransactionScope()) { - var dlls = Enumerable.Repeat<string>(gameInstance.game.PrimaryModDirectoryRelative, 1) + var dlls = Enumerable.Repeat(gameInstance.game.PrimaryModDirectoryRelative, 1) .Concat(gameInstance.game.AlternateModDirectoriesRelative) .Select(relDir => gameInstance.ToAbsoluteGameDir(relDir)) .Where(absDir => Directory.Exists(absDir)) diff --git a/Core/Relationships/RelationshipResolver.cs b/Core/Relationships/RelationshipResolver.cs index 918d0f9388..473f810ea8 100644 --- a/Core/Relationships/RelationshipResolver.cs +++ b/Core/Relationships/RelationshipResolver.cs @@ -16,7 +16,7 @@ namespace CKAN /// Resolves relationships between mods. Primarily used to satisfy missing dependencies and to check for conflicts on proposed installs. /// </summary> /// <remarks> - /// All constructors start with currently installed modules, to remove <see cref="RelationshipResolver.RemoveModsFromInstalledList" /> + /// All constructors start with currently installed modules, to remove <see cref="RemoveModsFromInstalledList" /> /// </remarks> public class RelationshipResolver { @@ -559,7 +559,7 @@ private IEnumerable<T> BreadthFirstSearch<T>(IEnumerable<T> private IEnumerable<CkanModule> allDependers(CkanModule module, Func<SelectionReason, bool> followReason = null) - => BreadthFirstSearch(Enumerable.Repeat<CkanModule>(module, 1), + => BreadthFirstSearch(Enumerable.Repeat(module, 1), (searching, found) => ReasonsFor(searching).Where(followReason ?? AnyRelationship) .Select(r => r.Parent) @@ -611,7 +611,7 @@ public ParallelQuery<KeyValuePair<CkanModule, HashSet<string>>> Supporters( /// The keys are the mods that the user chose that led to the conflict being in the list! /// Use this for coloring/labelling rows, use ConflictDescriptions for reporting the conflicts to the user. /// </summary> - public Dictionary<CkanModule, String> ConflictList + public Dictionary<CkanModule, string> ConflictList => conflicts .SelectMany(kvp => UserReasonsFor(kvp.Key).Select(k => new KeyValuePair<CkanModule, ModPair>(k, kvp))) .GroupBy(kvp => kvp.Key) @@ -879,7 +879,9 @@ public Replacement(CkanModule module) { if (module == null) { + #pragma warning disable IDE0016 throw new ArgumentNullException(); + #pragma warning restore IDE0016 } Parent = module; } @@ -894,7 +896,9 @@ public Suggested(CkanModule module) { if (module == null) { + #pragma warning disable IDE0016 throw new ArgumentNullException(); + #pragma warning restore IDE0016 } Parent = module; } @@ -909,7 +913,9 @@ public Depends(CkanModule module) { if (module == null) { + #pragma warning disable IDE0016 throw new ArgumentNullException(); + #pragma warning restore IDE0016 } Parent = module; } @@ -928,7 +934,9 @@ public Recommended(CkanModule module, int providesIndex) { if (module == null) { + #pragma warning disable IDE0016 throw new ArgumentNullException(); + #pragma warning restore IDE0016 } Parent = module; ProvidesIndex = providesIndex; diff --git a/Core/Relationships/SanityChecker.cs b/Core/Relationships/SanityChecker.cs index bb0e845d7e..ab36d3fc20 100644 --- a/Core/Relationships/SanityChecker.cs +++ b/Core/Relationships/SanityChecker.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - -using CKAN.Extensions; using CKAN.Versioning; namespace CKAN diff --git a/Core/Repositories/AvailableModule.cs b/Core/Repositories/AvailableModule.cs index 00d4fc0a75..94b9f5bd1e 100644 --- a/Core/Repositories/AvailableModule.cs +++ b/Core/Repositories/AvailableModule.cs @@ -70,7 +70,9 @@ public static AvailableModule Merge(IEnumerable<AvailableModule> availMods) new SortedDictionary<ModuleVersion, CkanModule>(); [OnError] + #pragma warning disable IDE0051, IDE0060 private void OnError(StreamingContext context, ErrorContext errorContext) + #pragma warning restore IDE0051, IDE0060 { log.WarnFormat("Discarding CkanModule, failed to parse {0}: {1}", errorContext.Path, errorContext.Error.GetBaseException().Message); @@ -83,8 +85,10 @@ private void OnError(StreamingContext context, ErrorContext errorContext) private void Add(CkanModule module) { if (!module.identifier.Equals(identifier)) + { throw new ArgumentException( string.Format("This AvailableModule is for tracking {0} not {1}", identifier, module.identifier)); + } log.DebugFormat("Adding to available module: {0}", module); module_version[module.version] = module; diff --git a/Core/Repositories/ReadProgressStream.cs b/Core/Repositories/ReadProgressStream.cs index c60eb3d03b..854b461779 100644 --- a/Core/Repositories/ReadProgressStream.cs +++ b/Core/Repositories/ReadProgressStream.cs @@ -42,7 +42,9 @@ protected ContainerStream(Stream stream) { if (stream == null) { + #pragma warning disable IDE0016 throw new ArgumentNullException("stream"); + #pragma warning restore IDE0016 } inner = stream; } @@ -56,10 +58,12 @@ protected ContainerStream(Stream stream) public override long Position { get => inner.Position; + #pragma warning disable IDE0027 set { inner.Position = value; } + #pragma warning restore IDE0027 } public override void Flush() { diff --git a/Core/Repositories/Repository.cs b/Core/Repositories/Repository.cs index be1e37d356..8dd85c5f5c 100644 --- a/Core/Repositories/Repository.cs +++ b/Core/Repositories/Repository.cs @@ -42,7 +42,7 @@ public Repository(string name, string uri, int priority) this.priority = priority; } - public override bool Equals(Object other) + public override bool Equals(object other) => Equals(other as Repository); public bool Equals(Repository other) diff --git a/Core/Repositories/RepositoryData.cs b/Core/Repositories/RepositoryData.cs index 3352ff3daf..3bfd700d92 100644 --- a/Core/Repositories/RepositoryData.cs +++ b/Core/Repositories/RepositoryData.cs @@ -150,7 +150,7 @@ public static RepositoryData FromJson(string path, IProgress<int> progress) ? null : new ProgressImmediate<int>(p => // Treat CkanModule creation as the last 50% - progress.Report(50 + p / 2))), + progress.Report(50 + (p / 2)))), }; return JsonSerializer.Create(settings) .Deserialize<RepositoryData>(jStream); diff --git a/Core/Repositories/RepositoryDataManager.cs b/Core/Repositories/RepositoryDataManager.cs index fc51bbc590..1908f6fcef 100644 --- a/Core/Repositories/RepositoryDataManager.cs +++ b/Core/Repositories/RepositoryDataManager.cs @@ -77,8 +77,7 @@ public IEnumerable<AvailableModule> GetAllAvailableModules(IEnumerable<Repositor => GetRepoDatas(repos) .Select(data => data.DownloadCounts.TryGetValue(identifier, out int count) ? (int?)count : null) - .Where(count => count != null) - .FirstOrDefault(); + .FirstOrDefault(count => count != null); #endregion @@ -144,10 +143,9 @@ public UpdateResult Update(Repository[] repos, .DistinctBy(r => r.uri) .Where(r => r.uri.IsFile || skipETags - || (etags.TryGetValue(r.uri, out string etag) - ? !File.Exists(GetRepoDataPath(r)) - || etag != Net.CurrentETag(r.uri) - : true)) + || (!etags.TryGetValue(r.uri, out string etag) + || !File.Exists(GetRepoDataPath(r)) + || etag != Net.CurrentETag(r.uri))) .ToArray(); if (toUpdate.Length < 1) { diff --git a/Core/Repositories/RepositoryList.cs b/Core/Repositories/RepositoryList.cs index d5efcca9e8..c8a2f2a2d0 100644 --- a/Core/Repositories/RepositoryList.cs +++ b/Core/Repositories/RepositoryList.cs @@ -17,7 +17,7 @@ public static RepositoryList DefaultRepositories(IGame game) } catch { - return default(RepositoryList); + return default; } } } diff --git a/Core/ServiceLocator.cs b/Core/ServiceLocator.cs index 24d60e7e27..1ba9fa817f 100644 --- a/Core/ServiceLocator.cs +++ b/Core/ServiceLocator.cs @@ -25,10 +25,12 @@ public static IContainer Container return _container; } + #pragma warning disable IDE0027 set { _container = value; } + #pragma warning restore IDE0027 } private static void Init() diff --git a/Core/SingleAssemblyResourceManager.cs b/Core/SingleAssemblyResourceManager.cs index cb452c67ef..30db7db008 100644 --- a/Core/SingleAssemblyResourceManager.cs +++ b/Core/SingleAssemblyResourceManager.cs @@ -8,7 +8,7 @@ namespace CKAN { // Thanks and credit to this guy: https://stackoverflow.com/q/1952638/2422988 - class SingleAssemblyResourceManager : ResourceManager + public class SingleAssemblyResourceManager : ResourceManager { public SingleAssemblyResourceManager(string basename, Assembly assembly) : base(basename, assembly) { @@ -22,7 +22,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -33,7 +33,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/Core/SuppressedCompatWarningIdentifiers.cs b/Core/SuppressedCompatWarningIdentifiers.cs index 525f0ea968..1de097fb91 100644 --- a/Core/SuppressedCompatWarningIdentifiers.cs +++ b/Core/SuppressedCompatWarningIdentifiers.cs @@ -8,7 +8,7 @@ namespace CKAN { - class SuppressedCompatWarningIdentifiers + public class SuppressedCompatWarningIdentifiers { public GameVersion GameVersionWhenWritten; public HashSet<string> Identifiers = new HashSet<string>(); diff --git a/Core/Types/CkanModule.cs b/Core/Types/CkanModule.cs index 1b72b48bbe..25a77d2626 100644 --- a/Core/Types/CkanModule.cs +++ b/Core/Types/CkanModule.cs @@ -13,7 +13,6 @@ using Newtonsoft.Json; using CKAN.Versioning; -using CKAN.Extensions; using CKAN.Games; namespace CKAN @@ -217,16 +216,18 @@ public ModuleVersion spec_version get { if (specVersion == null) + { specVersion = new ModuleVersion("1"); + } + return specVersion; } + #pragma warning disable IDE0027 set { - if (value == null) - specVersion = new ModuleVersion("1"); - else - specVersion = value; + specVersion = value ?? new ModuleVersion("1"); } + #pragma warning restore IDE0027 } [JsonProperty("tags", Order = 16, NullValueHandling = NullValueHandling.Ignore)] @@ -327,7 +328,7 @@ public CkanModule( this.version = version; this.download = new List<Uri> { download }; this.kind = kind; - this._comparator = comparator ?? ServiceLocator.Container.Resolve<IGameComparator>(); + _comparator = comparator ?? ServiceLocator.Container.Resolve<IGameComparator>(); CheckHealth(); CalculateSearchables(); } @@ -391,10 +392,10 @@ private void CheckHealth() /// </summary> private void CalculateSearchables() { - SearchableIdentifier = identifier == null ? string.Empty : CkanModule.nonAlphaNums.Replace(identifier, ""); - SearchableName = name == null ? string.Empty : CkanModule.nonAlphaNums.Replace(name, ""); - SearchableAbstract = @abstract == null ? string.Empty : CkanModule.nonAlphaNums.Replace(@abstract, ""); - SearchableDescription = description == null ? string.Empty : CkanModule.nonAlphaNums.Replace(description, ""); + SearchableIdentifier = identifier == null ? string.Empty : nonAlphaNums.Replace(identifier, ""); + SearchableName = name == null ? string.Empty : nonAlphaNums.Replace(name, ""); + SearchableAbstract = @abstract == null ? string.Empty : nonAlphaNums.Replace(@abstract, ""); + SearchableDescription = description == null ? string.Empty : nonAlphaNums.Replace(description, ""); SearchableAuthors = new List<string>(); if (author == null) @@ -405,7 +406,7 @@ private void CalculateSearchables() { foreach (string auth in author) { - SearchableAuthors.Add(CkanModule.nonAlphaNums.Replace(auth, "")); + SearchableAuthors.Add(nonAlphaNums.Replace(auth, "")); } } } @@ -457,8 +458,10 @@ public static CkanModule FromIDandVersion(IRegistryQuerier registry, string mod, if (module == null || (ksp_version != null && !module.IsCompatible(ksp_version))) + { throw new ModuleNotFoundKraken(ident, version, string.Format(Properties.Resources.CkanModuleNotAvailable, ident, version)); + } } else { @@ -466,8 +469,10 @@ public static CkanModule FromIDandVersion(IRegistryQuerier registry, string mod, ?? registry.InstalledModule(mod)?.Module; if (module == null) + { throw new ModuleNotFoundKraken(mod, null, string.Format(Properties.Resources.CkanModuleNotInstalledOrAvailable, mod)); + } } return module; } @@ -587,12 +592,9 @@ protected bool Equals(CkanModule other) => string.Equals(identifier, other.identifier) && version.Equals(other.version); public override bool Equals(object obj) - { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((CkanModule)obj); - } + => !(obj is null) + && (ReferenceEquals(this, obj) + || (obj.GetType() == GetType() && Equals((CkanModule)obj))); public bool MetadataEquals(CkanModule other) { @@ -607,7 +609,9 @@ public bool MetadataEquals(CkanModule other) for (int i = 0; i < install.Length; i++) { if (!install[i].Equals(other.install[i])) + { return false; + } } } if (install_size != other.install_size) @@ -616,20 +620,30 @@ public bool MetadataEquals(CkanModule other) } if (!RelationshipsAreEquivalent(conflicts, other.conflicts)) + { return false; + } if (!RelationshipsAreEquivalent(depends, other.depends)) + { return false; + } if (!RelationshipsAreEquivalent(recommends, other.recommends)) + { return false; + } if (provides != other.provides) { if (provides == null || other.provides == null) + { return false; + } else if (!provides.OrderBy(i => i).SequenceEqual(other.provides.OrderBy(i => i))) + { return false; + } } return true; } @@ -637,16 +651,22 @@ public bool MetadataEquals(CkanModule other) private static bool RelationshipsAreEquivalent(List<RelationshipDescriptor> a, List<RelationshipDescriptor> b) { if (a == b) + { // If they're the same exact object they must be equivalent return true; + } if (a == null || b == null) + { // If they're not the same exact object and either is null then must not be equivalent return false; + } if (a.Count != b.Count) + { // If their counts different they must not be equivalent return false; + } // Sort the lists so we can compare each relationship var aSorted = a.OrderBy(i => i.ToString()).ToList(); @@ -833,11 +853,11 @@ public static void GetMinMaxVersions(IEnumerable<CkanModule> modVersions, } GameVersion relMin = rel.EarliestCompatibleGameVersion(); GameVersion relMax = rel.LatestCompatibleGameVersion(); - if (minGame == null || !minGame.IsAny && (minGame > relMin || relMin.IsAny)) + if (minGame == null || (!minGame.IsAny && (minGame > relMin || relMin.IsAny))) { minGame = relMin; } - if (maxGame == null || !maxGame.IsAny && (maxGame < relMax || relMax.IsAny)) + if (maxGame == null || (!maxGame.IsAny && (maxGame < relMax || relMax.IsAny))) { maxGame = relMax; } diff --git a/Core/Types/GameComparator/GrasGameComparator.cs b/Core/Types/GameComparator/GrasGameComparator.cs index 51df90cb8b..2216037d27 100644 --- a/Core/Types/GameComparator/GrasGameComparator.cs +++ b/Core/Types/GameComparator/GrasGameComparator.cs @@ -9,22 +9,22 @@ namespace CKAN /// </summary> public class GrasGameComparator : BaseGameComparator { - static readonly StrictGameComparator strict = new StrictGameComparator(); - static readonly GameVersion v103 = GameVersion.Parse("1.0.3"); - static readonly GameVersion v104 = GameVersion.Parse("1.0.4"); + private static readonly StrictGameComparator strict = new StrictGameComparator(); + private static readonly GameVersion v103 = GameVersion.Parse("1.0.3"); + private static readonly GameVersion v104 = GameVersion.Parse("1.0.4"); public override bool Compatible(GameVersionCriteria gameVersionCriteria, CkanModule module) { // If it's strictly compatible, then it's compatible. if (strict.Compatible(gameVersionCriteria, module)) + { return true; + } // If we're in strict mode, and it's not strictly compatible, then it's // not compatible. - if (module.ksp_version_strict) - return false; - - return base.Compatible(gameVersionCriteria, module); + return !module.ksp_version_strict + && base.Compatible(gameVersionCriteria, module); } public override bool SingleVersionsCompatible (GameVersion gameVersion, CkanModule module) @@ -34,10 +34,8 @@ public override bool SingleVersionsCompatible (GameVersion gameVersion, CkanModu // If we're running KSP 1.0.4, then allow the mod to run if we would have // considered it compatible under 1.0.3 (as 1.0.4 was "just a hotfix"). - if (gameVersion.Equals(v104)) - return strict.SingleVersionsCompatible(v103, module); - - return false; + return gameVersion.Equals(v104) + && strict.SingleVersionsCompatible(v103, module); } } } diff --git a/Core/Types/Kraken.cs b/Core/Types/Kraken.cs index bc05a4add2..4ec8f869ed 100644 --- a/Core/Types/Kraken.cs +++ b/Core/Types/Kraken.cs @@ -387,10 +387,7 @@ public class ModNotInstalledKraken : Kraken { public readonly string mod; - public override string Message - { - get { return string.Format(Properties.Resources.KrakenNotInstalled, mod); } - } + public override string Message => string.Format(Properties.Resources.KrakenNotInstalled, mod); // TODO: Since we override message, should we really allow users to pass in a reason // here? Is there a way we can check if that was set, and then access it directly from @@ -453,7 +450,7 @@ public class RegistryInUseKraken : Kraken public RegistryInUseKraken(string path, string reason = null, Exception inner_exception = null) :base(reason, inner_exception) { - this.lockfilePath = path; + lockfilePath = path; } public override string ToString() @@ -531,7 +528,7 @@ public class InstanceNameTakenKraken : Kraken public InstanceNameTakenKraken(string name, string reason = null) : base(reason) { - this.instName = name; + instName = name; } } diff --git a/Core/Types/License.cs b/Core/Types/License.cs index 8eb7202c88..b618ac1132 100644 --- a/Core/Types/License.cs +++ b/Core/Types/License.cs @@ -3,8 +3,6 @@ using Newtonsoft.Json; -using CKAN.Extensions; - namespace CKAN { /// <summary> @@ -61,8 +59,6 @@ public License(string license) /// Returns the license as a string. /// </summary> public override string ToString() - { - return license; - } + => license; } } diff --git a/Core/Types/ModuleInstallDescriptor.cs b/Core/Types/ModuleInstallDescriptor.cs index e73968a1e6..49095dbf97 100644 --- a/Core/Types/ModuleInstallDescriptor.cs +++ b/Core/Types/ModuleInstallDescriptor.cs @@ -150,40 +150,85 @@ public override bool Equals(object other) public bool Equals(ModuleInstallDescriptor otherStanza) { if (otherStanza == null) + { // Not even the right type! return false; + } + if (CKANPathUtils.NormalizePath(file) != CKANPathUtils.NormalizePath(otherStanza.file)) + { return false; + } + if (CKANPathUtils.NormalizePath(find) != CKANPathUtils.NormalizePath(otherStanza.find)) + { return false; + } + if (find_regexp != otherStanza.find_regexp) + { return false; + } + if (CKANPathUtils.NormalizePath(install_to) != CKANPathUtils.NormalizePath(otherStanza.install_to)) + { return false; + } + if (@as != otherStanza.@as) + { return false; + } + if ((filter == null) != (otherStanza.filter == null)) + { return false; + } + if (filter != null && !filter.SequenceEqual(otherStanza.filter)) + { return false; + } + if ((filter_regexp == null) != (otherStanza.filter_regexp == null)) + { return false; + } + if (filter_regexp != null && !filter_regexp.SequenceEqual(otherStanza.filter_regexp)) + { return false; + } + if (find_matches_files != otherStanza.find_matches_files) + { return false; + } + if ((include_only == null) != (otherStanza.include_only == null)) + { return false; + } + if (include_only != null && !include_only.SequenceEqual(otherStanza.include_only)) + { return false; + } + if ((include_only_regexp == null) != (otherStanza.include_only_regexp == null)) + { return false; + } + if (include_only_regexp != null && !include_only_regexp.SequenceEqual(otherStanza.include_only_regexp)) + { return false; + } + return true; } @@ -302,14 +347,7 @@ private bool IsWanted(string path, int? matchWhere) return true; } - if (include_only != null || include_only_regexp != null) - { - return false; - } - else - { - return true; - } + return include_only == null && include_only_regexp == null; } /// <summary> @@ -334,8 +372,10 @@ public List<InstallableFile> FindInstallableFiles(ZipFile zipfile, GameInstance // The installation path cannot contain updirs if (install_to.Contains("/../") || install_to.EndsWith("/..")) + { throw new BadInstallLocationKraken(string.Format( Properties.Resources.ModuleInstallDescriptorInvalidInstallPath, install_to)); + } if (ksp == null) { @@ -376,7 +416,7 @@ public List<InstallableFile> FindInstallableFiles(ZipFile zipfile, GameInstance EnsurePattern(); // `find` is supposed to match the "topmost" folder. Find it. - var shortestMatch = find == null ? (int?)null + var shortestMatch = find == null ? null : zipfile.Cast<ZipEntry>() .Select(entry => inst_pattern.Match(entry.Name.Replace('\\', '/'))) .Where(match => match.Success) @@ -421,7 +461,7 @@ public List<InstallableFile> FindInstallableFiles(ZipFile zipfile, GameInstance if (files.Count == 0) { // We have null as the first argument here, because we don't know which module we're installing - throw new BadMetadataKraken(null, String.Format( + throw new BadMetadataKraken(null, string.Format( Properties.Resources.ModuleInstallDescriptorNoFilesFound, DescribeMatch())); } @@ -456,7 +496,7 @@ internal string TransformOutputName(IGame game, string outputName, string instal RegexOptions.Compiled); if (!leadingRE.IsMatch(outputName)) { - throw new BadMetadataKraken(null, String.Format( + throw new BadMetadataKraken(null, string.Format( "Output file name ({0}) not matching leading path of stanza ({1})", outputName, leadingPathToRemove)); } diff --git a/Core/Types/ReleaseStatus.cs b/Core/Types/ReleaseStatus.cs index a3155e1507..4d89ee8107 100644 --- a/Core/Types/ReleaseStatus.cs +++ b/Core/Types/ReleaseStatus.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Newtonsoft.Json; @@ -47,7 +46,7 @@ public ReleaseStatus(string status) { throw new BadMetadataKraken( null, - String.Format(Properties.Resources.ReleaseStatusInvalid, status) + string.Format(Properties.Resources.ReleaseStatusInvalid, status) ); } diff --git a/Core/Types/TimeLog.cs b/Core/Types/TimeLog.cs index 8705b72a14..fbb032e6ae 100644 --- a/Core/Types/TimeLog.cs +++ b/Core/Types/TimeLog.cs @@ -13,9 +13,7 @@ public class TimeLog public TimeSpan Time; public static string GetPath(string dir) - { - return Path.Combine(dir, filename); - } + => Path.Combine(dir, filename); public static TimeLog Load(string path) { @@ -34,10 +32,8 @@ public void Save(string path) File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); } - public override String ToString() - { - return Time.TotalHours.ToString("N1"); - } + public override string ToString() + => Time.TotalHours.ToString("N1"); private readonly Stopwatch playTime = new Stopwatch(); diff --git a/Core/User.cs b/Core/User.cs index e161fdcd3d..7d94cb44a4 100644 --- a/Core/User.cs +++ b/Core/User.cs @@ -33,10 +33,7 @@ public class NullUser : IUser /// <summary> /// NullUser is headless. Variable not used for NullUser. /// </summary> - public bool Headless - { - get { return true; } - } + public bool Headless => true; /// <summary> /// NullUser returns true. diff --git a/Core/Versioning/GameVersion.cs b/Core/Versioning/GameVersion.cs index 09e2c718f6..1efe095fb0 100644 --- a/Core/Versioning/GameVersion.cs +++ b/Core/Versioning/GameVersion.cs @@ -124,7 +124,9 @@ public GameVersion() public GameVersion(int major) { if (major < 0) + { throw new ArgumentOutOfRangeException("major"); + } _major = major; _minor = Undefined; @@ -143,10 +145,14 @@ public GameVersion(int major) public GameVersion(int major, int minor) { if (major < 0) + { throw new ArgumentOutOfRangeException("major"); + } if (minor < 0) + { throw new ArgumentOutOfRangeException("minor"); + } _major = major; _minor = minor; @@ -166,13 +172,19 @@ public GameVersion(int major, int minor) public GameVersion(int major, int minor, int patch) { if (major < 0) + { throw new ArgumentOutOfRangeException("major"); + } if (minor < 0) + { throw new ArgumentOutOfRangeException("minor"); + } if (patch < 0) + { throw new ArgumentOutOfRangeException("patch"); + } _major = major; _minor = minor; @@ -193,16 +205,24 @@ public GameVersion(int major, int minor, int patch) public GameVersion(int major, int minor, int patch, int build) { if (major < 0) + { throw new ArgumentOutOfRangeException("major", major, $"{major}"); + } if (minor < 0) + { throw new ArgumentOutOfRangeException("minor", minor, $"{minor}"); + } if (patch < 0) + { throw new ArgumentOutOfRangeException("patch", patch, $"{patch}"); + } if (build < 0) + { throw new ArgumentOutOfRangeException("build", build, $"{build}"); + } _major = major; _minor = minor; @@ -213,12 +233,12 @@ public GameVersion(int major, int minor, int patch, int build) } /// <summary> - /// Converts the value of the current <see cref="GameVersion"/> to its equivalent <see cref="String"/> + /// Converts the value of the current <see cref="GameVersion"/> to its equivalent <see cref="string"/> /// representation. /// </summary> /// <returns> /// <para> - /// The <see cref="String"/> representation of the values of the major, minor, patch, and build components of + /// The <see cref="string"/> representation of the values of the major, minor, patch, and build components of /// the current <see cref="GameVersion"/> object as depicted in the following format. Each component is /// separated by a period character ('.'). Square brackets ('[' and ']') indicate a component that will not /// appear in the return value if the component is not defined: @@ -343,7 +363,7 @@ public static bool TryParse(string input, out GameVersion result) if (input == "any") { - result = GameVersion.Any; + result = Any; return true; } @@ -364,43 +384,71 @@ public static bool TryParse(string input, out GameVersion result) if (majorGroup.Success) { if (!int.TryParse(majorGroup.Value, out major)) + { return false; - if (major < 0 || major == Int32.MaxValue) + } + + if (major < 0 || major == int.MaxValue) + { major = Undefined; + } } if (minorGroup.Success) { if (!int.TryParse(minorGroup.Value, out minor)) + { return false; - if (minor < 0 || minor == Int32.MaxValue) + } + + if (minor < 0 || minor == int.MaxValue) + { minor = Undefined; + } } if (patchGroup.Success) { if (!int.TryParse(patchGroup.Value, out patch)) + { return false; - if (patch < 0 || patch == Int32.MaxValue) + } + + if (patch < 0 || patch == int.MaxValue) + { patch = Undefined; + } } if (buildGroup.Success) { if (!int.TryParse(buildGroup.Value, out build)) + { return false; - if (build < 0 || build == Int32.MaxValue) + } + + if (build < 0 || build == int.MaxValue) + { build = Undefined; + } } if (minor == Undefined) + { result = new GameVersion(major); + } else if (patch == Undefined) + { result = new GameVersion(major, minor); + } else if (build == Undefined) + { result = new GameVersion(major, minor, patch); + } else + { result = new GameVersion(major, minor, patch, build); + } return true; } @@ -542,8 +590,16 @@ public sealed partial class GameVersion : IEquatable<GameVersion> /// </returns> public bool Equals(GameVersion obj) { - if (obj is null) return false; - if (ReferenceEquals(obj, this)) return true; + if (obj is null) + { + return false; + } + + if (ReferenceEquals(obj, this)) + { + return true; + } + return _major == obj._major && _minor == obj._minor && _patch == obj._patch && _build == obj._build; } @@ -561,8 +617,16 @@ public bool Equals(GameVersion obj) /// </returns> public override bool Equals(object obj) { - if (obj is null) return false; - if (ReferenceEquals(obj, this)) return true; + if (obj is null) + { + return false; + } + + if (ReferenceEquals(obj, this)) + { + return true; + } + return obj is GameVersion gv && Equals(gv); } @@ -833,13 +897,19 @@ public sealed partial class GameVersion public static GameVersion Min(params GameVersion[] versions) { if (versions == null) + { throw new ArgumentNullException("versions"); + } if (!versions.Any()) + { throw new ArgumentException("Value cannot be empty.", "versions"); + } if (versions.Any(i => i == null)) + { throw new ArgumentException("Value cannot contain null.", "versions"); + } return versions.Min(); } @@ -847,13 +917,19 @@ public static GameVersion Min(params GameVersion[] versions) public static GameVersion Max(params GameVersion[] versions) { if (versions == null) + { throw new ArgumentNullException("versions"); + } if (!versions.Any()) + { throw new ArgumentException("Value cannot be empty.", "versions"); + } if (versions.Any(i => i == null)) + { throw new ArgumentException("Value cannot contain null.", "versions"); + } return versions.Max(); } diff --git a/Core/Versioning/GameVersionBound.cs b/Core/Versioning/GameVersionBound.cs index 5777942bda..f125d03494 100644 --- a/Core/Versioning/GameVersionBound.cs +++ b/Core/Versioning/GameVersionBound.cs @@ -17,11 +17,15 @@ public GameVersionBound() public GameVersionBound(GameVersion value, bool inclusive) { - if (ReferenceEquals(value, null)) + if (value is null) + { throw new ArgumentNullException("value"); + } if (!value.IsAny && !value.IsFullyDefined) + { throw new ArgumentException("Version must be either fully undefined or fully defined.", "value"); + } Value = value; Inclusive = inclusive; @@ -68,16 +72,32 @@ public sealed partial class GameVersionBound : IEquatable<GameVersionBound> { public bool Equals(GameVersionBound other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (other is null) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Equals(Value, other.Value) && Inclusive == other.Inclusive; } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - return obj is GameVersionBound && Equals((GameVersionBound) obj); + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + return obj is GameVersionBound bound && Equals(bound); } public override int GetHashCode() @@ -104,13 +124,19 @@ public sealed partial class GameVersionBound public static GameVersionBound Lowest(params GameVersionBound[] versionBounds) { if (versionBounds == null) + { throw new ArgumentNullException("versionBounds"); + } if (!versionBounds.Any()) + { throw new ArgumentException("Value cannot be empty.", "versionBounds"); + } if (versionBounds.Any(i => i == null)) + { throw new ArgumentException("Value cannot contain null.", "versionBounds"); + } return versionBounds .OrderBy(i => i == Unbounded) @@ -129,13 +155,19 @@ public static GameVersionBound Lowest(params GameVersionBound[] versionBounds) public static GameVersionBound Highest(params GameVersionBound[] versionBounds) { if (versionBounds == null) + { throw new ArgumentNullException("versionBounds"); + } if (!versionBounds.Any()) + { throw new ArgumentException("Value cannot be empty.", "versionBounds"); + } if (versionBounds.Any(i => i == null)) + { throw new ArgumentException("Value cannot contain null.", "versionBounds"); + } return versionBounds .OrderBy(i => i == Unbounded) diff --git a/Core/Versioning/GameVersionCriteria.cs b/Core/Versioning/GameVersionCriteria.cs index b71df9130e..e7a6435e2b 100644 --- a/Core/Versioning/GameVersionCriteria.cs +++ b/Core/Versioning/GameVersionCriteria.cs @@ -8,13 +8,13 @@ namespace CKAN.Versioning { public class GameVersionCriteria : IEquatable<GameVersionCriteria> { - private List<GameVersion> _versions = new List<GameVersion>(); + private readonly List<GameVersion> _versions = new List<GameVersion>(); public GameVersionCriteria(GameVersion v) { if (v != null) { - this._versions.Add(v); + _versions.Add(v); } } @@ -22,10 +22,10 @@ public GameVersionCriteria(GameVersion v, List<GameVersion> compatibleVersions) { if (v != null) { - this._versions.Add(v); + _versions.Add(v); } - this._versions.AddRange(compatibleVersions); - this._versions = this._versions.Distinct().ToList(); + _versions.AddRange(compatibleVersions); + _versions = _versions.Distinct().ToList(); } public IList<GameVersion> Versions => _versions.AsReadOnly(); @@ -46,14 +46,13 @@ public override bool Equals(object obj) // From IEquatable<GameVersionCriteria> public bool Equals(GameVersionCriteria other) - => other == null ? false - : !_versions.Except(other._versions).Any() - && !other._versions.Except(_versions).Any(); + => other != null && !_versions.Except(other._versions).Any() + && !other._versions.Except(_versions).Any(); public override int GetHashCode() - => _versions.Aggregate(19, (code, vers) => code * 31 + vers.GetHashCode()); + => _versions.Aggregate(19, (code, vers) => (code * 31) + vers.GetHashCode()); - public override String ToString() + public override string ToString() => string.Format(Properties.Resources.GameVersionCriteriaToString, string.Join(", ", _versions.Select(v => v.ToString()))); diff --git a/Core/Versioning/GameVersionRange.cs b/Core/Versioning/GameVersionRange.cs index d366c8e8ee..20bcc84d60 100644 --- a/Core/Versioning/GameVersionRange.cs +++ b/Core/Versioning/GameVersionRange.cs @@ -16,11 +16,15 @@ public sealed partial class GameVersionRange public GameVersionRange(GameVersionBound lower, GameVersionBound upper) { - if (ReferenceEquals(lower, null)) + if (lower is null) + { throw new ArgumentNullException("lower"); + } - if (ReferenceEquals(upper, null)) + if (upper is null) + { throw new ArgumentNullException("upper"); + } Lower = lower; Upper = upper; @@ -35,8 +39,10 @@ public GameVersionRange(GameVersion lower, GameVersion upper) public GameVersionRange IntersectWith(GameVersionRange other) { - if (ReferenceEquals(other, null)) + if (other is null) + { throw new ArgumentNullException("other"); + } var highestLow = GameVersionBound.Highest(Lower, other.Lower); var lowestHigh = GameVersionBound.Lowest(Upper, other.Upper); @@ -51,8 +57,10 @@ private bool Intersects(GameVersionRange other) public bool IsSupersetOf(GameVersionRange other) { - if (ReferenceEquals(other, null)) + if (other is null) + { throw new ArgumentNullException("other"); + } var lowerIsOkay = Lower.Value.IsAny || (Lower.Value < other.Lower.Value) @@ -84,12 +92,16 @@ private static string DeriveString(GameVersionRange versionRange) sb.Append(versionRange.Lower.Inclusive ? '[' : '('); if (versionRange.Lower.Value != null) + { sb.Append(versionRange.Lower.Value); + } sb.Append(','); if (versionRange.Upper.Value != null) + { sb.Append(versionRange.Upper.Value); + } sb.Append(versionRange.Upper.Inclusive ? ']' : ')'); @@ -129,16 +141,32 @@ public sealed partial class GameVersionRange : IEquatable<GameVersionRange> { public bool Equals(GameVersionRange other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (other is null) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Equals(Lower, other.Lower) && Equals(Upper, other.Upper); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - return obj is GameVersionRange && Equals((GameVersionRange) obj); + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + return obj is GameVersionRange range && Equals(range); } public override int GetHashCode() diff --git a/Core/Versioning/ModuleVersion.cs b/Core/Versioning/ModuleVersion.cs index 7c5ac2883b..ef3d656efc 100644 --- a/Core/Versioning/ModuleVersion.cs +++ b/Core/Versioning/ModuleVersion.cs @@ -41,13 +41,15 @@ public partial class ModuleVersion /// <summary> /// Initializes a new instance of the <see cref="ModuleVersion"/> class using the specified string. /// </summary> - /// <param name="version">A <see cref="String"/> in the appropriate format.</param> + /// <param name="version">A <see cref="string"/> in the appropriate format.</param> public ModuleVersion(string version) { var match = Pattern.Match(version); if (!match.Success) + { throw new FormatException("Input string was not in a correct format."); + } // If we have an epoch, then record it. if (match.Groups["epoch"].Value.Length > 0) @@ -77,10 +79,10 @@ public ModuleVersion IncrementEpoch() /// <summary> /// Converts the value of the current <see cref="ModuleVersion"/> object to its equivalent - /// <see cref="String"/> representation. + /// <see cref="string"/> representation. /// </summary> /// <returns> - /// The <see cref="String"/> representation of the current <see cref="ModuleVersion"/> object. + /// The <see cref="string"/> representation of the current <see cref="ModuleVersion"/> object. /// </returns> /// /// <remarks> /// The return value should not be considered safe for use in file paths. @@ -103,7 +105,9 @@ public partial class ModuleVersion : IEquatable<ModuleVersion> public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) + { return true; + } return obj is ModuleVersion version && Equals(version); } @@ -111,7 +115,9 @@ public override bool Equals(object obj) public bool Equals(ModuleVersion other) { if (ReferenceEquals(this, other)) + { return true; + } return CompareTo(other) == 0; } @@ -312,30 +318,42 @@ Comparison numComp(string v1, string v2) if (!int.TryParse(v1.Substring(0, minimumLength1), out var integer1)) + { integer1 = 0; + } if (!int.TryParse(v2.Substring(0, minimumLength2), out var integer2)) + { integer2 = 0; + } comparison.CompareTo = integer1.CompareTo(integer2); return comparison; } if (other == null) + { throw new ArgumentNullException(nameof(other)); + } if (other._epoch == _epoch && other._version.Equals(_version)) + { return 0; + } // Compare epochs first. if (_epoch != other._epoch) + { return _epoch > other._epoch ? 1 : -1; + } // Epochs are the same. Do the dance described in // https://github.com/KSP-CKAN/CKAN/blob/master/Spec.md#version-ordering var tuple = new Tuple<string, string>(_string, other._string); if (ComparisonCache.TryGetValue(tuple, out var ret)) + { return ret; + } Comparison comp; comp.FirstRemainder = _version; @@ -602,10 +620,14 @@ public partial class ModuleVersion public static ModuleVersion Max(ModuleVersion ver1, ModuleVersion ver2) { if (ver1 == null) + { throw new ArgumentNullException(nameof(ver1)); + } if (ver2 == null) + { throw new ArgumentNullException(nameof(ver2)); + } return ver1.IsGreaterThan(ver2) ? ver1 : ver2; } @@ -623,10 +645,14 @@ public static ModuleVersion Max(ModuleVersion ver1, ModuleVersion ver2) public static ModuleVersion Min(ModuleVersion ver1, ModuleVersion ver2) { if (ver1 == null) + { throw new ArgumentNullException(nameof(ver1)); + } if (ver2 == null) + { throw new ArgumentNullException(nameof(ver2)); + } return ver1.IsLessThan(ver2) ? ver1 : ver2; } @@ -634,9 +660,9 @@ public static ModuleVersion Min(ModuleVersion ver1, ModuleVersion ver2) /// <summary> /// Converts the specified string to a new instance of the <see cref="ModuleVersion"/> class. /// </summary> - /// <param name="version">A <see cref="String"/> in the appropriate format.</param> + /// <param name="version">A <see cref="string"/> in the appropriate format.</param> /// <returns> - /// A new <see cref="ModuleVersion"/> instance representing the specified <see cref="String"/>. + /// A new <see cref="ModuleVersion"/> instance representing the specified <see cref="string"/>. /// </returns> public static explicit operator ModuleVersion(string version) { diff --git a/Core/Versioning/ProvidesModuleVersion.cs b/Core/Versioning/ProvidesModuleVersion.cs index 8ec52cf448..2ec3a23962 100644 --- a/Core/Versioning/ProvidesModuleVersion.cs +++ b/Core/Versioning/ProvidesModuleVersion.cs @@ -29,8 +29,6 @@ public ProvidesModuleVersion(string identifier, string version) : base(version) /// The returned value is not a real version string and is for display purposes only. /// </remarks> public override string ToString() - { - return _string; - } + => _string; } } diff --git a/Core/Versioning/UnmanagedModuleVersion.cs b/Core/Versioning/UnmanagedModuleVersion.cs index 44f0113421..f71cc77980 100644 --- a/Core/Versioning/UnmanagedModuleVersion.cs +++ b/Core/Versioning/UnmanagedModuleVersion.cs @@ -19,8 +19,6 @@ public UnmanagedModuleVersion(string version) : base(version ?? "0") } public override string ToString() - { - return _string; - } + => _string; } } diff --git a/GUI/Controls/ChooseProvidedMods.cs b/GUI/Controls/ChooseProvidedMods.cs index 17b1abb817..60cb9dde73 100644 --- a/GUI/Controls/ChooseProvidedMods.cs +++ b/GUI/Controls/ChooseProvidedMods.cs @@ -46,13 +46,7 @@ public CkanModule Wait() return task.Task.Result; } - public ListView.SelectedListViewItemCollection SelectedItems - { - get - { - return ChooseProvidedModsListView.SelectedItems; - } - } + public ListView.SelectedListViewItemCollection SelectedItems => ChooseProvidedModsListView.SelectedItems; public event Action<ListView.SelectedListViewItemCollection> OnSelectedItemsChanged; diff --git a/GUI/Controls/ChooseRecommendedMods.cs b/GUI/Controls/ChooseRecommendedMods.cs index a1ef0cbc77..a28ec8c08d 100644 --- a/GUI/Controls/ChooseRecommendedMods.cs +++ b/GUI/Controls/ChooseRecommendedMods.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using System.Windows.Forms; -using CKAN.Extensions; using CKAN.Versioning; using CKAN.GUI.Attributes; @@ -184,7 +183,9 @@ private void RecommendedModsToggleCheckbox_CheckedChanged(object sender, EventAr foreach (ListViewItem item in RecommendedModsListView.Items) { if (item.Checked != state) + { item.Checked = state; + } } MarkConflicts(); RecommendedModsListView.EndUpdate(); diff --git a/GUI/Controls/DeleteDirectories.cs b/GUI/Controls/DeleteDirectories.cs index dab1b62d85..ab9fdccde7 100644 --- a/GUI/Controls/DeleteDirectories.cs +++ b/GUI/Controls/DeleteDirectories.cs @@ -4,8 +4,6 @@ using System.Threading.Tasks; using System.Collections.Generic; using System.Windows.Forms; - -using CKAN.Extensions; using CKAN.GUI.Attributes; namespace CKAN.GUI @@ -98,7 +96,7 @@ protected override void OnHelpRequested(HelpEventArgs evt) evt.Handled = Util.TryOpenWebPage(HelpURLs.DeleteDirectories); } - private void DirectoriesListView_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e) + private void DirectoriesListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { ContentsListView.Items.Clear(); ContentsListView.Items.AddRange( diff --git a/GUI/Controls/DropdownMenuButton.cs b/GUI/Controls/DropdownMenuButton.cs index f99fe7c70e..c1bdbb12e6 100644 --- a/GUI/Controls/DropdownMenuButton.cs +++ b/GUI/Controls/DropdownMenuButton.cs @@ -33,7 +33,7 @@ protected override void OnPaint(PaintEventArgs pevent) if (Menu != null) { int arrowX = ClientRectangle.Width - 14, - arrowY = ClientRectangle.Height / 2 - 1; + arrowY = (ClientRectangle.Height / 2) - 1; pevent.Graphics.FillPolygon( Enabled ? SystemBrushes.ControlText : SystemBrushes.ButtonShadow, diff --git a/GUI/Controls/EditModSearch.cs b/GUI/Controls/EditModSearch.cs index fd209a29e2..0e8a87206d 100644 --- a/GUI/Controls/EditModSearch.cs +++ b/GUI/Controls/EditModSearch.cs @@ -112,7 +112,7 @@ private void ImmediateHandler(object sender, EventArgs e) } catch (Kraken k) { - Main.Instance.AddStatusMessage(k.Message); + Main.Instance?.AddStatusMessage(k.Message); } } @@ -241,7 +241,9 @@ private static string CombinePieces(string joined, string piece) private void SearchDetails_ApplySearch(object sender, EventArgs e) { if (suppressSearch) + { return; + } var knownLabels = Main.Instance.ManageMods.mainModList.ModuleLabels.LabelsFor(Main.Instance.CurrentInstance.Name).ToList(); diff --git a/GUI/Controls/EditModpack.cs b/GUI/Controls/EditModpack.cs index dd45adb145..8799e2c7ef 100644 --- a/GUI/Controls/EditModpack.cs +++ b/GUI/Controls/EditModpack.cs @@ -18,20 +18,20 @@ public EditModpack() { InitializeComponent(); - this.ToolTip.SetToolTip(IdentifierTextBox, Properties.Resources.EditModpackTooltipIdentifier); - this.ToolTip.SetToolTip(NameTextBox, Properties.Resources.EditModpackTooltipName); - this.ToolTip.SetToolTip(AbstractTextBox, Properties.Resources.EditModpackTooltipAbstract); - this.ToolTip.SetToolTip(VersionTextBox, Properties.Resources.EditModpackTooltipVersion); - this.ToolTip.SetToolTip(GameVersionMinComboBox, Properties.Resources.EditModpackTooltipGameVersionMin); - this.ToolTip.SetToolTip(GameVersionMaxComboBox, Properties.Resources.EditModpackTooltipGameVersionMax); - this.ToolTip.SetToolTip(LicenseComboBox, Properties.Resources.EditModpackTooltipLicense); - this.ToolTip.SetToolTip(IncludeVersionsCheckbox, Properties.Resources.EditModpackTooltipIncludeVersions); - this.ToolTip.SetToolTip(DependsRadioButton, Properties.Resources.EditModpackTooltipDepends); - this.ToolTip.SetToolTip(RecommendsRadioButton, Properties.Resources.EditModpackTooltipRecommends); - this.ToolTip.SetToolTip(SuggestsRadioButton, Properties.Resources.EditModpackTooltipSuggests); - this.ToolTip.SetToolTip(IgnoreRadioButton, Properties.Resources.EditModpackTooltipIgnore); - this.ToolTip.SetToolTip(CancelExportButton, Properties.Resources.EditModpackTooltipCancel); - this.ToolTip.SetToolTip(ExportModpackButton, Properties.Resources.EditModpackTooltipExport); + ToolTip.SetToolTip(IdentifierTextBox, Properties.Resources.EditModpackTooltipIdentifier); + ToolTip.SetToolTip(NameTextBox, Properties.Resources.EditModpackTooltipName); + ToolTip.SetToolTip(AbstractTextBox, Properties.Resources.EditModpackTooltipAbstract); + ToolTip.SetToolTip(VersionTextBox, Properties.Resources.EditModpackTooltipVersion); + ToolTip.SetToolTip(GameVersionMinComboBox, Properties.Resources.EditModpackTooltipGameVersionMin); + ToolTip.SetToolTip(GameVersionMaxComboBox, Properties.Resources.EditModpackTooltipGameVersionMax); + ToolTip.SetToolTip(LicenseComboBox, Properties.Resources.EditModpackTooltipLicense); + ToolTip.SetToolTip(IncludeVersionsCheckbox, Properties.Resources.EditModpackTooltipIncludeVersions); + ToolTip.SetToolTip(DependsRadioButton, Properties.Resources.EditModpackTooltipDepends); + ToolTip.SetToolTip(RecommendsRadioButton, Properties.Resources.EditModpackTooltipRecommends); + ToolTip.SetToolTip(SuggestsRadioButton, Properties.Resources.EditModpackTooltipSuggests); + ToolTip.SetToolTip(IgnoreRadioButton, Properties.Resources.EditModpackTooltipIgnore); + ToolTip.SetToolTip(CancelExportButton, Properties.Resources.EditModpackTooltipCancel); + ToolTip.SetToolTip(ExportModpackButton, Properties.Resources.EditModpackTooltipExport); } [ForbidGUICalls] diff --git a/GUI/Controls/InstallationHistory.cs b/GUI/Controls/InstallationHistory.cs index 6295248dcc..fa847f1623 100644 --- a/GUI/Controls/InstallationHistory.cs +++ b/GUI/Controls/InstallationHistory.cs @@ -16,7 +16,7 @@ public InstallationHistory() public void LoadHistory(GameInstance inst, GUIConfiguration config, RepositoryDataManager repoData) { this.inst = inst; - this.registry = RegistryManager.Instance(inst, repoData).registry; + registry = RegistryManager.Instance(inst, repoData).registry; this.config = config; Util.Invoke(this, () => { @@ -38,7 +38,7 @@ public void LoadHistory(GameInstance inst, GUIConfiguration config, RepositoryDa Splitter.Panel1MinSize = Splitter.SplitterDistance = TimestampColumn.Width + SystemInformation.VerticalScrollBarWidth - + 4 * SystemInformation.BorderSize.Width; + + (4 * SystemInformation.BorderSize.Width); HistoryListView.EndUpdate(); HistoryListView_ItemSelectionChanged(null, null); UseWaitCursor = false; @@ -70,7 +70,7 @@ protected override void OnHelpRequested(HelpEventArgs evt) evt.Handled = Util.TryOpenWebPage(HelpURLs.InstallationHistory); } - private void HistoryListView_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e) + private void HistoryListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { UseWaitCursor = true; Task.Factory.StartNew(() => @@ -190,7 +190,7 @@ private CkanModule SaneLatestAvail(string identifier) } } - private void ModsListView_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e) + private void ModsListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { var mod = ModsListView.SelectedItems .Cast<ListViewItem>() diff --git a/GUI/Controls/LeftRightRowPanel.cs b/GUI/Controls/LeftRightRowPanel.cs index 6ee1196f36..95c210d323 100644 --- a/GUI/Controls/LeftRightRowPanel.cs +++ b/GUI/Controls/LeftRightRowPanel.cs @@ -62,7 +62,9 @@ public LeftRightRowPanel() /// true if the borders of the panels should be shown, false to hide them. /// Useful for debugging. /// </summary> + #pragma warning disable IDE0051 private bool BordersVisible + #pragma warning restore IDE0051 { get => BorderStyle == BorderStyle.FixedSingle; set diff --git a/GUI/Controls/ManageMods.cs b/GUI/Controls/ManageMods.cs index fc8e6bdc73..b319806cd1 100644 --- a/GUI/Controls/ManageMods.cs +++ b/GUI/Controls/ManageMods.cs @@ -107,7 +107,9 @@ private List<ModChange> ChangeSet var orig = currentChangeSet; currentChangeSet = value; if (!ReferenceEquals(orig, value)) + { ChangeSetUpdated(); + } } } @@ -216,7 +218,7 @@ private void ConflictsUpdated(Dictionary<GUIMod, string> prevConflicts) private void RefreshToolButton_Click(object sender, EventArgs e) { // If user is holding Shift or Ctrl, force a full update - Main.Instance.UpdateRepo((Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0); + Main.Instance.UpdateRepo((ModifierKeys & (Keys.Control | Keys.Shift)) != 0); } #region Filter dropdown @@ -337,74 +339,74 @@ private void editLabelsToolStripMenuItem_Click(object sender, EventArgs e) private void tagFilterButton_Click(object sender, EventArgs e) { var clicked = sender as ToolStripMenuItem; - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Tag, clicked.Tag as ModuleTag, null), merge); } private void customFilterButton_Click(object sender, EventArgs e) { var clicked = sender as ToolStripMenuItem; - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.CustomLabel, null, clicked.Tag as ModuleLabel), merge); } private void FilterCompatibleButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Compatible), merge); } private void FilterInstalledButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Installed), merge); } private void FilterInstalledUpdateButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.InstalledUpdateAvailable), merge); } private void FilterReplaceableButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Replaceable), merge); } private void FilterCachedButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Cached), merge); } private void FilterUncachedButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Uncached), merge); } private void FilterNewButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.NewInRepository), merge); } private void FilterNotInstalledButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.NotInstalled), merge); } private void FilterIncompatibleButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.Incompatible), merge); } private void FilterAllButton_Click(object sender, EventArgs e) { - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; Filter(ModList.FilterToSavedSearch(GUIModFilter.All), merge); } @@ -571,7 +573,7 @@ private void ModGrid_HeaderMouseClick(object sender, DataGridViewCellMouseEventA // Left click -> sort by new column / change sorting direction. if (e.Button == MouseButtons.Left) { - if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) + if ((ModifierKeys & Keys.Shift) == Keys.Shift) { AddSort(ModGrid.Columns[e.ColumnIndex]); } @@ -666,14 +668,20 @@ private void ModGrid_KeyDown(object sender, KeyEventArgs e) case Keys.Home: // First row. if (ModGrid.Rows.Count > 0) //Handles for empty filters + { ModGrid.CurrentCell = ModGrid.Rows[0].Cells[SelectableColumnIndex()]; + } + e.Handled = true; break; case Keys.End: // Last row. if (ModGrid.Rows.Count > 0) //Handles for empty filters + { ModGrid.CurrentCell = ModGrid.Rows[ModGrid.Rows.Count - 1].Cells[SelectableColumnIndex()]; + } + e.Handled = true; break; @@ -753,14 +761,20 @@ private void ModGrid_CellContentClick(object sender, DataGridViewCellEventArgs e private void ModGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button != MouseButtons.Left) + { return; + } if (e.RowIndex < 0) + { return; + } DataGridViewRow row = ModGrid.Rows[e.RowIndex]; if (!(row.Cells[0] is DataGridViewCheckBoxCell)) + { return; + } // Need to change the state here, because the user hasn't clicked on a checkbox. row.Cells[0].Value = !(bool)row.Cells[0].Value; @@ -773,7 +787,9 @@ private void ModGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e int column_index = e.ColumnIndex; if (row_index < 0 || column_index < 0) + { return; + } DataGridView grid = sender as DataGridView; DataGridViewRow row = grid?.Rows[row_index]; @@ -785,7 +801,9 @@ private void ModGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e DataGridViewLinkCell cell = gridCell as DataGridViewLinkCell; string cmd = cell?.Value.ToString(); if (!string.IsNullOrEmpty(cmd)) + { Utilities.ProcessStartURL(cmd); + } } else { @@ -927,11 +945,15 @@ public void FocusMod(string key, bool exactMatch, bool showAsFirst = false) GUIMod mod = row.Tag as GUIMod; bool row_match; if (exactMatch) + { row_match = mod.Name == key || mod.Identifier == key; + } else + { row_match = mod.Name.StartsWith(key, StringComparison.OrdinalIgnoreCase) || mod.Abbrevation.StartsWith(key, StringComparison.OrdinalIgnoreCase) || mod.Identifier.StartsWith(key, StringComparison.OrdinalIgnoreCase); + } if (row_match && first_match == null) { @@ -964,7 +986,9 @@ public void FocusMod(string key, bool exactMatch, bool showAsFirst = false) ModGrid.CurrentCell = match.Cells[SelectableColumnIndex()]; if (showAsFirst) + { ModGrid.FirstDisplayedScrollingRowIndex = match.Index; + } } else { @@ -1092,7 +1116,9 @@ public void UpdateFilters() private void _UpdateFilters() { if (ModGrid == null || mainModList?.full_list_of_mod_rows == null) + { return; + } // Each time a row in DataGridViewRow is changed, DataGridViewRow updates the view. Which is slow. // To make the filtering process faster, Copy the list of rows. Filter out the hidden and replace the @@ -1220,7 +1246,7 @@ private bool _UpdateModsList(Dictionary<string, bool> old_modules = null) Main.Instance.Wait.AddLogMessage(Properties.Resources.MainModListPopulatingList); // Update our mod listing - mainModList.ConstructModList(gui_mods as IReadOnlyCollection<GUIMod>, + mainModList.ConstructModList(gui_mods, Main.Instance.CurrentInstance.Name, Main.Instance.CurrentInstance.game, ChangeSet); @@ -1232,25 +1258,25 @@ private bool _UpdateModsList(Dictionary<string, bool> old_modules = null) var has_unheld_updates = mainModList.Modules.Any(mod => mod.HasUpdate && !Main.Instance.LabelsHeld(mod.Identifier)); Util.Invoke(menuStrip2, () => { - FilterCompatibleButton.Text = String.Format(Properties.Resources.MainModListCompatible, + FilterCompatibleButton.Text = string.Format(Properties.Resources.MainModListCompatible, mainModList.CountModsByFilter(GUIModFilter.Compatible)); - FilterInstalledButton.Text = String.Format(Properties.Resources.MainModListInstalled, + FilterInstalledButton.Text = string.Format(Properties.Resources.MainModListInstalled, mainModList.CountModsByFilter(GUIModFilter.Installed)); - FilterInstalledUpdateButton.Text = String.Format(Properties.Resources.MainModListUpgradeable, + FilterInstalledUpdateButton.Text = string.Format(Properties.Resources.MainModListUpgradeable, mainModList.CountModsByFilter(GUIModFilter.InstalledUpdateAvailable)); - FilterReplaceableButton.Text = String.Format(Properties.Resources.MainModListReplaceable, + FilterReplaceableButton.Text = string.Format(Properties.Resources.MainModListReplaceable, mainModList.CountModsByFilter(GUIModFilter.Replaceable)); - FilterCachedButton.Text = String.Format(Properties.Resources.MainModListCached, + FilterCachedButton.Text = string.Format(Properties.Resources.MainModListCached, mainModList.CountModsByFilter(GUIModFilter.Cached)); - FilterUncachedButton.Text = String.Format(Properties.Resources.MainModListUncached, + FilterUncachedButton.Text = string.Format(Properties.Resources.MainModListUncached, mainModList.CountModsByFilter(GUIModFilter.Uncached)); - FilterNewButton.Text = String.Format(Properties.Resources.MainModListNewlyCompatible, + FilterNewButton.Text = string.Format(Properties.Resources.MainModListNewlyCompatible, mainModList.CountModsByFilter(GUIModFilter.NewInRepository)); - FilterNotInstalledButton.Text = String.Format(Properties.Resources.MainModListNotInstalled, + FilterNotInstalledButton.Text = string.Format(Properties.Resources.MainModListNotInstalled, mainModList.CountModsByFilter(GUIModFilter.NotInstalled)); - FilterIncompatibleButton.Text = String.Format(Properties.Resources.MainModListIncompatible, + FilterIncompatibleButton.Text = string.Format(Properties.Resources.MainModListIncompatible, mainModList.CountModsByFilter(GUIModFilter.Incompatible)); - FilterAllButton.Text = String.Format(Properties.Resources.MainModListAll, + FilterAllButton.Text = string.Format(Properties.Resources.MainModListAll, mainModList.CountModsByFilter(GUIModFilter.All)); UpdateAllToolButton.Enabled = has_unheld_updates; @@ -1517,7 +1543,9 @@ private void NavInit() navHistory.IsReadOnly = false; var currentMod = SelectedModule; if (currentMod != null) + { navHistory.AddToHistory(currentMod); + } } private void NavUpdateUI() @@ -1534,13 +1562,17 @@ private void NavSelectMod(GUIMod module) public void NavGoBackward() { if (navHistory.CanNavigateBackward) + { NavGoToMod(navHistory.NavigateBackward()); + } } public void NavGoForward() { if (navHistory.CanNavigateForward) + { NavGoToMod(navHistory.NavigateForward()); + } } private void NavGoToMod(GUIMod module) @@ -1574,7 +1606,9 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) case Keys.Control | Keys.S: if (ChangeSet != null && ChangeSet.Any()) + { ApplyToolButton_Click(null, null); + } return true; } diff --git a/GUI/Controls/ModInfo.cs b/GUI/Controls/ModInfo.cs index 34b6e318af..73c3119789 100644 --- a/GUI/Controls/ModInfo.cs +++ b/GUI/Controls/ModInfo.cs @@ -158,7 +158,7 @@ private void UpdateTagsAndLabels(CkanModule mod) foreach (ModuleTag tag in tags) { MetadataTagsLabelsPanel.Controls.Add(TagLabelLink( - tag.Name, tag, new LinkLabelLinkClickedEventHandler(this.TagLinkLabel_LinkClicked) + tag.Name, tag, new LinkLabelLinkClickedEventHandler(TagLinkLabel_LinkClicked) )); } } @@ -170,7 +170,7 @@ private void UpdateTagsAndLabels(CkanModule mod) foreach (ModuleLabel mlbl in labels) { MetadataTagsLabelsPanel.Controls.Add(TagLabelLink( - mlbl.Name, mlbl, new LinkLabelLinkClickedEventHandler(this.LabelLinkLabel_LinkClicked) + mlbl.Name, mlbl, new LinkLabelLinkClickedEventHandler(LabelLinkLabel_LinkClicked) )); } } @@ -198,7 +198,7 @@ private LinkLabel TagLabelLink(string name, object tag, LinkLabelLinkClickedEven private void TagLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var link = sender as LinkLabel; - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; OnChangeFilter?.Invoke( ModList.FilterToSavedSearch(GUIModFilter.Tag, link.Tag as ModuleTag, null), merge); @@ -207,7 +207,7 @@ private void TagLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventAr private void LabelLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var link = sender as LinkLabel; - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; OnChangeFilter?.Invoke( ModList.FilterToSavedSearch(GUIModFilter.CustomLabel, null, link.Tag as ModuleLabel), merge); diff --git a/GUI/Controls/ModInfoTabs/Metadata.cs b/GUI/Controls/ModInfoTabs/Metadata.cs index 6fea26e068..ec6b99f428 100644 --- a/GUI/Controls/ModInfoTabs/Metadata.cs +++ b/GUI/Controls/ModInfoTabs/Metadata.cs @@ -113,7 +113,7 @@ private void OnAuthorClick(object sender, LinkLabelLinkClickedEventArgs e) { var link = sender as LinkLabel; var author = link.Text; - var merge = (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0; + var merge = (ModifierKeys & (Keys.Control | Keys.Shift)) != 0; OnChangeFilter?.Invoke( new SavedSearch() { diff --git a/GUI/Controls/ModInfoTabs/Relationships.cs b/GUI/Controls/ModInfoTabs/Relationships.cs index 09a3798afc..6a3fc22a61 100644 --- a/GUI/Controls/ModInfoTabs/Relationships.cs +++ b/GUI/Controls/ModInfoTabs/Relationships.cs @@ -105,7 +105,7 @@ private void ReverseRelationshipsCheckbox_Click(object sender, EventArgs e) ReverseRelationshipsCheckbox.CheckState == CheckState.Unchecked // If user holds ctrl or shift, go to "sticky" indeterminate state, // else normal checked - ? (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0 + ? (ModifierKeys & (Keys.Control | Keys.Shift)) != 0 ? CheckState.Indeterminate : CheckState.Checked : CheckState.Unchecked; diff --git a/GUI/Controls/TriStateToggle.cs b/GUI/Controls/TriStateToggle.cs index 6d245d8419..f89a04c895 100644 --- a/GUI/Controls/TriStateToggle.cs +++ b/GUI/Controls/TriStateToggle.cs @@ -28,7 +28,7 @@ public TriStateToggle() Controls.Add(BothRadioButton); Controls.Add(NoRadioButton); - Size = new Size(3 * buttonXOffset + 1, 20); + Size = new Size((3 * buttonXOffset) + 1, 20); ResumeLayout(false); PerformLayout(); @@ -36,12 +36,9 @@ public TriStateToggle() public bool? Value { - get - { - return YesRadioButton.Checked ? (bool?)true - : NoRadioButton.Checked ? (bool?)false - : null; - } + get => YesRadioButton.Checked ? true + : NoRadioButton.Checked ? (bool?)false + : null; set { if (!value.HasValue) @@ -66,7 +63,7 @@ private RadioButton MakeRadioButton(int index, Bitmap icon, string tooltip, bool var rb = new RadioButton() { Appearance = Appearance.Button, - BackColor = check ? SystemColors.Highlight : RadioButton.DefaultBackColor, + BackColor = check ? SystemColors.Highlight : DefaultBackColor, FlatStyle = FlatStyle.Flat, Location = new Point(index * buttonXOffset, 0), Size = new Size(buttonWidth, 20), @@ -90,7 +87,7 @@ private void RadioButtonChanged(object sender, EventArgs e) } else { - butt.BackColor = RadioButton.DefaultBackColor; + butt.BackColor = DefaultBackColor; } } diff --git a/GUI/Controls/UnmanagedFiles.cs b/GUI/Controls/UnmanagedFiles.cs index f3313cf831..0102d4b331 100644 --- a/GUI/Controls/UnmanagedFiles.cs +++ b/GUI/Controls/UnmanagedFiles.cs @@ -25,7 +25,7 @@ public void LoadFiles(GameInstance inst, RepositoryDataManager repoData, IUser u { this.inst = inst; this.user = user; - this.registry = RegistryManager.Instance(inst, repoData).registry; + registry = RegistryManager.Instance(inst, repoData).registry; Util.Invoke(this, _UpdateGameFolderTree); } diff --git a/GUI/Controls/Wait.cs b/GUI/Controls/Wait.cs index d298a6b8ed..c37353bb90 100644 --- a/GUI/Controls/Wait.cs +++ b/GUI/Controls/Wait.cs @@ -40,6 +40,8 @@ public void StartWaiting(Action<object, DoWorkEventArgs> mainWork, public event Action OnCancel; public event Action OnOk; + #pragma warning disable IDE0027 + public bool RetryEnabled { [ForbidGUICalls] @@ -73,6 +75,8 @@ public bool ProgressIndeterminate } } + #pragma warning restore IDE0027 + public void SetProgress(string label, long remaining, long total) { if (total > 0) diff --git a/GUI/Dialogs/CloneGameInstanceDialog.cs b/GUI/Dialogs/CloneGameInstanceDialog.cs index c86e6e0bf7..f5627c6e80 100644 --- a/GUI/Dialogs/CloneGameInstanceDialog.cs +++ b/GUI/Dialogs/CloneGameInstanceDialog.cs @@ -71,7 +71,9 @@ private void buttonInstancePathSelection_Click(object sender, EventArgs e) // Show the FileDialog and let the user search for the game directory. if (instanceDialog.ShowDialog(this) != DialogResult.OK || !File.Exists(instanceDialog.FileName)) + { return; + } // Write the path to the textbox textBoxClonePath.Text = Path.GetDirectoryName(instanceDialog.FileName); @@ -90,12 +92,12 @@ private async void buttonOK_Click(object sender, EventArgs e) string newPath = textBoxNewPath.Text; // Do some basic checks. - if (String.IsNullOrWhiteSpace(newName)) + if (string.IsNullOrWhiteSpace(newName)) { user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterName); return; } - if (String.IsNullOrWhiteSpace(newPath)) + if (string.IsNullOrWhiteSpace(newPath)) { user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterPath); return; diff --git a/GUI/Dialogs/CompatibleGameVersionsDialog.cs b/GUI/Dialogs/CompatibleGameVersionsDialog.cs index adcc967c2a..f996d4d721 100644 --- a/GUI/Dialogs/CompatibleGameVersionsDialog.cs +++ b/GUI/Dialogs/CompatibleGameVersionsDialog.cs @@ -21,7 +21,7 @@ public partial class CompatibleGameVersionsDialog : Form /// <param name="centerScreen">true to center the dialog on the screen, false to center on the parent</param> public CompatibleGameVersionsDialog(GameInstance inst, bool centerScreen) { - this._inst = inst; + _inst = inst; InitializeComponent(); if (centerScreen) @@ -145,7 +145,7 @@ private void ClearSelectionButton_Click(object sender, EventArgs e) private void CancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } private void SaveButton_Click(object sender, EventArgs e) @@ -155,7 +155,7 @@ private void SaveButton_Click(object sender, EventArgs e) ); DialogResult = DialogResult.OK; - this.Close(); + Close(); } } } diff --git a/GUI/Dialogs/DownloadsFailedDialog.cs b/GUI/Dialogs/DownloadsFailedDialog.cs index b46df1c5c4..e807677075 100644 --- a/GUI/Dialogs/DownloadsFailedDialog.cs +++ b/GUI/Dialogs/DownloadsFailedDialog.cs @@ -59,8 +59,8 @@ public DownloadsFailedDialog( ExplanationLabel.Height + ExplanationLabel.Padding.Vertical + DownloadsGrid.ColumnHeadersHeight - + DownloadsGrid.RowCount - * DownloadsGrid.RowTemplate.Height + + (DownloadsGrid.RowCount + * DownloadsGrid.RowTemplate.Height) + DownloadsGrid.Margin.Vertical + DownloadsGrid.Padding.Vertical + BottomButtonPanel.Height); @@ -190,7 +190,9 @@ public DownloadRow(object data, Exception exc) /// True if Skip column has a checkmark /// </summary> /// <value></value> + #pragma warning disable IDE0027 public bool Skip { get => !Retry; set { Retry = !value; } } + #pragma warning restore IDE0027 /// <summary> /// This row's data object /// </summary> diff --git a/GUI/Dialogs/EditLabelsDialog.cs b/GUI/Dialogs/EditLabelsDialog.cs index b5e1c3241e..21443bec92 100644 --- a/GUI/Dialogs/EditLabelsDialog.cs +++ b/GUI/Dialogs/EditLabelsDialog.cs @@ -34,7 +34,7 @@ private void LoadTree() { LabelSelectionTree.BeginUpdate(); LabelSelectionTree.Nodes.Clear(); - var groups = this.labels.Labels + var groups = labels.Labels .GroupBy(l => l.InstanceName) .OrderBy(g => g.Key == null) .ThenBy(g => g.Key); @@ -65,7 +65,7 @@ private void LoadTree() // Select the new node representing the label we're editing LabelSelectionTree.SelectedNode = LabelSelectionTree.Nodes.Cast<TreeNode>() .SelectMany(nd => nd.Nodes.Cast<TreeNode>()) - .FirstOrDefault(nd => nd.Tag as ModuleLabel == currentlyEditing); + .FirstOrDefault(nd => (nd.Tag as ModuleLabel) == currentlyEditing); LabelSelectionTree.BeforeSelect += LabelSelectionTree_BeforeSelect; } LabelSelectionTree.ExpandAll(); @@ -88,7 +88,7 @@ protected override void OnHelpButtonClicked(CancelEventArgs evt) evt.Cancel = Util.TryOpenWebPage(HelpURLs.Labels); } - private void LabelSelectionTree_BeforeSelect(Object sender, TreeViewCancelEventArgs e) + private void LabelSelectionTree_BeforeSelect(object sender, TreeViewCancelEventArgs e) { if (e.Node == null) { diff --git a/GUI/Dialogs/ManageGameInstancesDialog.cs b/GUI/Dialogs/ManageGameInstancesDialog.cs index 56bfd055a0..8e93a44878 100644 --- a/GUI/Dialogs/ManageGameInstancesDialog.cs +++ b/GUI/Dialogs/ManageGameInstancesDialog.cs @@ -119,12 +119,16 @@ private string[] rowItems(GameInstance instance, bool includeGame, bool includeP }; if (includeGame) + { list.Add(instance.game.ShortName); + } list.Add(FormatVersion(instance.Version())); if (includePlayTime) + { list.Add(instance.playTime?.ToString() ?? ""); + } list.Add(instance.GameDir().Replace('/', Path.DirectorySeparatorChar)); return list.ToArray(); @@ -158,7 +162,9 @@ private void AddToCKANMenuItem_Click(object sender, EventArgs e) { if (_instanceDialog.ShowDialog(this) != DialogResult.OK || !File.Exists(_instanceDialog.FileName)) + { return; + } var path = Path.GetDirectoryName(_instanceDialog.FileName); try @@ -254,7 +260,9 @@ private void GameInstancesListView_SelectedIndexChanged(object sender, EventArgs UpdateButtonState(); if (GameInstancesListView.SelectedItems.Count == 0) + { return; + } string instName = (string)GameInstancesListView.SelectedItems[0].Tag; SetAsDefaultCheckbox.Checked = _manager.AutoStartInstance?.Equals(instName) ?? false; @@ -307,7 +315,9 @@ private void RenameButton_Click(object sender, EventArgs e) // show the dialog, and only continue if the user selected "OK" _renameInstanceDialog = new RenameInstanceDialog(); if (_renameInstanceDialog.ShowRenameInstanceDialog(instance) != DialogResult.OK) + { return; + } // proceed with instance rename _manager.RenameInstance(instance, _renameInstanceDialog.GetResult()); diff --git a/GUI/Dialogs/SelectionDialog.cs b/GUI/Dialogs/SelectionDialog.cs index bad631d34b..2baa2b9613 100644 --- a/GUI/Dialogs/SelectionDialog.cs +++ b/GUI/Dialogs/SelectionDialog.cs @@ -5,7 +5,7 @@ namespace CKAN.GUI { public partial class SelectionDialog : Form { - int currentSelected; + private int currentSelected; public SelectionDialog () { @@ -25,7 +25,7 @@ public int ShowSelectionDialog (string message, params object[] args) int return_cancel = -1; // Validate input. - if (String.IsNullOrWhiteSpace(message)) + if (string.IsNullOrWhiteSpace(message)) { throw new Kraken("Passed message string must be non-empty."); } @@ -68,7 +68,7 @@ public int ShowSelectionDialog (string message, params object[] args) // Further data validation. foreach (object argument in args) { - if (String.IsNullOrWhiteSpace(argument.ToString())) + if (string.IsNullOrWhiteSpace(argument.ToString())) { throw new Kraken("Candidate may not be empty."); } @@ -79,7 +79,7 @@ public int ShowSelectionDialog (string message, params object[] args) { if (defaultSelection == i) { - Util.Invoke(OptionsList, () => OptionsList.Items.Add(String.Concat(args[i].ToString(), " -- Default"))); + Util.Invoke(OptionsList, () => OptionsList.Items.Add(string.Concat(args[i].ToString(), " -- Default"))); } else diff --git a/GUI/Dialogs/SettingsDialog.cs b/GUI/Dialogs/SettingsDialog.cs index b8cc04dc53..a93d1646d7 100644 --- a/GUI/Dialogs/SettingsDialog.cs +++ b/GUI/Dialogs/SettingsDialog.cs @@ -34,7 +34,7 @@ public SettingsDialog(RegistryManager regMgr, IUser user) this.regMgr = regMgr; if (Platform.IsMono) { - this.ClearCacheMenu.Renderer = new FlatToolStripRenderer(); + ClearCacheMenu.Renderer = new FlatToolStripRenderer(); } config = ServiceLocator.Container.Resolve<IConfiguration>(); } @@ -253,7 +253,7 @@ private void PurgeAllMenuItem_Click(object sender, EventArgs e) out int cacheFileCount, out long cacheSize, out _); YesNoDialog deleteConfirmationDialog = new YesNoDialog(); - string confirmationText = String.Format( + string confirmationText = string.Format( Properties.Resources.SettingsDialogDeleteConfirm, cacheFileCount, CkanModule.FmtSize(cacheSize)); @@ -553,14 +553,8 @@ private void CheckForUpdatesButton_Click(object sender, EventArgs e) { AutoUpdate.Instance.FetchLatestReleaseInfo(); var latestVersion = AutoUpdate.Instance.latestUpdate.Version; - if (latestVersion.IsGreaterThan(new ModuleVersion(Meta.GetVersion(VersionFormat.Short))) && AutoUpdate.Instance.IsFetched()) - { - InstallUpdateButton.Enabled = true; - } - else - { - InstallUpdateButton.Enabled = false; - } + InstallUpdateButton.Enabled = latestVersion.IsGreaterThan(new ModuleVersion(Meta.GetVersion(VersionFormat.Short))) + && AutoUpdate.Instance.IsFetched(); LatestVersionLabel.Text = latestVersion.ToString(); } @@ -635,7 +629,9 @@ private void RefreshTextBox_TextChanged(object sender, EventArgs e) private void RefreshTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) + { e.Handled = true; + } } private void PauseRefreshCheckBox_CheckedChanged(object sender, EventArgs e) @@ -643,9 +639,13 @@ private void PauseRefreshCheckBox_CheckedChanged(object sender, EventArgs e) Main.Instance.configuration.RefreshPaused = PauseRefreshCheckBox.Checked; if (Main.Instance.configuration.RefreshPaused) + { Main.Instance.refreshTimer.Stop(); + } else + { Main.Instance.refreshTimer.Start(); + } } } } diff --git a/GUI/Dialogs/YesNoDialog.cs b/GUI/Dialogs/YesNoDialog.cs index a4b5be7950..27b4057731 100644 --- a/GUI/Dialogs/YesNoDialog.cs +++ b/GUI/Dialogs/YesNoDialog.cs @@ -42,7 +42,7 @@ public Tuple<DialogResult, bool> ShowSuppressableYesNoDialog(Form parentForm, st private void Setup(string text, string yesText, string noText) { - var height = Util.StringHeight(CreateGraphics(), text, DescriptionLabel.Font, ClientSize.Width - 25) + 2 * 54; + var height = Util.StringHeight(CreateGraphics(), text, DescriptionLabel.Font, ClientSize.Width - 25) + (2 * 54); DescriptionLabel.Text = text; DescriptionLabel.TextAlign = text.Contains("\n") ? HorizontalAlignment.Left diff --git a/GUI/Labels/ModuleLabel.cs b/GUI/Labels/ModuleLabel.cs index 7921fcf1ff..b99cd71b2b 100644 --- a/GUI/Labels/ModuleLabel.cs +++ b/GUI/Labels/ModuleLabel.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Drawing; using System.ComponentModel; using System.Collections.Generic; diff --git a/GUI/Labels/ModuleLabelList.cs b/GUI/Labels/ModuleLabelList.cs index 52357efc88..1275f90c7b 100644 --- a/GUI/Labels/ModuleLabelList.cs +++ b/GUI/Labels/ModuleLabelList.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using System.Collections.Generic; using System.IO; diff --git a/GUI/Main/Main.cs b/GUI/Main/Main.cs index 6a6d7532e6..9c5611d0b6 100644 --- a/GUI/Main/Main.cs +++ b/GUI/Main/Main.cs @@ -58,11 +58,18 @@ public Main(string[] cmdlineArgs, GameInstanceManager mgr) { focusIdent = cmdlineArgs[1]; if (focusIdent.StartsWith("//")) + { focusIdent = focusIdent.Substring(2); + } else if (focusIdent.StartsWith("ckan://")) + { focusIdent = focusIdent.Substring(7); + } + if (focusIdent.EndsWith("/")) + { focusIdent = focusIdent.Substring(0, focusIdent.Length - 1); + } } Configuration.IConfiguration mainConfig = ServiceLocator.Container.Resolve<Configuration.IConfiguration>(); @@ -123,7 +130,7 @@ public Main(string[] cmdlineArgs, GameInstanceManager mgr) HandleCreated += (sender, e) => X11.SetWMClass("CKAN", "CKAN", Handle); } - currentUser = new GUIUser(this, this.Wait); + currentUser = new GUIUser(this, Wait); if (mgr != null) { // With a working GUI, assign a GUIUser to the GameInstanceManager to replace the ConsoleUser @@ -243,7 +250,7 @@ protected override void OnShown(EventArgs e) } catch (RegistryInUseKraken kraken) { - if (Main.Instance.YesNoDialog( + if (Instance.YesNoDialog( kraken.ToString(), Properties.Resources.MainDeleteLockfileYes, Properties.Resources.MainDeleteLockfileNo)) @@ -325,7 +332,7 @@ private void manageGameInstancesMenuItem_Click(object sender, EventArgs e) } catch (RegistryInUseKraken kraken) { - if (Main.Instance.YesNoDialog( + if (Instance.YesNoDialog( kraken.ToString(), Properties.Resources.MainDeleteLockfileYes, Properties.Resources.MainDeleteLockfileNo)) @@ -397,13 +404,19 @@ private void CurrentInstanceUpdated(bool allowRepoUpdate) { log.Debug("Asking user if they wish for auto-updates"); if (new AskUserForAutoUpdatesDialog().ShowDialog(this) == DialogResult.OK) + { configuration.CheckForUpdatesOnLaunch = true; + } + configuration.CheckForUpdatesOnLaunchNoNag = true; } var pluginsPath = Path.Combine(CurrentInstance.CkanDir(), "Plugins"); if (!Directory.Exists(pluginsPath)) + { Directory.CreateDirectory(pluginsPath); + } + pluginController = new PluginController(pluginsPath, true); CurrentInstance.game.RebuildSubdirectories(CurrentInstance.GameDir()); @@ -688,7 +701,7 @@ private void InstallFromCkanFiles(string[] files) var myIncompat = toInstall.Where(mod => allIncompat.Contains(mod.identifier)).ToList(); if (!myIncompat.Any() // Confirm installation of incompatible like the Versions tab does - || Main.Instance.YesNoDialog( + || Instance.YesNoDialog( string.Format(Properties.Resources.ModpackInstallIncompatiblePrompt, string.Join(Environment.NewLine, myIncompat), crit.ToSummaryString(CurrentInstance.game)), @@ -861,7 +874,9 @@ public void LaunchGame() { var split = configuration.CommandLineArguments.Split(' '); if (split.Length == 0) + { return; + } var registry = RegistryManager.Instance(CurrentInstance, repoData).registry; @@ -985,7 +1000,7 @@ private void EnableMainWindow() * if childcontrol had focus. Depending on optimization steps, * parent.childcontrol.Enabled = true does not necessarily * re-enable the parent.*/ - this.Focus(); + Focus(); }); } diff --git a/GUI/Main/MainDialogs.cs b/GUI/Main/MainDialogs.cs index a8fcf0d347..bc94ee7b6a 100644 --- a/GUI/Main/MainDialogs.cs +++ b/GUI/Main/MainDialogs.cs @@ -28,7 +28,7 @@ public void RecreateDialogs() [ForbidGUICalls] public void AddStatusMessage(string text, params object[] args) { - string msg = String.Format(text, args); + string msg = string.Format(text, args); // No newlines in status bar Util.Invoke(statusStrip1, () => StatusLabel.ToolTipText = StatusLabel.Text = msg.Replace("\r\n", " ").Replace("\n", " ") @@ -39,7 +39,7 @@ public void AddStatusMessage(string text, params object[] args) [ForbidGUICalls] public void ErrorDialog(string text, params object[] args) { - errorDialog.ShowErrorDialog(String.Format(text, args)); + errorDialog.ShowErrorDialog(string.Format(text, args)); } public bool YesNoDialog(string text, string yesText = null, string noText = null) diff --git a/GUI/Main/MainDownload.cs b/GUI/Main/MainDownload.cs index fe2be98adf..be15d1218c 100644 --- a/GUI/Main/MainDownload.cs +++ b/GUI/Main/MainDownload.cs @@ -19,7 +19,9 @@ private void ModInfo_OnDownloadClick(GUIMod gmod) public void StartDownload(GUIMod module) { if (module == null || !module.IsCKAN) + { return; + } ShowWaitDialog(); if (downloader != null) diff --git a/GUI/Main/MainHistory.cs b/GUI/Main/MainHistory.cs index d0892dd8bf..22a9b65d01 100644 --- a/GUI/Main/MainHistory.cs +++ b/GUI/Main/MainHistory.cs @@ -1,8 +1,6 @@ using System; using System.Linq; -using CKAN.Extensions; - // Don't warn if we use our own obsolete properties #pragma warning disable 0618 diff --git a/GUI/Main/MainRecommendations.cs b/GUI/Main/MainRecommendations.cs index 0ca754d0b7..2031436ba5 100644 --- a/GUI/Main/MainRecommendations.cs +++ b/GUI/Main/MainRecommendations.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using System.Linq; -using CKAN.Extensions; using CKAN.Versioning; using CKAN.GUI.Attributes; diff --git a/GUI/Model/GUIConfiguration.cs b/GUI/Model/GUIConfiguration.cs index dede7a7777..423e6b3339 100644 --- a/GUI/Model/GUIConfiguration.cs +++ b/GUI/Model/GUIConfiguration.cs @@ -9,7 +9,7 @@ namespace CKAN.GUI { - [XmlRootAttribute("Configuration")] + [XmlRoot("Configuration")] public class GUIConfiguration { public string CommandLineArguments = ""; @@ -81,8 +81,10 @@ public void SetColumnVisibility(string name, bool vis) public Point WindowLoc { - get { return windowLocation; } + get => windowLocation; + #pragma warning disable IDE0027 set { windowLocation = value; } + #pragma warning restore IDE0027 } /// <summary> @@ -139,7 +141,9 @@ private static GUIConfiguration LoadConfiguration(string path) if (e is InvalidOperationException) // Exception thrown in Windows / .NET { if (e.InnerException != null) + { additionalErrorData = ": " + e.InnerException.Message; + } } else if (e is XmlException) // Exception thrown in Mono { @@ -209,7 +213,7 @@ private static void SaveConfiguration(GUIConfiguration configuration) } } - [XmlRootAttribute("SavedSearch")] + [XmlRoot("SavedSearch")] public class SavedSearch { public string Name; diff --git a/GUI/Model/GUIMod.cs b/GUI/Model/GUIMod.cs index 1f500e47c2..2d098330af 100644 --- a/GUI/Model/GUIMod.cs +++ b/GUI/Model/GUIMod.cs @@ -25,7 +25,7 @@ public sealed class GUIMod : INotifyPropertyChanged /// </summary> public CkanModule SelectedMod { - get { return selectedMod; } + get => selectedMod; set { if (!(selectedMod?.Equals(value) ?? value?.Equals(selectedMod) ?? true)) @@ -152,7 +152,7 @@ public GUIMod(InstalledModule instMod, LatestVersion = InstalledVersion; } // For mods not known to the registry LatestCompatibleMod is null, however the installed module might be compatible - IsIncompatible = incompatible ?? LatestCompatibleMod == null && !instMod.Module.IsCompatible(current_game_version); + IsIncompatible = incompatible ?? (LatestCompatibleMod == null && !instMod.Module.IsCompatible(current_game_version)); } /// <summary> @@ -298,8 +298,11 @@ public void UpdateIsCached() public CkanModule ToCkanModule() { if (!IsCKAN) + { throw new InvalidCastException(Properties.Resources.GUIModMethodNotCKAN); - var mod = Mod as CkanModule; + } + + var mod = Mod; return mod; } @@ -422,7 +425,9 @@ public void SetReplaceChecked(DataGridViewRow row, DataGridViewColumn col, bool? bool value = set_value_to ?? old_value; IsReplaceChecked = value; if (old_value != value) + { replace_cell.Value = value; + } } } @@ -447,9 +452,21 @@ public void SetAutoInstallChecked(DataGridViewRow row, DataGridViewColumn col, b public override bool Equals(object obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != GetType()) + { + return false; + } + return Equals((GUIMod) obj); } diff --git a/GUI/Model/ModChange.cs b/GUI/Model/ModChange.cs index a60405b2f2..942402836b 100644 --- a/GUI/Model/ModChange.cs +++ b/GUI/Model/ModChange.cs @@ -59,7 +59,7 @@ public ModChange(CkanModule mod, GUIModChangeType changeType) } public ModChange(CkanModule mod, GUIModChangeType changeType, SelectionReason reason) - : this(mod, changeType, Enumerable.Repeat<SelectionReason>(reason, 1)) + : this(mod, changeType, Enumerable.Repeat(reason, 1)) { } @@ -73,9 +73,21 @@ public ModChange(CkanModule mod, GUIModChangeType changeType, IEnumerable<Select public override bool Equals(object obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != GetType()) + { + return false; + } + return (obj as ModChange).Mod.Equals(Mod); } @@ -85,7 +97,7 @@ public override int GetHashCode() // Distinguish between installing and removing => Mod == null ? 0 - : ((maxEnumVal + 1) * Mod.GetHashCode() + (int)ChangeType); + : (((maxEnumVal + 1) * Mod.GetHashCode()) + (int)ChangeType); public override string ToString() => $"{ChangeType.Localize()} {Mod} ({Description})"; diff --git a/GUI/NavigationHistory.cs b/GUI/NavigationHistory.cs index a9f7e34595..ed61fce90d 100644 --- a/GUI/NavigationHistory.cs +++ b/GUI/NavigationHistory.cs @@ -10,8 +10,8 @@ namespace CKAN.GUI /// <typeparam name="T"></typeparam> public class NavigationHistory<T> { - readonly List<T> m_navigationHistory; - int m_currentIndex; + private readonly List<T> m_navigationHistory; + private int m_currentIndex; public NavigationHistory() { @@ -36,24 +36,12 @@ public void InvokeOnHistoryChange() /// <summary> /// Indicates whether it's possible to navigate backwards. /// </summary> - public bool CanNavigateBackward - { - get - { - return m_currentIndex > 0; - } - } + public bool CanNavigateBackward => m_currentIndex > 0; /// <summary> /// Indicates whether it's possible to navigate forwards. /// </summary> - public bool CanNavigateForward - { - get - { - return m_currentIndex < (m_navigationHistory.Count - 1); - } - } + public bool CanNavigateForward => m_currentIndex < (m_navigationHistory.Count - 1); /// <summary> /// Indicates whether the history is in read-only mode. @@ -112,7 +100,7 @@ public T NavigateBackward() { if (IsReadOnly) { - return default(T); + return default; } if (!CanNavigateBackward) @@ -134,7 +122,7 @@ public T NavigateForward() { if (IsReadOnly) { - return default(T); + return default; } if (!CanNavigateForward) diff --git a/GUI/Plugins/PluginController.cs b/GUI/Plugins/PluginController.cs index 9f86776707..41ad67d8e9 100644 --- a/GUI/Plugins/PluginController.cs +++ b/GUI/Plugins/PluginController.cs @@ -51,7 +51,7 @@ private void LoadAssembly(string dll) try { var typeName = Path.GetFileNameWithoutExtension(dll); - typeName = String.Format("{0}.{1}", typeName, typeName); + typeName = string.Format("{0}.{1}", typeName, typeName); Type type = assembly.GetType(typeName); IGUIPlugin pluginInstance = (IGUIPlugin)Activator.CreateInstance(type); diff --git a/GUI/Program.cs b/GUI/Program.cs index 073863e0b0..4ecc3e570e 100644 --- a/GUI/Program.cs +++ b/GUI/Program.cs @@ -41,7 +41,7 @@ public static void Main_(string[] args, GameInstanceManager manager = null, bool } } - public static void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e) + public static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject; diff --git a/GUI/SingleAssemblyComponentResourceManager.cs b/GUI/SingleAssemblyComponentResourceManager.cs index c367d99cea..6735355c99 100644 --- a/GUI/SingleAssemblyComponentResourceManager.cs +++ b/GUI/SingleAssemblyComponentResourceManager.cs @@ -24,7 +24,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -35,7 +35,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(contextTypeInfo, resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(contextTypeInfo, resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/GUI/SingleAssemblyResourceManager.cs b/GUI/SingleAssemblyResourceManager.cs index 8648531042..1f3b4c6709 100644 --- a/GUI/SingleAssemblyResourceManager.cs +++ b/GUI/SingleAssemblyResourceManager.cs @@ -8,7 +8,7 @@ namespace CKAN.GUI { // Thanks and credit to this guy: https://stackoverflow.com/q/1952638/2422988 - class SingleAssemblyResourceManager : ResourceManager + public class SingleAssemblyResourceManager : ResourceManager { public SingleAssemblyResourceManager(string basename, Assembly assembly) : base(basename, assembly) { @@ -22,7 +22,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done) if (neutralResourcesCulture == null) { - neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly); + neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } // If we're asking for the default language, then ask for the @@ -33,7 +33,7 @@ protected override ResourceSet InternalGetResourceSet(CultureInfo culture, } string resourceFileName = GetResourceFileName(culture); - Stream store = this.MainAssembly.GetManifestResourceStream(resourceFileName); + Stream store = MainAssembly.GetManifestResourceStream(resourceFileName); // If we found the appropriate resources in the local assembly if (store != null) diff --git a/GUI/Util.cs b/GUI/Util.cs index e31891fcce..53c094256a 100644 --- a/GUI/Util.cs +++ b/GUI/Util.cs @@ -51,10 +51,10 @@ public static void AsyncInvoke<T>(T obj, Action action) where T : Control // hides the console window on windows // useful when running the GUI [DllImport("kernel32.dll")] - static extern IntPtr GetConsoleWindow(); + private static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public static void HideConsoleWindow() { @@ -103,7 +103,9 @@ public static bool TryOpenWebPage(string url, IEnumerable<string> prefixes = nul .Concat(prefixes.Select(p => p + url).Where(CheckURLValid))) { if (Utilities.ProcessStartURL(fullUrl)) + { return true; + } } return false; } @@ -120,11 +122,11 @@ public static void HandleLinkClicked(string url, LinkLabelLinkClickedEventArgs e switch (e.Button) { case MouseButtons.Left: - Util.OpenLinkFromLinkLabel(url); + OpenLinkFromLinkLabel(url); break; case MouseButtons.Right: - Util.LinkContextMenu(url); + LinkContextMenu(url); break; } } @@ -182,13 +184,25 @@ public static Point ClampedLocation(Point location, Size size, Screen screen = n log.DebugFormat("Found screen: {0}", screen.WorkingArea); // Slide the whole rectangle fully onto the screen if (location.X < screen.WorkingArea.Left) + { location.X = screen.WorkingArea.Left; + } + if (location.Y < screen.WorkingArea.Top) + { location.Y = screen.WorkingArea.Top; + } + if (location.X + size.Width > screen.WorkingArea.Right) + { location.X = screen.WorkingArea.Right - size.Width; + } + if (location.Y + size.Height > screen.WorkingArea.Bottom) + { location.Y = screen.WorkingArea.Bottom - size.Height; + } + log.DebugFormat("Clamped location: {0}", location); } return location; @@ -239,7 +253,7 @@ public static EventHandler<EventT> Debounce<EventT>( { // Store the most recent event we received object receivedFrom = null; - EventT received = default(EventT); + EventT received = default; // Set up the timer that will track the delay Timer timer = new Timer() { Interval = timeoutMs }; @@ -259,7 +273,7 @@ public static EventHandler<EventT> Debounce<EventT>( { doneFunc(sender, evt); receivedFrom = null; - received = default(EventT); + received = default; } else { diff --git a/GUI/X11.cs b/GUI/X11.cs index 3af9a9d101..d4faec6a18 100644 --- a/GUI/X11.cs +++ b/GUI/X11.cs @@ -48,17 +48,11 @@ public static void SetWMClass(string name, string wmClass, IntPtr handle) .GetType("System.Windows.Forms.Hwnd"); private static IntPtr DisplayHandle - { - get - { - return (IntPtr)MonoWinformsAssembly - .GetType("System.Windows.Forms.XplatUIX11") - .GetField( - "DisplayHandle", - BindingFlags.NonPublic | BindingFlags.Static - ).GetValue(null); - } - } + => (IntPtr)MonoWinformsAssembly + .GetType("System.Windows.Forms.XplatUIX11") + .GetField("DisplayHandle", + BindingFlags.NonPublic | BindingFlags.Static) + .GetValue(null); private static IntPtr GetWindow(IntPtr handle) { @@ -77,6 +71,6 @@ private static object GetHwnd(IntPtr handle) } [DllImport("libX11", EntryPoint = "XSetClassHint", CharSet = CharSet.Ansi)] - private extern static int XSetClassHint(IntPtr display, IntPtr window, IntPtr classHint); + private static extern int XSetClassHint(IntPtr display, IntPtr window, IntPtr classHint); } } diff --git a/Netkan/ConsoleUser.cs b/Netkan/ConsoleUser.cs index 33091453ef..8c5ce31b3d 100644 --- a/Netkan/ConsoleUser.cs +++ b/Netkan/ConsoleUser.cs @@ -95,7 +95,7 @@ public int RaiseSelectionDialog(string message, params object[] args) } // Validate input. - if (String.IsNullOrWhiteSpace(message)) + if (string.IsNullOrWhiteSpace(message)) { throw new Kraken("Passed message string must be non-empty."); } @@ -132,7 +132,7 @@ public int RaiseSelectionDialog(string message, params object[] args) // Further data validation. foreach (object argument in args) { - if (String.IsNullOrWhiteSpace(argument.ToString())) + if (string.IsNullOrWhiteSpace(argument.ToString())) { throw new Kraken("Candidate may not be empty."); } @@ -141,24 +141,24 @@ public int RaiseSelectionDialog(string message, params object[] args) // List options. for (int i = 0; i < args.Length; i++) { - string CurrentRow = String.Format("{0}", i + 1); + string CurrentRow = string.Format("{0}", i + 1); if (i == defaultSelection) { CurrentRow += "*"; } - CurrentRow += String.Format(") {0}", args[i]); + CurrentRow += string.Format(") {0}", args[i]); RaiseMessage(CurrentRow); } // Create message string. - string output = String.Format("Enter a number between {0} and {1} (To cancel press \"c\" or \"n\".", 1, args.Length); + string output = string.Format("Enter a number between {0} and {1} (To cancel press \"c\" or \"n\".", 1, args.Length); if (defaultSelection >= 0) { - output += String.Format(" \"Enter\" will select {0}.", defaultSelection + 1); + output += string.Format(" \"Enter\" will select {0}.", defaultSelection + 1); } output += "): "; @@ -182,7 +182,7 @@ public int RaiseSelectionDialog(string message, params object[] args) input = input.Trim().ToLower(); // Check for default selection. - if (String.IsNullOrEmpty(input)) + if (string.IsNullOrEmpty(input)) { if (defaultSelection >= 0) { diff --git a/Netkan/Extensions/JObjectExtensions.cs b/Netkan/Extensions/JObjectExtensions.cs index a5c71ae2cd..c89492ec2e 100644 --- a/Netkan/Extensions/JObjectExtensions.cs +++ b/Netkan/Extensions/JObjectExtensions.cs @@ -17,7 +17,7 @@ internal static class JObjectExtensions /// <param name="token">The value of the property to write if it does not exist.</param> public static void SafeAdd(this JObject jobject, string propertyName, JToken token) { - if (String.IsNullOrWhiteSpace(propertyName)) + if (string.IsNullOrWhiteSpace(propertyName)) { Log.Warn("Asked to set a property named null on a JSON object!"); return; @@ -38,7 +38,7 @@ public static void SafeAdd(this JObject jobject, string propertyName, JToken tok /// <param name="tokenCallback">Function to generate value of the property to write if it does not exist</param> public static void SafeAdd(this JObject jobject, string propertyName, Func<JToken> tokenCallback) { - if (String.IsNullOrWhiteSpace(propertyName)) + if (string.IsNullOrWhiteSpace(propertyName)) { Log.Warn("Asked to set a property named null on a JSON object!"); return; diff --git a/Netkan/Extensions/VersionExtensions.cs b/Netkan/Extensions/VersionExtensions.cs index 46f30e1204..4739054ee3 100644 --- a/Netkan/Extensions/VersionExtensions.cs +++ b/Netkan/Extensions/VersionExtensions.cs @@ -6,15 +6,8 @@ namespace CKAN.NetKAN.Extensions internal static class VersionExtensions { public static JToken ToSpecVersionJson(this ModuleVersion specVersion) - { - if (specVersion.IsEqualTo(new ModuleVersion("v1.0"))) - { - return 1; - } - else - { - return specVersion.ToString(); - } - } + => specVersion.IsEqualTo(new ModuleVersion("v1.0")) + ? (JToken)1 + : (JToken)specVersion.ToString(); } } diff --git a/Netkan/Services/CachingHttpService.cs b/Netkan/Services/CachingHttpService.cs index ab4a9f3a8f..96d521daa1 100644 --- a/Netkan/Services/CachingHttpService.cs +++ b/Netkan/Services/CachingHttpService.cs @@ -151,7 +151,7 @@ private string TryGetCached(Uri url, Func<string> uncached) return val; } - public IEnumerable<Uri> RequestedURLs { get { return _requestedURLs; } } + public IEnumerable<Uri> RequestedURLs => _requestedURLs; public void ClearRequestedURLs() { _requestedURLs?.Clear(); diff --git a/Netkan/Services/ModuleService.cs b/Netkan/Services/ModuleService.cs index 699e3ef7f1..c85cad37c5 100644 --- a/Netkan/Services/ModuleService.cs +++ b/Netkan/Services/ModuleService.cs @@ -148,16 +148,24 @@ public static void ApplyVersions(JObject json, GameVersion ver, GameVersion minV var gameVerMaxes = new List<GameVersion>(); if (!GameVersion.IsNullOrAny(existingMin)) + { gameVerMins.Add(existingMin); + } if (!GameVersion.IsNullOrAny(avcMin)) + { gameVerMins.Add(avcMin); + } if (!GameVersion.IsNullOrAny(existingMax)) + { gameVerMaxes.Add(existingMax); + } if (!GameVersion.IsNullOrAny(avcMax)) + { gameVerMaxes.Add(avcMax); + } var gameVerMin = gameVerMins.DefaultIfEmpty(null).Min(); var gameVerMax = gameVerMaxes.DefaultIfEmpty(null).Max(); @@ -267,8 +275,7 @@ public Tuple<ZipEntry, bool> FindInternalAvc(CkanModule module, ZipFile zipfile, { Regex internalRE = new Regex(internalFilePath, RegexOptions.Compiled); ZipEntry avcEntry = files - .Where(f => f.Name == internalFilePath || internalRE.IsMatch(f.Name)) - .FirstOrDefault(); + .FirstOrDefault(f => f.Name == internalFilePath || internalRE.IsMatch(f.Name)); if (avcEntry == null) { throw new Kraken( diff --git a/Netkan/Sources/Avc/JsonAvcToGameVersion.cs b/Netkan/Sources/Avc/JsonAvcToGameVersion.cs index cbb5044b1f..e968cad0ce 100644 --- a/Netkan/Sources/Avc/JsonAvcToGameVersion.cs +++ b/Netkan/Sources/Avc/JsonAvcToGameVersion.cs @@ -61,15 +61,15 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist //AVC uses -1 to indicate a wildcard. string version; - if (major == null || int.TryParse(major, out int integer) && integer == AvcWildcard) + if (major == null || (int.TryParse(major, out int integer) && integer == AvcWildcard)) { return GameVersion.Any; } - else if (minor == null || int.TryParse(minor, out integer) && integer == AvcWildcard) + else if (minor == null || (int.TryParse(minor, out integer) && integer == AvcWildcard)) { version = major; } - else if (patch == null || int.TryParse(patch, out integer) && integer == AvcWildcard) + else if (patch == null || (int.TryParse(patch, out integer) && integer == AvcWildcard)) { version = string.Join(".", major, minor); } @@ -84,10 +84,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return result; } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -117,7 +114,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist string build = null; var token = JToken.Load(reader); - Log.DebugFormat("Read Token: {0}, {1}", new Object[] {token.Type, token.ToString()}); + Log.DebugFormat("Read Token: {0}, {1}", new object[] {token.Type, token.ToString()}); switch (token.Type) { case JTokenType.String: @@ -168,10 +165,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return result; } - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { diff --git a/Netkan/Sources/Curse/CurseApi.cs b/Netkan/Sources/Curse/CurseApi.cs index 99d8a92bf9..bd826bcf05 100755 --- a/Netkan/Sources/Curse/CurseApi.cs +++ b/Netkan/Sources/Curse/CurseApi.cs @@ -75,7 +75,10 @@ public static Uri ResolveRedirect(Uri url) { redirects++; if (redirects > 6) + { throw new Kraken("More than 6 redirects when resolving the following url: " + url); + } + redirUrl = new Uri(redirUrl, response.Headers["Location"]); request = (HttpWebRequest) WebRequest.Create(redirUrl); request.AllowAutoRedirect = false; @@ -90,7 +93,7 @@ private string Call(string nameOrId) { // If it's numeric, use the old URL format, // otherwise use the new. - var url = Int32.TryParse(nameOrId, out int id) + var url = int.TryParse(nameOrId, out int id) ? CurseApiBaseOld + id : CurseApiBase + nameOrId; Log.InfoFormat("Calling {0}", url); diff --git a/Netkan/Sources/Curse/CurseFile.cs b/Netkan/Sources/Curse/CurseFile.cs index 2abfa628aa..0eeacc8558 100755 --- a/Netkan/Sources/Curse/CurseFile.cs +++ b/Netkan/Sources/Curse/CurseFile.cs @@ -67,8 +67,9 @@ public string GetFilename() if (_filename == null) { Match match = Regex.Match(GetDownloadUrl(), "[^/]*\\.zip"); - if (match.Groups.Count > 0) _filename = match.Groups[0].Value; - else _filename = GetCurseIdVersion(); + _filename = match.Groups.Count > 0 + ? match.Groups[0].Value + : GetCurseIdVersion(); } return _filename; } @@ -83,9 +84,13 @@ public string GetFileVersion() { Match match = Regex.Match(GetDownloadUrl(), "(v?[0-9][0-9a-z.]*[0-9a-z])[^0-9]*\\.zip"); if (match.Groups.Count > 1) + { _fileVersion = match.Groups[1].Value; + } else + { _fileVersion = GetCurseIdVersion(); + } } return _fileVersion; } @@ -118,7 +123,10 @@ public override object ReadJson( else { if (reader.Value == null) + { return null; + } + string raw_version = reader.Value.ToString(); return GameVersion.Parse(Regex.Replace(raw_version, @"-.*$", "")); } diff --git a/Netkan/Sources/Curse/CurseMod.cs b/Netkan/Sources/Curse/CurseMod.cs index 32f63b2ac4..3d137a4018 100755 --- a/Netkan/Sources/Curse/CurseMod.cs +++ b/Netkan/Sources/Curse/CurseMod.cs @@ -17,11 +17,7 @@ internal class CurseMod [JsonProperty] public string game; [JsonProperty] public List<CurseModMember> members; - public string[] authors { - get { - return members.Select(m => m.username).ToArray(); - } - } + public string[] authors => members.Select(m => m.username).ToArray(); private string _pageUrl; private string _name; @@ -69,8 +65,14 @@ public string GetName() // Matches the longest sequence of letters and spaces ending in two letters from the beggining of the string // This is to filter out version information Match match = Regex.Match(title, "^([A-Za-z ]*[A-Za-z][A-Za-z])"); - if (match.Groups.Count > 1) _name = match.Groups[1].Value; - else _name = "title"; ; + if (match.Groups.Count > 1) + { + _name = match.Groups[1].Value; + } + else + { + _name = "title"; + }; } return _name; } diff --git a/Netkan/Sources/Github/GithubReleaseAsset.cs b/Netkan/Sources/Github/GithubReleaseAsset.cs index a17d129aa2..b9397400bd 100644 --- a/Netkan/Sources/Github/GithubReleaseAsset.cs +++ b/Netkan/Sources/Github/GithubReleaseAsset.cs @@ -4,9 +4,9 @@ namespace CKAN.NetKAN.Sources.Github { public sealed class GithubReleaseAsset { - public String Name { get; } - public Uri Download { get; } - public DateTime? Updated { get; } + public string Name { get; } + public Uri Download { get; } + public DateTime? Updated { get; } public GithubReleaseAsset(string name, Uri download, DateTime? updated) { diff --git a/Netkan/Sources/Jenkins/JenkinsApi.cs b/Netkan/Sources/Jenkins/JenkinsApi.cs index d579713e82..c645bf10e7 100644 --- a/Netkan/Sources/Jenkins/JenkinsApi.cs +++ b/Netkan/Sources/Jenkins/JenkinsApi.cs @@ -44,7 +44,9 @@ public IEnumerable<JenkinsBuild> GetAllBuilds(JenkinsRef reference, JenkinsOptio JenkinsBuild build = Call<JenkinsBuild>($"{buildEntry["url"]}api/json"); // Make sure build status matches options.BuildType if (resultVal == null || build.Result == resultVal) + { yield return build; + } } } diff --git a/Netkan/Sources/Jenkins/JenkinsOptions.cs b/Netkan/Sources/Jenkins/JenkinsOptions.cs index 8e83395a9f..376f2e9e38 100644 --- a/Netkan/Sources/Jenkins/JenkinsOptions.cs +++ b/Netkan/Sources/Jenkins/JenkinsOptions.cs @@ -18,8 +18,10 @@ public class JenkinsOptions [JsonProperty("asset_match")] public Regex AssetMatchPattern { - get { return _assetMatch ?? Constants.DefaultAssetMatchPattern; } + get => _assetMatch ?? Constants.DefaultAssetMatchPattern; + #pragma warning disable IDE0027 set { _assetMatch = value; } + #pragma warning restore IDE0027 } } } diff --git a/Netkan/Sources/Spacedock/JsonConvertFromRelativeSdUri.cs b/Netkan/Sources/Spacedock/JsonConvertFromRelativeSdUri.cs index 0f8890f7a5..31d74c51f7 100644 --- a/Netkan/Sources/Spacedock/JsonConvertFromRelativeSdUri.cs +++ b/Netkan/Sources/Spacedock/JsonConvertFromRelativeSdUri.cs @@ -14,7 +14,10 @@ internal class JsonConvertFromRelativeSdUri : JsonConverter public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value != null) + { return ExpandPath(reader.Value.ToString()); + } + return null; } diff --git a/Netkan/Sources/Spacedock/SDVersion.cs b/Netkan/Sources/Spacedock/SDVersion.cs index 04279f5297..cec36f48d2 100644 --- a/Netkan/Sources/Spacedock/SDVersion.cs +++ b/Netkan/Sources/Spacedock/SDVersion.cs @@ -37,7 +37,9 @@ public override object ReadJson( ) { if (reader.Value == null) + { return null; + } string raw_version = reader.Value.ToString(); diff --git a/Netkan/Transformers/AvcKrefTransformer.cs b/Netkan/Transformers/AvcKrefTransformer.cs index a40b9b0590..775c284524 100644 --- a/Netkan/Transformers/AvcKrefTransformer.cs +++ b/Netkan/Transformers/AvcKrefTransformer.cs @@ -18,7 +18,7 @@ internal sealed class AvcKrefTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(AvcKrefTransformer)); - public string Name { get { return "avc-kref"; } } + public string Name => "avc-kref"; private readonly IHttpService httpSvc; private readonly IGithubApi githubSrc; @@ -40,7 +40,7 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) var url = new Uri(metadata.Kref.Id); AvcVersion remoteAvc = JsonConvert.DeserializeObject<AvcVersion>( githubSrc?.DownloadText(url) - ?? httpSvc.DownloadText(CKAN.Net.GetRawUri(url)) + ?? httpSvc.DownloadText(Net.GetRawUri(url)) ); json.SafeAdd("name", remoteAvc.Name); @@ -52,7 +52,10 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { // Make sure resources exist. if (json["resources"] == null) + { json["resources"] = new JObject(); + } + var resourcesJson = (JObject)json["resources"]; resourcesJson.SafeAdd("repository", $"https://github.com/{remoteAvc.Github.Username}/{remoteAvc.Github.Repository}"); } diff --git a/Netkan/Transformers/AvcTransformer.cs b/Netkan/Transformers/AvcTransformer.cs index a6148d59c0..150be62a83 100644 --- a/Netkan/Transformers/AvcTransformer.cs +++ b/Netkan/Transformers/AvcTransformer.cs @@ -28,7 +28,7 @@ internal sealed class AvcTransformer : ITransformer private readonly IGithubApi _github; private readonly VrefValidator _vrefValidator; - public string Name { get { return "avc"; } } + public string Name => "avc"; public AvcTransformer(IHttpService http, IModuleService moduleService, IGithubApi github, IGame game) { @@ -157,7 +157,7 @@ private static Uri GetRemoteAvcUri(AvcVersion avc) Log.InfoFormat("Remote AVC version file at: {0}", remoteUri); - return CKAN.Net.GetRawUri(remoteUri); + return Net.GetRawUri(remoteUri); } } } diff --git a/Netkan/Transformers/CurseTransformer.cs b/Netkan/Transformers/CurseTransformer.cs index bbec42cde2..6b96949ab0 100755 --- a/Netkan/Transformers/CurseTransformer.cs +++ b/Netkan/Transformers/CurseTransformer.cs @@ -20,7 +20,7 @@ internal sealed class CurseTransformer : ITransformer private readonly ICurseApi _api; - public string Name { get { return "curse"; } } + public string Name => "curse"; public CurseTransformer(ICurseApi api) { @@ -121,10 +121,22 @@ private Metadata TransformOne(JObject json, CurseMod curseMod, CurseFile latestV json.SafeAdd("name", curseMod.GetName()); json.SafeAdd("abstract", curseMod.description); - if (useDownloadNameVersion) json.SafeAdd("version", latestVersion.name); - else if (useFilenameVersion) json.SafeAdd("version", latestVersion.GetFilename()); - else if (useCurseIdVersion) json.SafeAdd("version", latestVersion.GetCurseIdVersion()); - else json.SafeAdd("version", latestVersion.GetFileVersion()); + if (useDownloadNameVersion) + { + json.SafeAdd("version", latestVersion.name); + } + else if (useFilenameVersion) + { + json.SafeAdd("version", latestVersion.GetFilename()); + } + else if (useCurseIdVersion) + { + json.SafeAdd("version", latestVersion.GetCurseIdVersion()); + } + else + { + json.SafeAdd("version", latestVersion.GetFileVersion()); + } json.SafeAdd("author", () => JToken.FromObject(curseMod.authors)); json.Remove("$kref"); diff --git a/Netkan/Transformers/DownloadAttributeTransformer.cs b/Netkan/Transformers/DownloadAttributeTransformer.cs index 956109ef9e..6428d8df9a 100644 --- a/Netkan/Transformers/DownloadAttributeTransformer.cs +++ b/Netkan/Transformers/DownloadAttributeTransformer.cs @@ -18,7 +18,7 @@ internal sealed class DownloadAttributeTransformer : ITransformer private readonly IHttpService _http; private readonly IFileService _fileService; - public string Name { get { return "download_attributes"; } } + public string Name => "download_attributes"; public DownloadAttributeTransformer(IHttpService http, IFileService fileService) { diff --git a/Netkan/Transformers/EpochTransformer.cs b/Netkan/Transformers/EpochTransformer.cs index cf88e49889..2889cde26d 100644 --- a/Netkan/Transformers/EpochTransformer.cs +++ b/Netkan/Transformers/EpochTransformer.cs @@ -14,7 +14,7 @@ internal sealed class EpochTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(EpochTransformer)); - public string Name { get { return "epoch"; } } + public string Name => "epoch"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { @@ -31,7 +31,9 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { //Implicit if zero. No need to add if (epochNumber != 0) + { json["version"] = epochNumber + ":" + json["version"]; + } Log.DebugFormat("Transformed metadata:{0}{1}", Environment.NewLine, json); } diff --git a/Netkan/Transformers/ForcedVTransformer.cs b/Netkan/Transformers/ForcedVTransformer.cs index e44e89922a..9b07b0236c 100644 --- a/Netkan/Transformers/ForcedVTransformer.cs +++ b/Netkan/Transformers/ForcedVTransformer.cs @@ -13,7 +13,7 @@ internal sealed class ForcedVTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(ForcedVTransformer)); - public string Name { get { return "forced_v"; } } + public string Name => "forced_v"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/GeneratedByTransformer.cs b/Netkan/Transformers/GeneratedByTransformer.cs index df50f9f77f..804d0deb8c 100644 --- a/Netkan/Transformers/GeneratedByTransformer.cs +++ b/Netkan/Transformers/GeneratedByTransformer.cs @@ -13,7 +13,7 @@ internal sealed class GeneratedByTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(GeneratedByTransformer)); - public string Name { get { return "generated_by"; } } + public string Name => "generated_by"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/GithubTransformer.cs b/Netkan/Transformers/GithubTransformer.cs index d9b504b41a..00582dd384 100644 --- a/Netkan/Transformers/GithubTransformer.cs +++ b/Netkan/Transformers/GithubTransformer.cs @@ -19,7 +19,7 @@ internal sealed class GithubTransformer : ITransformer private readonly IGithubApi _api; private readonly bool _matchPreleases; - public string Name { get { return "github"; } } + public string Name => "github"; public GithubTransformer(IGithubApi api, bool matchPreleases) { @@ -84,11 +84,15 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { var match = ghRef.VersionFromAsset.Match(asset.Name); if (!match.Success) + { continue; + } var extractedVersion = match.Groups["version"]; if (!extractedVersion.Success) + { throw new Exception("version_from_asset contains no 'version' capturing group"); + } returnedAny = true; yield return TransformOne(metadata, metadata.Json(), ghRef, ghRepo, rel, asset, extractedVersion.Value); @@ -130,25 +134,33 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) private Metadata TransformOne( Metadata metadata, JObject json, GithubRef ghRef, GithubRepo ghRepo, GithubRelease ghRelease, - GithubReleaseAsset ghAsset, String version + GithubReleaseAsset ghAsset, string version ) { if (!string.IsNullOrWhiteSpace(ghRepo.Description)) + { json.SafeAdd("abstract", ghRepo.Description); + } // GitHub says NOASSERTION if it can't figure out the repo's license if (!string.IsNullOrWhiteSpace(ghRepo.License?.Id) && ghRepo.License.Id != "NOASSERTION") + { json.SafeAdd("license", ghRepo.License.Id); + } // Make sure resources exist. if (json["resources"] == null) + { json["resources"] = new JObject(); + } var resourcesJson = (JObject)json["resources"]; if (!string.IsNullOrWhiteSpace(ghRepo.Homepage)) + { resourcesJson.SafeAdd("homepage", ghRepo.Homepage); + } resourcesJson.SafeAdd("repository", ghRepo.HtmlUrl); if (ghRepo.HasIssues) @@ -181,7 +193,8 @@ private Metadata TransformOne( var repoName = ghRef.Project; for (var i = 1; i < repoName.Length - 1; ++i) { - if (char.IsLower(repoName[i - 1]) && char.IsUpper(repoName[i]) || repoName[i - 1] != ' ' && char.IsUpper(repoName[i]) && char.IsLower(repoName[i + 1])) + if ((char.IsLower(repoName[i - 1]) && char.IsUpper(repoName[i])) + || (repoName[i - 1] != ' ' && char.IsUpper(repoName[i]) && char.IsLower(repoName[i + 1]))) { repoName = repoName.Insert(i, " "); } @@ -217,7 +230,10 @@ private JToken getAuthors(GithubRepo repo, GithubRelease release) case userType: // Prepend repo owner if (!authors.Contains(r.Owner.Login)) + { authors.Insert(0, r.Owner.Login); + } + break; case orgType: // Prepend org members diff --git a/Netkan/Transformers/HttpTransformer.cs b/Netkan/Transformers/HttpTransformer.cs index 68c37baf40..53f44a2fda 100644 --- a/Netkan/Transformers/HttpTransformer.cs +++ b/Netkan/Transformers/HttpTransformer.cs @@ -12,7 +12,7 @@ internal sealed class HttpTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(HttpTransformer)); - public string Name { get { return "http"; } } + public string Name => "http"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/InstallSizeTransformer.cs b/Netkan/Transformers/InstallSizeTransformer.cs index ea2bcfceb6..5ca04d046f 100644 --- a/Netkan/Transformers/InstallSizeTransformer.cs +++ b/Netkan/Transformers/InstallSizeTransformer.cs @@ -11,7 +11,7 @@ namespace CKAN.NetKAN.Transformers { internal sealed class InstallSizeTransformer : ITransformer { - public string Name { get { return "install_size"; } } + public string Name => "install_size"; public InstallSizeTransformer(IHttpService http, IModuleService moduleService, IGame game) { diff --git a/Netkan/Transformers/InternalCkanTransformer.cs b/Netkan/Transformers/InternalCkanTransformer.cs index 5d30d06054..a8369da937 100644 --- a/Netkan/Transformers/InternalCkanTransformer.cs +++ b/Netkan/Transformers/InternalCkanTransformer.cs @@ -21,7 +21,7 @@ internal sealed class InternalCkanTransformer : ITransformer private readonly IModuleService _moduleService; private readonly IGame _game; - public string Name { get { return "internal_ckan"; } } + public string Name => "internal_ckan"; public InternalCkanTransformer(IHttpService http, IModuleService moduleService, IGame game) { diff --git a/Netkan/Transformers/JenkinsTransformer.cs b/Netkan/Transformers/JenkinsTransformer.cs index 7658b48dbd..2e8a3ff04a 100644 --- a/Netkan/Transformers/JenkinsTransformer.cs +++ b/Netkan/Transformers/JenkinsTransformer.cs @@ -19,7 +19,7 @@ public JenkinsTransformer(IJenkinsApi api) _api = api; } - public string Name { get { return "jenkins"; } } + public string Name => "jenkins"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/LocalizationsTransformer.cs b/Netkan/Transformers/LocalizationsTransformer.cs index 88b87089f0..9097d22bd2 100644 --- a/Netkan/Transformers/LocalizationsTransformer.cs +++ b/Netkan/Transformers/LocalizationsTransformer.cs @@ -31,7 +31,7 @@ public LocalizationsTransformer(IHttpService http, IModuleService moduleService, /// <summary> /// Name of this transformer /// </summary> - public string Name { get { return "localizations"; } } + public string Name => "localizations"; /// <summary> /// Apply the locale transformation to the metadata diff --git a/Netkan/Transformers/MetaNetkanTransformer.cs b/Netkan/Transformers/MetaNetkanTransformer.cs index c4f8df216f..1ca2642f75 100644 --- a/Netkan/Transformers/MetaNetkanTransformer.cs +++ b/Netkan/Transformers/MetaNetkanTransformer.cs @@ -25,7 +25,7 @@ internal sealed class MetaNetkanTransformer : ITransformer private readonly IHttpService _http; private readonly IGithubApi _github; - public string Name { get { return "metanetkan"; } } + public string Name => "metanetkan"; public MetaNetkanTransformer(IHttpService http, IGithubApi github) { @@ -44,13 +44,16 @@ public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) // Make sure resources exist, save metanetkan if (json["resources"] == null) + { json["resources"] = new JObject(); + } + var resourcesJson = (JObject)json["resources"]; resourcesJson.SafeAdd("metanetkan", metadata.Kref.Id); var uri = new Uri(metadata.Kref.Id); var targetFileText = _github?.DownloadText(uri) - ?? _http.DownloadText(CKAN.Net.GetRawUri(uri)); + ?? _http.DownloadText(Net.GetRawUri(uri)); Log.DebugFormat("Target netkan:{0}{1}", Environment.NewLine, targetFileText); diff --git a/Netkan/Transformers/NetkanTransformer.cs b/Netkan/Transformers/NetkanTransformer.cs index 238776d07c..2ab7964e3d 100644 --- a/Netkan/Transformers/NetkanTransformer.cs +++ b/Netkan/Transformers/NetkanTransformer.cs @@ -21,7 +21,7 @@ internal sealed class NetkanTransformer : ITransformer private readonly List<ITransformer> _transformers; private readonly IValidator _validator; - public string Name { get { return "netkan"; } } + public string Name => "netkan"; public NetkanTransformer( IHttpService http, @@ -96,7 +96,9 @@ private static List<ITransformer> InjectVersionedOverrideTransformers(List<ITran before.Add(transformers[i].Name); if (i - 1 >= 0) + { after.Add(transformers[i - 1].Name); + } result.Add(new VersionedOverrideTransformer(before, after)); result.Add(transformers[i]); diff --git a/Netkan/Transformers/OptimusPrimeTransformer.cs b/Netkan/Transformers/OptimusPrimeTransformer.cs index 5e01d3e797..3387f05d3f 100644 --- a/Netkan/Transformers/OptimusPrimeTransformer.cs +++ b/Netkan/Transformers/OptimusPrimeTransformer.cs @@ -9,7 +9,7 @@ internal sealed class OptimusPrimeTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(OptimusPrimeTransformer)); - public string Name { get { return "optimus_prime"; } } + public string Name => "optimus_prime"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/PropertySortTransformer.cs b/Netkan/Transformers/PropertySortTransformer.cs index 1c4aacd666..b59e474a73 100644 --- a/Netkan/Transformers/PropertySortTransformer.cs +++ b/Netkan/Transformers/PropertySortTransformer.cs @@ -66,7 +66,7 @@ internal sealed class PropertySortTransformer : ITransformer .Select((str, index) => new {index, str}) .ToDictionary(t => t.str, t=> t.index); - public string Name { get { return "property_sort"; } } + public string Name => "property_sort"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/SpaceWarpInfoTransformer.cs b/Netkan/Transformers/SpaceWarpInfoTransformer.cs index 4962892c5c..7ebc3bfb4e 100644 --- a/Netkan/Transformers/SpaceWarpInfoTransformer.cs +++ b/Netkan/Transformers/SpaceWarpInfoTransformer.cs @@ -11,7 +11,6 @@ using CKAN.NetKAN.Services; using CKAN.NetKAN.Extensions; using CKAN.NetKAN.Sources.Github; -using CKAN.Extensions; using CKAN.Versioning; using CKAN.Games; diff --git a/Netkan/Transformers/SpacedockTransformer.cs b/Netkan/Transformers/SpacedockTransformer.cs index bda35d2959..1b58e86a7d 100644 --- a/Netkan/Transformers/SpacedockTransformer.cs +++ b/Netkan/Transformers/SpacedockTransformer.cs @@ -22,7 +22,7 @@ internal sealed class SpacedockTransformer : ITransformer private readonly ISpacedockApi _api; private readonly IGithubApi _githubApi; - public string Name { get { return "spacedock"; } } + public string Name => "spacedock"; public SpacedockTransformer(ISpacedockApi api, IGithubApi githubApi) { @@ -84,14 +84,18 @@ private Metadata TransformOne(Metadata metadata, JObject json, SpacedockMod sdMo json.SafeAdd("version", latestVersion.friendly_version.ToString()); json.Remove("$kref"); json.SafeAdd("download", latestVersion.download_path.OriginalString); - json.SafeAdd(Model.Metadata.UpdatedPropertyName, latestVersion.created); + json.SafeAdd(Metadata.UpdatedPropertyName, latestVersion.created); var authors = GetAuthors(sdMod); if (authors.Count == 1) + { json.SafeAdd("author", sdMod.author); + } else if (authors.Count > 1) + { json.SafeAdd("author", new JArray(authors)); + } // SD provides users with the following default selection of licenses. Let's convert them to CKAN // compatible license strings if possible. @@ -239,7 +243,9 @@ private static List<string> GetAuthors(SpacedockMod mod) var result = new List<string> { mod.author }; if (mod.shared_authors != null) + { result.AddRange(mod.shared_authors.Select(i => i.Username).Distinct()); + } return result; } diff --git a/Netkan/Transformers/StagingLinksTransformer.cs b/Netkan/Transformers/StagingLinksTransformer.cs index dafc5ccec4..c9f7bfcf90 100644 --- a/Netkan/Transformers/StagingLinksTransformer.cs +++ b/Netkan/Transformers/StagingLinksTransformer.cs @@ -10,7 +10,7 @@ namespace CKAN.NetKAN.Transformers { internal sealed class StagingLinksTransformer : ITransformer { - public string Name { get { return "staging_links"; } } + public string Name => "staging_links"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/StagingTransformer.cs b/Netkan/Transformers/StagingTransformer.cs index a40f226b74..2bdf10b95c 100644 --- a/Netkan/Transformers/StagingTransformer.cs +++ b/Netkan/Transformers/StagingTransformer.cs @@ -18,7 +18,7 @@ public StagingTransformer(IGame game) currentRelease = game.KnownVersions.Max().ToVersionRange(); } - public string Name { get { return "staging"; } } + public string Name => "staging"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/StripNetkanMetadataTransformer.cs b/Netkan/Transformers/StripNetkanMetadataTransformer.cs index 2b46040c13..9d3d4eaeed 100644 --- a/Netkan/Transformers/StripNetkanMetadataTransformer.cs +++ b/Netkan/Transformers/StripNetkanMetadataTransformer.cs @@ -14,7 +14,7 @@ internal sealed class StripNetkanMetadataTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(StripNetkanMetadataTransformer)); - public string Name { get { return "strip_netkan_metadata"; } } + public string Name => "strip_netkan_metadata"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { @@ -40,17 +40,20 @@ private static void Strip(JObject metadata) { propertiesToRemove.Add(property.Name); } - else switch (property.Value.Type) + else { - case JTokenType.Object: - Strip((JObject)property.Value); - break; - case JTokenType.Array: - foreach (var element in ((JArray)property.Value).Where(i => i.Type == JTokenType.Object)) - { - Strip((JObject)element); - } - break; + switch (property.Value.Type) + { + case JTokenType.Object: + Strip((JObject)property.Value); + break; + case JTokenType.Array: + foreach (var element in ((JArray)property.Value).Where(i => i.Type == JTokenType.Object)) + { + Strip((JObject)element); + } + break; + } } } diff --git a/Netkan/Transformers/VersionEditTransformer.cs b/Netkan/Transformers/VersionEditTransformer.cs index 5232d46a95..4fc66a08ce 100644 --- a/Netkan/Transformers/VersionEditTransformer.cs +++ b/Netkan/Transformers/VersionEditTransformer.cs @@ -15,7 +15,7 @@ internal sealed class VersionEditTransformer : ITransformer { private static readonly ILog Log = LogManager.GetLogger(typeof(VersionEditTransformer)); - public string Name { get { return "version_edit"; } } + public string Name => "version_edit"; public IEnumerable<Metadata> Transform(Metadata metadata, TransformOptions opts) { diff --git a/Netkan/Transformers/VersionedOverrideTransformer.cs b/Netkan/Transformers/VersionedOverrideTransformer.cs index 9f262da0bd..52595a3a43 100644 --- a/Netkan/Transformers/VersionedOverrideTransformer.cs +++ b/Netkan/Transformers/VersionedOverrideTransformer.cs @@ -20,7 +20,7 @@ internal sealed class VersionedOverrideTransformer : ITransformer private readonly HashSet<string> _before; private readonly HashSet<string> _after; - public string Name { get { return "versioned_override"; } } + public string Name => "versioned_override"; public VersionedOverrideTransformer(IEnumerable<string> before, IEnumerable<string> after) { @@ -90,17 +90,25 @@ private void ProcessOverrideStanza(JObject overrideStanza, JObject metadata) if (overrideStanza.TryGetValue("before", out JToken jBefore)) { if (jBefore.Type == JTokenType.String) + { before = (string)jBefore; + } else + { throw new Kraken("override before property must be a string"); + } } if (overrideStanza.TryGetValue("after", out JToken jAfter)) { if (jAfter.Type == JTokenType.String) + { after = (string)jAfter; + } else + { throw new Kraken("override after property must be a string"); + } } if (_before.Contains(before) || _after.Contains(after)) @@ -136,7 +144,9 @@ private void ProcessOverrideStanza(JObject overrideStanza, JObject metadata) // If the constraints don't apply, then do nothing. if (!ConstraintsApply(constraints, new ModuleVersion(metadata["version"].ToString()))) + { return; + } // All the constraints pass; let's replace the metadata we have with what's // in the override. @@ -200,15 +210,19 @@ private static bool ConstraintsApply(IEnumerable<string> constraints, ModuleVers RegexOptions.IgnorePatternWhitespace); if (!match.Success) + { throw new Kraken( string.Format("Unable to parse x_netkan_override - {0}", constraint)); + } var op = match.Groups["op"].Value; var desiredVersion = new ModuleVersion(match.Groups["version"].Value); // This contstraint failed. This stanza is not for us. if (!ConstraintPasses(op, version, desiredVersion)) + { return false; + } } // All the constraints passed! We want to apply this stanza! diff --git a/Netkan/Validators/InstallValidator.cs b/Netkan/Validators/InstallValidator.cs index 1ae62f7687..9312f35885 100644 --- a/Netkan/Validators/InstallValidator.cs +++ b/Netkan/Validators/InstallValidator.cs @@ -35,13 +35,13 @@ public void Validate(Metadata metadata) } if (metadata.SpecVersion < v1p29 && ( install_to.StartsWith("Ships/Script") - || install_to.Equals("Ships") && ( + || (install_to.Equals("Ships") && ( // find: .../Script, install_to: Ships ((string)stanza["find"])?.Split(new char[] {'/'})?.LastOrDefault() == "Script" // file: .../Script, install_to: Ships || ((string)stanza["file"])?.Split(new char[] {'/'})?.LastOrDefault() == "Script" // install_to: Ships, as: Script - || (((string)stanza["as"])?.EndsWith("Script") ?? false)))) + || (((string)stanza["as"])?.EndsWith("Script") ?? false))))) { throw new Kraken("spec_version v1.29+ required to install to Ships/Script"); } diff --git a/Netkan/Validators/InstallsFilesValidator.cs b/Netkan/Validators/InstallsFilesValidator.cs index 59bec2b36a..0745798784 100644 --- a/Netkan/Validators/InstallsFilesValidator.cs +++ b/Netkan/Validators/InstallsFilesValidator.cs @@ -42,7 +42,7 @@ public void Validate(Metadata metadata) var allFiles = _moduleService.FileDestinations(mod, file).Memoize(); // Make sure no paths include GameData other than at the start - foreach (var dir in Enumerable.Repeat<string>(_game.PrimaryModDirectoryRelative, 1) + foreach (var dir in Enumerable.Repeat(_game.PrimaryModDirectoryRelative, 1) .Concat(_game.AlternateModDirectoriesRelative)) { var gamedatas = allFiles diff --git a/Netkan/Validators/LicensesValidator.cs b/Netkan/Validators/LicensesValidator.cs index 0b3e00c5d9..f31f5b2e4a 100644 --- a/Netkan/Validators/LicensesValidator.cs +++ b/Netkan/Validators/LicensesValidator.cs @@ -43,16 +43,19 @@ public void Validate(Metadata metadata) { throw new Kraken("License should match spec"); } - else foreach (var lic in licenses) + else { - try + foreach (var lic in licenses) { - // This will throw BadMetadataKraken if the license isn't known - new License((string)lic); - } - catch - { - throw new Kraken($"License {lic} should match spec"); + try + { + // This will throw BadMetadataKraken if the license isn't known + new License((string)lic); + } + catch + { + throw new Kraken($"License {lic} should match spec"); + } } } } diff --git a/Netkan/Validators/PluginsValidator.cs b/Netkan/Validators/PluginsValidator.cs index 28f3b3f628..d280f36500 100644 --- a/Netkan/Validators/PluginsValidator.cs +++ b/Netkan/Validators/PluginsValidator.cs @@ -3,7 +3,6 @@ using ICSharpCode.SharpZipLib.Zip; using log4net; -using CKAN.Extensions; using CKAN.NetKAN.Services; using CKAN.NetKAN.Model; using CKAN.Games; diff --git a/Tests/AutoUpdate/ResourcesTests.cs b/Tests/AutoUpdate/ResourcesTests.cs index 2e36f396aa..dae4e05492 100644 --- a/Tests/AutoUpdate/ResourcesTests.cs +++ b/Tests/AutoUpdate/ResourcesTests.cs @@ -29,7 +29,7 @@ public void PropertiesResources_LanguageResource_NotSet() } // The cultures to test - private static CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages + private static readonly CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages .Select(l => new CultureInfo(l)) .ToArray(); } diff --git a/Tests/CapturingUser.cs b/Tests/CapturingUser.cs index 567268d9d3..dff6d988c5 100644 --- a/Tests/CapturingUser.cs +++ b/Tests/CapturingUser.cs @@ -52,7 +52,7 @@ public void RaiseMessage(string message, params object[] args) public readonly List<string> RaisedMessages = new List<string>(); - private Func<string, bool> yesNoAnswerer; - private Func<string, object[], int> selectionDialogAnswerer; + private readonly Func<string, bool> yesNoAnswerer; + private readonly Func<string, object[], int> selectionDialogAnswerer; } } diff --git a/Tests/CmdLine/ResourcesTests.cs b/Tests/CmdLine/ResourcesTests.cs index 486b67d5a2..81961df10d 100644 --- a/Tests/CmdLine/ResourcesTests.cs +++ b/Tests/CmdLine/ResourcesTests.cs @@ -30,7 +30,7 @@ public void PropertiesResources_LanguageResource_NotSet() } // The cultures to test - private static CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages + private static readonly CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages .Select(l => new CultureInfo(l)) .ToArray(); } diff --git a/Tests/ConsoleUI/ResourcesTests.cs b/Tests/ConsoleUI/ResourcesTests.cs index 273672e7bc..874d6f5b38 100644 --- a/Tests/ConsoleUI/ResourcesTests.cs +++ b/Tests/ConsoleUI/ResourcesTests.cs @@ -29,7 +29,7 @@ public void PropertiesResources_LanguageResource_NotSet() } // The cultures to test - private static CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages + private static readonly CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages .Select(l => new CultureInfo(l)) .ToArray(); } diff --git a/Tests/Core/CKANPathUtils.cs b/Tests/Core/CKANPathUtils.cs index f5bb57e90c..1d42dbe9d1 100644 --- a/Tests/Core/CKANPathUtils.cs +++ b/Tests/Core/CKANPathUtils.cs @@ -9,36 +9,36 @@ public class CKANPathUtilsTests [Test] public void NormalizePath() { - Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("/a/b/c"), "Identity function failed"); - Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a\\b\\c"), "Actual replace"); - Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a/b\\c"), "Mixed slashes"); - Assert.AreEqual("a/b/c", CKAN.CKANPathUtils.NormalizePath("a/b\\c"), "No starting slash"); - Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a/b\\c\\"), "Trailing slash"); - Assert.AreEqual("SPACE", CKAN.CKANPathUtils.NormalizePath("SPACE"), "All upper-case, no slashes"); + Assert.AreEqual("/a/b/c", CKANPathUtils.NormalizePath("/a/b/c"), "Identity function failed"); + Assert.AreEqual("/a/b/c", CKANPathUtils.NormalizePath("\\a\\b\\c"), "Actual replace"); + Assert.AreEqual("/a/b/c", CKANPathUtils.NormalizePath("\\a/b\\c"), "Mixed slashes"); + Assert.AreEqual("a/b/c", CKANPathUtils.NormalizePath("a/b\\c"), "No starting slash"); + Assert.AreEqual("/a/b/c", CKANPathUtils.NormalizePath("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("SPACE", CKANPathUtils.NormalizePath("SPACE"), "All upper-case, no slashes"); } [Test] public void GetLastPathElement() { - Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("/a/b/c"), "Simple case"); - Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a\\b\\c"), "With other slashes"); - Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a/b\\c"), "With mixed slashes"); - Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("a/b\\c"), "No starting slash"); - Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a/b\\c\\"), "Trailing slash"); - Assert.AreEqual("kOS", CKAN.CKANPathUtils.GetLastPathElement("GameData/kOS"), "Real world test"); - Assert.AreEqual("buckethead", CKAN.CKANPathUtils.GetLastPathElement("buckethead"), "No slashes at all"); + Assert.AreEqual("c", CKANPathUtils.GetLastPathElement("/a/b/c"), "Simple case"); + Assert.AreEqual("c", CKANPathUtils.GetLastPathElement("\\a\\b\\c"), "With other slashes"); + Assert.AreEqual("c", CKANPathUtils.GetLastPathElement("\\a/b\\c"), "With mixed slashes"); + Assert.AreEqual("c", CKANPathUtils.GetLastPathElement("a/b\\c"), "No starting slash"); + Assert.AreEqual("c", CKANPathUtils.GetLastPathElement("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("kOS", CKANPathUtils.GetLastPathElement("GameData/kOS"), "Real world test"); + Assert.AreEqual("buckethead", CKANPathUtils.GetLastPathElement("buckethead"), "No slashes at all"); } [Test] public void GetLeadingPathElements() { - Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("/a/b/c"), "Simple case"); - Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a\\b\\c"), "With other slashes"); - Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a/b\\c"), "With mixed slashes"); - Assert.AreEqual("a/b", CKAN.CKANPathUtils.GetLeadingPathElements("a/b\\c"), "No starting slash"); - Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("/a/b", CKANPathUtils.GetLeadingPathElements("/a/b/c"), "Simple case"); + Assert.AreEqual("/a/b", CKANPathUtils.GetLeadingPathElements("\\a\\b\\c"), "With other slashes"); + Assert.AreEqual("/a/b", CKANPathUtils.GetLeadingPathElements("\\a/b\\c"), "With mixed slashes"); + Assert.AreEqual("a/b", CKANPathUtils.GetLeadingPathElements("a/b\\c"), "No starting slash"); + Assert.AreEqual("/a/b", CKANPathUtils.GetLeadingPathElements("\\a/b\\c\\"), "Trailing slash"); - Assert.IsEmpty(CKAN.CKANPathUtils.GetLeadingPathElements("ModuleManager.2.5.1.dll")); + Assert.IsEmpty(CKANPathUtils.GetLeadingPathElements("ModuleManager.2.5.1.dll")); } [Test] @@ -46,85 +46,85 @@ public void ToRelative() { Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP"), + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP"), "Basic operation" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative(@"\home\fionna\KSP\GameData\Cake", "/home/fionna/KSP"), + CKANPathUtils.ToRelative(@"\home\fionna\KSP\GameData\Cake", "/home/fionna/KSP"), "Swapped slashes" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP"), + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP"), "Trailing slash in path" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP/"), + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP/"), "Trailing slash in root" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP/"), + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP/"), "Trailing slashes for everyone!" ); - + // Mono can't handle these tests if (Platform.IsWindows) { Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("K:GameData/Cake", "K:"), + CKANPathUtils.ToRelative("K:GameData/Cake", "K:"), "Root of a Windows drive" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("K:GameData/Cake", "K:/"), + CKANPathUtils.ToRelative("K:GameData/Cake", "K:/"), "Root of a Windows drive, slash in root" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("K:/GameData/Cake", "K:"), + CKANPathUtils.ToRelative("K:/GameData/Cake", "K:"), "Root of a Windows drive, slash in path" ); Assert.AreEqual( "GameData/Cake", - CKAN.CKANPathUtils.ToRelative("K:/GameData/Cake", "K:/"), + CKANPathUtils.ToRelative("K:/GameData/Cake", "K:/"), "Root of a Windows drive, slash in both" ); } Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/finn/KSP"); + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/finn/KSP"); }, "Not a sub-path"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToRelative("KSP/GameData/Cake", "/KSP/GameData"); + CKANPathUtils.ToRelative("KSP/GameData/Cake", "/KSP/GameData"); }, "Path not absolute"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "home/fionna/KSP"); + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "home/fionna/KSP"); }, "Root not absolute"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToRelative(null, "/home/fionna/KSP"); + CKANPathUtils.ToRelative(null, "/home/fionna/KSP"); }, "null path"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", null); + CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", null); }, "null root"); } @@ -138,7 +138,7 @@ public void ToRelative_PathEqualsRoot_DontCrash() // Act & Assert Assert.DoesNotThrow(() => { - string s = CKAN.CKANPathUtils.ToRelative(path, root); + string s = CKANPathUtils.ToRelative(path, root); Assert.IsEmpty(s); }); } @@ -148,52 +148,52 @@ public void ToAbsolute() { Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP"), + CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP"), "Basic functionality" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP"), + CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP"), "Trailing slashes path" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP/"), + CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP/"), "Trailing slashes root" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP/"), + CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP/"), "Trailing slashes for all" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.CKANPathUtils.ToAbsolute(@"GameData\Cake\","/home/fionna/KSP"), + CKANPathUtils.ToAbsolute(@"GameData\Cake\","/home/fionna/KSP"), "Swapped slashes" ); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToAbsolute("/GameData/Cake", "/home/fionna/KSP"); + CKANPathUtils.ToAbsolute("/GameData/Cake", "/home/fionna/KSP"); }, "Rooted path"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToAbsolute("GameData/Cake", "home/fionna/KSP"); + CKANPathUtils.ToAbsolute("GameData/Cake", "home/fionna/KSP"); }, "Unrooted root"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToAbsolute(null, "/home/fionna/KSP"); + CKANPathUtils.ToAbsolute(null, "/home/fionna/KSP"); }, "null path"); Assert.Throws<PathErrorKraken>(delegate { - CKAN.CKANPathUtils.ToAbsolute("/home/fionna/KSP/GameData/Cake", null); + CKANPathUtils.ToAbsolute("/home/fionna/KSP/GameData/Cake", null); }, "null root"); } diff --git a/Tests/Core/Cache.cs b/Tests/Core/Cache.cs index 4e66bcaa9f..51e964290a 100644 --- a/Tests/Core/Cache.cs +++ b/Tests/Core/Cache.cs @@ -169,7 +169,7 @@ public void ZipValidation() // Make sure it's stored Assert.IsTrue(cache.IsCached(url)); // Make sure it's not valid as a zip - Assert.IsFalse(NetModuleCache.ZipValid(cache.GetCachedFilename(url), out string invalidReason, null)); + Assert.IsFalse(NetModuleCache.ZipValid(cache.GetCachedFilename(url), out _, null)); // Store a good zip. cache.Store(url, TestData.DogeCoinFlagZip()); diff --git a/Tests/Core/Configuration/FakeConfiguration.cs b/Tests/Core/Configuration/FakeConfiguration.cs index 533d435b60..aab6748509 100644 --- a/Tests/Core/Configuration/FakeConfiguration.cs +++ b/Tests/Core/Configuration/FakeConfiguration.cs @@ -68,10 +68,12 @@ public FakeConfiguration(List<Tuple<string, string, string>> instances, string a public string AutoStartInstance { get => _AutoStartInstance ?? string.Empty; + #pragma warning disable IDE0027 set { _AutoStartInstance = value; } + #pragma warning restore IDE0027 } /// <summary> diff --git a/Tests/Core/Configuration/JsonConfiguration.cs b/Tests/Core/Configuration/JsonConfiguration.cs index 1356ef4c67..49946eb0c8 100644 --- a/Tests/Core/Configuration/JsonConfiguration.cs +++ b/Tests/Core/Configuration/JsonConfiguration.cs @@ -60,8 +60,7 @@ public void LoadsGoodConfig() "host3" }, reg.GetAuthTokenHosts()); - var token = ""; - Assert.IsTrue(reg.TryGetAuthToken("host1", out token)); + Assert.IsTrue(reg.TryGetAuthToken("host1", out string token)); Assert.AreEqual("token1", token); Assert.IsTrue(reg.TryGetAuthToken("host2", out token)); Assert.AreEqual("token2", token); @@ -138,8 +137,7 @@ public void LoadsExtraConfig() "host3" }, reg.GetAuthTokenHosts()); - var token = ""; - Assert.IsTrue(reg.TryGetAuthToken("host1", out token)); + Assert.IsTrue(reg.TryGetAuthToken("host1", out string token)); Assert.AreEqual("token1", token); Assert.IsTrue(reg.TryGetAuthToken("host2", out token)); Assert.AreEqual("token2", token); @@ -183,13 +181,14 @@ public void FailsToLoadBadConfig() public void AutoStartInstancePersists(string val, string expected) { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - reg.AutoStartInstance = val; + _ = new JsonConfiguration(tmpFile1) + { + AutoStartInstance = val + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(expected, reg.AutoStartInstance); @@ -221,14 +220,14 @@ public void DownloadCacheDirPersistsRooted() public void DownloadCacheDirPersistsUnrooted() { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - - reg.DownloadCacheDir = "file"; + _ = new JsonConfiguration(tmpFile1) + { + DownloadCacheDir = "file" + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(Path.GetFullPath("file"), reg.DownloadCacheDir); @@ -241,14 +240,14 @@ public void DownloadCacheDirPersistsUnrooted() public void DownloadCacheDirPersistsNull() { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - - reg.DownloadCacheDir = null; + _ = new JsonConfiguration(tmpFile1) + { + DownloadCacheDir = null + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(JsonConfiguration.DefaultDownloadCacheDir, reg.DownloadCacheDir); @@ -260,14 +259,14 @@ public void DownloadCacheDirPersistsNull() public void DownloadCacheDirPersistsEmpty() { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - - reg.DownloadCacheDir = ""; + _ = new JsonConfiguration(tmpFile1) + { + DownloadCacheDir = "" + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(JsonConfiguration.DefaultDownloadCacheDir, reg.DownloadCacheDir); @@ -284,13 +283,14 @@ public void DownloadCacheDirPersistsEmpty() public void CacheSizeLimitPersists(long? val, long? expected) { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - reg.CacheSizeLimit = val; + _ = new JsonConfiguration(tmpFile1) + { + CacheSizeLimit = val + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(expected, reg.CacheSizeLimit); @@ -306,13 +306,14 @@ public void CacheSizeLimitPersists(long? val, long? expected) public void RefreshRatePersists(int val, int expected) { string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - reg.RefreshRate = val; + _ = new JsonConfiguration(tmpFile1) + { + RefreshRate = val + }; string tmpFile2 = Path.GetTempFileName(); File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); + JsonConfiguration reg = new JsonConfiguration(tmpFile2); Assert.AreEqual(expected, reg.RefreshRate); @@ -336,8 +337,7 @@ public void AuthTokensPersist() CollectionAssert.Contains(reg.GetAuthTokenHosts(), "test_host1"); CollectionAssert.Contains(reg.GetAuthTokenHosts(), "test_host2"); - string token = ""; - Assert.IsTrue(reg.TryGetAuthToken("test_host1", out token)); + Assert.IsTrue(reg.TryGetAuthToken("test_host1", out string token)); Assert.AreEqual("hunter2", token); Assert.IsTrue(reg.TryGetAuthToken("test_host2", out token)); Assert.AreEqual("asdf", token); diff --git a/Tests/Core/GameInstance.cs b/Tests/Core/GameInstance.cs index 83aabee1a7..1a70b9e7e4 100644 --- a/Tests/Core/GameInstance.cs +++ b/Tests/Core/GameInstance.cs @@ -13,7 +13,7 @@ namespace Tests.Core [TestFixture] public class GameInstanceTests { - private CKAN.GameInstance ksp; + private GameInstance ksp; private string ksp_dir; private IUser nullUser; @@ -23,7 +23,7 @@ public void Setup() ksp_dir = TestData.NewTempDir(); nullUser = new NullUser(); CKAN.Utilities.CopyDirectory(TestData.good_ksp_dir(), ksp_dir, true); - ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), ksp_dir, "test", nullUser); + ksp = new GameInstance(new KerbalSpaceProgram(), ksp_dir, "test", nullUser); } [TearDown] @@ -34,7 +34,7 @@ public void TearDown() // Manually dispose of RegistryManager // For some reason the KSP instance doesn't do this itself causing test failures because the registry // lock file is still in use. So just dispose of it ourselves. - CKAN.RegistryManager.DisposeInstance(ksp); + RegistryManager.DisposeInstance(ksp); } Directory.Delete(ksp_dir, true); @@ -67,8 +67,7 @@ public void Tutorial() //Use Uri to avoid issues with windows vs linux line separators. var canonicalPath = new Uri(Path.Combine(ksp_dir, "saves", "training")).LocalPath; var game = new KerbalSpaceProgram(); - string dest; - Assert.IsTrue(game.AllowInstallationIn("Tutorial", out dest)); + Assert.IsTrue(game.AllowInstallationIn("Tutorial", out string dest)); Assert.AreEqual( new DirectoryInfo(ksp.ToAbsoluteGameDir(dest)), new DirectoryInfo(canonicalPath) @@ -79,7 +78,7 @@ public void Tutorial() public void ToAbsolute() { Assert.AreEqual( - CKAN.CKANPathUtils.NormalizePath( + CKANPathUtils.NormalizePath( Path.Combine(ksp_dir, "GameData/HydrazinePrincess") ), ksp.ToAbsoluteGameDir("GameData/HydrazinePrincess") @@ -121,7 +120,7 @@ public void Valid_MissingVersionData_False() File.WriteAllText(jsonpath, compatible_ksp_versions_json); // Act - CKAN.GameInstance my_ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), gamedir, "missing-ver-test", nullUser); + GameInstance my_ksp = new GameInstance(new KerbalSpaceProgram(), gamedir, "missing-ver-test", nullUser); // Assert Assert.IsFalse(my_ksp.Valid); @@ -155,7 +154,7 @@ public void Constructor_NullMainCompatVer_NoCrash() // Act & Assert Assert.DoesNotThrow(() => { - CKAN.GameInstance my_ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), gamedir, "null-compat-ver-test", nullUser); + GameInstance my_ksp = new GameInstance(new KerbalSpaceProgram(), gamedir, "null-compat-ver-test", nullUser); }); Directory.Delete(gamedir, true); diff --git a/Tests/Core/GameInstanceManager.cs b/Tests/Core/GameInstanceManager.cs index f0ef7446b2..a41acfa8d5 100644 --- a/Tests/Core/GameInstanceManager.cs +++ b/Tests/Core/GameInstanceManager.cs @@ -20,7 +20,7 @@ [TestFixture] public class GameInstanceManagerTests private DisposableKSP tidy; private const string nameInReg = "testing"; private FakeConfiguration cfg; - GameInstanceManager manager; + private GameInstanceManager manager; [SetUp] public void SetUp() @@ -126,7 +126,7 @@ public void CloneInstance_BadInstance_ThrowsNotKSPDirKraken() { string badName = "badInstance"; string tempdir = TestData.NewTempDir(); - CKAN.GameInstance badKSP = new CKAN.GameInstance(new KerbalSpaceProgram(), TestData.bad_ksp_dirs().First(), "badDir", new NullUser()); + GameInstance badKSP = new GameInstance(new KerbalSpaceProgram(), TestData.bad_ksp_dirs().First(), "badDir", new NullUser()); Assert.Throws<NotKSPDirKraken>(() => manager.CloneInstance(badKSP, badName, tempdir)); @@ -242,7 +242,7 @@ public void FakeInstance_ValidArgumentsWithDLCs_ManagerHasValidInstance() }; manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs); - CKAN.GameInstance newKSP = new CKAN.GameInstance(new KerbalSpaceProgram(), tempdir, name, new NullUser()); + GameInstance newKSP = new GameInstance(new KerbalSpaceProgram(), tempdir, name, new NullUser()); MakingHistoryDlcDetector mhDetector = new MakingHistoryDlcDetector(); BreakingGroundDlcDetector bgDetector = new BreakingGroundDlcDetector(); @@ -253,7 +253,7 @@ public void FakeInstance_ValidArgumentsWithDLCs_ManagerHasValidInstance() Assert.IsTrue(detectedBgVersion == new UnmanagedModuleVersion(bgVersion.ToString())); // Tidy up. - CKAN.RegistryManager.DisposeInstance(newKSP); + RegistryManager.DisposeInstance(newKSP); Directory.Delete(tempdir, true); } diff --git a/Tests/Core/ModuleInstallerDirTest.cs b/Tests/Core/ModuleInstallerDirTest.cs index f108d67e69..beef941ced 100644 --- a/Tests/Core/ModuleInstallerDirTest.cs +++ b/Tests/Core/ModuleInstallerDirTest.cs @@ -18,16 +18,16 @@ namespace Tests.Core [TestFixture] public class ModuleInstallerDirTest { - private GameInstanceManager _manager; - private DisposableKSP _instance; - private FakeConfiguration _config; - private CKAN.RegistryManager _registryManager; - private CKAN.Registry _registry; - private CKAN.ModuleInstaller _installer; - private CkanModule _testModule; - private string _gameDir; - private string _gameDataDir; - private IUser _nullUser; + private GameInstanceManager _manager; + private DisposableKSP _instance; + private FakeConfiguration _config; + private RegistryManager _registryManager; + private CKAN.Registry _registry; + private ModuleInstaller _installer; + private CkanModule _testModule; + private string _gameDir; + private string _gameDataDir; + private IUser _nullUser; private TemporaryRepository repo; private TemporaryRepositoryData repoData; @@ -46,14 +46,14 @@ public void SetUp() _config = new FakeConfiguration(_instance.KSP, _instance.KSP.Name); _manager = new GameInstanceManager(_nullUser, _config); - _registryManager = CKAN.RegistryManager.Instance(_instance.KSP, repoData.Manager); + _registryManager = RegistryManager.Instance(_instance.KSP, repoData.Manager); _registry = _registryManager.registry; _registry.RepositoriesClear(); _registry.RepositoriesAdd(repo.repo); _testModule = _registry.GetModuleByVersion("DogeCoinFlag", "1.01"); Assert.IsNotNull(_testModule, "DogeCoinFlag 1.01 should exist"); - _installer = new CKAN.ModuleInstaller(_instance.KSP, _manager.Cache, _nullUser); + _installer = new ModuleInstaller(_instance.KSP, _manager.Cache, _nullUser); _gameDir = _instance.KSP.GameDir(); _gameDataDir = _instance.KSP.game.PrimaryModDirectory(_instance.KSP); @@ -127,7 +127,7 @@ public void TestNullPath() public void TestSlashVariants() { var rawInstallDir = Path.Combine(_gameDataDir, _testModule.identifier); - var normalizedInstallDir = CKAN.CKANPathUtils.NormalizePath(rawInstallDir); + var normalizedInstallDir = CKANPathUtils.NormalizePath(rawInstallDir); var windowsInstallDir = normalizedInstallDir.Replace('/', '\\'); Assert.DoesNotThrow(delegate () @@ -151,10 +151,12 @@ public void TestSlashVariants() [Test] public void TestCaseSensitivity() { - var paths = new HashSet<string>(); - // add in all-uppercase and all-lowercase version - paths.Add(Path.Combine(_gameDataDir.ToUpper(), _testModule.identifier)); - paths.Add(Path.Combine(_gameDataDir.ToLower(), _testModule.identifier)); + var paths = new HashSet<string>() + { + // add in all-uppercase and all-lowercase version + Path.Combine(_gameDataDir.ToUpper(), _testModule.identifier), + Path.Combine(_gameDataDir.ToLower(), _testModule.identifier), + }; // here we are looking for no PathErrorKraken Assert.DoesNotThrow(delegate() { diff --git a/Tests/Core/ModuleInstallerTests.cs b/Tests/Core/ModuleInstallerTests.cs index 3b220666bb..be0ffa18f7 100644 --- a/Tests/Core/ModuleInstallerTests.cs +++ b/Tests/Core/ModuleInstallerTests.cs @@ -21,9 +21,9 @@ namespace Tests.Core public class ModuleInstallerTests { private const string flag_path = "DogeCoinFlag-1.01/GameData/DogeCoinFlag/Flags/dogecoin.png"; - private IUser nullUser = new NullUser(); + private readonly IUser nullUser = new NullUser(); - private DisposableKSP ksp = new DisposableKSP(); + private readonly DisposableKSP ksp = new DisposableKSP(); [OneTimeTearDown] public void TearDown() @@ -72,7 +72,7 @@ public void GenerateDefaultInstall() [TestCaseSource("doge_mods")] public void FindInstallableFiles(CkanModule mod) { - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, TestData.DogeCoinFlagZip(), ksp.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(mod, TestData.DogeCoinFlagZip(), ksp.KSP); List<string> filenames = new List<string>(); Assert.IsNotNull(contents); @@ -101,7 +101,7 @@ public void FindInstallableFilesWithKSP(CkanModule mod) { using (var tidy = new DisposableKSP()) { - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, TestData.DogeCoinFlagZip(), tidy.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(mod, TestData.DogeCoinFlagZip(), tidy.KSP); // See if we can find an expected destination path in the right place. string file = contents @@ -133,7 +133,7 @@ public void FindInstallableFilesWithBonusPath(string path) dogemod.install[0].install_to = path; using (var tidy = new DisposableKSP()) { - IEnumerable<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles( + IEnumerable<InstallableFile> contents = ModuleInstaller.FindInstallableFiles( dogemod, TestData.DogeCoinFlagZip(), tidy.KSP ); @@ -150,7 +150,7 @@ public void ModuleManagerInstall() { using (var tidy = new DisposableKSP()) { - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(TestData.ModuleManagerModule(), TestData.ModuleManagerZip(), tidy.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(TestData.ModuleManagerModule(), TestData.ModuleManagerZip(), tidy.KSP); string file = contents .Select(x => x.destination).FirstOrDefault( @@ -165,7 +165,7 @@ public void MissionInstall() { using (var tidy = new DisposableKSP()) { - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(TestData.MissionModule(), TestData.MissionZip(), tidy.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(TestData.MissionModule(), TestData.MissionZip(), tidy.KSP); string failBanner = contents.Select(x => x.destination).FirstOrDefault( x => Regex.IsMatch(x, "Missions/AwesomeMission/Banners/Fail/default\\.png$")); @@ -193,7 +193,7 @@ public void FindInstallableFilesWithFilter(CkanModule mod) { string extra_doge = TestData.DogeCoinFlagZipWithExtras(); - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); var files = contents.Select(x => x.source.Name); @@ -210,7 +210,7 @@ public void FindInstallableFilesWithInclude() string extra_doge = TestData.DogeCoinFlagZipWithExtras(); CkanModule mod = TestData.DogeCoinFlag_101_module_include(); - List<InstallableFile> contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); + List<InstallableFile> contents = ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); var files = contents.Select(x => x.source.Name); @@ -229,12 +229,12 @@ public void No_Installable_Files() Assert.Throws<BadMetadataKraken>(delegate { - CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, TestData.DogeCoinFlagZip(), ksp.KSP); + ModuleInstaller.FindInstallableFiles(bugged_mod, TestData.DogeCoinFlagZip(), ksp.KSP); }); try { - CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, TestData.DogeCoinFlagZip(), ksp.KSP); + ModuleInstaller.FindInstallableFiles(bugged_mod, TestData.DogeCoinFlagZip(), ksp.KSP); } catch (BadMetadataKraken ex) { @@ -265,7 +265,7 @@ public void FindInstallableFilesWithBadTarget(string location) Assert.Throws<BadInstallLocationKraken>(delegate { - CKAN.ModuleInstaller.FindInstallableFiles(dogemod, TestData.DogeCoinFlagZip(), ksp.KSP); + ModuleInstaller.FindInstallableFiles(dogemod, TestData.DogeCoinFlagZip(), ksp.KSP); }); } @@ -319,7 +319,7 @@ public void DontOverWrite_208() Assert.Throws<FileExistsKraken>(delegate { - CKAN.ModuleInstaller.CopyZipEntry(zipfile, entry, tmpfile, false); + ModuleInstaller.CopyZipEntry(zipfile, entry, tmpfile, false); }); // Cleanup @@ -341,7 +341,7 @@ public void CorruptZip_242() ModuleInstallDescriptor.DefaultInstallStanza(new KerbalSpaceProgram(), "DogeCoinFlag"); // FindInstallableFiles - CKAN.ModuleInstaller.FindInstallableFiles(TestData.DogeCoinFlag_101_module(), corrupt_dogezip, ksp.KSP); + ModuleInstaller.FindInstallableFiles(TestData.DogeCoinFlag_101_module(), corrupt_dogezip, ksp.KSP); } } @@ -354,7 +354,7 @@ private string CopyDogeFromZip() // We have to delete our temporary file, as CZE refuses to overwrite; huzzah! File.Delete(tmpfile); - CKAN.ModuleInstaller.CopyZipEntry(zipfile, entry, tmpfile, false); + ModuleInstaller.CopyZipEntry(zipfile, entry, tmpfile, false); return tmpfile; } @@ -374,10 +374,10 @@ public void UninstallModNotFound() { HashSet<string> possibleConfigOnlyDirs = null; // This should throw, as our tidy KSP has no mods installed. - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .UninstallList(new List<string> {"Foo"}, ref possibleConfigOnlyDirs, - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); }); // I weep even more. @@ -415,7 +415,7 @@ public void CanInstallMod() Assert.IsTrue(manager.Cache.IsCached(TestData.DogeCoinFlag_101_module())); Assert.IsTrue(File.Exists(cache_path)); - var registry = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager).registry; + var registry = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); @@ -425,10 +425,10 @@ public void CanInstallMod() var modules = new List<CkanModule> { TestData.DogeCoinFlag_101_module() }; HashSet<string> possibleConfigOnlyDirs = null; - new CKAN.ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) .InstallList(modules, new RelationshipResolverOptions(), - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); // Check that the module is installed. @@ -454,7 +454,7 @@ public void CanUninstallMod() string mod_file_path = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), mod_file_name); // Install the test mod. - var registry = CKAN.RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; + var registry = RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); manager.Cache.Store(TestData.DogeCoinFlag_101_module(), @@ -464,19 +464,19 @@ public void CanUninstallMod() var modules = new List<CkanModule> { TestData.DogeCoinFlag_101_module() }; HashSet<string> possibleConfigOnlyDirs = null; - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .InstallList(modules, new RelationshipResolverOptions(), - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); // Check that the module is installed. Assert.IsTrue(File.Exists(mod_file_path)); // Attempt to uninstall it. - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .UninstallList(modules.Select(m => m.identifier), ref possibleConfigOnlyDirs, - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); // Check that the module is not installed. Assert.IsFalse(File.Exists(mod_file_path)); @@ -502,7 +502,7 @@ public void UninstallEmptyDirs() string directoryPath = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), emptyFolderName); // Install the base test mod. - var registry = CKAN.RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; + var registry = RegistryManager.Instance(ksp.KSP, repoData.Manager).registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); manager.Cache.Store(TestData.DogeCoinFlag_101_module(), @@ -512,10 +512,10 @@ public void UninstallEmptyDirs() var modules = new List<CkanModule> { TestData.DogeCoinFlag_101_module() }; HashSet<string> possibleConfigOnlyDirs = null; - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .InstallList(modules, new RelationshipResolverOptions(), - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); modules.Clear(); @@ -527,10 +527,10 @@ public void UninstallEmptyDirs() modules.Add(TestData.DogeCoinPlugin_module()); - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .InstallList(modules, new RelationshipResolverOptions(), - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); modules.Clear(); @@ -543,10 +543,10 @@ public void UninstallEmptyDirs() modules.Add(TestData.DogeCoinFlag_101_module()); modules.Add(TestData.DogeCoinPlugin_module()); - new CKAN.ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) + new ModuleInstaller(manager.CurrentInstance, manager.Cache, nullUser) .UninstallList(modules.Select(m => m.identifier), ref possibleConfigOnlyDirs, - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager)); // Check that the directory has been deleted. Assert.IsFalse(Directory.Exists(directoryPath)); @@ -656,7 +656,7 @@ public void GroupFilesByRemovable_WithFiles_CorrectOutput(string relRoot, using (var repoData = new TemporaryRepositoryData(nullUser)) { var game = new KerbalSpaceProgram(); - var registry = CKAN.RegistryManager.Instance(inst.KSP, repoData.Manager).registry; + var registry = RegistryManager.Instance(inst.KSP, repoData.Manager).registry; // Make files to be registered to another mod var absFiles = registeredFiles.Select(f => inst.KSP.ToAbsoluteGameDir(f)) .ToArray(); @@ -675,7 +675,7 @@ public void GroupFilesByRemovable_WithFiles_CorrectOutput(string relRoot, absFiles, inst.KSP, false); // Act - CKAN.ModuleInstaller.GroupFilesByRemovable(relRoot, + ModuleInstaller.GroupFilesByRemovable(relRoot, registry, new string[] {}, game, @@ -708,7 +708,7 @@ public void ModuleManagerInstancesAreDecoupled() CurrentInstance = ksp.KSP }) { - var regMgr = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); + var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; registry.RepositoriesClear(); registry.RepositoriesAdd(repo.repo); @@ -722,10 +722,10 @@ public void ModuleManagerInstancesAreDecoupled() var modules = new List<CkanModule> { TestData.DogeCoinFlag_101_module() }; HashSet<string> possibleConfigOnlyDirs = null; - new CKAN.ModuleInstaller(ksp.KSP, manager.Cache, nullUser) + new ModuleInstaller(ksp.KSP, manager.Cache, nullUser) .InstallList(modules, new RelationshipResolverOptions(), - CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), + RegistryManager.Instance(manager.CurrentInstance, repoData.Manager), ref possibleConfigOnlyDirs); // Check that the module is installed. @@ -814,7 +814,7 @@ public void AllowInstallsToScenarios() var results = mod.install.First().FindInstallableFiles(zip, ksp.KSP); Assert.AreEqual( - CKAN.CKANPathUtils.NormalizePath( + CKANPathUtils.NormalizePath( Path.Combine(ksp.KSP.GameDir(), "saves/scenarios/AwesomeRace.sfs")), results.First().destination); } @@ -858,7 +858,7 @@ public void Replace_WithCompatibleModule_Succeeds() CurrentInstance = inst.KSP }) { - var regMgr = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); + var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; IRegistryQuerier querier = registry; registry.RepositoriesAdd(repo.repo); @@ -866,7 +866,7 @@ public void Replace_WithCompatibleModule_Succeeds() Assert.IsNotNull(replaced, "Replaced module should exist"); var replacer = registry.GetModuleByVersion("replacer", "1.0"); Assert.IsNotNull(replacer, "Replacer module should exist"); - var installer = new CKAN.ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); HashSet<string> possibleConfigOnlyDirs = null; var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); @@ -875,14 +875,14 @@ public void Replace_WithCompatibleModule_Succeeds() manager.Cache.Store(replaced, TestData.DogeCoinFlagZip(), new Progress<long>(bytes => {})); var replacement = querier.GetReplacement(replaced.identifier, new GameVersionCriteria(new GameVersion(1, 12))); - installer.Replace(Enumerable.Repeat<ModuleReplacement>(replacement, 1), + installer.Replace(Enumerable.Repeat(replacement, 1), new RelationshipResolverOptions(), downloader, ref possibleConfigOnlyDirs, regMgr, false); // Assert CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(replacer, 1), + Enumerable.Repeat(replacer, 1), registry.InstalledModules.Select(im => im.Module)); } } @@ -925,7 +925,7 @@ public void Replace_WithIncompatibleModule_Fails() CurrentInstance = inst.KSP }) { - var regMgr = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); + var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; IRegistryQuerier querier = registry; registry.RepositoriesAdd(repo.repo); @@ -933,7 +933,7 @@ public void Replace_WithIncompatibleModule_Fails() Assert.IsNotNull(replaced, "Replaced module should exist"); var replacer = registry.GetModuleByVersion("replacer", "1.0"); Assert.IsNotNull(replacer, "Replacer module should exist"); - var installer = new CKAN.ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); // Act @@ -945,7 +945,7 @@ public void Replace_WithIncompatibleModule_Fails() // Assert Assert.IsNull(replacement); CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(replaced, 1), + Enumerable.Repeat(replaced, 1), registry.InstalledModules.Select(im => im.Module)); } } @@ -996,8 +996,8 @@ public void UninstallList_WithAutoInst_RemovesAutoRemovable(string[] regularMods using (var repo = new TemporaryRepository(regularMods.Concat(autoInstMods).ToArray())) using (var repoData = new TemporaryRepositoryData(nullUser, repo.repo)) { - var installer = new CKAN.ModuleInstaller(inst.KSP, manager.Cache, nullUser); - var regMgr = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); + var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; var possibleConfigOnlyDirs = new HashSet<string>(); foreach (var m in regularMods) @@ -1076,9 +1076,9 @@ public void Upgrade_WithAutoInst_RemovesAutoRemovable(string[] regularMods, using (var repo = new TemporaryRepository(regularMods.Concat(autoInstMods).ToArray())) using (var repoData = new TemporaryRepositoryData(nullUser, repo.repo)) { - var installer = new CKAN.ModuleInstaller(inst.KSP, manager.Cache, nullUser); + var installer = new ModuleInstaller(inst.KSP, manager.Cache, nullUser); var downloader = new NetAsyncModulesDownloader(nullUser, manager.Cache); - var regMgr = CKAN.RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); + var regMgr = RegistryManager.Instance(manager.CurrentInstance, repoData.Manager); var registry = regMgr.registry; registry.RepositoriesSet(new SortedDictionary<string, Repository>() { diff --git a/Tests/Core/Net/AutoUpdateTests.cs b/Tests/Core/Net/AutoUpdateTests.cs index 2027c0703b..faf3e00c2c 100644 --- a/Tests/Core/Net/AutoUpdateTests.cs +++ b/Tests/Core/Net/AutoUpdateTests.cs @@ -1,4 +1,3 @@ -using System; using System.Net; using NUnit.Framework; using CKAN; @@ -9,9 +8,6 @@ namespace Tests.Core.AutoUpdateTests [TestFixture] public class AutoUpdateTests { - // pjf's repo has no releases, so tests on this URL should fail - private readonly Uri test_ckan_release = new Uri("https://api.github.com/repos/pjf/CKAN/releases/latest"); - [Test] [Category("Online")] // This could fail if run during a release, so it's marked as Flaky. @@ -22,7 +18,7 @@ public void FetchLatestReleaseInfo() // This is on by default in .NET 4.6, but not in 4.5. ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; - var updater = CKAN.AutoUpdate.Instance; + var updater = AutoUpdate.Instance; // Is is a *really* basic test to just make sure we get release info // if we ask for it. diff --git a/Tests/Core/Net/Net.cs b/Tests/Core/Net/Net.cs index 6389343563..3f53842036 100644 --- a/Tests/Core/Net/Net.cs +++ b/Tests/Core/Net/Net.cs @@ -10,7 +10,7 @@ public class NetTests { // TODO: Test certificate errors. How? // URL we expect to always be up. - const string KnownURL = "http://example.com/"; + private const string KnownURL = "http://example.com/"; private static void BadDownload() { CKAN.Net.Download("cheese sandwich"); diff --git a/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs b/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs index 0bc51bef3f..c7e8f1cfd2 100644 --- a/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs +++ b/Tests/Core/Net/NetAsyncModulesDownloaderTests.cs @@ -7,7 +7,6 @@ using Tests.Data; using CKAN; -using CKAN.Extensions; namespace Tests.Core.Net { @@ -18,13 +17,12 @@ namespace Tests.Core.Net [TestFixture] public class NetAsyncModulesDownloaderTests { - private CKAN.GameInstanceManager manager; - private CKAN.RegistryManager registry_manager; + private GameInstanceManager manager; + private RegistryManager registry_manager; private CKAN.Registry registry; private DisposableKSP ksp; - private CKAN.IDownloader async; + private IDownloader async; private NetModuleCache cache; - private NetAsyncDownloader downloader; private TemporaryRepositoryData repoData; private static readonly ILog log = LogManager.GetLogger(typeof(NetAsyncModulesDownloaderTests)); @@ -47,16 +45,14 @@ public void Setup() manager = new GameInstanceManager(user); // Give us a registry to play with. ksp = new DisposableKSP(); - registry_manager = CKAN.RegistryManager.Instance(ksp.KSP, repoData.Manager); + registry_manager = RegistryManager.Instance(ksp.KSP, repoData.Manager); registry = registry_manager.registry; registry.Installed().Clear(); // Make sure we have a registry we can use. registry.RepositoriesSet(repos); - downloader = new NetAsyncDownloader(user); - // Ready our downloader. - async = new CKAN.NetAsyncModulesDownloader(user, manager.Cache); + async = new NetAsyncModulesDownloader(user, manager.Cache); // General shortcuts cache = manager.Cache; diff --git a/Tests/Core/Registry/CompatibilitySorter.cs b/Tests/Core/Registry/CompatibilitySorter.cs index 390c353b98..9a323aa109 100644 --- a/Tests/Core/Registry/CompatibilitySorter.cs +++ b/Tests/Core/Registry/CompatibilitySorter.cs @@ -81,7 +81,7 @@ public void Constructor_OverlappingModules_HigherPriorityOverrides(string[] modu var dlls = new HashSet<string>(); var dlcs = new Dictionary<string, ModuleVersion>(); var highPrio = repoData.Manager - .GetAvailableModules(Enumerable.Repeat<Repository>(repo1.repo, 1), + .GetAvailableModules(Enumerable.Repeat(repo1.repo, 1), identifier) .First() .Latest(); diff --git a/Tests/Core/Registry/Registry.cs b/Tests/Core/Registry/Registry.cs index a05babf834..d2d3edd40c 100644 --- a/Tests/Core/Registry/Registry.cs +++ b/Tests/Core/Registry/Registry.cs @@ -407,13 +407,13 @@ public void TxEmbeddedCommit() gameInstWrapper.KSP, false); CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(module, 1), + Enumerable.Repeat(module, 1), reg.InstalledModules.Select(im => im.Module)); tScope.Complete(); } CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(module, 1), + Enumerable.Repeat(module, 1), reg.InstalledModules.Select(im => im.Module)); } @@ -438,13 +438,13 @@ public void TxCommit() gameInstWrapper.KSP, false); CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(module, 1), + Enumerable.Repeat(module, 1), registry.InstalledModules.Select(im => im.Module)); tScope.Complete(); } CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(module, 1), + Enumerable.Repeat(module, 1), registry.InstalledModules.Select(im => im.Module)); } @@ -468,7 +468,7 @@ public void TxRollback() gameInstWrapper.KSP, false); CollectionAssert.AreEqual( - Enumerable.Repeat<CkanModule>(module, 1), + Enumerable.Repeat(module, 1), registry.InstalledModules.Select(im => im.Module)); // Rollback, our module should no longer be registered diff --git a/Tests/Core/Registry/RegistryManager.cs b/Tests/Core/Registry/RegistryManager.cs index fb176965d2..9794496ea8 100644 --- a/Tests/Core/Registry/RegistryManager.cs +++ b/Tests/Core/Registry/RegistryManager.cs @@ -63,10 +63,7 @@ private bool TestLock(string path) } finally { - if (lockfileStream != null) - { - lockfileStream.Close(); - } + lockfileStream?.Close(); } } diff --git a/Tests/Core/Relationships/RelationshipResolver.cs b/Tests/Core/Relationships/RelationshipResolver.cs index 33378aab9e..1a4691c9ab 100644 --- a/Tests/Core/Relationships/RelationshipResolver.cs +++ b/Tests/Core/Relationships/RelationshipResolver.cs @@ -975,9 +975,9 @@ public void AutodetectedCanSatisfyRelationships() } }); - var depends = new List<CKAN.RelationshipDescriptor> + var depends = new List<RelationshipDescriptor> { - new CKAN.ModuleRelationshipDescriptor { name = "ModuleManager" } + new ModuleRelationshipDescriptor { name = "ModuleManager" } }; CkanModule mod = generator.GeneratorRandomModule(depends: depends); diff --git a/Tests/Core/Relationships/SanityChecker.cs b/Tests/Core/Relationships/SanityChecker.cs index 9de023949d..98cb97600b 100644 --- a/Tests/Core/Relationships/SanityChecker.cs +++ b/Tests/Core/Relationships/SanityChecker.cs @@ -5,7 +5,6 @@ using Tests.Data; using CKAN; -using CKAN.Extensions; using CKAN.Versioning; // We're exercising FindReverseDependencies in here, because: @@ -17,7 +16,7 @@ namespace Tests.Core.Relationships [TestFixture] public class SanityChecker { - private CKAN.RegistryManager manager; + private RegistryManager manager; private CKAN.Registry registry; private DisposableKSP ksp; private TemporaryRepositoryData repoData; @@ -36,12 +35,11 @@ public void Setup() var user = new NullUser(); repoData = new TemporaryRepositoryData(user, repos.Values); - manager = CKAN.RegistryManager.Instance(ksp.KSP, repoData.Manager); + manager = RegistryManager.Instance(ksp.KSP, repoData.Manager); registry = manager.registry; registry.Installed().Clear(); registry.RepositoriesSet(repos); - var downloader = new NetAsyncDownloader(user); } [OneTimeTearDown] diff --git a/Tests/Core/Repositories/RepositoryDataManagerTests.cs b/Tests/Core/Repositories/RepositoryDataManagerTests.cs index 6eff656730..b51e058884 100644 --- a/Tests/Core/Repositories/RepositoryDataManagerTests.cs +++ b/Tests/Core/Repositories/RepositoryDataManagerTests.cs @@ -23,7 +23,7 @@ public void UpdateRegistryTarGz() var crit = new GameVersionCriteria(GameVersion.Parse("0.25.0")); // Act - var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat<Repository>(testRepo, 1), + var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat(testRepo, 1), "FerramAerospaceResearch") .Select(am => am.Latest(crit).version.ToString()) .ToArray(); @@ -45,7 +45,7 @@ public void UpdateRegistryZip() var crit = new GameVersionCriteria(GameVersion.Parse("0.25.0")); // Act - var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat<Repository>(testRepo, 1), + var versions = repoData.Manager.GetAvailableModules(Enumerable.Repeat(testRepo, 1), "FerramAerospaceResearch") .Select(am => am.Latest(crit).version.ToString()) .ToArray(); diff --git a/Tests/Core/ResourcesTests.cs b/Tests/Core/ResourcesTests.cs index 2e290b502d..3dd94fa681 100644 --- a/Tests/Core/ResourcesTests.cs +++ b/Tests/Core/ResourcesTests.cs @@ -29,7 +29,7 @@ public void PropertiesResources_LanguageResource_NotSet() } // The cultures to test - private static CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages + private static readonly CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages .Select(l => new CultureInfo(l)) .ToArray(); } diff --git a/Tests/Core/Types/GameComparator.cs b/Tests/Core/Types/GameComparator.cs index 71ed417f8e..20191af256 100644 --- a/Tests/Core/Types/GameComparator.cs +++ b/Tests/Core/Types/GameComparator.cs @@ -9,8 +9,8 @@ namespace Tests.Core.Types [TestFixture] public class GameComparator { - static readonly GameVersion gameVersion = GameVersion.Parse("1.0.4"); - CkanModule gameMod; + private static readonly GameVersion gameVersion = GameVersion.Parse("1.0.4"); + private CkanModule gameMod; [SetUp] public void Setup() @@ -20,12 +20,12 @@ public void Setup() } [Test] - [TestCase(typeof(CKAN.StrictGameComparator), true)] - [TestCase(typeof(CKAN.GrasGameComparator), true)] - [TestCase(typeof(CKAN.YoyoGameComparator), true)] + [TestCase(typeof(StrictGameComparator), true)] + [TestCase(typeof(GrasGameComparator), true)] + [TestCase(typeof(YoyoGameComparator), true)] public void TotallyCompatible(Type type, bool expected) { - var comparator = (CKAN.IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator) Activator.CreateInstance(type); // Mark the mod as being for 1.0.4 gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max @@ -36,12 +36,12 @@ public void TotallyCompatible(Type type, bool expected) } [Test] - [TestCase(typeof(CKAN.StrictGameComparator), false)] - [TestCase(typeof(CKAN.GrasGameComparator), true)] - [TestCase(typeof(CKAN.YoyoGameComparator), true)] + [TestCase(typeof(StrictGameComparator), false)] + [TestCase(typeof(GrasGameComparator), true)] + [TestCase(typeof(YoyoGameComparator), true)] public void GenerallySafeLax(Type type, bool expected) { - var comparator = (CKAN.IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator) Activator.CreateInstance(type); // We're going to tweak compatibly to mark the mod as being for 1.0.3 gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max @@ -52,12 +52,12 @@ public void GenerallySafeLax(Type type, bool expected) } [Test] - [TestCase(typeof(CKAN.StrictGameComparator), false)] - [TestCase(typeof(CKAN.GrasGameComparator), false)] - [TestCase(typeof(CKAN.YoyoGameComparator), true)] + [TestCase(typeof(StrictGameComparator), false)] + [TestCase(typeof(GrasGameComparator), false)] + [TestCase(typeof(YoyoGameComparator), true)] public void GenerallySafeStrict(Type type, bool expected) { - var comparator = (CKAN.IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator) Activator.CreateInstance(type); // We're going to tweak compatibly to mark the mod as being for 1.0.3 ONLY gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max @@ -70,12 +70,12 @@ public void GenerallySafeStrict(Type type, bool expected) } [Test] - [TestCase(typeof(CKAN.StrictGameComparator), false)] - [TestCase(typeof(CKAN.GrasGameComparator), false)] - [TestCase(typeof(CKAN.YoyoGameComparator), true)] + [TestCase(typeof(StrictGameComparator), false)] + [TestCase(typeof(GrasGameComparator), false)] + [TestCase(typeof(YoyoGameComparator), true)] public void Incompatible(Type type, bool expected) { - var comparator = (CKAN.IGameComparator) Activator.CreateInstance(type); + var comparator = (IGameComparator) Activator.CreateInstance(type); // The mod already starts off being incompatible, so just do the test. :) Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); @@ -118,9 +118,9 @@ public void Incompatible(Type type, bool expected) }; [TestCaseSource("TestStrictGameComparatorCases")] - public void TestStrictGameComparator(String modVersion, String gameVersion, bool expectedResult) + public void TestStrictGameComparator(string modVersion, string gameVersion, bool expectedResult) { - var comparator = new CKAN.StrictGameComparator(); + var comparator = new StrictGameComparator(); // We're going to tweak compatibly of the mod gameMod.ksp_version = GameVersion.Parse(modVersion); @@ -164,9 +164,9 @@ public void TestStrictGameComparator(String modVersion, String gameVersion, bool }; [TestCaseSource("TestStrictGameComparatorMinMaxCases")] - public void TestStrictGameComparatorMinMax(String modMinVersion, String modMaxVersion, String gameVersion, bool expectedResult) + public void TestStrictGameComparatorMinMax(string modMinVersion, string modMaxVersion, string gameVersion, bool expectedResult) { - var comparator = new CKAN.StrictGameComparator(); + var comparator = new StrictGameComparator(); gameMod.ksp_version = null; gameMod.ksp_version_min = modMinVersion == null ? null : GameVersion.Parse(modMinVersion); diff --git a/Tests/Core/Types/RelationshipDescriptor.cs b/Tests/Core/Types/RelationshipDescriptor.cs index e9c3c15449..9e12b35315 100644 --- a/Tests/Core/Types/RelationshipDescriptor.cs +++ b/Tests/Core/Types/RelationshipDescriptor.cs @@ -6,8 +6,7 @@ namespace Tests.Core.Types [TestFixture] public class RelationshipDescriptor { - - ModuleVersion autodetected = new UnmanagedModuleVersion(null); + private readonly ModuleVersion autodetected = new UnmanagedModuleVersion(null); [Test] [TestCase("0.23","0.23", true)] diff --git a/Tests/Core/Types/ReleaseStatus.cs b/Tests/Core/Types/ReleaseStatus.cs index dfd891f7c0..d54ca53ee8 100644 --- a/Tests/Core/Types/ReleaseStatus.cs +++ b/Tests/Core/Types/ReleaseStatus.cs @@ -9,7 +9,7 @@ public class ReleaseStatus // These get used by our tests, but we have to disable 'used only once' (0414) // to stop the compiler from giving us warnings. - #pragma warning disable 0414 + #pragma warning disable 0414, IDE0052 private static readonly string[] GoodStatuses = { "stable", "testing", "development" @@ -21,7 +21,7 @@ public class ReleaseStatus "42" }; - #pragma warning restore 0414 + #pragma warning restore 0414, IDE0052 [Test][TestCaseSource("GoodStatuses")] public void ReleaseGood(string status) @@ -49,4 +49,3 @@ public void Null() } } } - diff --git a/Tests/Core/Utilities.cs b/Tests/Core/Utilities.cs index ad2008c396..cc7ba0d8b7 100644 --- a/Tests/Core/Utilities.cs +++ b/Tests/Core/Utilities.cs @@ -7,8 +7,8 @@ namespace Tests.Core { [TestFixture] public class Utilities { - string tempDir; - string goodKspDir = TestData.good_ksp_dir(); + private string tempDir; + private readonly string goodKspDir = TestData.good_ksp_dir(); [SetUp] public void CreateTempDir() diff --git a/Tests/Core/Versioning/KspVersionBoundTests.cs b/Tests/Core/Versioning/KspVersionBoundTests.cs index dc6235b3c3..d88087b77f 100644 --- a/Tests/Core/Versioning/KspVersionBoundTests.cs +++ b/Tests/Core/Versioning/KspVersionBoundTests.cs @@ -9,6 +9,7 @@ namespace Tests.Core.Versioning [TestFixture] public sealed class GameVersionBoundTests { + #pragma warning disable 0414, IDE0052 private static readonly object[] EqualityCases = { new object[] @@ -36,6 +37,7 @@ public sealed class GameVersionBoundTests false } }; + #pragma warning restore 0414, IDE0052 [Test] public void ParameterlessCtorWorksCorrectly() diff --git a/Tests/Core/Versioning/KspVersionRangeTests.cs b/Tests/Core/Versioning/KspVersionRangeTests.cs index e82b535cf2..b106c70853 100644 --- a/Tests/Core/Versioning/KspVersionRangeTests.cs +++ b/Tests/Core/Versioning/KspVersionRangeTests.cs @@ -10,6 +10,7 @@ namespace Tests.Core.Versioning { public sealed class GameVersionRangeTests { + #pragma warning disable 0414, IDE0052 private static readonly object[] EqualityCases = { new object[] @@ -426,6 +427,7 @@ public sealed class GameVersionRangeTests true }, }; + #pragma warning restore 0414, IDE0052 [Test] public void CtorWorksCorrectly() diff --git a/Tests/Core/Versioning/KspVersionTests.cs b/Tests/Core/Versioning/KspVersionTests.cs index 32fd98f729..7563e37daa 100644 --- a/Tests/Core/Versioning/KspVersionTests.cs +++ b/Tests/Core/Versioning/KspVersionTests.cs @@ -9,6 +9,7 @@ namespace Tests.Core.Versioning [TestFixture] public class GameVersionTests { + #pragma warning disable 0414, IDE0052 private static readonly object[] ParseCases = { new object[] { "1", new GameVersion(1) }, @@ -99,6 +100,7 @@ public class GameVersionTests ) } }; + #pragma warning restore 0414, IDE0052 [Test] public void ParameterlessCtorWorksCorrectly() @@ -301,8 +303,7 @@ public void ToVersionRangeWorksCorrectly(GameVersion version, GameVersionRange e public void TryParseWorksCorrectly(string s, GameVersion version) { // Act - GameVersion result; - var success = GameVersion.TryParse(s, out result); + var success = GameVersion.TryParse(s, out GameVersion result); // Assert Assert.IsTrue(success); @@ -314,8 +315,7 @@ public void TryParseWorksCorrectly(string s, GameVersion version) public void TryParseReturnsFalseOnInvalidParameter(string s) { // Act - GameVersion result; - var success = GameVersion.TryParse(s, out result); + var success = GameVersion.TryParse(s, out _); // Assert Assert.IsFalse(success); diff --git a/Tests/Data/TestData.cs b/Tests/Data/TestData.cs index 17f34c46e8..403b922b2b 100644 --- a/Tests/Data/TestData.cs +++ b/Tests/Data/TestData.cs @@ -8,7 +8,7 @@ namespace Tests.Data { - static public class TestData + public static class TestData { public static string DataDir() // FIXME: Come up with a better solution for test data @@ -287,7 +287,7 @@ public static CkanModule DogeCoinFlag_101_module_include() doge.install[0].filter = null; doge.install[0].filter_regexp = null; - doge.install[0].include_only = new List<String> { "dogecoin.png" }; + doge.install[0].include_only = new List<string> { "dogecoin.png" }; doge.install[0].include_only_regexp = new List<string> { "\\.bak$" }; return doge; @@ -777,7 +777,7 @@ public CkanModule GeneratorRandomModule( List<RelationshipDescriptor> conflicts = null, List<RelationshipDescriptor> depends = null, List<RelationshipDescriptor> suggests = null, - List<String> provides = null, + List<string> provides = null, string identifier = null, ModuleVersion version = null) { diff --git a/Tests/GUI/GUIConfiguration.cs b/Tests/GUI/GUIConfiguration.cs index 1ac8fe9ff0..c5a11c77d4 100644 --- a/Tests/GUI/GUIConfiguration.cs +++ b/Tests/GUI/GUIConfiguration.cs @@ -13,7 +13,7 @@ namespace Tests.GUI [TestFixture] public class GuiConfigurationTests { - string tempDir; + private string tempDir; [OneTimeSetUp] public void Setup() diff --git a/Tests/GUI/Model/ModList.cs b/Tests/GUI/Model/ModList.cs index 5d5f2e1478..52575d3b67 100644 --- a/Tests/GUI/Model/ModList.cs +++ b/Tests/GUI/Model/ModList.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; -using System.Threading.Tasks; using System.ComponentModel; using System.Windows.Forms; @@ -150,7 +148,7 @@ public void InstallAndSortByCompat_WithAnyCompat_NoCrash() Assert.IsNotNull(anyVersionModule, "DogeCoinFlag 1.01 should exist"); var modList = new ModList(); var listGui = new DataGridView(); - var installer = new CKAN.ModuleInstaller(instance.KSP, manager.Cache, manager.User); + var installer = new ModuleInstaller(instance.KSP, manager.Cache, manager.User); var downloader = new NetAsyncModulesDownloader(user, manager.Cache); // Act @@ -183,7 +181,7 @@ public void InstallAndSortByCompat_WithAnyCompat_NoCrash() Assert.IsNotNull(manager); Assert.IsNotNull(modList); - var modules = repoData.Manager.GetAllAvailableModules(Enumerable.Repeat<Repository>(repo.repo, 1)) + var modules = repoData.Manager.GetAllAvailableModules(Enumerable.Repeat(repo.repo, 1)) .Select(mod => new GUIMod(mod.Latest(), repoData.Manager, registry, instance.KSP.VersionCriteria(), null, false, false)) .ToList(); diff --git a/Tests/GUI/NavigationHistoryTests.cs b/Tests/GUI/NavigationHistoryTests.cs index 469b3ad92e..2e51262907 100644 --- a/Tests/GUI/NavigationHistoryTests.cs +++ b/Tests/GUI/NavigationHistoryTests.cs @@ -238,9 +238,10 @@ public void ReadOnlyMode_BlocksAddingToHistory() { // arrange - var nav = new NavigationHistory<int>(); - - nav.IsReadOnly = true; + var nav = new NavigationHistory<int> + { + IsReadOnly = true + }; // act diff --git a/Tests/GUI/ResourcesTests.cs b/Tests/GUI/ResourcesTests.cs index bd76d16178..1322f58ad7 100644 --- a/Tests/GUI/ResourcesTests.cs +++ b/Tests/GUI/ResourcesTests.cs @@ -116,7 +116,7 @@ public void ControlOrDialog_AllLocales_LanguageNotSetAndAllStrings(Type t) } // The cultures to test - private static CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages + private static readonly CultureInfo[] cultures = CKAN.Utilities.AvailableLanguages .Select(l => new CultureInfo(l)) .ToArray(); } diff --git a/Tests/GUI/ThreadSafetyTests.cs b/Tests/GUI/ThreadSafetyTests.cs index b3afca4769..90528c7a15 100644 --- a/Tests/GUI/ThreadSafetyTests.cs +++ b/Tests/GUI/ThreadSafetyTests.cs @@ -7,14 +7,12 @@ using Mono.Cecil; using Mono.Cecil.Cil; using NUnit.Framework; - -using CKAN.Extensions; using CKAN.GUI.Attributes; namespace Tests.GUI { using MethodCall = List<MethodDefinition>; - using CallsDict = Dictionary<MethodDefinition, List<MethodDefinition>>; + using CallsDict = Dictionary<MethodDefinition, List<MethodDefinition>>; [TestFixture] public class ThreadSafetyTests @@ -46,7 +44,7 @@ public void GUIAssemblyModule_MethodsWithForbidGUICalls_DontCallGUI() } private IEnumerable<TypeDefinition> GetAllNestedTypes(TypeDefinition td) - => Enumerable.Repeat<TypeDefinition>(td, 1) + => Enumerable.Repeat(td, 1) .Concat(td.NestedTypes.SelectMany(nested => GetAllNestedTypes(nested))); private IEnumerable<MethodCall> FindStartedTasks(MethodDefinition md) @@ -137,13 +135,12 @@ private bool unsafeCall(MethodDefinition md) // Any method on a type in WinForms or inheriting from anything in WinForms is presumed unsafe private bool unsafeType(TypeDefinition t) => t.Namespace == winformsNamespace - ? true - : (t.BaseType != null && unsafeType(t.BaseType.Resolve())); + || (t.BaseType != null && unsafeType(t.BaseType.Resolve())); private static readonly Type forbidAttrib = typeof(ForbidGUICallsAttribute); private static readonly string winformsNamespace = typeof(Control).Namespace; - private static HashSet<string> callOpCodes = new HashSet<string> + private static readonly HashSet<string> callOpCodes = new HashSet<string> { // Constructors "newobj", diff --git a/Tests/NetKAN/MainClass.cs b/Tests/NetKAN/MainClass.cs index 1d5c3e4ff6..96cff11cc2 100644 --- a/Tests/NetKAN/MainClass.cs +++ b/Tests/NetKAN/MainClass.cs @@ -11,7 +11,7 @@ namespace Tests.NetKAN [TestFixture] public class MainClassTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void FixVersionStringsUnharmed() @@ -65,9 +65,13 @@ public void Invalid(string json, bool expected_to_throw) { TestDelegate test_delegate = () => new EpochTransformer().Transform(new Metadata(JObject.Parse(json)), opts).First().Json(); if (expected_to_throw) + { Assert.Throws<BadMetadataKraken>(test_delegate); + } else + { Assert.DoesNotThrow(test_delegate); + } } } } diff --git a/Tests/NetKAN/NetkanOverride.cs b/Tests/NetKAN/NetkanOverride.cs index 7d3a8fd875..96fb32a0b7 100644 --- a/Tests/NetKAN/NetkanOverride.cs +++ b/Tests/NetKAN/NetkanOverride.cs @@ -10,8 +10,8 @@ namespace Tests.NetKAN [TestFixture] public class NetkanOverride { - JObject such_metadata; - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private JObject such_metadata; + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [SetUp] public void Setup() @@ -106,10 +106,8 @@ public void RangedOverride(string label, string expected_author, string override [Test] public void DeleteOverride() { - JToken token; - - Assert.IsTrue(such_metadata.TryGetValue("abstract", out token)); - Assert.IsTrue(such_metadata.TryGetValue("author", out token)); + Assert.IsTrue(such_metadata.TryGetValue("abstract", out _)); + Assert.IsTrue(such_metadata.TryGetValue("author", out _)); JObject new_metadata = ProcessOverrides( such_metadata, @@ -119,8 +117,8 @@ public void DeleteOverride() }]"); - Assert.IsFalse(new_metadata.TryGetValue("abstract", out token)); - Assert.IsFalse(new_metadata.TryGetValue("author", out token)); + Assert.IsFalse(new_metadata.TryGetValue("abstract", out _)); + Assert.IsFalse(new_metadata.TryGetValue("author", out _)); } [Test] diff --git a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs index bab6922f44..4b57309123 100644 --- a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs @@ -12,7 +12,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class AvcKrefTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test, TestCase( diff --git a/Tests/NetKAN/Transformers/AvcTransformerTests.cs b/Tests/NetKAN/Transformers/AvcTransformerTests.cs index c383bf2976..90b125d1a1 100644 --- a/Tests/NetKAN/Transformers/AvcTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcTransformerTests.cs @@ -18,8 +18,8 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class AvcTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); - private IGame game = new KerbalSpaceProgram(); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly IGame game = new KerbalSpaceProgram(); [Test] public void AddsMissingVersionInfo() @@ -188,24 +188,36 @@ public void CorrectlyCalculatesGameVersionInfo( json["download"] = "https://awesomemod.example/AwesomeMod.zip"; if (!string.IsNullOrWhiteSpace(existingKsp)) + { json["ksp_version"] = existingKsp; + } if (!string.IsNullOrWhiteSpace(existingKspMin)) + { json["ksp_version_min"] = existingKspMin; + } if (!string.IsNullOrWhiteSpace(existingKspMax)) + { json["ksp_version_max"] = existingKspMax; + } var avcVersion = new AvcVersion(); if (!string.IsNullOrWhiteSpace(avcKsp)) + { avcVersion.ksp_version = GameVersion.Parse(avcKsp); + } if (!string.IsNullOrWhiteSpace(avcKspMin)) + { avcVersion.ksp_version_min = GameVersion.Parse(avcKspMin); + } if (!string.IsNullOrWhiteSpace(avcKspMax)) + { avcVersion.ksp_version_max = GameVersion.Parse(avcKspMax); + } var mHttp = new Mock<IHttpService>(); var mModuleService = new Mock<IModuleService>(); diff --git a/Tests/NetKAN/Transformers/CurseTransformerTests.cs b/Tests/NetKAN/Transformers/CurseTransformerTests.cs index bb68e5ac7f..8bee722a40 100644 --- a/Tests/NetKAN/Transformers/CurseTransformerTests.cs +++ b/Tests/NetKAN/Transformers/CurseTransformerTests.cs @@ -12,7 +12,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class CurseTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); // GH #199: Don't pre-fill KSP version fields if we see a ksp_min/max [Test] @@ -47,10 +47,9 @@ private static CurseMod MakeTestMod() license = "CC-BY", title = "Dogecoin Flag", description = "Such test. Very unit. Wow.", - members = new List<CurseModMember>{ new CurseModMember { username = "pjf" } } + members = new List<CurseModMember> { new CurseModMember { username = "pjf" } }, + files = new List<CurseFile>() { new CurseFile() } }; - - cmod.files = new List<CurseFile>() { new CurseFile() }; cmod.files[0].SetFileVersion("0.25"); cmod.files[0].SetDownloadUrl("http://example.com/download.zip"); diff --git a/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs b/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs index b1322d8d0e..066958148d 100644 --- a/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs +++ b/Tests/NetKAN/Transformers/DownloadAttributeTransformerTests.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using Moq; using Newtonsoft.Json.Linq; @@ -12,7 +11,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class DownloadAttributeTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void AddsDownloadAttributes() diff --git a/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs b/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs index 20c34ccc69..3d22301d53 100644 --- a/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs +++ b/Tests/NetKAN/Transformers/GeneratedByTransformerTests.cs @@ -9,7 +9,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class GeneratedByTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void AddsGeneratedByProperty() diff --git a/Tests/NetKAN/Transformers/HttpTransformerTests.cs b/Tests/NetKAN/Transformers/HttpTransformerTests.cs index 9d52c2a044..d2dba40551 100644 --- a/Tests/NetKAN/Transformers/HttpTransformerTests.cs +++ b/Tests/NetKAN/Transformers/HttpTransformerTests.cs @@ -9,7 +9,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class HttpTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [TestCase("#/ckan/github/foo/bar")] [TestCase("#/ckan/netkan/http://awesomemod.example/awesomemod.netkan")] diff --git a/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs b/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs index cf208e9e47..3ea1b7a6ab 100644 --- a/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs +++ b/Tests/NetKAN/Transformers/InstallSizeTransformerTests.cs @@ -38,6 +38,6 @@ public void Transform_NormalModule_CorrectInstallSize() Assert.AreEqual(52291, (int)transformedJson["install_size"]); } - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); } } diff --git a/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs b/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs index fce69f6b54..25d3cf934b 100644 --- a/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs +++ b/Tests/NetKAN/Transformers/InternalCkanTransformerTests.cs @@ -15,7 +15,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class InternalCkanTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void AddsMissingProperties() diff --git a/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs b/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs index dd4089cf6b..d27f0c9eae 100644 --- a/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs +++ b/Tests/NetKAN/Transformers/MetaNetkanTransformerTests.cs @@ -13,7 +13,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class MetaNetkanTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void DoesNothingWhenNoMatch() diff --git a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs index 2ff71e0214..a348308731 100644 --- a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs +++ b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs @@ -15,7 +15,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class SpacedockTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); // GH #199: Don't pre-fill KSP version fields if we see a ksp_min/max [Test] diff --git a/Tests/NetKAN/Transformers/StripNetkanMetadataTransformerTests.cs b/Tests/NetKAN/Transformers/StripNetkanMetadataTransformerTests.cs index 274726d394..3b1d1f5fa2 100644 --- a/Tests/NetKAN/Transformers/StripNetkanMetadataTransformerTests.cs +++ b/Tests/NetKAN/Transformers/StripNetkanMetadataTransformerTests.cs @@ -10,7 +10,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class StripNetkanMetadataTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [TestCaseSource("StripNetkanMetadataTestCaseSource")] public void StripNetkanMetadata(string json, string expected) @@ -28,6 +28,7 @@ public void StripNetkanMetadata(string json, string expected) Assert.AreEqual(expectedJson, transformedJson); } + #pragma warning disable 0414, IDE0051 private static IEnumerable<object[]> StripNetkanMetadataTestCaseSource { get @@ -120,5 +121,6 @@ private static IEnumerable<object[]> StripNetkanMetadataTestCaseSource }; } } + #pragma warning restore 0414, IDE0051 } } diff --git a/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs b/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs index 067d595eb4..7f7cc4aab6 100644 --- a/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs +++ b/Tests/NetKAN/Transformers/VersionEditTransformerTests.cs @@ -10,7 +10,7 @@ namespace Tests.NetKAN.Transformers [TestFixture] public sealed class VersionEditTransformerTests { - private TransformOptions opts = new TransformOptions(1, null, null, false, null); + private readonly TransformOptions opts = new TransformOptions(1, null, null, false, null); [Test] public void DoesNothingWhenNoMatch() diff --git a/Tests/Util.cs b/Tests/Util.cs index c6c0994d30..dc9d495e1e 100644 --- a/Tests/Util.cs +++ b/Tests/Util.cs @@ -64,7 +64,7 @@ public static void AssertNoAsyncVoidMethods(Assembly assembly) method.Name)) .ToList(); Assert.False(messages.Any(), - "Async void methods found!" + Environment.NewLine + String.Join(Environment.NewLine, messages)); + "Async void methods found!" + Environment.NewLine + string.Join(Environment.NewLine, messages)); } private static IEnumerable<MethodInfo> GetAsyncVoidMethods(this Assembly assembly) @@ -82,7 +82,11 @@ private static IEnumerable<MethodInfo> GetAsyncVoidMethods(this Assembly assembl private static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { - if (assembly == null) throw new ArgumentNullException("assembly"); + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + try { return assembly.GetTypes(); @@ -117,18 +121,24 @@ public static bool CompareFiles(string file1, string file2) { // Determine if the same file was referenced two times. if (file1 == file2) + { return true; + } if (!File.Exists(file1) || !File.Exists(file2)) + { return false; + } using (FileStream fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read), fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read)) { - //// Check the file sizes. If they are not the same, the files + //// Check the file sizes. If they are not the same, the files //// are not the same. if (fs1.Length != fs2.Length) + { return false; + } // Read and compare a byte from each file until either a // non-matching set of bytes is found or until the end of @@ -145,8 +155,8 @@ public static bool CompareFiles(string file1, string file2) // Make sure that file2 has not more bytes than file1. // If not, the files are the same, after all these checks. - return ((file1byte - file2byte) == 0); + return (file1byte - file2byte) == 0; } } } -} \ No newline at end of file +}