diff --git a/RombaSharp/Features/BaseFeature.cs b/RombaSharp/Features/BaseFeature.cs index f58589f3..1b1b5605 100644 --- a/RombaSharp/Features/BaseFeature.cs +++ b/RombaSharp/Features/BaseFeature.cs @@ -9,6 +9,7 @@ using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.Help; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; using Microsoft.Data.Sqlite; @@ -367,13 +368,97 @@ namespace RombaSharp.Features // Other internal variables internal const string _config = "config.xml"; - internal const string _dbSchema = "rombasharp"; internal static string _connectionString; + /// + /// Logging object + /// + protected Logger logger = new Logger(); + public override void ProcessFeatures(Dictionary features) { InitializeConfiguration(); - DatabaseTools.EnsureDatabase(_dbSchema, _db, _connectionString); + EnsureDatabase(_db, _connectionString); + } + + /// + /// Ensure that the databse exists and has the proper schema + /// + /// Name of the databse + /// Connection string for SQLite + public void EnsureDatabase(string db, string connectionString) + { + // Make sure the file exists + if (!File.Exists(db)) + File.Create(db); + + // Open the database connection + SqliteConnection dbc = new SqliteConnection(connectionString); + dbc.Open(); + + // Make sure the database has the correct schema + try + { + string query = @" +CREATE TABLE IF NOT EXISTS crc ( + 'crc' TEXT NOT NULL, + PRIMARY KEY (crc) +)"; + SqliteCommand slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + + query = @" +CREATE TABLE IF NOT EXISTS md5 ( + 'md5' TEXT NOT NULL, + PRIMARY KEY (md5) +)"; + slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + + query = @" +CREATE TABLE IF NOT EXISTS sha1 ( + 'sha1' TEXT NOT NULL, + 'depot' TEXT, + PRIMARY KEY (sha1) +)"; + slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + + query = @" +CREATE TABLE IF NOT EXISTS crcsha1 ( + 'crc' TEXT NOT NULL, + 'sha1' TEXT NOT NULL, + PRIMARY KEY (crc, sha1) +)"; + slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + + query = @" +CREATE TABLE IF NOT EXISTS md5sha1 ( + 'md5' TEXT NOT NULL, + 'sha1' TEXT NOT NULL, + PRIMARY KEY (md5, sha1) +)"; + slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + + query = @" +CREATE TABLE IF NOT EXISTS dat ( + 'hash' TEXT NOT NULL, + PRIMARY KEY (hash) +)"; + slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + slc.Dispose(); + } + catch (Exception ex) + { + logger.Error(ex); + } + finally + { + dbc.Dispose(); + } } #region Helper methods @@ -383,7 +468,7 @@ namespace RombaSharp.Features /// /// List of input strings to check for, presumably file names /// Dictionary of hash/full path for each of the valid DATs - internal static Dictionary GetValidDats(List inputs) + internal Dictionary GetValidDats(List inputs) { // Get a dictionary of filenames that actually exist in the DATRoot, logging which ones are not List datRootDats = Directory.EnumerateFiles(_dats, "*", SearchOption.AllDirectories).ToList(); @@ -399,7 +484,7 @@ namespace RombaSharp.Features } else { - Globals.Logger.Warning($"The file '{input}' could not be found in the DAT root"); + logger.Warning($"The file '{input}' could not be found in the DAT root"); } } @@ -409,7 +494,7 @@ namespace RombaSharp.Features /// /// Initialize the Romba application from XML config /// - private static void InitializeConfiguration() + private void InitializeConfiguration() { // Get default values if they're not written int workers = 4, @@ -604,13 +689,13 @@ namespace RombaSharp.Features /// /// DatFile hash information to add /// Database connection to use - internal static void AddDatToDatabase(Rom dat, SqliteConnection dbc) + internal void AddDatToDatabase(Rom dat, SqliteConnection dbc) { // Get the dat full path string fullpath = Path.Combine(_dats, (dat.Machine.Name == "dats" ? string.Empty : dat.Machine.Name), dat.Name); // Parse the Dat if possible - Globals.Logger.User($"Adding from '{dat.Name}'"); + logger.User($"Adding from '{dat.Name}'"); DatFile tempdat = DatFile.CreateAndParse(fullpath); // If the Dat wasn't empty, add the information @@ -627,7 +712,7 @@ namespace RombaSharp.Features { foreach (DatItem datItem in tempdat.Items[romkey]) { - Globals.Logger.Verbose($"Checking and adding file '{datItem.GetName() ?? string.Empty}'"); + logger.Verbose($"Checking and adding file '{datItem.GetName() ?? string.Empty}'"); if (datItem.ItemType == ItemType.Disk) { diff --git a/RombaSharp/Features/Cancel.cs b/RombaSharp/Features/Cancel.cs index 75ff8048..c6772003 100644 --- a/RombaSharp/Features/Cancel.cs +++ b/RombaSharp/Features/Cancel.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -22,7 +21,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.User("This feature is not yet implemented: cancel"); + logger.User("This feature is not yet implemented: cancel"); } } } diff --git a/RombaSharp/Features/DbStats.cs b/RombaSharp/Features/DbStats.cs index addd3517..1d122b9b 100644 --- a/RombaSharp/Features/DbStats.cs +++ b/RombaSharp/Features/DbStats.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; using Microsoft.Data.Sqlite; @@ -30,22 +29,22 @@ namespace RombaSharp.Features // Total number of CRCs string query = "SELECT COUNT(*) FROM crc"; SqliteCommand slc = new SqliteCommand(query, dbc); - Globals.Logger.User($"Total CRCs: {(long)slc.ExecuteScalar()}"); + logger.User($"Total CRCs: {(long)slc.ExecuteScalar()}"); // Total number of MD5s query = "SELECT COUNT(*) FROM md5"; slc = new SqliteCommand(query, dbc); - Globals.Logger.User($"Total MD5s: {(long)slc.ExecuteScalar()}"); + logger.User($"Total MD5s: {(long)slc.ExecuteScalar()}"); // Total number of SHA1s query = "SELECT COUNT(*) FROM sha1"; slc = new SqliteCommand(query, dbc); - Globals.Logger.User($"Total SHA1s: {(long)slc.ExecuteScalar()}"); + logger.User($"Total SHA1s: {(long)slc.ExecuteScalar()}"); // Total number of DATs query = "SELECT COUNT(*) FROM dat"; slc = new SqliteCommand(query, dbc); - Globals.Logger.User($"Total DATs: {(long)slc.ExecuteScalar()}"); + logger.User($"Total DATs: {(long)slc.ExecuteScalar()}"); slc.Dispose(); dbc.Dispose(); diff --git a/RombaSharp/Features/Diffdat.cs b/RombaSharp/Features/Diffdat.cs index 405e5f1e..d42818e0 100644 --- a/RombaSharp/Features/Diffdat.cs +++ b/RombaSharp/Features/Diffdat.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; -using SabreTools.Library.Filtering; using SabreTools.Library.Help; using SabreTools.Library.IO; @@ -47,13 +45,13 @@ in -old DAT file. Ignores those entries in -old that are not in -new."; // Check that all required files exist if (!File.Exists(olddat)) { - Globals.Logger.Error($"File '{olddat}' does not exist!"); + logger.Error($"File '{olddat}' does not exist!"); return; } if (!File.Exists(newdat)) { - Globals.Logger.Error($"File '{newdat}' does not exist!"); + logger.Error($"File '{newdat}' does not exist!"); return; } diff --git a/RombaSharp/Features/Dir2Dat.cs b/RombaSharp/Features/Dir2Dat.cs index 11fdcc15..28e4bd2e 100644 --- a/RombaSharp/Features/Dir2Dat.cs +++ b/RombaSharp/Features/Dir2Dat.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.Filtering; using SabreTools.Library.Help; @@ -45,7 +44,7 @@ namespace RombaSharp.Features // Check that all required directories exist if (!Directory.Exists(source)) { - Globals.Logger.Error($"File '{source}' does not exist!"); + logger.Error($"File '{source}' does not exist!"); return; } diff --git a/RombaSharp/Features/EDiffdat.cs b/RombaSharp/Features/EDiffdat.cs index 3da7ba99..195a3e20 100644 --- a/RombaSharp/Features/EDiffdat.cs +++ b/RombaSharp/Features/EDiffdat.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; -using SabreTools.Library.Filtering; using SabreTools.Library.Help; using SabreTools.Library.IO; @@ -42,13 +40,13 @@ namespace RombaSharp.Features // Check that all required files exist if (!File.Exists(olddat)) { - Globals.Logger.Error($"File '{olddat}' does not exist!"); + logger.Error($"File '{olddat}' does not exist!"); return; } if (!File.Exists(newdat)) { - Globals.Logger.Error($"File '{newdat}' does not exist!"); + logger.Error($"File '{newdat}' does not exist!"); return; } diff --git a/RombaSharp/Features/Fixdat.cs b/RombaSharp/Features/Fixdat.cs index 548e8361..261b2dd4 100644 --- a/RombaSharp/Features/Fixdat.cs +++ b/RombaSharp/Features/Fixdat.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; +using SabreTools.Library.Logging; namespace RombaSharp.Features { @@ -35,7 +35,7 @@ namespace RombaSharp.Features int workers = GetInt32(features, WorkersInt32Value); string outdat = GetString(features, OutStringValue); - Globals.Logger.Error("This feature is not yet implemented: fixdat"); + logger.Error("This feature is not yet implemented: fixdat"); } } } diff --git a/RombaSharp/Features/Import.cs b/RombaSharp/Features/Import.cs index d52bef84..1a1673ba 100644 --- a/RombaSharp/Features/Import.cs +++ b/RombaSharp/Features/Import.cs @@ -2,9 +2,9 @@ using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.Help; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using Microsoft.Data.Sqlite; namespace RombaSharp.Features @@ -27,7 +27,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.Error("This feature is not yet implemented: import"); + logger.Error("This feature is not yet implemented: import"); // First ensure the inputs and database connection Inputs = DirectoryExtensions.GetFilesOnly(Inputs).Select(p => p.CurrentPath).ToList(); @@ -44,7 +44,7 @@ namespace RombaSharp.Features string line = sr.ReadLine(); if (line != "CRC,MD5,SHA-1") // ,Depot { - Globals.Logger.Error($"{input} is not a valid export file"); + logger.Error($"{input} is not a valid export file"); continue; } diff --git a/RombaSharp/Features/Lookup.cs b/RombaSharp/Features/Lookup.cs index d80bb64c..9c3fc048 100644 --- a/RombaSharp/Features/Lookup.cs +++ b/RombaSharp/Features/Lookup.cs @@ -82,11 +82,11 @@ namespace RombaSharp.Features count++; } - Globals.Logger.User($"For hash '{input}' there were {count} matches in the database"); + logger.User($"For hash '{input}' there were {count} matches in the database"); } else { - Globals.Logger.User($"Hash '{input}' had no matches in the database"); + logger.User($"Hash '{input}' had no matches in the database"); } sldr.Dispose(); @@ -105,11 +105,11 @@ namespace RombaSharp.Features count++; } - Globals.Logger.User($"For hash '{input}' there were {count} matches in the database"); + logger.User($"For hash '{input}' there were {count} matches in the database"); } else { - Globals.Logger.User($"Hash '{input}' had no matches in the database"); + logger.User($"Hash '{input}' had no matches in the database"); } sldr.Dispose(); @@ -128,11 +128,11 @@ namespace RombaSharp.Features count++; } - Globals.Logger.User($"For hash '{input}' there were {count} matches in the database"); + logger.User($"For hash '{input}' there were {count} matches in the database"); } else { - Globals.Logger.User($"Hash '{input}' had no matches in the database"); + logger.User($"Hash '{input}' had no matches in the database"); } sldr.Dispose(); diff --git a/RombaSharp/Features/Memstats.cs b/RombaSharp/Features/Memstats.cs index 672eb23a..201d5f9d 100644 --- a/RombaSharp/Features/Memstats.cs +++ b/RombaSharp/Features/Memstats.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -22,7 +21,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.User("This feature is not yet implemented: memstats"); + logger.User("This feature is not yet implemented: memstats"); } } } diff --git a/RombaSharp/Features/Merge.cs b/RombaSharp/Features/Merge.cs index 733b0bcf..fcbdd97b 100644 --- a/RombaSharp/Features/Merge.cs +++ b/RombaSharp/Features/Merge.cs @@ -2,7 +2,6 @@ using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.Help; using SabreTools.Library.IO; @@ -38,7 +37,7 @@ namespace RombaSharp.Features int workers = GetInt32(features, WorkersInt32Value); string resume = GetString(features, ResumeStringValue); - Globals.Logger.Error("This feature is not yet implemented: merge"); + logger.Error("This feature is not yet implemented: merge"); // Verify that the inputs are valid directories Inputs = DirectoryExtensions.GetDirectoriesOnly(Inputs).Select(p => p.CurrentPath).ToList(); diff --git a/RombaSharp/Features/Miss.cs b/RombaSharp/Features/Miss.cs index a7a058ca..ba9bc1a4 100644 --- a/RombaSharp/Features/Miss.cs +++ b/RombaSharp/Features/Miss.cs @@ -43,7 +43,7 @@ namespace RombaSharp.Features /* ended here */ } - Globals.Logger.Error("This feature is not yet implemented: miss"); + logger.Error("This feature is not yet implemented: miss"); } } } diff --git a/RombaSharp/Features/Progress.cs b/RombaSharp/Features/Progress.cs index a970c042..d9c39957 100644 --- a/RombaSharp/Features/Progress.cs +++ b/RombaSharp/Features/Progress.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -22,7 +21,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.User("This feature is not yet implemented: progress"); + logger.User("This feature is not yet implemented: progress"); } } } diff --git a/RombaSharp/Features/PurgeBackup.cs b/RombaSharp/Features/PurgeBackup.cs index 6b205667..4dc47eac 100644 --- a/RombaSharp/Features/PurgeBackup.cs +++ b/RombaSharp/Features/PurgeBackup.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -40,7 +39,7 @@ structure. It also deletes the specified DATs from the DAT index."; List dats = GetList(features, DatsListStringValue); List depot = GetList(features, DepotListStringValue); - Globals.Logger.Error("This feature is not yet implemented: purge-backup"); + logger.Error("This feature is not yet implemented: purge-backup"); } } } diff --git a/RombaSharp/Features/PurgeDelete.cs b/RombaSharp/Features/PurgeDelete.cs index 151a6429..2ca12d48 100644 --- a/RombaSharp/Features/PurgeDelete.cs +++ b/RombaSharp/Features/PurgeDelete.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -39,7 +38,7 @@ structure. It also deletes the specified DATs from the DAT index."; List dats = GetList(features, DatsListStringValue); List depot = GetList(features, DepotListStringValue); - Globals.Logger.Error("This feature is not yet implemented: purge-delete"); + logger.Error("This feature is not yet implemented: purge-delete"); } } } diff --git a/RombaSharp/Features/RefreshDats.cs b/RombaSharp/Features/RefreshDats.cs index b3690c44..0abd2f89 100644 --- a/RombaSharp/Features/RefreshDats.cs +++ b/RombaSharp/Features/RefreshDats.cs @@ -46,7 +46,7 @@ contents of any changed dats."; // Make sure the file exists if (!File.Exists(_db)) - DatabaseTools.EnsureDatabase(_dbSchema, _db, _connectionString); + EnsureDatabase(_db, _connectionString); // Make sure the dats dir is set if (string.IsNullOrWhiteSpace(_dats)) diff --git a/RombaSharp/Features/RescanDepots.cs b/RombaSharp/Features/RescanDepots.cs index 46dd16d7..ddcb720b 100644 --- a/RombaSharp/Features/RescanDepots.cs +++ b/RombaSharp/Features/RescanDepots.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using Microsoft.Data.Sqlite; @@ -26,21 +25,21 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.Error("This feature is not yet implemented: rescan-depots"); + logger.Error("This feature is not yet implemented: rescan-depots"); foreach (string depotname in Inputs) { // Check that it's a valid depot first if (!_depots.ContainsKey(depotname)) { - Globals.Logger.User($"'{depotname}' is not a recognized depot. Please add it to your configuration file and try again"); + logger.User($"'{depotname}' is not a recognized depot. Please add it to your configuration file and try again"); return; } // Then check that the depot is online if (!Directory.Exists(depotname)) { - Globals.Logger.User($"'{depotname}' does not appear to be online. Please check its status and try again"); + logger.User($"'{depotname}' does not appear to be online. Please check its status and try again"); return; } diff --git a/RombaSharp/Features/Shutdown.cs b/RombaSharp/Features/Shutdown.cs index 4e31479d..ad636f74 100644 --- a/RombaSharp/Features/Shutdown.cs +++ b/RombaSharp/Features/Shutdown.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.Help; namespace RombaSharp.Features @@ -22,7 +21,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.User("This feature is not yet implemented: shutdown"); + logger.User("This feature is not yet implemented: shutdown"); } } } diff --git a/RombaSharp/Features/Version.cs b/RombaSharp/Features/Version.cs index 15e6eafb..df76d8d4 100644 --- a/RombaSharp/Features/Version.cs +++ b/RombaSharp/Features/Version.cs @@ -22,7 +22,7 @@ namespace RombaSharp.Features public override void ProcessFeatures(Dictionary features) { base.ProcessFeatures(features); - Globals.Logger.User($"RombaSharp version: {Constants.Version}"); + logger.User($"RombaSharp version: {Constants.Version}"); } } } diff --git a/RombaSharp/Program.cs b/RombaSharp/Program.cs index 39de014f..54166174 100644 --- a/RombaSharp/Program.cs +++ b/RombaSharp/Program.cs @@ -18,20 +18,31 @@ namespace RombaSharp /// public class Program { + #region Static Variables + + /// + /// Help object that determines available functionality + /// private static Help _help; + /// + /// Logging object + /// + private static Logger logger = new Logger(); + + #endregion + /// /// Entry class for the RombaSharp application /// public static void Main(string[] args) { // Perform initial setup and verification - Globals.Logger = new Logger("romba.log") - { - AppendPrefix = true, - LowestLogLevel = LogLevel.VERBOSE, - ThrowOnError = false, - }; + LoggerImpl.SetFilename("romba.log", true); + LoggerImpl.AppendPrefix = true; + LoggerImpl.LowestLogLevel = LogLevel.VERBOSE; + LoggerImpl.ThrowOnError = false; + LoggerImpl.Start(); // Create a new Help object for this program _help = RetrieveHelp(); @@ -58,7 +69,7 @@ namespace RombaSharp if ((new List(args)).Contains("--credits")) { _help.OutputCredits(); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -66,7 +77,7 @@ namespace RombaSharp if (args.Length == 0) { _help.OutputGenericHelp(); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -76,9 +87,9 @@ namespace RombaSharp // Verify that the flag is valid if (!_help.TopLevelFlag(featureName)) { - Globals.Logger.User($"'{featureName}' is not valid feature flag"); + logger.User($"'{featureName}' is not valid feature flag"); _help.OutputIndividualFeature(featureName); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -92,14 +103,14 @@ namespace RombaSharp if (featureName == DisplayHelp.Value || featureName == DisplayHelpDetailed.Value) { feature.ProcessArgs(args, _help); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } // Now verify that all other flags are valid if (!feature.ProcessArgs(args, _help)) { - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -115,7 +126,7 @@ namespace RombaSharp // Require input verification case Archive.Value: - case Features.Build.Value: + case Build.Value: case DatStats.Value: case Fixdat.Value: case Import.Value: @@ -150,7 +161,7 @@ namespace RombaSharp break; } - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -178,7 +189,7 @@ namespace RombaSharp help.Add(new DisplayHelpDetailed()); help.Add(new Script()); help.Add(new Archive()); - help.Add(new Features.Build()); + help.Add(new Build()); help.Add(new Cancel()); help.Add(new DatStats()); help.Add(new DbStats()); @@ -212,7 +223,7 @@ namespace RombaSharp { if (inputs.Count == 0) { - Globals.Logger.Error("This feature requires at least one input"); + logger.Error("This feature requires at least one input"); _help.OutputIndividualFeature(feature); Environment.Exit(0); } diff --git a/SabreTools.Library/DatFiles/AttractMode.cs b/SabreTools.Library/DatFiles/AttractMode.cs index f696344c..3c52c09e 100644 --- a/SabreTools.Library/DatFiles/AttractMode.cs +++ b/SabreTools.Library/DatFiles/AttractMode.cs @@ -103,7 +103,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {svr.LineNumber} '{svr.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { svr.Dispose(); @@ -132,13 +132,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -177,13 +177,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose($"File written!{Environment.NewLine}"); + logger.Verbose($"File written!{Environment.NewLine}"); svw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/ClrMamePro.cs b/SabreTools.Library/DatFiles/ClrMamePro.cs index 9c6b355a..551db677 100644 --- a/SabreTools.Library/DatFiles/ClrMamePro.cs +++ b/SabreTools.Library/DatFiles/ClrMamePro.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -88,7 +87,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {cmpr.LineNumber} '{cmpr.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { cmpr.Dispose(); @@ -458,13 +457,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -518,13 +517,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(cmpw); - Globals.Logger.Verbose($"File written!{Environment.NewLine}"); + logger.Verbose($"File written!{Environment.NewLine}"); cmpw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/DatFile.cs b/SabreTools.Library/DatFiles/DatFile.cs index 3cc2d64e..6c496685 100644 --- a/SabreTools.Library/DatFiles/DatFile.cs +++ b/SabreTools.Library/DatFiles/DatFile.cs @@ -13,6 +13,7 @@ using SabreTools.Library.DatItems; using SabreTools.Library.FileTypes; using SabreTools.Library.Filtering; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using SabreTools.Library.Reports; using SabreTools.Library.Skippers; using SabreTools.Library.Tools; @@ -32,19 +33,27 @@ namespace SabreTools.Library.DatFiles /// /// Header values /// - [JsonProperty("header")] - [XmlElement("header")] + [JsonProperty("header"), XmlElement("header")] public DatHeader Header { get; set; } = new DatHeader(); /// /// DatItems and related statistics /// - [JsonProperty("items")] - [XmlElement("items")] + [JsonProperty("items"), XmlElement("items")] public ItemDictionary Items { get; set; } = new ItemDictionary(); #endregion + #region Logging + + /// + /// Logging object + /// + [JsonIgnore, XmlIgnore] + protected Logger logger = new Logger(); + + #endregion + #region Constructors /// @@ -242,7 +251,7 @@ namespace SabreTools.Library.DatFiles /// True if descriptions should only be replaced if the game name is the same, false otherwise public void BaseReplace(DatFile intDat, List updateFields, bool onlySame) { - Globals.Logger.User($"Replacing items in '{intDat.Header.FileName}' from the base DAT"); + logger.User($"Replacing items in '{intDat.Header.FileName}' from the base DAT"); // If we are matching based on DatItem fields of any sort if (updateFields.Intersect(DatItem.DatItemFields).Any()) @@ -315,7 +324,7 @@ namespace SabreTools.Library.DatFiles else Items.BucketBy(Field.DatItem_CRC, DedupeType.None); - Globals.Logger.User($"Comparing '{intDat.Header.FileName}' to base DAT"); + logger.User($"Comparing '{intDat.Header.FileName}' to base DAT"); // For comparison's sake, we want to a the base bucketing if (useGames) @@ -682,7 +691,7 @@ namespace SabreTools.Library.DatFiles Parallel.For(0, inputs.Count, Globals.ParallelOptions, i => { var input = inputs[i]; - Globals.Logger.User($"Adding DAT: {input.CurrentPath}"); + logger.User($"Adding DAT: {input.CurrentPath}"); datFiles[i] = Create(Header.CloneFiltering()); datFiles[i].Parse(input, i, keep: true); }); @@ -752,7 +761,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } @@ -813,7 +822,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } @@ -886,7 +895,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } @@ -934,7 +943,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } @@ -1055,7 +1064,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex.ToString()); + logger.Warning(ex.ToString()); if (throwOnError) throw ex; } } @@ -1174,7 +1183,7 @@ namespace SabreTools.Library.DatFiles fields = new List(); // Output the logging statement - Globals.Logger.User("Removing filtered fields"); + logger.User("Removing filtered fields"); // Now process all of the roms Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => @@ -1196,7 +1205,7 @@ namespace SabreTools.Library.DatFiles public void StripSceneDatesFromItems() { // Output the logging statement - Globals.Logger.User("Stripping scene-style dates"); + logger.User("Stripping scene-style dates"); // Set the regex pattern to use string pattern = @"([0-9]{2}\.[0-9]{2}\.[0-9]{2}-)(.*?-.*?)"; @@ -1238,7 +1247,7 @@ namespace SabreTools.Library.DatFiles /// Dedupe type to be used private void CreateDeviceNonMergedSets(DedupeType mergeroms) { - Globals.Logger.User("Creating device non-merged sets from the DAT"); + logger.User("Creating device non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); @@ -1257,7 +1266,7 @@ namespace SabreTools.Library.DatFiles /// Dedupe type to be used private void CreateFullyNonMergedSets(DedupeType mergeroms) { - Globals.Logger.User("Creating fully non-merged sets from the DAT"); + logger.User("Creating fully non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); @@ -1280,7 +1289,7 @@ namespace SabreTools.Library.DatFiles /// Dedupe type to be used private void CreateMergedSets(DedupeType mergeroms) { - Globals.Logger.User("Creating merged sets from the DAT"); + logger.User("Creating merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); @@ -1302,7 +1311,7 @@ namespace SabreTools.Library.DatFiles /// Dedupe type to be used private void CreateNonMergedSets(DedupeType mergeroms) { - Globals.Logger.User("Creating non-merged sets from the DAT"); + logger.User("Creating non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); @@ -1324,7 +1333,7 @@ namespace SabreTools.Library.DatFiles /// Dedupe type to be used private void CreateSplitSets(DedupeType mergeroms) { - Globals.Logger.User("Creating split sets from the DAT"); + logger.User("Creating split sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); @@ -1868,7 +1877,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex, $"Error with file '{currentPath}'"); + logger.Error(ex, $"Error with file '{currentPath}'"); if (throwOnError) throw ex; } } @@ -1892,7 +1901,7 @@ namespace SabreTools.Library.DatFiles && string.IsNullOrWhiteSpace(disk.MD5) && string.IsNullOrWhiteSpace(disk.SHA1)) { - Globals.Logger.Verbose($"Incomplete entry for '{disk.Name}' will be output as nodump"); + logger.Verbose($"Incomplete entry for '{disk.Name}' will be output as nodump"); disk.ItemStatus = ItemStatus.Nodump; } @@ -1906,7 +1915,7 @@ namespace SabreTools.Library.DatFiles if (rom.Size == null && !rom.HasHashes()) { // No-op, just catch it so it doesn't go further - Globals.Logger.Verbose($"{Header.FileName}: Entry with only SHA-1 found - '{rom.Name}'"); + logger.Verbose($"{Header.FileName}: Entry with only SHA-1 found - '{rom.Name}'"); } // If we have a rom and it's missing size AND the hashes match a 0-byte file, fill in the rest of the info @@ -1930,7 +1939,7 @@ namespace SabreTools.Library.DatFiles // If the file has no size and it's not the above case, skip and log else if (rom.ItemStatus != ItemStatus.Nodump && (rom.Size == 0 || rom.Size == null)) { - Globals.Logger.Verbose($"{Header.FileName}: Incomplete entry for '{rom.Name}' will be output as nodump"); + logger.Verbose($"{Header.FileName}: Incomplete entry for '{rom.Name}' will be output as nodump"); rom.ItemStatus = ItemStatus.Nodump; } @@ -1939,7 +1948,7 @@ namespace SabreTools.Library.DatFiles && rom.Size != null && rom.Size > 0 && !rom.HasHashes()) { - Globals.Logger.Verbose($"{Header.FileName}: Incomplete entry for '{rom.Name}' will be output as nodump"); + logger.Verbose($"{Header.FileName}: Incomplete entry for '{rom.Name}' will be output as nodump"); rom.ItemStatus = ItemStatus.Nodump; } @@ -1988,7 +1997,7 @@ namespace SabreTools.Library.DatFiles // Process the input if (Directory.Exists(basePath)) { - Globals.Logger.Verbose($"Folder found: {basePath}"); + logger.Verbose($"Folder found: {basePath}"); // Process the files in the main folder or any subfolder List files = Directory.EnumerateFiles(basePath, "*", SearchOption.AllDirectories).ToList(); @@ -2008,7 +2017,7 @@ namespace SabreTools.Library.DatFiles } // Now that we're done, delete the temp folder (if it's not the default) - Globals.Logger.User("Cleaning temp folder"); + logger.User("Cleaning temp folder"); if (Globals.TempDir != Path.GetTempPath()) DirectoryExtensions.TryDelete(Globals.TempDir); @@ -2106,11 +2115,11 @@ namespace SabreTools.Library.DatFiles // Add the list if it doesn't exist already Rom rom = new Rom(baseFile); Items.Add(rom.GetKey(Field.DatItem_CRC), rom); - Globals.Logger.User($"File added: {Path.GetFileNameWithoutExtension(item)}{Environment.NewLine}"); + logger.User($"File added: {Path.GetFileNameWithoutExtension(item)}{Environment.NewLine}"); } else { - Globals.Logger.User($"File not added: {Path.GetFileNameWithoutExtension(item)}{Environment.NewLine}"); + logger.User($"File not added: {Path.GetFileNameWithoutExtension(item)}{Environment.NewLine}"); return true; } @@ -2199,7 +2208,7 @@ namespace SabreTools.Library.DatFiles gamename = gamename.Trim(Path.DirectorySeparatorChar); romname = romname.Trim(Path.DirectorySeparatorChar); - Globals.Logger.Verbose($"Adding blank empty folder: {gamename}"); + logger.Verbose($"Adding blank empty folder: {gamename}"); Items["null"].Add(new Rom(romname, gamename)); }); } @@ -2213,7 +2222,7 @@ namespace SabreTools.Library.DatFiles /// TreatAsFiles representing CHD and Archive scanning private void ProcessFile(string item, string basePath, Hash hashes, TreatAsFile asFiles) { - Globals.Logger.Verbose($"'{Path.GetFileName(item)}' treated like a file"); + logger.Verbose($"'{Path.GetFileName(item)}' treated like a file"); BaseFile baseFile = FileExtensions.GetInfo(item, header: Header.HeaderSkipper, hashes: hashes, asFiles: asFiles); DatItem datItem = DatItem.Create(baseFile); ProcessFileHelper(item, datItem, basePath, string.Empty); @@ -2249,11 +2258,11 @@ namespace SabreTools.Library.DatFiles string key = datItem.GetKey(Field.DatItem_CRC); Items.Add(key, datItem); - Globals.Logger.User($"File added: {datItem.GetName() ?? string.Empty}{Environment.NewLine}"); + logger.User($"File added: {datItem.GetName() ?? string.Empty}{Environment.NewLine}"); } catch (IOException ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return; } } @@ -2372,7 +2381,7 @@ namespace SabreTools.Library.DatFiles // If the DAT is not populated and inverse is not set, inform the user and quit if (Items.TotalCount == 0 && !inverse) { - Globals.Logger.User("No entries were found to rebuild, exiting..."); + logger.User("No entries were found to rebuild, exiting..."); return false; } @@ -2402,7 +2411,7 @@ namespace SabreTools.Library.DatFiles // Add to the list if the input is a directory if (Directory.Exists(input)) { - Globals.Logger.Verbose($"Adding depot: {input}"); + logger.Verbose($"Adding depot: {input}"); lock (directories) { directories.Add(input); @@ -2425,7 +2434,7 @@ namespace SabreTools.Library.DatFiles if (hash.Length != Constants.SHA1Length) continue; - Globals.Logger.User($"Checking hash '{hash}'"); + logger.User($"Checking hash '{hash}'"); // Get the extension path for the hash string subpath = PathExtensions.GetDepotPath(hash, Header.InputDepot.Depth); @@ -2508,7 +2517,7 @@ namespace SabreTools.Library.DatFiles // If the DAT is not populated and inverse is not set, inform the user and quit if (Items.TotalCount == 0 && !inverse) { - Globals.Logger.User("No entries were found to rebuild, exiting..."); + logger.User("No entries were found to rebuild, exiting..."); return false; } @@ -2541,7 +2550,7 @@ namespace SabreTools.Library.DatFiles // If the input is a file if (File.Exists(input)) { - Globals.Logger.User($"Checking file: {input}"); + logger.User($"Checking file: {input}"); bool rebuilt = RebuildGenericHelper(input, outDir, quickScan, date, inverse, outputFormat, asFiles); // If we are supposed to delete the file, do so @@ -2552,10 +2561,10 @@ namespace SabreTools.Library.DatFiles // If the input is a directory else if (Directory.Exists(input)) { - Globals.Logger.Verbose($"Checking directory: {input}"); + logger.Verbose($"Checking directory: {input}"); foreach (string file in Directory.EnumerateFiles(input, "*", SearchOption.AllDirectories)) { - Globals.Logger.User($"Checking file: {file}"); + logger.User($"Checking file: {file}"); bool rebuilt = RebuildGenericHelper(file, outDir, quickScan, date, inverse, outputFormat, asFiles); // If we are supposed to delete the file, do so @@ -2701,7 +2710,7 @@ namespace SabreTools.Library.DatFiles if (RebuildTorrentXz(datItem, file, outDir, outputFormat, isZip)) return true; - Globals.Logger.User($"{(inverse ? "No matches" : "Matches")} found for '{Path.GetFileName(datItem.GetName() ?? datItem.ItemType.ToString())}', rebuilding accordingly..."); + logger.User($"{(inverse ? "No matches" : "Matches")} found for '{Path.GetFileName(datItem.GetName() ?? datItem.ItemType.ToString())}', rebuilding accordingly..."); rebuilt = true; // Special case for partial packing mode @@ -2751,7 +2760,7 @@ namespace SabreTools.Library.DatFiles // If we have duplicates and we're not filtering if (ShouldRebuild(headerless, transformStream, false, out dupes)) { - Globals.Logger.User($"Headerless matches found for '{Path.GetFileName(datItem.GetName() ?? datItem.ItemType.ToString())}', rebuilding accordingly..."); + logger.User($"Headerless matches found for '{Path.GetFileName(datItem.GetName() ?? datItem.ItemType.ToString())}', rebuilding accordingly..."); rebuilt = true; // Now loop through the list and rebuild accordingly @@ -2856,7 +2865,7 @@ namespace SabreTools.Library.DatFiles BaseFile tgzRom = tgz.GetTorrentGZFileInfo(); if (isZip == false && tgzRom != null && (outputFormat == OutputFormat.TorrentGzip || outputFormat == OutputFormat.TorrentGzipRomba)) { - Globals.Logger.User($"Matches found for '{Path.GetFileName(datItem.GetName() ?? string.Empty)}', rebuilding accordingly..."); + logger.User($"Matches found for '{Path.GetFileName(datItem.GetName() ?? string.Empty)}', rebuilding accordingly..."); // Get the proper output path string sha1 = (datItem as Rom).SHA1 ?? string.Empty; @@ -2899,7 +2908,7 @@ namespace SabreTools.Library.DatFiles BaseFile txzRom = txz.GetTorrentXZFileInfo(); if (isZip == false && txzRom != null && (outputFormat == OutputFormat.TorrentXZ || outputFormat == OutputFormat.TorrentXZRomba)) { - Globals.Logger.User($"Matches found for '{Path.GetFileName(datItem.GetName() ?? string.Empty)}', rebuilding accordingly..."); + logger.User($"Matches found for '{Path.GetFileName(datItem.GetName() ?? string.Empty)}', rebuilding accordingly..."); // Get the proper output path string sha1 = (datItem as Rom).SHA1 ?? string.Empty; @@ -3002,7 +3011,7 @@ namespace SabreTools.Library.DatFiles // Add to the list if the input is a directory if (Directory.Exists(input)) { - Globals.Logger.Verbose($"Adding depot: {input}"); + logger.Verbose($"Adding depot: {input}"); directories.Add(input); } } @@ -3022,7 +3031,7 @@ namespace SabreTools.Library.DatFiles if (hash.Length != Constants.SHA1Length) continue; - Globals.Logger.User($"Checking hash '{hash}'"); + logger.User($"Checking hash '{hash}'"); // Get the extension path for the hash string subpath = PathExtensions.GetDepotPath(hash, Header.InputDepot.Depth); @@ -3175,7 +3184,7 @@ namespace SabreTools.Library.DatFiles public Dictionary SplitByHash() { // Create each of the respective output DATs - Globals.Logger.User("Creating and populating new DATs"); + logger.User("Creating and populating new DATs"); // Create the set of field-to-dat mappings Dictionary fieldDats = new Dictionary(); @@ -3406,7 +3415,7 @@ namespace SabreTools.Library.DatFiles public (DatFile lessThan, DatFile greaterThan) SplitBySize(long radix) { // Create each of the respective output DATs - Globals.Logger.User("Creating and populating new DATs"); + logger.User("Creating and populating new DATs"); DatFile lessThan = Create(Header.CloneStandard()); lessThan.Header.FileName += $" (less than {radix})"; @@ -3453,7 +3462,7 @@ namespace SabreTools.Library.DatFiles public Dictionary SplitByType() { // Create each of the respective output DATs - Globals.Logger.User("Creating and populating new DATs"); + logger.User("Creating and populating new DATs"); // Create the set of type-to-dat mappings Dictionary typeDats = new Dictionary(); @@ -3508,7 +3517,7 @@ namespace SabreTools.Library.DatFiles // If we have nothing writable, abort if (!HasWritable()) { - Globals.Logger.User("There were no items to write out!"); + logger.User("There were no items to write out!"); return false; } @@ -3518,7 +3527,7 @@ namespace SabreTools.Library.DatFiles // If the DAT has no output format, default to XML if (Header.DatFormat == 0) { - Globals.Logger.Verbose("No DAT format defined, defaulting to XML"); + logger.Verbose("No DAT format defined, defaulting to XML"); Header.DatFormat = DatFormat.Logiqx; } @@ -3529,7 +3538,7 @@ namespace SabreTools.Library.DatFiles Items.BucketBy(Field.Machine_Name, DedupeType.None); // Output the number of items we're going to be writing - Globals.Logger.User($"A total of {Items.TotalCount - Items.RemovedCount} items will be written out to '{Header.FileName}'"); + logger.User($"A total of {Items.TotalCount - Items.RemovedCount} items will be written out to '{Header.FileName}'"); // Get the outfile names Dictionary outfiles = Header.CreateOutFileNames(outDir, overwrite); @@ -3546,7 +3555,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex, $"Datfile {outfile} could not be written out"); + logger.Error(ex, $"Datfile {outfile} could not be written out"); if (throwOnError) throw ex; } @@ -3554,7 +3563,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } @@ -3774,7 +3783,7 @@ namespace SabreTools.Library.DatFiles // If the Rom has "null" characteristics, ensure all fields if (rom.Size == null && rom.CRC == "null") { - Globals.Logger.Verbose($"Empty folder found: {datItem.Machine.Name}"); + logger.Verbose($"Empty folder found: {datItem.Machine.Name}"); rom.Name = (rom.Name == "null" ? "-" : rom.Name); rom.Size = Constants.SizeZero; diff --git a/SabreTools.Library/DatFiles/DosCenter.cs b/SabreTools.Library/DatFiles/DosCenter.cs index 682ae61d..d1036b56 100644 --- a/SabreTools.Library/DatFiles/DosCenter.cs +++ b/SabreTools.Library/DatFiles/DosCenter.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -71,7 +70,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {cmpr.LineNumber} '{cmpr.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { cmpr.Dispose(); @@ -277,13 +276,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -339,13 +338,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(cmpw); - Globals.Logger.Verbose($"File written!{Environment.NewLine}"); + logger.Verbose($"File written!{Environment.NewLine}"); cmpw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/EverdriveSmdb.cs b/SabreTools.Library/DatFiles/EverdriveSmdb.cs index 503d1a0e..f9fc3792 100644 --- a/SabreTools.Library/DatFiles/EverdriveSmdb.cs +++ b/SabreTools.Library/DatFiles/EverdriveSmdb.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -86,7 +85,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {svr.LineNumber} '{svr.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { svr.Dispose(); @@ -115,13 +114,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -157,13 +156,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose($"File written!{Environment.NewLine}"); + logger.Verbose($"File written!{Environment.NewLine}"); svw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/Hashfile.cs b/SabreTools.Library/DatFiles/Hashfile.cs index 488df195..b26ee1bd 100644 --- a/SabreTools.Library/DatFiles/Hashfile.cs +++ b/SabreTools.Library/DatFiles/Hashfile.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -99,7 +98,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing at position {sr.BaseStream.Position}"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { sr.Dispose(); @@ -128,13 +127,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -170,13 +169,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose($"File written!{Environment.NewLine}"); + logger.Verbose($"File written!{Environment.NewLine}"); svw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/ItemDictionary.cs b/SabreTools.Library/DatFiles/ItemDictionary.cs index da1e1595..76bd0274 100644 --- a/SabreTools.Library/DatFiles/ItemDictionary.cs +++ b/SabreTools.Library/DatFiles/ItemDictionary.cs @@ -11,6 +11,7 @@ using System.Xml.Serialization; using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using SabreTools.Library.Reports; using NaturalSort; using Newtonsoft.Json; @@ -45,6 +46,11 @@ namespace SabreTools.Library.DatFiles /// private object statsLock = new object(); + /// + /// Logging object + /// + private static Logger logger = new Logger(); + #endregion #region Publically available fields @@ -968,7 +974,7 @@ namespace SabreTools.Library.DatFiles // If the sorted type isn't the same, we want to sort the dictionary accordingly if (bucketedBy != bucketBy) { - Globals.Logger.User($"Organizing roms by {bucketBy}"); + logger.User($"Organizing roms by {bucketBy}"); // Set the sorted type bucketedBy = bucketBy; @@ -1010,7 +1016,7 @@ namespace SabreTools.Library.DatFiles // If the merge type isn't the same, we want to merge the dictionary accordingly if (mergedBy != dedupeType) { - Globals.Logger.User($"Deduping roms by {dedupeType}"); + logger.User($"Deduping roms by {dedupeType}"); // Set the sorted type mergedBy = dedupeType; @@ -1411,13 +1417,13 @@ namespace SabreTools.Library.DatFiles dirStats.ResetStatistics(); } - Globals.Logger.Verbose($"Beginning stat collection for '{file.CurrentPath}'"); + logger.Verbose($"Beginning stat collection for '{file.CurrentPath}'"); List games = new List(); DatFile datdata = DatFile.CreateAndParse(file.CurrentPath); datdata.Items.BucketBy(Field.Machine_Name, DedupeType.None, norename: true); // Output single DAT stats (if asked) - Globals.Logger.User($"Adding stats for file '{file.CurrentPath}'\n"); + logger.User($"Adding stats for file '{file.CurrentPath}'\n"); if (single) { reports.ForEach(report => report.ReplaceStatistics(datdata.Header.FileName, datdata.Items.Keys.Count, datdata.Items)); @@ -1461,7 +1467,7 @@ namespace SabreTools.Library.DatFiles // Output footer if needed reports.ForEach(report => report.WriteFooter()); - Globals.Logger.User($"{Environment.NewLine}Please check the log folder if the stats scrolled offscreen"); + logger.User($"{Environment.NewLine}Please check the log folder if the stats scrolled offscreen"); } /// diff --git a/SabreTools.Library/DatFiles/Listrom.cs b/SabreTools.Library/DatFiles/Listrom.cs index 316713b9..7596faf2 100644 --- a/SabreTools.Library/DatFiles/Listrom.cs +++ b/SabreTools.Library/DatFiles/Listrom.cs @@ -4,7 +4,6 @@ using System.IO; using System.Text; using System.Text.RegularExpressions; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -90,7 +89,7 @@ namespace SabreTools.Library.DatFiles // If the split is still unsuccessful, log it and skip if (split.Length == 1) - Globals.Logger.Warning($"Possibly malformed line: '{line}'"); + logger.Warning($"Possibly malformed line: '{line}'"); string romname = split[0]; line = line.Substring(romname.Length); @@ -246,14 +245,14 @@ namespace SabreTools.Library.DatFiles // If we have something else, it's invalid else { - Globals.Logger.Warning($"Invalid line detected: '{romname} {line}'"); + logger.Warning($"Invalid line detected: '{romname} {line}'"); } } } catch (Exception ex) { string message = $"'{filename}' - There was an error parsing at position {sr.BaseStream.Position}"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { sr.Dispose(); @@ -280,13 +279,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -331,13 +330,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); sw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/Listxml.cs b/SabreTools.Library/DatFiles/Listxml.cs index f837cb45..3d5fba91 100644 --- a/SabreTools.Library/DatFiles/Listxml.cs +++ b/SabreTools.Library/DatFiles/Listxml.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Text; using System.Xml; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -90,7 +89,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -1169,13 +1168,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -1231,13 +1230,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/Logiqx.cs b/SabreTools.Library/DatFiles/Logiqx.cs index 78feea27..7d62d97a 100644 --- a/SabreTools.Library/DatFiles/Logiqx.cs +++ b/SabreTools.Library/DatFiles/Logiqx.cs @@ -6,7 +6,6 @@ using System.Text; using System.Text.RegularExpressions; using System.Xml; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -70,8 +69,8 @@ namespace SabreTools.Library.DatFiles { // The datafile tag can have some attributes case "datafile": - Header.Build = (Header.Build == null ? xtr.GetAttribute("build") : Header.Build); - Header.Debug = (Header.Debug == null ? xtr.GetAttribute("debug").AsYesNo() : Header.Debug); + Header.Build = Header.Build ?? xtr.GetAttribute("build"); + Header.Debug = Header.Debug ?? xtr.GetAttribute("debug").AsYesNo(); xtr.Read(); break; @@ -107,7 +106,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -688,13 +687,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -750,13 +749,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/Missfile.cs b/SabreTools.Library/DatFiles/Missfile.cs index b18e7e61..b33a9080 100644 --- a/SabreTools.Library/DatFiles/Missfile.cs +++ b/SabreTools.Library/DatFiles/Missfile.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -47,13 +46,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -90,13 +89,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); sw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/OfflineList.cs b/SabreTools.Library/DatFiles/OfflineList.cs index a501d426..81c10f2e 100644 --- a/SabreTools.Library/DatFiles/OfflineList.cs +++ b/SabreTools.Library/DatFiles/OfflineList.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; using System.Xml; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -78,7 +76,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -675,13 +673,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -729,13 +727,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/OpenMSX.cs b/SabreTools.Library/DatFiles/OpenMSX.cs index 74e220c0..0537bd3e 100644 --- a/SabreTools.Library/DatFiles/OpenMSX.cs +++ b/SabreTools.Library/DatFiles/OpenMSX.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; using System.Xml; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -80,7 +78,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -529,13 +527,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -591,13 +589,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/RomCenter.cs b/SabreTools.Library/DatFiles/RomCenter.cs index c432797e..26987d79 100644 --- a/SabreTools.Library/DatFiles/RomCenter.cs +++ b/SabreTools.Library/DatFiles/RomCenter.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -85,7 +84,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {ir.LineNumber} '{ir.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { ir.Dispose(); @@ -129,37 +128,37 @@ namespace SabreTools.Library.DatFiles switch (kvp?.Key.ToLowerInvariant()) { case "author": - Header.Author = Header.Author == null ? kvp?.Value : Header.Author; + Header.Author = Header.Author ?? kvp?.Value; reader.ReadNextLine(); break; case "version": - Header.Version = Header.Version == null ? kvp?.Value : Header.Version; + Header.Version = Header.Version ?? kvp?.Value; reader.ReadNextLine(); break; case "email": - Header.Email = Header.Email == null ? kvp?.Value : Header.Email; + Header.Email = Header.Email ?? kvp?.Value; reader.ReadNextLine(); break; case "homepage": - Header.Homepage = Header.Homepage == null ? kvp?.Value : Header.Homepage; + Header.Homepage = Header.Homepage ?? kvp?.Value; reader.ReadNextLine(); break; case "url": - Header.Url = Header.Url == null ? kvp?.Value : Header.Url; + Header.Url = Header.Url ?? kvp?.Value; reader.ReadNextLine(); break; case "date": - Header.Date = Header.Date == null ? kvp?.Value : Header.Date; + Header.Date = Header.Date ?? kvp?.Value; reader.ReadNextLine(); break; case "comment": - Header.Comment = Header.Comment == null ? kvp?.Value : Header.Comment; + Header.Comment = Header.Comment ?? kvp?.Value; reader.ReadNextLine(); break; @@ -204,7 +203,7 @@ namespace SabreTools.Library.DatFiles switch (kvp?.Key.ToLowerInvariant()) { case "version": - Header.RomCenterVersion = (Header.RomCenterVersion == null ? kvp?.Value : Header.RomCenterVersion); + Header.RomCenterVersion = Header.RomCenterVersion ?? (kvp?.Value); reader.ReadNextLine(); break; @@ -383,13 +382,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -430,13 +429,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); iw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/SabreJSON.cs b/SabreTools.Library/DatFiles/SabreJSON.cs index 1ee6e94e..99e0c47f 100644 --- a/SabreTools.Library/DatFiles/SabreJSON.cs +++ b/SabreTools.Library/DatFiles/SabreJSON.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -78,7 +77,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning($"Exception found while parsing '{filename}': {ex}"); + logger.Warning($"Exception found while parsing '{filename}': {ex}"); if (throwOnError) throw ex; } @@ -342,13 +341,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -405,13 +404,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(jtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); jtw.Close(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/SabreXML.cs b/SabreTools.Library/DatFiles/SabreXML.cs index 4dafb49e..4dab691f 100644 --- a/SabreTools.Library/DatFiles/SabreXML.cs +++ b/SabreTools.Library/DatFiles/SabreXML.cs @@ -5,7 +5,6 @@ using System.Text; using System.Xml; using System.Xml.Serialization; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -77,7 +76,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -190,13 +189,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -252,13 +251,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/SeparatedValue.cs b/SabreTools.Library/DatFiles/SeparatedValue.cs index 431b1220..a0ded5d2 100644 --- a/SabreTools.Library/DatFiles/SeparatedValue.cs +++ b/SabreTools.Library/DatFiles/SeparatedValue.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -91,7 +90,7 @@ namespace SabreTools.Library.DatFiles catch (Exception ex) { string message = $"'{filename}' - There was an error parsing line {svr.LineNumber} '{svr.CurrentLine}'"; - Globals.Logger.Error(ex, message); + logger.Error(ex, message); if (throwOnError) { svr.Dispose(); @@ -120,13 +119,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -165,13 +164,13 @@ namespace SabreTools.Library.DatFiles } } - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); svw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatFiles/SoftwareList.cs b/SabreTools.Library/DatFiles/SoftwareList.cs index 1b465821..01127abb 100644 --- a/SabreTools.Library/DatFiles/SoftwareList.cs +++ b/SabreTools.Library/DatFiles/SoftwareList.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Text; using System.Xml; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; using SabreTools.Library.Tools; @@ -81,7 +80,7 @@ namespace SabreTools.Library.DatFiles } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{filename}'"); + logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); @@ -530,13 +529,13 @@ namespace SabreTools.Library.DatFiles { try { - Globals.Logger.User($"Opening file for writing: {outfile}"); + logger.User($"Opening file for writing: {outfile}"); FileStream fs = FileExtensions.TryCreate(outfile); // If we get back null for some reason, just log and return if (fs == null) { - Globals.Logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); + logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return false; } @@ -592,13 +591,13 @@ namespace SabreTools.Library.DatFiles // Write the file footer out WriteFooter(xtw); - Globals.Logger.Verbose("File written!" + Environment.NewLine); + logger.Verbose("File written!" + Environment.NewLine); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); if (throwOnError) throw ex; return false; } diff --git a/SabreTools.Library/DatItems/DatItem.cs b/SabreTools.Library/DatItems/DatItem.cs index eff0b372..a89836c5 100644 --- a/SabreTools.Library/DatItems/DatItem.cs +++ b/SabreTools.Library/DatItems/DatItem.cs @@ -7,6 +7,7 @@ using System.Xml.Serialization; using SabreTools.Library.Data; using SabreTools.Library.FileTypes; using SabreTools.Library.Filtering; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; using NaturalSort; using Newtonsoft.Json; @@ -371,6 +372,16 @@ namespace SabreTools.Library.DatItems #endregion + #endregion + + #region Logging + + /// + /// Logging object + /// + [JsonIgnore, XmlIgnore] + protected static Logger logger = new Logger(); + #endregion #region Instance Methods @@ -1016,14 +1027,14 @@ namespace SabreTools.Library.DatItems // If the current item exactly matches the last item, then we don't add it if (datItem.GetDuplicateStatus(lastItem).HasFlag(DupeType.All)) { - Globals.Logger.Verbose($"Exact duplicate found for '{datItemName}'"); + logger.Verbose($"Exact duplicate found for '{datItemName}'"); continue; } // If the current name matches the previous name, rename the current item else if (datItemName == lastItemName) { - Globals.Logger.Verbose($"Name duplicate found for '{datItemName}'"); + logger.Verbose($"Name duplicate found for '{datItemName}'"); if (datItem.ItemType == ItemType.Disk || datItem.ItemType == ItemType.Media || datItem.ItemType == ItemType.Rom) { diff --git a/SabreTools.Library/Data/Constants.cs b/SabreTools.Library/Data/Constants.cs index 44bb18be..94f6fd12 100644 --- a/SabreTools.Library/Data/Constants.cs +++ b/SabreTools.Library/Data/Constants.cs @@ -112,7 +112,6 @@ namespace SabreTools.Library.Data #region Database schema - public const string HeadererDbSchema = "Headerer"; public static string HeadererFileName = Path.Combine(Globals.ExeDir, "Headerer.sqlite"); public static string HeadererConnectionString = $"Data Source={HeadererFileName};Version = 3;"; diff --git a/SabreTools.Library/Data/Globals.cs b/SabreTools.Library/Data/Globals.cs index 09fb72a0..df74f2f7 100644 --- a/SabreTools.Library/Data/Globals.cs +++ b/SabreTools.Library/Data/Globals.cs @@ -12,12 +12,6 @@ namespace SabreTools.Library.Data /// public class Globals { - #region Private implementations - - private static Logger _logger = null; - - #endregion - #region Public accessors /// @@ -35,21 +29,6 @@ namespace SabreTools.Library.Data /// public static string ExeName => new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath; - /// - /// Logging object for writing to file and console - /// - public static Logger Logger - { - get - { - if (_logger == null) - _logger = new Logger(); - - return _logger; - } - set { _logger = value; } - } - /// /// Maximum threads to use during parallel operations /// diff --git a/SabreTools.Library/FileTypes/BaseArchive.cs b/SabreTools.Library/FileTypes/BaseArchive.cs index 489a21d9..69fedfd6 100644 --- a/SabreTools.Library/FileTypes/BaseArchive.cs +++ b/SabreTools.Library/FileTypes/BaseArchive.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; +using SabreTools.Library.Logging; namespace SabreTools.Library.FileTypes { @@ -63,7 +63,7 @@ namespace SabreTools.Library.FileTypes return archive; // Create the archive based on the type - Globals.Logger.Verbose($"Found archive of type: {at}"); + logger.Verbose($"Found archive of type: {at}"); switch (at) { case FileType.GZipArchive: diff --git a/SabreTools.Library/FileTypes/Folder.cs b/SabreTools.Library/FileTypes/Folder.cs index d509ba66..82a324e0 100644 --- a/SabreTools.Library/FileTypes/Folder.cs +++ b/SabreTools.Library/FileTypes/Folder.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; namespace SabreTools.Library.FileTypes @@ -18,7 +18,12 @@ namespace SabreTools.Library.FileTypes #region Protected instance variables protected List _children; - + + /// + /// Logging object + /// + protected static Logger logger = new Logger(); + /// /// Flag specific to Folder to omit Machine name from output path /// @@ -125,7 +130,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return false; } @@ -203,7 +208,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return realentry; } @@ -242,7 +247,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return (ms, realentry); } @@ -372,7 +377,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } finally diff --git a/SabreTools.Library/FileTypes/GZipArchive.cs b/SabreTools.Library/FileTypes/GZipArchive.cs index 9d29a369..0d11cc81 100644 --- a/SabreTools.Library/FileTypes/GZipArchive.cs +++ b/SabreTools.Library/FileTypes/GZipArchive.cs @@ -87,16 +87,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -183,7 +183,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -251,7 +251,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } } @@ -286,21 +286,21 @@ namespace SabreTools.Library.FileTypes // If we have the romba depot files, just skip them gracefully if (datum == ".romba_size" || datum == ".romba_size.backup") { - Globals.Logger.Verbose($"Romba depot file found, skipping: {this.Filename}"); + logger.Verbose($"Romba depot file found, skipping: {this.Filename}"); return false; } // Check if the name is the right length if (!Regex.IsMatch(datum, @"^[0-9a-f]{" + Constants.SHA1Length + @"}\.gz")) { - Globals.Logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); + logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); return false; } // Check if the file is at least the minimum length if (filesize < 40 /* bytes */) { - Globals.Logger.Warning($"Possibly corrupt file '{Path.GetFullPath(this.Filename)}' with size {Utilities.GetBytesReadable(filesize)}"); + logger.Warning($"Possibly corrupt file '{Path.GetFullPath(this.Filename)}' with size {Utilities.GetBytesReadable(filesize)}"); return false; } @@ -347,21 +347,21 @@ namespace SabreTools.Library.FileTypes // If we have the romba depot files, just skip them gracefully if (datum == ".romba_size" || datum == ".romba_size.backup") { - Globals.Logger.Verbose($"Romba depot file found, skipping: {this.Filename}"); + logger.Verbose($"Romba depot file found, skipping: {this.Filename}"); return null; } // Check if the name is the right length if (!Regex.IsMatch(datum, @"^[0-9a-f]{" + Constants.SHA1Length + @"}\.gz")) { - Globals.Logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); + logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); return null; } // Check if the file is at least the minimum length if (filesize < 40 /* bytes */) { - Globals.Logger.Warning($"Possibly corrupt file '{Path.GetFullPath(this.Filename)}' with size {Utilities.GetBytesReadable(filesize)}"); + logger.Warning($"Possibly corrupt file '{Path.GetFullPath(this.Filename)}' with size {Utilities.GetBytesReadable(filesize)}"); return null; } @@ -427,7 +427,7 @@ namespace SabreTools.Library.FileTypes // Check that the input file exists if (!File.Exists(inputFile)) { - Globals.Logger.Warning($"File '{inputFile}' does not exist!"); + logger.Warning($"File '{inputFile}' does not exist!"); return false; } diff --git a/SabreTools.Library/FileTypes/RarArchive.cs b/SabreTools.Library/FileTypes/RarArchive.cs index 35aa4ac0..253724cd 100644 --- a/SabreTools.Library/FileTypes/RarArchive.cs +++ b/SabreTools.Library/FileTypes/RarArchive.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -71,16 +70,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -160,7 +159,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -216,7 +215,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } @@ -257,7 +256,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); } return empties; diff --git a/SabreTools.Library/FileTypes/SevenZipArchive.cs b/SabreTools.Library/FileTypes/SevenZipArchive.cs index bd5dea4a..1428e8f0 100644 --- a/SabreTools.Library/FileTypes/SevenZipArchive.cs +++ b/SabreTools.Library/FileTypes/SevenZipArchive.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -120,16 +119,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -244,7 +243,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -291,7 +290,7 @@ namespace SabreTools.Library.FileTypes // If we get a read error, log it and continue if (zr != ZipReturn.ZipGood) { - Globals.Logger.Warning($"An error occurred while reading archive {this.Filename}: Zip Error - {zr}"); + logger.Warning($"An error occurred while reading archive {this.Filename}: Zip Error - {zr}"); zr = zf.ZipFileCloseReadStream(); continue; } @@ -323,7 +322,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } @@ -376,7 +375,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); } return empties; @@ -589,7 +588,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } finally @@ -816,7 +815,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } diff --git a/SabreTools.Library/FileTypes/TapeArchive.cs b/SabreTools.Library/FileTypes/TapeArchive.cs index 19bf9247..6154e0b3 100644 --- a/SabreTools.Library/FileTypes/TapeArchive.cs +++ b/SabreTools.Library/FileTypes/TapeArchive.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -76,16 +75,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -165,7 +164,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -221,7 +220,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } @@ -262,7 +261,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); } return empties; @@ -412,7 +411,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } finally @@ -586,7 +585,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } finally diff --git a/SabreTools.Library/FileTypes/XZArchive.cs b/SabreTools.Library/FileTypes/XZArchive.cs index 0635014f..f026b45f 100644 --- a/SabreTools.Library/FileTypes/XZArchive.cs +++ b/SabreTools.Library/FileTypes/XZArchive.cs @@ -81,16 +81,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -175,7 +175,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -239,7 +239,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } } @@ -273,7 +273,7 @@ namespace SabreTools.Library.FileTypes // Check if the name is the right length if (!Regex.IsMatch(datum, @"^[0-9a-f]{" + Constants.SHA1Length + @"}\.xz")) { - Globals.Logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); + logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); return false; } @@ -295,7 +295,7 @@ namespace SabreTools.Library.FileTypes // Check if the name is the right length if (!Regex.IsMatch(datum, @"^[0-9a-f]{" + Constants.SHA1Length + @"}\.xz")) { - Globals.Logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); + logger.Warning($"Non SHA-1 filename found, skipping: '{Path.GetFullPath(this.Filename)}'"); return null; } @@ -327,7 +327,7 @@ namespace SabreTools.Library.FileTypes // Check that the input file exists if (!File.Exists(inputFile)) { - Globals.Logger.Warning($"File '{inputFile}' does not exist!"); + logger.Warning($"File '{inputFile}' does not exist!"); return false; } diff --git a/SabreTools.Library/FileTypes/ZipArchive.cs b/SabreTools.Library/FileTypes/ZipArchive.cs index 01a69687..cd7a1632 100644 --- a/SabreTools.Library/FileTypes/ZipArchive.cs +++ b/SabreTools.Library/FileTypes/ZipArchive.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.IO; @@ -121,16 +120,16 @@ namespace SabreTools.Library.FileTypes catch (EndOfStreamException ex) { // Catch this but don't count it as an error because SharpCompress is unsafe - Globals.Logger.Verbose(ex); + logger.Verbose(ex); } catch (InvalidOperationException ex) { - Globals.Logger.Warning(ex); + logger.Warning(ex); encounteredErrors = true; } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); encounteredErrors = true; } @@ -245,7 +244,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); ms = null; realEntry = null; } @@ -292,7 +291,7 @@ namespace SabreTools.Library.FileTypes // If we get a read error, log it and continue if (zr != ZipReturn.ZipGood) { - Globals.Logger.Warning($"An error occurred while reading archive {this.Filename}: Zip Error - {zr}"); + logger.Warning($"An error occurred while reading archive {this.Filename}: Zip Error - {zr}"); zr = zf.ZipFileCloseReadStream(); continue; } @@ -325,7 +324,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return null; } @@ -378,7 +377,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); } return empties; @@ -590,7 +589,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } finally @@ -818,7 +817,7 @@ namespace SabreTools.Library.FileTypes } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); success = false; } diff --git a/SabreTools.Library/Filtering/ExtraIni.cs b/SabreTools.Library/Filtering/ExtraIni.cs index 26338e5a..2a9096a7 100644 --- a/SabreTools.Library/Filtering/ExtraIni.cs +++ b/SabreTools.Library/Filtering/ExtraIni.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using SabreTools.Library.Data; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; namespace SabreTools.Library.Filtering @@ -16,6 +16,15 @@ namespace SabreTools.Library.Filtering #endregion + #region Logging + + /// + /// Logging object + /// + private Logger logger = new Logger(); + + #endregion + #region Extras Population /// @@ -31,7 +40,7 @@ namespace SabreTools.Library.Filtering // If we don't even have a possible field and file combination if (!input.Contains(":")) { - Globals.Logger.Warning($"'{input}` is not a valid INI extras string. Valid INI extras strings are of the form 'key:value'. Please refer to README.1ST or the help feature for more details."); + logger.Warning($"'{input}` is not a valid INI extras string. Valid INI extras strings are of the form 'key:value'. Please refer to README.1ST or the help feature for more details."); return; } diff --git a/SabreTools.Library/Filtering/ExtraIniItem.cs b/SabreTools.Library/Filtering/ExtraIniItem.cs index 832e305c..2e296860 100644 --- a/SabreTools.Library/Filtering/ExtraIniItem.cs +++ b/SabreTools.Library/Filtering/ExtraIniItem.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; using SabreTools.Library.IO; +using SabreTools.Library.Logging; namespace SabreTools.Library.Filtering { @@ -93,7 +93,7 @@ namespace SabreTools.Library.Filtering } catch (Exception ex) { - Globals.Logger.Warning(ex, $"Exception found while parsing '{ini}'"); + LoggerImpl.Warning(ex, $"Exception found while parsing '{ini}'"); return false; } diff --git a/SabreTools.Library/Filtering/Filter.cs b/SabreTools.Library/Filtering/Filter.cs index 99c257b8..6a92d003 100644 --- a/SabreTools.Library/Filtering/Filter.cs +++ b/SabreTools.Library/Filtering/Filter.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.DatItems; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; namespace SabreTools.Library.Filtering @@ -286,6 +286,15 @@ namespace SabreTools.Library.Filtering #endregion // Fields + #region Logging + + /// + /// Logging object + /// + private Logger logger = new Logger(); + + #endregion + #region Instance methods #region Filter Population @@ -301,7 +310,7 @@ namespace SabreTools.Library.Filtering // If we don't even have a possible filter pair if (!filterPair.Contains(":")) { - Globals.Logger.Warning($"'{filterPair}` is not a valid filter string. Valid filter strings are of the form 'key:value'. Please refer to README.1ST or the help feature for more details."); + logger.Warning($"'{filterPair}` is not a valid filter string. Valid filter strings are of the form 'key:value'. Please refer to README.1ST or the help feature for more details."); continue; } diff --git a/SabreTools.Library/Help/TopLevel.cs b/SabreTools.Library/Help/TopLevel.cs index 2c074b80..33eadaec 100644 --- a/SabreTools.Library/Help/TopLevel.cs +++ b/SabreTools.Library/Help/TopLevel.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; +using SabreTools.Library.Logging; namespace SabreTools.Library.Help { @@ -13,6 +13,15 @@ namespace SabreTools.Library.Help { public List Inputs = new List(); + #region Logging + + /// + /// Logging object + /// + private Logger logger = new Logger(); + + #endregion + /// /// Process args list based on current feature /// @@ -38,9 +47,9 @@ namespace SabreTools.Library.Help // Everything else isn't a file else { - Globals.Logger.Error($"Invalid input detected: {args[i]}"); + logger.Error($"Invalid input detected: {args[i]}"); help.OutputIndividualFeature(this.Name); - Globals.Logger.Close(); + LoggerImpl.Close(); return false; } } diff --git a/SabreTools.Library/IO/DirectoryExtensions.cs b/SabreTools.Library/IO/DirectoryExtensions.cs index 81ccb765..4713f04a 100644 --- a/SabreTools.Library/IO/DirectoryExtensions.cs +++ b/SabreTools.Library/IO/DirectoryExtensions.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using SabreTools.Library.Data; +using SabreTools.Library.Logging; using NaturalSort; namespace SabreTools.Library.IO @@ -91,7 +91,7 @@ namespace SabreTools.Library.IO } catch (Exception ex) { - Globals.Logger.Error(ex, $"An exception occurred getting the full path for '{input}'"); + LoggerImpl.Error(ex, $"An exception occurred getting the full path for '{input}'"); continue; } @@ -106,11 +106,11 @@ namespace SabreTools.Library.IO } catch (PathTooLongException ex) { - Globals.Logger.Warning(ex, $"The path for '{dir}' was too long"); + LoggerImpl.Warning(ex, $"The path for '{dir}' was too long"); } catch (Exception ex) { - Globals.Logger.Error(ex, $"An exception occurred processing '{dir}'"); + LoggerImpl.Error(ex, $"An exception occurred processing '{dir}'"); } } } @@ -187,7 +187,7 @@ namespace SabreTools.Library.IO } catch (Exception ex) { - Globals.Logger.Error(ex, $"An exception occurred getting the full path for '{input}'"); + LoggerImpl.Error(ex, $"An exception occurred getting the full path for '{input}'"); continue; } @@ -202,11 +202,11 @@ namespace SabreTools.Library.IO } catch (PathTooLongException ex) { - Globals.Logger.Warning(ex, $"The path for '{file}' was too long"); + LoggerImpl.Warning(ex, $"The path for '{file}' was too long"); } catch (Exception ex) { - Globals.Logger.Error(ex, $"An exception occurred processing '{file}'"); + LoggerImpl.Error(ex, $"An exception occurred processing '{file}'"); } } } @@ -218,11 +218,11 @@ namespace SabreTools.Library.IO } catch (PathTooLongException ex) { - Globals.Logger.Warning(ex, $"The path for '{input}' was too long"); + LoggerImpl.Warning(ex, $"The path for '{input}' was too long"); } catch (Exception ex) { - Globals.Logger.Error(ex, $"An exception occurred processing '{input}'"); + LoggerImpl.Error(ex, $"An exception occurred processing '{input}'"); } } } diff --git a/SabreTools.Library/IO/FileExtensions.cs b/SabreTools.Library/IO/FileExtensions.cs index 429ee9fe..2f76b508 100644 --- a/SabreTools.Library/IO/FileExtensions.cs +++ b/SabreTools.Library/IO/FileExtensions.cs @@ -8,6 +8,7 @@ using System.Xml.Schema; using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.FileTypes; +using SabreTools.Library.Logging; using SabreTools.Library.Skippers; namespace SabreTools.Library.IO @@ -17,6 +18,15 @@ namespace SabreTools.Library.IO /// public static class FileExtensions { + #region Logging + + /// + /// Logging object + /// + private static Logger logger = new Logger(); + + #endregion + /// /// Add an aribtrary number of bytes to the inputted file /// @@ -59,12 +69,12 @@ namespace SabreTools.Library.IO string ext = PathExtensions.GetNormalizedExtension(filename); // Read the input file, if possible - Globals.Logger.Verbose($"Attempting to read file to get format: {filename}"); + logger.Verbose($"Attempting to read file to get format: {filename}"); // Check if file exists if (!File.Exists(filename)) { - Globals.Logger.Warning($"File '{filename}' could not read from!"); + logger.Warning($"File '{filename}' could not read from!"); return 0; } @@ -189,7 +199,7 @@ namespace SabreTools.Library.IO } catch (Exception ex) { - Globals.Logger.Warning(ex, $"An exception occurred trying to figure out the format of '{filename}'"); + logger.Warning(ex, $"An exception occurred trying to figure out the format of '{filename}'"); return 0; } } @@ -305,7 +315,7 @@ namespace SabreTools.Library.IO } catch (Exception ex) { - Globals.Logger.Warning(ex, $"An exception occurred determining file type of '{input}'"); + logger.Warning(ex, $"An exception occurred determining file type of '{input}'"); } return outFileType; @@ -401,12 +411,12 @@ namespace SabreTools.Library.IO /// The IniReader representing the (possibly converted) file, null otherwise public static IniReader GetIniReader(this string filename, bool validateRows) { - Globals.Logger.Verbose($"Attempting to read file: {filename}"); + logger.Verbose($"Attempting to read file: {filename}"); // Check if file exists if (!File.Exists(filename)) { - Globals.Logger.Warning($"File '{filename}' could not read from!"); + logger.Warning($"File '{filename}' could not read from!"); return null; } @@ -424,12 +434,12 @@ namespace SabreTools.Library.IO /// The XmlTextReader representing the (possibly converted) file, null otherwise public static XmlReader GetXmlTextReader(this string filename) { - Globals.Logger.Verbose($"Attempting to read file: {filename}"); + logger.Verbose($"Attempting to read file: {filename}"); // Check if file exists if (!File.Exists(filename)) { - Globals.Logger.Warning($"File '{filename}' could not read from!"); + logger.Warning($"File '{filename}' could not read from!"); return null; } diff --git a/SabreTools.Library/IO/StreamExtensions.cs b/SabreTools.Library/IO/StreamExtensions.cs index b516df57..101c4764 100644 --- a/SabreTools.Library/IO/StreamExtensions.cs +++ b/SabreTools.Library/IO/StreamExtensions.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.FileTypes; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; using Compress.ThreadReaders; @@ -161,7 +162,7 @@ namespace SabreTools.Library.IO } catch (IOException ex) { - Globals.Logger.Warning(ex, "An exception occurred during hashing."); + LoggerImpl.Warning(ex, "An exception occurred during hashing."); return new BaseFile(); } finally @@ -194,11 +195,11 @@ namespace SabreTools.Library.IO } catch (NotSupportedException ex) { - Globals.Logger.Verbose(ex, "Stream does not support seeking to starting offset. Stream position not changed"); + LoggerImpl.Verbose(ex, "Stream does not support seeking to starting offset. Stream position not changed"); } catch (NotImplementedException ex) { - Globals.Logger.Warning(ex, "Stream does not support seeking to starting offset. Stream position not changed"); + LoggerImpl.Warning(ex, "Stream does not support seeking to starting offset. Stream position not changed"); } return -1; diff --git a/SabreTools.Library/Logging/Logger.cs b/SabreTools.Library/Logging/Logger.cs index 387235c3..d2dc5102 100644 --- a/SabreTools.Library/Logging/Logger.cs +++ b/SabreTools.Library/Logging/Logger.cs @@ -1,293 +1,26 @@ using System; -using System.IO; -using System.Text; - -using SabreTools.Library.Data; -using SabreTools.Library.IO; namespace SabreTools.Library.Logging { /// - /// Log either to file or to the console + /// Per-class logging /// public class Logger { - #region Fields - /// - /// Optional output filename for logs + /// Instance associated with this logger /// - public string Filename { get; set; } = null; - + /// TODO: Derive class name for this object, if possible + private object instance; + /// - /// Determines if we're logging to file or not + /// Constructor /// - public bool LogToFile { get { return !string.IsNullOrWhiteSpace(Filename); } } - - /// - /// Optional output log directory - /// - /// TODO: Make this either passed in or optional - public string LogDirectory { get; set; } = Path.Combine(Globals.ExeDir, "logs") + Path.DirectorySeparatorChar; - - /// - /// Determines the lowest log level to output - /// - public LogLevel LowestLogLevel { get; set; } = LogLevel.VERBOSE; - - /// - /// Determines whether to prefix log lines with level and datetime - /// - public bool AppendPrefix { get; set; } = true; - - /// - /// Determines whether to throw if an exception is logged - /// - public bool ThrowOnError { get; set; } = false; - - /// - /// Logging start time for metrics - /// - public DateTime StartTime { get; private set; } - - /// - /// Determines if there were errors logged - /// - public bool LoggedErrors { get; private set; } = false; - - /// - /// Determines if there were warnings logged - /// - public bool LoggedWarnings { get; private set; } = false; - - #endregion - - #region Private instance variables - - /// - /// StreamWriter representing the output log file - /// - private StreamWriter _log; - - /// - /// Object lock for multithreaded logging - /// - private readonly object _lock = new object(); - - #endregion - - #region Constructors - - /// - /// Initialize a console-only logger object - /// - public Logger() + public Logger(object instance = null) { - Start(); + this.instance = instance; } - /// - /// Initialize a Logger object with the given information - /// - /// Filename representing log location - /// True to add a date string to the filename (default), false otherwise - public Logger(string filename, bool addDate = true) - { - // Set and create the output - if (addDate) - Filename = $"{Path.GetFileNameWithoutExtension(filename)} ({DateTime.Now:yyyy-MM-dd HH-mm-ss}).{PathExtensions.GetNormalizedExtension(filename)}"; - else - Filename = filename; - - if (!string.IsNullOrEmpty(LogDirectory) && !Directory.Exists(LogDirectory)) - Directory.CreateDirectory(LogDirectory); - - Start(); - } - - #endregion - - #region Control - - /// - /// Start logging by opening output file (if necessary) - /// - /// True if the logging was started correctly, false otherwise - public bool Start() - { - // Setup the logging handler to always use the internal log - LogEventHandler += HandleLogEvent; - - // Start the logging - StartTime = DateTime.Now; - if (!LogToFile) - return true; - - // Setup file output and perform initial log - try - { - FileStream logfile = FileExtensions.TryCreate(Path.Combine(LogDirectory, Filename)); - _log = new StreamWriter(logfile, Encoding.UTF8, (int)(4 * Constants.KibiByte), true) - { - AutoFlush = true - }; - - _log.WriteLine($"Logging started {StartTime:yyyy-MM-dd HH:mm:ss}"); - _log.WriteLine($"Command run: {Globals.CommandLineArgs}"); - } - catch - { - return false; - } - - return true; - } - - /// - /// End logging by closing output file (if necessary) - /// - /// True if all ending output is to be suppressed, false otherwise (default) - /// True if the logging was ended correctly, false otherwise - public bool Close(bool suppress = false) - { - if (!suppress) - { - if (LoggedWarnings) - Console.WriteLine("There were warnings in the last run! Check the log for more details"); - - if (LoggedErrors) - Console.WriteLine("There were errors in the last run! Check the log for more details"); - - TimeSpan span = DateTime.Now.Subtract(StartTime); - - // Special case for multi-day runs - string total; - if (span >= TimeSpan.FromDays(1)) - total = span.ToString(@"d\:hh\:mm\:ss"); - else - total = span.ToString(@"hh\:mm\:ss"); - - if (!LogToFile) - { - Console.WriteLine($"Total runtime: {total}"); - return true; - } - - try - { - _log.WriteLine($"Logging ended {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); - _log.WriteLine($"Total runtime: {total}"); - Console.WriteLine($"Total runtime: {total}"); - _log.Close(); - } - catch - { - return false; - } - } - else - { - try - { - _log.Close(); - } - catch - { - return false; - } - } - - return true; - } - - #endregion - - #region Event Handling - - /// - /// Handler for log events - /// - public static event LogEventHandler LogEventHandler = delegate { }; - - /// - /// Default log event handling - /// - public void HandleLogEvent(object sender, LogEventArgs args) - { - // Null args means we can't handle it - if (args == null) - return; - - // If we have an exception and we're throwing on that - if (ThrowOnError && args.Exception != null) - throw args.Exception; - - // If we have a warning or error, set the flags accordingly - if (args.LogLevel == LogLevel.WARNING) - LoggedWarnings = true; - if (args.LogLevel == LogLevel.ERROR) - LoggedErrors = true; - - // Setup the statement based on the inputs - string logLine; - if (args.Exception == null) - { - logLine = args.Statement ?? string.Empty; - } - else if (args.TotalCount != null && args.CurrentCount != null) - { - double percentage = (args.CurrentCount.Value / args.TotalCount.Value) * 100; - logLine = $"{percentage:N2}%{(args.Statement != null ? ": " + args.Statement : string.Empty)}"; - } - else - { - logLine = $"{(args.Statement != null ? args.Statement + ": " : string.Empty)}{args.Exception}"; - } - - // Then write to the log - Log(logLine, args.LogLevel); - } - - /// - /// Write the given string to the log output - /// - /// String to be written log - /// Severity of the information being logged - /// True if the output could be written, false otherwise - private bool Log(string output, LogLevel loglevel) - { - // If the log level is less than the filter level, we skip it but claim we didn't - if (loglevel < LowestLogLevel) - return true; - - // USER and ERROR writes to console - if (loglevel == LogLevel.USER || loglevel == LogLevel.ERROR) - Console.WriteLine((loglevel == LogLevel.ERROR && this.AppendPrefix ? loglevel.ToString() + " " : string.Empty) + output); - - // If we're writing to file, use the existing stream - if (LogToFile) - { - try - { - lock (_lock) - { - _log.WriteLine((this.AppendPrefix ? $"{loglevel} - {DateTime.Now} - " : string.Empty) + output); - } - } - catch (Exception ex) - { - Console.WriteLine(ex); - Console.WriteLine("Could not write to log file!"); - if (ThrowOnError) throw ex; - return false; - } - } - - return true; - } - - #endregion - #region Log Event Triggers /// @@ -298,7 +31,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Verbose(Exception ex, string output = null) { - LogEventHandler(this, new LogEventArgs(LogLevel.VERBOSE, output, ex)); + LoggerImpl.Verbose(this.instance, ex, output); } /// @@ -308,7 +41,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Verbose(string output) { - LogEventHandler(this, new LogEventArgs(LogLevel.VERBOSE, output, null)); + LoggerImpl.Verbose(this.instance, output); } /// @@ -319,7 +52,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void User(Exception ex, string output = null) { - LogEventHandler(this, new LogEventArgs(LogLevel.USER, output, ex)); + LoggerImpl.User(this.instance, ex, output); } /// @@ -329,7 +62,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void User(string output) { - LogEventHandler(this, new LogEventArgs(LogLevel.USER, output, null)); + LoggerImpl.User(this.instance, output); } /// @@ -340,7 +73,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Warning(Exception ex, string output = null) { - LogEventHandler(this, new LogEventArgs(LogLevel.WARNING, output, ex)); + LoggerImpl.Warning(this.instance, ex, output); } /// @@ -350,7 +83,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Warning(string output) { - LogEventHandler(this, new LogEventArgs(LogLevel.WARNING, output, null)); + LoggerImpl.Warning(this.instance, output); } /// @@ -361,7 +94,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Error(Exception ex, string output = null) { - LogEventHandler(this, new LogEventArgs(LogLevel.ERROR, output, ex)); + LoggerImpl.Error(this.instance, ex, output); } /// @@ -371,7 +104,7 @@ namespace SabreTools.Library.Logging /// True if the output could be written, false otherwise public void Error(string output) { - LogEventHandler(this, new LogEventArgs(LogLevel.ERROR, output, null)); + LoggerImpl.Error(this.instance, output); } #endregion diff --git a/SabreTools.Library/Logging/LoggerImpl.cs b/SabreTools.Library/Logging/LoggerImpl.cs new file mode 100644 index 00000000..fd7dbd54 --- /dev/null +++ b/SabreTools.Library/Logging/LoggerImpl.cs @@ -0,0 +1,373 @@ +using System; +using System.IO; +using System.Text; + +using SabreTools.Library.Data; +using SabreTools.Library.IO; + +namespace SabreTools.Library.Logging +{ + /// + /// Internal logging implementation + /// + public static class LoggerImpl + { + #region Fields + + /// + /// Optional output filename for logs + /// + public static string Filename { get; set; } = null; + + /// + /// Determines if we're logging to file or not + /// + public static bool LogToFile { get { return !string.IsNullOrWhiteSpace(Filename); } } + + /// + /// Optional output log directory + /// + /// TODO: Make this either passed in or optional + public static string LogDirectory { get; set; } = Path.Combine(Globals.ExeDir, "logs") + Path.DirectorySeparatorChar; + + /// + /// Determines the lowest log level to output + /// + public static LogLevel LowestLogLevel { get; set; } = LogLevel.VERBOSE; + + /// + /// Determines whether to prefix log lines with level and datetime + /// + public static bool AppendPrefix { get; set; } = true; + + /// + /// Determines whether to throw if an exception is logged + /// + public static bool ThrowOnError { get; set; } = false; + + /// + /// Logging start time for metrics + /// + public static DateTime StartTime { get; private set; } + + /// + /// Determines if there were errors logged + /// + public static bool LoggedErrors { get; private set; } = false; + + /// + /// Determines if there were warnings logged + /// + public static bool LoggedWarnings { get; private set; } = false; + + #endregion + + #region Private variables + + /// + /// StreamWriter representing the output log file + /// + private static StreamWriter _log; + + /// + /// Object lock for multithreaded logging + /// + private static readonly object _lock = new object(); + + #endregion + + #region Control + + /// + /// Generate and set the log filename + /// + /// Base filename to use + /// True to append a date to the filename, false otherwise + public static void SetFilename(string filename, bool addDate = true) + { + // Set and create the output + if (addDate) + Filename = $"{Path.GetFileNameWithoutExtension(filename)} ({DateTime.Now:yyyy-MM-dd HH-mm-ss}).{PathExtensions.GetNormalizedExtension(filename)}"; + else + Filename = filename; + } + + /// + /// Start logging by opening output file (if necessary) + /// + /// True if the logging was started correctly, false otherwise + public static bool Start() + { + // Setup the logging handler to always use the internal log + LogEventHandler += HandleLogEvent; + + // Start the logging + StartTime = DateTime.Now; + if (!LogToFile) + return true; + + // Setup file output and perform initial log + try + { + if (!string.IsNullOrEmpty(LogDirectory) && !Directory.Exists(LogDirectory)) + Directory.CreateDirectory(LogDirectory); + + FileStream logfile = FileExtensions.TryCreate(Path.Combine(LogDirectory, Filename)); + _log = new StreamWriter(logfile, Encoding.UTF8, (int)(4 * Constants.KibiByte), true) + { + AutoFlush = true + }; + + _log.WriteLine($"Logging started {StartTime:yyyy-MM-dd HH:mm:ss}"); + _log.WriteLine($"Command run: {Globals.CommandLineArgs}"); + } + catch + { + return false; + } + + return true; + } + + /// + /// End logging by closing output file (if necessary) + /// + /// True if all ending output is to be suppressed, false otherwise (default) + /// True if the logging was ended correctly, false otherwise + public static bool Close(bool suppress = false) + { + if (!suppress) + { + if (LoggedWarnings) + Console.WriteLine("There were warnings in the last run! Check the log for more details"); + + if (LoggedErrors) + Console.WriteLine("There were errors in the last run! Check the log for more details"); + + TimeSpan span = DateTime.Now.Subtract(StartTime); + + // Special case for multi-day runs + string total; + if (span >= TimeSpan.FromDays(1)) + total = span.ToString(@"d\:hh\:mm\:ss"); + else + total = span.ToString(@"hh\:mm\:ss"); + + if (!LogToFile) + { + Console.WriteLine($"Total runtime: {total}"); + return true; + } + + try + { + _log.WriteLine($"Logging ended {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + _log.WriteLine($"Total runtime: {total}"); + Console.WriteLine($"Total runtime: {total}"); + _log.Close(); + } + catch + { + return false; + } + } + else + { + try + { + _log.Close(); + } + catch + { + return false; + } + } + + return true; + } + + #endregion + + #region Event Handling + + /// + /// Handler for log events + /// + public static event LogEventHandler LogEventHandler = delegate { }; + + /// + /// Default log event handling + /// + public static void HandleLogEvent(object sender, LogEventArgs args) + { + // Null args means we can't handle it + if (args == null) + return; + + // If we have an exception and we're throwing on that + if (ThrowOnError && args.Exception != null) + throw args.Exception; + + // If we have a warning or error, set the flags accordingly + if (args.LogLevel == LogLevel.WARNING) + LoggedWarnings = true; + if (args.LogLevel == LogLevel.ERROR) + LoggedErrors = true; + + // Setup the statement based on the inputs + string logLine; + if (args.Exception == null) + { + logLine = args.Statement ?? string.Empty; + } + else if (args.TotalCount != null && args.CurrentCount != null) + { + double percentage = (args.CurrentCount.Value / args.TotalCount.Value) * 100; + logLine = $"{percentage:N2}%{(args.Statement != null ? ": " + args.Statement : string.Empty)}"; + } + else + { + logLine = $"{(args.Statement != null ? args.Statement + ": " : string.Empty)}{args.Exception}"; + } + + // Then write to the log + Log(logLine, args.LogLevel); + } + + /// + /// Write the given string to the log output + /// + /// String to be written log + /// Severity of the information being logged + /// True if the output could be written, false otherwise + public static bool Log(string output, LogLevel loglevel) + { + // If the log level is less than the filter level, we skip it but claim we didn't + if (loglevel < LowestLogLevel) + return true; + + // USER and ERROR writes to console + if (loglevel == LogLevel.USER || loglevel == LogLevel.ERROR) + Console.WriteLine((loglevel == LogLevel.ERROR && AppendPrefix ? loglevel.ToString() + " " : string.Empty) + output); + + // If we're writing to file, use the existing stream + if (LogToFile) + { + try + { + lock (_lock) + { + _log.WriteLine((AppendPrefix ? $"{loglevel} - {DateTime.Now} - " : string.Empty) + output); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + Console.WriteLine("Could not write to log file!"); + if (ThrowOnError) throw ex; + return false; + } + } + + return true; + } + + #endregion + + #region Log Event Triggers + + /// + /// Write the given exception as a verbose message to the log output + /// + /// Instance object that's the source of logging + /// Exception to be written log + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Verbose(object instance, Exception ex, string output = null) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.VERBOSE, output, ex)); + } + + /// + /// Write the given string as a verbose message to the log output + /// + /// Instance object that's the source of logging + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Verbose(object instance, string output) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.VERBOSE, output, null)); + } + + /// + /// Write the given exception as a user message to the log output + /// + /// Instance object that's the source of logging + /// Exception to be written log + /// String to be written log + /// True if the output could be written, false otherwise + internal static void User(object instance, Exception ex, string output = null) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.USER, output, ex)); + } + + /// + /// Write the given string as a user message to the log output + /// + /// Instance object that's the source of logging + /// String to be written log + /// True if the output could be written, false otherwise + internal static void User(object instance, string output) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.USER, output, null)); + } + + /// + /// Write the given exception as a warning to the log output + /// + /// Instance object that's the source of logging + /// Exception to be written log + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Warning(object instance, Exception ex, string output = null) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.WARNING, output, ex)); + } + + /// + /// Write the given string as a warning to the log output + /// + /// Instance object that's the source of logging + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Warning(object instance, string output) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.WARNING, output, null)); + } + + /// + /// Writes the given exception as an error in the log + /// + /// Instance object that's the source of logging + /// Exception to be written log + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Error(object instance, Exception ex, string output = null) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.ERROR, output, ex)); + } + + /// + /// Writes the given string as an error in the log + /// + /// Instance object that's the source of logging + /// String to be written log + /// True if the output could be written, false otherwise + internal static void Error(object instance, string output) + { + LogEventHandler(instance, new LogEventArgs(LogLevel.ERROR, output, null)); + } + + #endregion + } +} diff --git a/SabreTools.Library/SabreTools.Library.csproj b/SabreTools.Library/SabreTools.Library.csproj index b0ba4101..d26ae9ef 100644 --- a/SabreTools.Library/SabreTools.Library.csproj +++ b/SabreTools.Library/SabreTools.Library.csproj @@ -1,4 +1,4 @@ - + net48;netcoreapp3.1 diff --git a/SabreTools.Library/Skippers/SkipperRule.cs b/SabreTools.Library/Skippers/SkipperRule.cs index 13bb166e..fc7e6a40 100644 --- a/SabreTools.Library/Skippers/SkipperRule.cs +++ b/SabreTools.Library/Skippers/SkipperRule.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.IO; -using SabreTools.Library.Data; using SabreTools.Library.IO; +using SabreTools.Library.Logging; namespace SabreTools.Library.Skippers { @@ -38,6 +38,15 @@ namespace SabreTools.Library.Skippers #endregion + #region Logging + + /// + /// Logging object + /// + private Logger logger = new Logger(); + + #endregion + /// /// Check if a Stream passes all tests in the SkipperRule /// @@ -66,14 +75,14 @@ namespace SabreTools.Library.Skippers // If the input file doesn't exist, fail if (!File.Exists(input)) { - Globals.Logger.Error($"I'm sorry but '{input}' doesn't exist!"); + logger.Error($"I'm sorry but '{input}' doesn't exist!"); return false; } // Create the output directory if it doesn't already DirectoryExtensions.Ensure(Path.GetDirectoryName(output)); - Globals.Logger.User($"Attempting to apply rule to '{input}'"); + logger.User($"Attempting to apply rule to '{input}'"); bool success = TransformStream(FileExtensions.TryOpenRead(input), FileExtensions.TryCreate(output)); // If the output file has size 0, delete it @@ -104,7 +113,7 @@ namespace SabreTools.Library.Skippers || (Operation > HeaderSkipOperation.Byteswap && (extsize % 4) != 0) || (Operation > HeaderSkipOperation.Bitswap && (StartOffset == null || StartOffset % 2 == 0))) { - Globals.Logger.Error("The stream did not have the correct size to be transformed!"); + logger.Error("The stream did not have the correct size to be transformed!"); return false; } @@ -113,7 +122,7 @@ namespace SabreTools.Library.Skippers BinaryReader br = null; try { - Globals.Logger.User("Applying found rule to input stream"); + logger.User("Applying found rule to input stream"); bw = new BinaryWriter(output); br = new BinaryReader(input); @@ -201,7 +210,7 @@ namespace SabreTools.Library.Skippers } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); return false; } finally diff --git a/SabreTools.Library/Skippers/Transform.cs b/SabreTools.Library/Skippers/Transform.cs index 7aa51b74..bbf91fee 100644 --- a/SabreTools.Library/Skippers/Transform.cs +++ b/SabreTools.Library/Skippers/Transform.cs @@ -5,6 +5,7 @@ using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.FileTypes; using SabreTools.Library.IO; +using SabreTools.Library.Logging; using SabreTools.Library.Tools; namespace SabreTools.Library.Skippers @@ -31,6 +32,15 @@ namespace SabreTools.Library.Skippers /// private static List List; + #region Logging + + /// + /// Logging object + /// + private static Logger logger = new Logger(); + + #endregion + /// /// Local paths /// @@ -74,7 +84,7 @@ namespace SabreTools.Library.Skippers // Create the output directory if it doesn't exist DirectoryExtensions.Ensure(outDir, create: true); - Globals.Logger.User($"\nGetting skipper information for '{file}'"); + logger.User($"\nGetting skipper information for '{file}'"); // Get the skipper rule that matches the file, if any SkipperRule rule = GetMatchingRule(file, string.Empty); @@ -83,7 +93,7 @@ namespace SabreTools.Library.Skippers if (rule.Tests == null || rule.Tests.Count == 0 || rule.Operation != HeaderSkipOperation.None) return false; - Globals.Logger.User("File has a valid copier header"); + logger.User("File has a valid copier header"); // Get the header bytes from the file first string hstr; @@ -152,9 +162,9 @@ namespace SabreTools.Library.Skippers for (int i = 0; i < headers.Count; i++) { string outputFile = (string.IsNullOrWhiteSpace(outDir) ? $"{Path.GetFullPath(file)}.new" : Path.Combine(outDir, Path.GetFileName(file))) + i; - Globals.Logger.User($"Creating reheadered file: {outputFile}"); + logger.User($"Creating reheadered file: {outputFile}"); FileExtensions.AppendBytes(file, outputFile, Utilities.StringToByteArray(headers[i]), null); - Globals.Logger.User("Reheadered file created!"); + logger.User("Reheadered file created!"); } return true; @@ -172,7 +182,7 @@ namespace SabreTools.Library.Skippers // If the file doesn't exist, return a blank skipper rule if (!File.Exists(input)) { - Globals.Logger.Error($"The file '{input}' does not exist so it cannot be tested"); + logger.Error($"The file '{input}' does not exist so it cannot be tested"); return new SkipperRule(); } @@ -195,7 +205,7 @@ namespace SabreTools.Library.Skippers return skipperRule; // Loop through and find a Skipper that has the right name - Globals.Logger.Verbose("Beginning search for matching header skip rules"); + logger.Verbose("Beginning search for matching header skip rules"); List tempList = new List(); tempList.AddRange(List); @@ -217,9 +227,9 @@ namespace SabreTools.Library.Skippers // If we have a blank rule, inform the user if (skipperRule.Tests == null) - Globals.Logger.Verbose("No matching rule found!"); + logger.Verbose("No matching rule found!"); else - Globals.Logger.User("Matching rule found!"); + logger.User("Matching rule found!"); return skipperRule; } diff --git a/SabreTools.Library/Tools/DatabaseTools.cs b/SabreTools.Library/Tools/DatabaseTools.cs index 75178c9c..b1be9620 100644 --- a/SabreTools.Library/Tools/DatabaseTools.cs +++ b/SabreTools.Library/Tools/DatabaseTools.cs @@ -3,6 +3,7 @@ using System.IO; using System.Collections.Generic; using SabreTools.Library.Data; +using SabreTools.Library.Logging; using Microsoft.Data.Sqlite; namespace SabreTools.Library.Tools @@ -12,6 +13,15 @@ namespace SabreTools.Library.Tools /// public static class DatabaseTools { + #region Logging + + /// + /// Logging object + /// + private static Logger logger = new Logger(); + + #endregion + /// /// Add a header to the database /// @@ -21,7 +31,7 @@ namespace SabreTools.Library.Tools public static void AddHeaderToDatabase(string header, string SHA1, string source) { // Ensure the database exists - EnsureDatabase(Constants.HeadererDbSchema, Constants.HeadererFileName, Constants.HeadererConnectionString); + EnsureDatabase(Constants.HeadererFileName, Constants.HeadererConnectionString); // Open the database connection SqliteConnection dbc = new SqliteConnection(Constants.HeadererConnectionString); @@ -36,7 +46,7 @@ namespace SabreTools.Library.Tools { query = $"INSERT INTO data (sha1, header, type) VALUES ('{SHA1}', '{header}', '{source}')"; slc = new SqliteCommand(query, dbc); - Globals.Logger.Verbose($"Result of inserting header: {slc.ExecuteNonQuery()}"); + logger.Verbose($"Result of inserting header: {slc.ExecuteNonQuery()}"); } // Dispose of database objects @@ -48,15 +58,10 @@ namespace SabreTools.Library.Tools /// /// Ensure that the databse exists and has the proper schema /// - /// Schema type to use /// Name of the databse /// Connection string for SQLite - /// TODO: Re-evaluate why this method needs to exist - public static void EnsureDatabase(string type, string db, string connectionString) + public static void EnsureDatabase(string db, string connectionString) { - // Set the type to lowercase - type = type.ToLowerInvariant(); - // Make sure the file exists if (!File.Exists(db)) File.Create(db); @@ -68,77 +73,20 @@ namespace SabreTools.Library.Tools // Make sure the database has the correct schema try { - if (type == "rombasharp") - { - string query = @" -CREATE TABLE IF NOT EXISTS crc ( - 'crc' TEXT NOT NULL, - PRIMARY KEY (crc) -)"; - SqliteCommand slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - - query = @" -CREATE TABLE IF NOT EXISTS md5 ( - 'md5' TEXT NOT NULL, - PRIMARY KEY (md5) -)"; - slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - - query = @" -CREATE TABLE IF NOT EXISTS sha1 ( - 'sha1' TEXT NOT NULL, - 'depot' TEXT, - PRIMARY KEY (sha1) -)"; - slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - - query = @" -CREATE TABLE IF NOT EXISTS crcsha1 ( - 'crc' TEXT NOT NULL, - 'sha1' TEXT NOT NULL, - PRIMARY KEY (crc, sha1) -)"; - slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - - query = @" -CREATE TABLE IF NOT EXISTS md5sha1 ( - 'md5' TEXT NOT NULL, - 'sha1' TEXT NOT NULL, - PRIMARY KEY (md5, sha1) -)"; - slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - - query = @" -CREATE TABLE IF NOT EXISTS dat ( - 'hash' TEXT NOT NULL, - PRIMARY KEY (hash) -)"; - slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - slc.Dispose(); - } - else if (type == "headerer") - { - string query = @" + string query = @" CREATE TABLE IF NOT EXISTS data ( 'sha1' TEXT NOT NULL, 'header' TEXT NOT NULL, 'type' TEXT NOT NULL, PRIMARY KEY (sha1, header, type) )"; - SqliteCommand slc = new SqliteCommand(query, dbc); - slc.ExecuteNonQuery(); - slc.Dispose(); - } + SqliteCommand slc = new SqliteCommand(query, dbc); + slc.ExecuteNonQuery(); + slc.Dispose(); } catch (Exception ex) { - Globals.Logger.Error(ex); + logger.Error(ex); } finally { @@ -154,7 +102,7 @@ CREATE TABLE IF NOT EXISTS data ( public static List RetrieveHeadersFromDatabase(string SHA1) { // Ensure the database exists - EnsureDatabase(Constants.HeadererDbSchema, Constants.HeadererFileName, Constants.HeadererConnectionString); + EnsureDatabase(Constants.HeadererFileName, Constants.HeadererConnectionString); // Open the database connection SqliteConnection dbc = new SqliteConnection(Constants.HeadererConnectionString); @@ -171,13 +119,13 @@ CREATE TABLE IF NOT EXISTS data ( { while (sldr.Read()) { - Globals.Logger.Verbose($"Found match with rom type '{sldr.GetString(1)}'"); + logger.Verbose($"Found match with rom type '{sldr.GetString(1)}'"); headers.Add(sldr.GetString(0)); } } else { - Globals.Logger.Warning("No matching header could be found!"); + logger.Warning("No matching header could be found!"); } // Dispose of database objects diff --git a/SabreTools.Library/Tools/InternalStopwatch.cs b/SabreTools.Library/Tools/InternalStopwatch.cs index c900daf7..c77d51da 100644 --- a/SabreTools.Library/Tools/InternalStopwatch.cs +++ b/SabreTools.Library/Tools/InternalStopwatch.cs @@ -1,6 +1,6 @@ using System; -using SabreTools.Library.Data; +using SabreTools.Library.Logging; namespace SabreTools.Library.Tools { @@ -11,6 +11,7 @@ namespace SabreTools.Library.Tools { private string _subject; private DateTime _startTime; + private Logger _logger = new Logger(); /// /// Constructor that initalizes the stopwatch @@ -36,7 +37,7 @@ namespace SabreTools.Library.Tools public void Start() { _startTime = DateTime.Now; - Globals.Logger.User($"{_subject}..."); + _logger.User($"{_subject}..."); } /// @@ -54,7 +55,7 @@ namespace SabreTools.Library.Tools /// public void Stop() { - Globals.Logger.User($"{_subject} completed in {DateTime.Now.Subtract(_startTime):G}"); + _logger.User($"{_subject} completed in {DateTime.Now.Subtract(_startTime):G}"); } } } diff --git a/SabreTools/Features/BaseFeature.cs b/SabreTools/Features/BaseFeature.cs index 20cb39fe..2c242009 100644 --- a/SabreTools/Features/BaseFeature.cs +++ b/SabreTools/Features/BaseFeature.cs @@ -7,6 +7,7 @@ using SabreTools.Library.DatItems; using SabreTools.Library.FileTypes; using SabreTools.Library.Filtering; using SabreTools.Library.Help; +using SabreTools.Library.Logging; using SabreTools.Library.Reports; using SabreTools.Library.Tools; @@ -14,6 +15,15 @@ namespace SabreTools.Features { internal class BaseFeature : TopLevel { + #region Logging + + /// + /// Logging object + /// + protected Logger logger = new Logger(); + + #endregion + #region Enums /// @@ -2592,19 +2602,19 @@ Some special strings that can be used: if (GetBoolean(features, UpdateDescriptionValue)) { - Globals.Logger.User($"This flag '{(UpdateDescriptionValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateDescriptionValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.Machine_Description); } if (GetBoolean(features, UpdateGameTypeValue)) { - Globals.Logger.User($"This flag '{(UpdateGameTypeValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateGameTypeValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.Machine_Type); } if (GetBoolean(features, UpdateHashesValue)) { - Globals.Logger.User($"This flag '{(UpdateHashesValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateHashesValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.DatItem_CRC); updateFields.Add(Field.DatItem_MD5); #if NET_FRAMEWORK @@ -2619,19 +2629,19 @@ Some special strings that can be used: if (GetBoolean(features, UpdateManufacturerValue)) { - Globals.Logger.User($"This flag '{(UpdateManufacturerValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateManufacturerValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.Machine_Manufacturer); } if (GetBoolean(features, UpdateNamesValue)) { - Globals.Logger.User($"This flag '{(UpdateNamesValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateNamesValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.DatItem_Name); } if (GetBoolean(features, UpdateParentsValue)) { - Globals.Logger.User($"This flag '{(UpdateParentsValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateParentsValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.Machine_CloneOf); updateFields.Add(Field.Machine_RomOf); updateFields.Add(Field.Machine_SampleOf); @@ -2639,7 +2649,7 @@ Some special strings that can be used: if (GetBoolean(features, UpdateYearValue)) { - Globals.Logger.User($"This flag '{(UpdateYearValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(UpdateYearValue)}' is deprecated, please use {(string.Join(", ", UpdateFieldListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); updateFields.Add(Field.Machine_Year); } @@ -2819,108 +2829,108 @@ Some special strings that can be used: // Category if (features.ContainsKey(NotCategoryListValue)) { - Globals.Logger.User($"This flag '{(NotCategoryListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotCategoryListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Category, GetList(features, NotCategoryListValue), true); } if (features.ContainsKey(CategoryListValue)) { - Globals.Logger.User($"This flag '{(CategoryListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(CategoryListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Category, GetList(features, CategoryListValue), false); } // CRC if (features.ContainsKey(NotCrcListValue)) { - Globals.Logger.User($"This flag '{(NotCrcListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotCrcListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_CRC, GetList(features, NotCrcListValue), true); } if (features.ContainsKey(CrcListValue)) { - Globals.Logger.User($"This flag '{(CrcListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(CrcListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_CRC, GetList(features, NotCrcListValue), false); } // Item name if (features.ContainsKey(NotItemNameListValue)) { - Globals.Logger.User($"This flag '{(NotItemNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotItemNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Name, GetList(features, NotItemNameListValue), true); } if (features.ContainsKey(ItemNameListValue)) { - Globals.Logger.User($"This flag '{(ItemNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(ItemNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Name, GetList(features, ItemNameListValue), false); } // Item status if (features.ContainsKey(NotStatusListValue)) { - Globals.Logger.User($"This flag '{(NotStatusListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotStatusListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Status, GetList(features, NotStatusListValue), true); } if (features.ContainsKey(StatusListValue)) { - Globals.Logger.User($"This flag '{(StatusListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(StatusListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Status, GetList(features, StatusListValue), false); } // Item type if (features.ContainsKey(NotItemTypeListValue)) { - Globals.Logger.User($"This flag '{(NotItemTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotItemTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Type, GetList(features, NotItemTypeListValue), true); } if (features.ContainsKey(ItemTypeListValue)) { - Globals.Logger.User($"This flag '{(ItemTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(ItemTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_Type, GetList(features, ItemTypeListValue), false); } // Machine description if (features.ContainsKey(NotGameDescriptionListValue)) { - Globals.Logger.User($"This flag '{(NotGameDescriptionListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotGameDescriptionListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Description, GetList(features, NotGameDescriptionListValue), true); } if (features.ContainsKey(GameDescriptionListValue)) { - Globals.Logger.User($"This flag '{(GameDescriptionListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(GameDescriptionListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Description, GetList(features, GameDescriptionListValue), false); } // Machine name if (features.ContainsKey(NotGameNameListValue)) { - Globals.Logger.User($"This flag '{(NotGameNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotGameNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Name, GetList(features, NotGameNameListValue), true); } if (features.ContainsKey(GameNameListValue)) { - Globals.Logger.User($"This flag '{(GameNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(GameNameListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Name, GetList(features, GameNameListValue), false); } // Machine type if (features.ContainsKey(NotGameTypeListValue)) { - Globals.Logger.User($"This flag '{(NotGameTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotGameTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Type, GetList(features, NotGameTypeListValue), true); } if (features.ContainsKey(GameTypeListValue)) { - Globals.Logger.User($"This flag '{(GameTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(GameTypeListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Type, GetList(features, GameTypeListValue), false); } // MD5 if (features.ContainsKey(NotMd5ListValue)) { - Globals.Logger.User($"This flag '{(NotMd5ListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{(NotMd5ListValue)}' is deprecated, please use {(string.Join(", ", FilterListInput.Flags))} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_MD5, GetList(features, NotMd5ListValue), true); } if (features.ContainsKey(Md5ListValue)) { - Globals.Logger.User($"This flag '{Md5ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{Md5ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_MD5, GetList(features, Md5ListValue), false); } @@ -2928,12 +2938,12 @@ Some special strings that can be used: // RIPEMD160 if (features.ContainsKey(NotRipeMd160ListValue)) { - Globals.Logger.User($"This flag '{NotRipeMd160ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotRipeMd160ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_RIPEMD160, GetList(features, NotRipeMd160ListValue), true); } if (features.ContainsKey(RipeMd160ListValue)) { - Globals.Logger.User($"This flag '{RipeMd160ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{RipeMd160ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_RIPEMD160, GetList(features, RipeMd160ListValue), false); } #endif @@ -2941,79 +2951,79 @@ Some special strings that can be used: // Runnable if (features.ContainsKey(NotRunnableValue)) { - Globals.Logger.User($"This flag '{NotRunnableValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotRunnableValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Runnable, string.Empty, true); } if (features.ContainsKey(RunnableValue)) { - Globals.Logger.User($"This flag '{RunnableValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{RunnableValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.Machine_Runnable, string.Empty, false); } // SHA1 if (features.ContainsKey(NotSha1ListValue)) { - Globals.Logger.User($"This flag '{NotSha1ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotSha1ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA1, GetList(features, NotSha1ListValue), true); } if (features.ContainsKey(Sha1ListValue)) { - Globals.Logger.User($"This flag '{Sha1ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{Sha1ListValue}' is deprecated, please use {string.Join(", ", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA1, GetList(features, Sha1ListValue), false); } // SHA256 if (features.ContainsKey(NotSha256ListValue)) { - Globals.Logger.User($"This flag '{NotSha256ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotSha256ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA256, GetList(features, NotSha256ListValue), true); } if (features.ContainsKey(Sha256ListValue)) { - Globals.Logger.User($"This flag '{Sha256ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{Sha256ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA256, GetList(features, Sha256ListValue), false); } // SHA384 if (features.ContainsKey(NotSha384ListValue)) { - Globals.Logger.User($"This flag '{NotSha384ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotSha384ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA384, GetList(features, NotSha384ListValue), true); } if (features.ContainsKey(Sha384ListValue)) { - Globals.Logger.User($"This flag '{Sha384ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{Sha384ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA384, GetList(features, Sha384ListValue), false); } // SHA512 if (features.ContainsKey(NotSha512ListValue)) { - Globals.Logger.User($"This flag '{NotSha512ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{NotSha512ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA512, GetList(features, NotSha512ListValue), true); } if (features.ContainsKey(Sha512ListValue)) { - Globals.Logger.User($"This flag '{Sha512ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{Sha512ListValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); filter.SetFilter(Field.DatItem_SHA512, GetList(features, Sha512ListValue), false); } // Size if (features.ContainsKey(LessStringValue)) { - Globals.Logger.User($"This flag '{LessStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{LessStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); var value = Sanitizer.ToSize(GetString(features, LessStringValue)); filter.SetFilter(Field.DatItem_Size, $"<{value}", false); } if (features.ContainsKey(EqualStringValue)) { - Globals.Logger.User($"This flag '{EqualStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{EqualStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); var value = Sanitizer.ToSize(GetString(features, EqualStringValue)); filter.SetFilter(Field.DatItem_Size, $"={value}", false); } if (features.ContainsKey(GreaterStringValue)) { - Globals.Logger.User($"This flag '{GreaterStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); + logger.User($"This flag '{GreaterStringValue}' is deprecated, please use {string.Join(",", FilterListInput.Flags)} instead. Please refer to README.1ST or the help feature for more details."); var value = Sanitizer.ToSize(GetString(features, GreaterStringValue)); filter.SetFilter(Field.DatItem_Size, $">{value}", false); } diff --git a/SabreTools/Features/Batch.cs b/SabreTools/Features/Batch.cs index 5b8ec916..af7a561c 100644 --- a/SabreTools/Features/Batch.cs +++ b/SabreTools/Features/Batch.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.DatItems; using SabreTools.Library.Filtering; @@ -55,7 +54,7 @@ Reset the internal state: reset();"; // If the file doesn't exist, warn but continue if (!File.Exists(path)) { - Globals.Logger.User($"{path} does not exist. Skipping..."); + logger.User($"{path} does not exist. Skipping..."); continue; } @@ -85,20 +84,20 @@ Reset the internal state: reset();"; var command = BatchCommand.Create(line); if (command == null) { - Globals.Logger.User($"Could not process {path} due to the following line: {line}"); + logger.User($"Could not process {path} due to the following line: {line}"); break; } // Now switch on the command - Globals.Logger.User($"Attempting to invoke {command.Name} with {(command.Arguments.Count == 0 ? "no arguments" : "the following argument(s): " + string.Join(", ", command.Arguments))}"); + logger.User($"Attempting to invoke {command.Name} with {(command.Arguments.Count == 0 ? "no arguments" : "the following argument(s): " + string.Join(", ", command.Arguments))}"); switch (command.Name.ToLowerInvariant()) { // Set a header field case "set": if (command.Arguments.Count != 2) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: set(header.field, value);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: set(header.field, value);"); continue; } @@ -109,7 +108,7 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (field == Field.NULL) { - Globals.Logger.User($"{command.Arguments[0]} was an invalid field name"); + logger.User($"{command.Arguments[0]} was an invalid field name"); continue; } @@ -122,8 +121,8 @@ Reset the internal state: reset();"; case "input": if (command.Arguments.Count == 0) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: input(datpath, ...);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: input(datpath, ...);"); continue; } @@ -143,8 +142,8 @@ Reset the internal state: reset();"; case "dfd": if (command.Arguments.Count == 0) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: d2d(path, ...);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: d2d(path, ...);"); continue; } @@ -168,8 +167,8 @@ Reset the internal state: reset();"; case "filter": if (command.Arguments.Count < 2 || command.Arguments.Count > 4) { - Globals.Logger.User($"Invoked {command.Name} and expected between 2-4 arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: filter(field, value, [remove = false, [perMachine = false]]);"); + logger.User($"Invoked {command.Name} and expected between 2-4 arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: filter(field, value, [remove = false, [perMachine = false]]);"); continue; } @@ -186,17 +185,17 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (filterField == Field.NULL) { - Globals.Logger.User($"{command.Arguments[0]} was an invalid field name"); + logger.User($"{command.Arguments[0]} was an invalid field name"); continue; } if (filterRemove == null) { - Globals.Logger.User($"{command.Arguments[2]} was an invalid true/false value"); + logger.User($"{command.Arguments[2]} was an invalid true/false value"); continue; } if (filterPerMachine == null) { - Globals.Logger.User($"{command.Arguments[3]} was an invalid true/false value"); + logger.User($"{command.Arguments[3]} was an invalid true/false value"); continue; } @@ -218,8 +217,8 @@ Reset the internal state: reset();"; case "extra": if (command.Arguments.Count != 2) { - Globals.Logger.User($"Invoked {command.Name} and expected 2 arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: extra(field, inipath);"); + logger.User($"Invoked {command.Name} and expected 2 arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: extra(field, inipath);"); continue; } @@ -230,12 +229,12 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (extraField == Field.NULL) { - Globals.Logger.User($"{command.Arguments[0]} was an invalid field name"); + logger.User($"{command.Arguments[0]} was an invalid field name"); continue; } if (!File.Exists(command.Arguments[1])) { - Globals.Logger.User($"{command.Arguments[1]} was an invalid file name"); + logger.User($"{command.Arguments[1]} was an invalid file name"); continue; } @@ -255,8 +254,8 @@ Reset the internal state: reset();"; case "merge": if (command.Arguments.Count != 1) { - Globals.Logger.User($"Invoked {command.Name} and expected 1 argument, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: merge(split|merged|nonmerged|full|device);"); + logger.User($"Invoked {command.Name} and expected 1 argument, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: merge(split|merged|nonmerged|full|device);"); continue; } @@ -266,7 +265,7 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (mergingFlag == MergingFlag.None) { - Globals.Logger.User($"{command.Arguments[0]} was an invalid merging flag"); + logger.User($"{command.Arguments[0]} was an invalid merging flag"); continue; } @@ -279,8 +278,8 @@ Reset the internal state: reset();"; case "descname": if (command.Arguments.Count != 0) { - Globals.Logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: descname();"); + logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: descname();"); continue; } @@ -293,8 +292,8 @@ Reset the internal state: reset();"; case "1g1r": if (command.Arguments.Count == 0) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: 1g1r(region, ...);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: 1g1r(region, ...);"); continue; } @@ -307,8 +306,8 @@ Reset the internal state: reset();"; case "orpg": if (command.Arguments.Count != 0) { - Globals.Logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: orpg();"); + logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: orpg();"); continue; } @@ -321,8 +320,8 @@ Reset the internal state: reset();"; case "remove": if (command.Arguments.Count == 0) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: remove(field, ...);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: remove(field, ...);"); continue; } @@ -335,8 +334,8 @@ Reset the internal state: reset();"; case "sds": if (command.Arguments.Count != 0) { - Globals.Logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: sds();"); + logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: sds();"); continue; } @@ -349,8 +348,8 @@ Reset the internal state: reset();"; case "format": if (command.Arguments.Count == 0) { - Globals.Logger.User($"Invoked {command.Name} but no arguments were provided"); - Globals.Logger.User("Usage: format(datformat, ...);"); + logger.User($"Invoked {command.Name} but no arguments were provided"); + logger.User("Usage: format(datformat, ...);"); continue; } @@ -364,7 +363,7 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (datFile.Header.DatFormat == 0x00) { - Globals.Logger.User($"No valid output format found"); + logger.User($"No valid output format found"); continue; } @@ -374,8 +373,8 @@ Reset the internal state: reset();"; case "output": if (command.Arguments.Count != 1) { - Globals.Logger.User($"Invoked {command.Name} and expected exactly 1 argument, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: output(outdir);"); + logger.User($"Invoked {command.Name} and expected exactly 1 argument, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: output(outdir);"); continue; } @@ -387,8 +386,8 @@ Reset the internal state: reset();"; case "write": if (command.Arguments.Count > 1) { - Globals.Logger.User($"Invoked {command.Name} and expected 0-1 arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: write([overwrite = true]);"); + logger.User($"Invoked {command.Name} and expected 0-1 arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: write([overwrite = true]);"); continue; } @@ -400,7 +399,7 @@ Reset the internal state: reset();"; // If we had an invalid input, log and continue if (overwrite == null) { - Globals.Logger.User($"{command.Arguments[0]} was an invalid true/false value"); + logger.User($"{command.Arguments[0]} was an invalid true/false value"); continue; } @@ -412,8 +411,8 @@ Reset the internal state: reset();"; case "reset": if (command.Arguments.Count != 0) { - Globals.Logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); - Globals.Logger.User("Usage: reset();"); + logger.User($"Invoked {command.Name} and expected no arguments, but {command.Arguments.Count} arguments were provided"); + logger.User("Usage: reset();"); continue; } @@ -424,14 +423,14 @@ Reset the internal state: reset();"; break; default: - Globals.Logger.User($"Could not find a match for '{command.Name}'. Please see the help text for more details."); + logger.User($"Could not find a match for '{command.Name}'. Please see the help text for more details."); break; } } } catch (Exception ex) { - Globals.Logger.Error(ex, $"There was an exception processing {path}"); + logger.Error(ex, $"There was an exception processing {path}"); continue; } } diff --git a/SabreTools/Features/Split.cs b/SabreTools/Features/Split.cs index 9ccd82f3..32d43324 100644 --- a/SabreTools/Features/Split.cs +++ b/SabreTools/Features/Split.cs @@ -93,7 +93,7 @@ namespace SabreTools.Features // Level splitting if (splittingMode.HasFlag(SplittingMode.Level)) { - Globals.Logger.Warning("This feature is not implemented: level-split"); + logger.Warning("This feature is not implemented: level-split"); internalDat.SplitByLevel( OutputDir, GetBoolean(features, ShortValue), diff --git a/SabreTools/Features/Update.cs b/SabreTools/Features/Update.cs index 77c170b5..f1ab6354 100644 --- a/SabreTools/Features/Update.cs +++ b/SabreTools/Features/Update.cs @@ -160,7 +160,7 @@ namespace SabreTools.Features { // Create a new base DatFile DatFile datFile = DatFile.Create(Header); - Globals.Logger.User($"Processing '{Path.GetFileName(inputPath.CurrentPath)}'"); + logger.User($"Processing '{Path.GetFileName(inputPath.CurrentPath)}'"); datFile.Parse(inputPath, keep: true, keepext: datFile.Header.DatFormat.HasFlag(DatFormat.TSV) || datFile.Header.DatFormat.HasFlag(DatFormat.CSV) diff --git a/SabreTools/Features/Verify.cs b/SabreTools/Features/Verify.cs index c7bd508f..0f74dee1 100644 --- a/SabreTools/Features/Verify.cs +++ b/SabreTools/Features/Verify.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.Help; using SabreTools.Library.IO; @@ -81,7 +80,7 @@ namespace SabreTools.Features else { // Loop through and add the inputs to check against - Globals.Logger.User("Processing files:\n"); + logger.User("Processing files:\n"); foreach (string input in Inputs) { datdata.PopulateFromDir(input, asFiles: asFiles, hashes: quickScan ? Hash.CRC : Hash.Standard); @@ -130,7 +129,7 @@ namespace SabreTools.Features else { // Loop through and add the inputs to check against - Globals.Logger.User("Processing files:\n"); + logger.User("Processing files:\n"); foreach (string input in Inputs) { datdata.PopulateFromDir(input, asFiles: asFiles, hashes: quickScan ? Hash.CRC : Hash.Standard); diff --git a/SabreTools/Program.cs b/SabreTools/Program.cs index 8ceca0f7..481566c8 100644 --- a/SabreTools/Program.cs +++ b/SabreTools/Program.cs @@ -10,9 +10,20 @@ namespace SabreTools { public class Program { - // Private required variables + #region Static Variables + + /// + /// Help object that determines available functionality + /// private static Help _help; + /// + /// Logging object + /// + private static Logger logger = new Logger(); + + #endregion + /// /// Entry point for the SabreTools application /// @@ -20,12 +31,11 @@ namespace SabreTools public static void Main(string[] args) { // Perform initial setup and verification - Globals.Logger = new Logger("sabretools.log") - { - AppendPrefix = true, - LowestLogLevel = LogLevel.VERBOSE, - ThrowOnError = false, - }; + LoggerImpl.SetFilename("sabretools.log", true); + LoggerImpl.AppendPrefix = true; + LoggerImpl.LowestLogLevel = LogLevel.VERBOSE; + LoggerImpl.ThrowOnError = false; + LoggerImpl.Start(); // Create a new Help object for this program _help = RetrieveHelp(); @@ -52,7 +62,7 @@ namespace SabreTools if ((new List(args)).Contains("--credits")) { _help.OutputCredits(); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -60,7 +70,7 @@ namespace SabreTools if (args.Length == 0) { _help.OutputGenericHelp(); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -70,9 +80,9 @@ namespace SabreTools // Verify that the flag is valid if (!_help.TopLevelFlag(featureName)) { - Globals.Logger.User($"'{featureName}' is not valid feature flag"); + logger.User($"'{featureName}' is not valid feature flag"); _help.OutputIndividualFeature(featureName); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -86,14 +96,14 @@ namespace SabreTools if (featureName == DisplayHelp.Value || featureName == DisplayHelpDetailed.Value) { feature.ProcessArgs(args, _help); - Globals.Logger.Close(); + LoggerImpl.Close(); return; } // Now verify that all other flags are valid if (!feature.ProcessArgs(args, _help)) { - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -131,7 +141,7 @@ namespace SabreTools break; } - Globals.Logger.Close(); + LoggerImpl.Close(); return; } @@ -180,7 +190,7 @@ namespace SabreTools { if (inputs.Count == 0) { - Globals.Logger.Error("This feature requires at least one input"); + logger.Error("This feature requires at least one input"); _help.OutputIndividualFeature(feature); Environment.Exit(0); }