Instance logging with backing static class instead of Global

This commit is contained in:
Matt Nadareski
2020-10-07 15:42:30 -07:00
parent 348a2a2bcb
commit b7db9f7f14
69 changed files with 1034 additions and 834 deletions

View File

@@ -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;
/// <summary>
/// Logging object
/// </summary>
protected Logger logger = new Logger();
public override void ProcessFeatures(Dictionary<string, SabreTools.Library.Help.Feature> features)
{
InitializeConfiguration();
DatabaseTools.EnsureDatabase(_dbSchema, _db, _connectionString);
EnsureDatabase(_db, _connectionString);
}
/// <summary>
/// Ensure that the databse exists and has the proper schema
/// </summary>
/// <param name="db">Name of the databse</param>
/// <param name="connectionString">Connection string for SQLite</param>
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
/// </summary>
/// <param name="inputs">List of input strings to check for, presumably file names</param>
/// <returns>Dictionary of hash/full path for each of the valid DATs</returns>
internal static Dictionary<string, string> GetValidDats(List<string> inputs)
internal Dictionary<string, string> GetValidDats(List<string> inputs)
{
// Get a dictionary of filenames that actually exist in the DATRoot, logging which ones are not
List<string> 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
/// <summary>
/// Initialize the Romba application from XML config
/// </summary>
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
/// </summary>
/// <param name="dat">DatFile hash information to add</param>
/// <param name="dbc">Database connection to use</param>
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)
{

View File

@@ -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<string, Feature> features)
{
base.ProcessFeatures(features);
Globals.Logger.User("This feature is not yet implemented: cancel");
logger.User("This feature is not yet implemented: cancel");
}
}
}

View File

@@ -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();

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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");
}
}
}

View File

@@ -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<string, Feature> 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;
}

View File

@@ -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();

View File

@@ -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<string, Feature> features)
{
base.ProcessFeatures(features);
Globals.Logger.User("This feature is not yet implemented: memstats");
logger.User("This feature is not yet implemented: memstats");
}
}
}

View File

@@ -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();

View File

@@ -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");
}
}
}

View File

@@ -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<string, Feature> features)
{
base.ProcessFeatures(features);
Globals.Logger.User("This feature is not yet implemented: progress");
logger.User("This feature is not yet implemented: progress");
}
}
}

View File

@@ -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<string> dats = GetList(features, DatsListStringValue);
List<string> 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");
}
}
}

View File

@@ -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<string> dats = GetList(features, DatsListStringValue);
List<string> 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");
}
}
}

View File

@@ -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))

View File

@@ -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<string, SabreTools.Library.Help.Feature> 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;
}

View File

@@ -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<string, Feature> features)
{
base.ProcessFeatures(features);
Globals.Logger.User("This feature is not yet implemented: shutdown");
logger.User("This feature is not yet implemented: shutdown");
}
}
}

View File

@@ -22,7 +22,7 @@ namespace RombaSharp.Features
public override void ProcessFeatures(Dictionary<string, Feature> features)
{
base.ProcessFeatures(features);
Globals.Logger.User($"RombaSharp version: {Constants.Version}");
logger.User($"RombaSharp version: {Constants.Version}");
}
}
}

View File

@@ -18,20 +18,31 @@ namespace RombaSharp
/// </remarks>
public class Program
{
#region Static Variables
/// <summary>
/// Help object that determines available functionality
/// </summary>
private static Help _help;
/// <summary>
/// Logging object
/// </summary>
private static Logger logger = new Logger();
#endregion
/// <summary>
/// Entry class for the RombaSharp application
/// </summary>
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<string>(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);
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
/// <summary>
/// Header values
/// </summary>
[JsonProperty("header")]
[XmlElement("header")]
[JsonProperty("header"), XmlElement("header")]
public DatHeader Header { get; set; } = new DatHeader();
/// <summary>
/// DatItems and related statistics
/// </summary>
[JsonProperty("items")]
[XmlElement("items")]
[JsonProperty("items"), XmlElement("items")]
public ItemDictionary Items { get; set; } = new ItemDictionary();
#endregion
#region Logging
/// <summary>
/// Logging object
/// </summary>
[JsonIgnore, XmlIgnore]
protected Logger logger = new Logger();
#endregion
#region Constructors
/// <summary>
@@ -242,7 +251,7 @@ namespace SabreTools.Library.DatFiles
/// <param name="onlySame">True if descriptions should only be replaced if the game name is the same, false otherwise</param>
public void BaseReplace(DatFile intDat, List<Field> 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<Field>();
// 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
/// <param name="mergeroms">Dedupe type to be used</param>
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
/// <param name="mergeroms">Dedupe type to be used</param>
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
/// <param name="mergeroms">Dedupe type to be used</param>
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
/// <param name="mergeroms">Dedupe type to be used</param>
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
/// <param name="mergeroms">Dedupe type to be used</param>
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<string> 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
/// <param name="asFiles">TreatAsFiles representing CHD and Archive scanning</param>
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<Field, DatFile> 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<Field, DatFile> fieldDats = new Dictionary<Field, DatFile>();
@@ -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<ItemType, DatFile> 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<ItemType, DatFile> typeDats = new Dictionary<ItemType, DatFile>();
@@ -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<DatFormat, string> 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;

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
/// </summary>
private object statsLock = new object();
/// <summary>
/// Logging object
/// </summary>
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<string> games = new List<string>();
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");
}
/// <summary>

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
/// <summary>
/// Logging object
/// </summary>
[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)
{

View File

@@ -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;";

View File

@@ -12,12 +12,6 @@ namespace SabreTools.Library.Data
/// </summary>
public class Globals
{
#region Private implementations
private static Logger _logger = null;
#endregion
#region Public accessors
/// <summary>
@@ -35,21 +29,6 @@ namespace SabreTools.Library.Data
/// </summary>
public static string ExeName => new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
/// <summary>
/// Logging object for writing to file and console
/// </summary>
public static Logger Logger
{
get
{
if (_logger == null)
_logger = new Logger();
return _logger;
}
set { _logger = value; }
}
/// <summary>
/// Maximum threads to use during parallel operations
/// </summary>

View File

@@ -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:

View File

@@ -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<BaseFile> _children;
/// <summary>
/// Logging object
/// </summary>
protected static Logger logger = new Logger();
/// <summary>
/// Flag specific to Folder to omit Machine name from output path
/// </summary>
@@ -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

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
/// <summary>
/// Logging object
/// </summary>
private Logger logger = new Logger();
#endregion
#region Extras Population
/// <summary>
@@ -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;
}

View File

@@ -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;
}

View File

@@ -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
/// <summary>
/// Logging object
/// </summary>
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;
}

View File

@@ -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<string> Inputs = new List<string>();
#region Logging
/// <summary>
/// Logging object
/// </summary>
private Logger logger = new Logger();
#endregion
/// <summary>
/// Process args list based on current feature
/// </summary>
@@ -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;
}
}

View File

@@ -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}'");
}
}
}

View File

@@ -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
/// </summary>
public static class FileExtensions
{
#region Logging
/// <summary>
/// Logging object
/// </summary>
private static Logger logger = new Logger();
#endregion
/// <summary>
/// Add an aribtrary number of bytes to the inputted file
/// </summary>
@@ -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
/// <returns>The IniReader representing the (possibly converted) file, null otherwise</returns>
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
/// <returns>The XmlTextReader representing the (possibly converted) file, null otherwise</returns>
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;
}

View File

@@ -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;

View File

@@ -1,293 +1,26 @@
using System;
using System.IO;
using System.Text;
using SabreTools.Library.Data;
using SabreTools.Library.IO;
namespace SabreTools.Library.Logging
{
/// <summary>
/// Log either to file or to the console
/// Per-class logging
/// </summary>
public class Logger
{
#region Fields
/// <summary>
/// Optional output filename for logs
/// Instance associated with this logger
/// </summary>
public string Filename { get; set; } = null;
/// TODO: Derive class name for this object, if possible
private object instance;
/// <summary>
/// Determines if we're logging to file or not
/// Constructor
/// </summary>
public bool LogToFile { get { return !string.IsNullOrWhiteSpace(Filename); } }
/// <summary>
/// Optional output log directory
/// </summary>
/// TODO: Make this either passed in or optional
public string LogDirectory { get; set; } = Path.Combine(Globals.ExeDir, "logs") + Path.DirectorySeparatorChar;
/// <summary>
/// Determines the lowest log level to output
/// </summary>
public LogLevel LowestLogLevel { get; set; } = LogLevel.VERBOSE;
/// <summary>
/// Determines whether to prefix log lines with level and datetime
/// </summary>
public bool AppendPrefix { get; set; } = true;
/// <summary>
/// Determines whether to throw if an exception is logged
/// </summary>
public bool ThrowOnError { get; set; } = false;
/// <summary>
/// Logging start time for metrics
/// </summary>
public DateTime StartTime { get; private set; }
/// <summary>
/// Determines if there were errors logged
/// </summary>
public bool LoggedErrors { get; private set; } = false;
/// <summary>
/// Determines if there were warnings logged
/// </summary>
public bool LoggedWarnings { get; private set; } = false;
#endregion
#region Private instance variables
/// <summary>
/// StreamWriter representing the output log file
/// </summary>
private StreamWriter _log;
/// <summary>
/// Object lock for multithreaded logging
/// </summary>
private readonly object _lock = new object();
#endregion
#region Constructors
/// <summary>
/// Initialize a console-only logger object
/// </summary>
public Logger()
public Logger(object instance = null)
{
Start();
this.instance = instance;
}
/// <summary>
/// Initialize a Logger object with the given information
/// </summary>
/// <param name="filename">Filename representing log location</param>
/// <param name="addDate">True to add a date string to the filename (default), false otherwise</param>
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
/// <summary>
/// Start logging by opening output file (if necessary)
/// </summary>
/// <returns>True if the logging was started correctly, false otherwise</returns>
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;
}
/// <summary>
/// End logging by closing output file (if necessary)
/// </summary>
/// <param name="suppress">True if all ending output is to be suppressed, false otherwise (default)</param>
/// <returns>True if the logging was ended correctly, false otherwise</returns>
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
/// <summary>
/// Handler for log events
/// </summary>
public static event LogEventHandler LogEventHandler = delegate { };
/// <summary>
/// Default log event handling
/// </summary>
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);
}
/// <summary>
/// Write the given string to the log output
/// </summary>
/// <param name="output">String to be written log</param>
/// <param name="loglevel">Severity of the information being logged</param>
/// <returns>True if the output could be written, false otherwise</returns>
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
/// <summary>
@@ -298,7 +31,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Verbose(Exception ex, string output = null)
{
LogEventHandler(this, new LogEventArgs(LogLevel.VERBOSE, output, ex));
LoggerImpl.Verbose(this.instance, ex, output);
}
/// <summary>
@@ -308,7 +41,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Verbose(string output)
{
LogEventHandler(this, new LogEventArgs(LogLevel.VERBOSE, output, null));
LoggerImpl.Verbose(this.instance, output);
}
/// <summary>
@@ -319,7 +52,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void User(Exception ex, string output = null)
{
LogEventHandler(this, new LogEventArgs(LogLevel.USER, output, ex));
LoggerImpl.User(this.instance, ex, output);
}
/// <summary>
@@ -329,7 +62,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void User(string output)
{
LogEventHandler(this, new LogEventArgs(LogLevel.USER, output, null));
LoggerImpl.User(this.instance, output);
}
/// <summary>
@@ -340,7 +73,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Warning(Exception ex, string output = null)
{
LogEventHandler(this, new LogEventArgs(LogLevel.WARNING, output, ex));
LoggerImpl.Warning(this.instance, ex, output);
}
/// <summary>
@@ -350,7 +83,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Warning(string output)
{
LogEventHandler(this, new LogEventArgs(LogLevel.WARNING, output, null));
LoggerImpl.Warning(this.instance, output);
}
/// <summary>
@@ -361,7 +94,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Error(Exception ex, string output = null)
{
LogEventHandler(this, new LogEventArgs(LogLevel.ERROR, output, ex));
LoggerImpl.Error(this.instance, ex, output);
}
/// <summary>
@@ -371,7 +104,7 @@ namespace SabreTools.Library.Logging
/// <returns>True if the output could be written, false otherwise</returns>
public void Error(string output)
{
LogEventHandler(this, new LogEventArgs(LogLevel.ERROR, output, null));
LoggerImpl.Error(this.instance, output);
}
#endregion

View File

@@ -0,0 +1,373 @@
using System;
using System.IO;
using System.Text;
using SabreTools.Library.Data;
using SabreTools.Library.IO;
namespace SabreTools.Library.Logging
{
/// <summary>
/// Internal logging implementation
/// </summary>
public static class LoggerImpl
{
#region Fields
/// <summary>
/// Optional output filename for logs
/// </summary>
public static string Filename { get; set; } = null;
/// <summary>
/// Determines if we're logging to file or not
/// </summary>
public static bool LogToFile { get { return !string.IsNullOrWhiteSpace(Filename); } }
/// <summary>
/// Optional output log directory
/// </summary>
/// TODO: Make this either passed in or optional
public static string LogDirectory { get; set; } = Path.Combine(Globals.ExeDir, "logs") + Path.DirectorySeparatorChar;
/// <summary>
/// Determines the lowest log level to output
/// </summary>
public static LogLevel LowestLogLevel { get; set; } = LogLevel.VERBOSE;
/// <summary>
/// Determines whether to prefix log lines with level and datetime
/// </summary>
public static bool AppendPrefix { get; set; } = true;
/// <summary>
/// Determines whether to throw if an exception is logged
/// </summary>
public static bool ThrowOnError { get; set; } = false;
/// <summary>
/// Logging start time for metrics
/// </summary>
public static DateTime StartTime { get; private set; }
/// <summary>
/// Determines if there were errors logged
/// </summary>
public static bool LoggedErrors { get; private set; } = false;
/// <summary>
/// Determines if there were warnings logged
/// </summary>
public static bool LoggedWarnings { get; private set; } = false;
#endregion
#region Private variables
/// <summary>
/// StreamWriter representing the output log file
/// </summary>
private static StreamWriter _log;
/// <summary>
/// Object lock for multithreaded logging
/// </summary>
private static readonly object _lock = new object();
#endregion
#region Control
/// <summary>
/// Generate and set the log filename
/// </summary>
/// <param name="filename">Base filename to use</param>
/// <param name="addDate">True to append a date to the filename, false otherwise</param>
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;
}
/// <summary>
/// Start logging by opening output file (if necessary)
/// </summary>
/// <returns>True if the logging was started correctly, false otherwise</returns>
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;
}
/// <summary>
/// End logging by closing output file (if necessary)
/// </summary>
/// <param name="suppress">True if all ending output is to be suppressed, false otherwise (default)</param>
/// <returns>True if the logging was ended correctly, false otherwise</returns>
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
/// <summary>
/// Handler for log events
/// </summary>
public static event LogEventHandler LogEventHandler = delegate { };
/// <summary>
/// Default log event handling
/// </summary>
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);
}
/// <summary>
/// Write the given string to the log output
/// </summary>
/// <param name="output">String to be written log</param>
/// <param name="loglevel">Severity of the information being logged</param>
/// <returns>True if the output could be written, false otherwise</returns>
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
/// <summary>
/// Write the given exception as a verbose message to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="ex">Exception to be written log</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Verbose(object instance, Exception ex, string output = null)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.VERBOSE, output, ex));
}
/// <summary>
/// Write the given string as a verbose message to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Verbose(object instance, string output)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.VERBOSE, output, null));
}
/// <summary>
/// Write the given exception as a user message to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="ex">Exception to be written log</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void User(object instance, Exception ex, string output = null)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.USER, output, ex));
}
/// <summary>
/// Write the given string as a user message to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void User(object instance, string output)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.USER, output, null));
}
/// <summary>
/// Write the given exception as a warning to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="ex">Exception to be written log</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Warning(object instance, Exception ex, string output = null)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.WARNING, output, ex));
}
/// <summary>
/// Write the given string as a warning to the log output
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Warning(object instance, string output)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.WARNING, output, null));
}
/// <summary>
/// Writes the given exception as an error in the log
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="ex">Exception to be written log</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Error(object instance, Exception ex, string output = null)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.ERROR, output, ex));
}
/// <summary>
/// Writes the given string as an error in the log
/// </summary>
/// <param name="instance">Instance object that's the source of logging</param>
/// <param name="output">String to be written log</param>
/// <returns>True if the output could be written, false otherwise</returns>
internal static void Error(object instance, string output)
{
LogEventHandler(instance, new LogEventArgs(LogLevel.ERROR, output, null));
}
#endregion
}
}

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48;netcoreapp3.1</TargetFrameworks>

View File

@@ -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
/// <summary>
/// Logging object
/// </summary>
private Logger logger = new Logger();
#endregion
/// <summary>
/// Check if a Stream passes all tests in the SkipperRule
/// </summary>
@@ -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

View File

@@ -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
/// </summary>
private static List<SkipperFile> List;
#region Logging
/// <summary>
/// Logging object
/// </summary>
private static Logger logger = new Logger();
#endregion
/// <summary>
/// Local paths
/// </summary>
@@ -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<SkipperFile> tempList = new List<SkipperFile>();
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;
}

View File

@@ -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
/// </summary>
public static class DatabaseTools
{
#region Logging
/// <summary>
/// Logging object
/// </summary>
private static Logger logger = new Logger();
#endregion
/// <summary>
/// Add a header to the database
/// </summary>
@@ -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
/// <summary>
/// Ensure that the databse exists and has the proper schema
/// </summary>
/// <param name="type">Schema type to use</param>
/// <param name="db">Name of the databse</param>
/// <param name="connectionString">Connection string for SQLite</param>
/// 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<string> 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

View File

@@ -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();
/// <summary>
/// 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}...");
}
/// <summary>
@@ -54,7 +55,7 @@ namespace SabreTools.Library.Tools
/// </summary>
public void Stop()
{
Globals.Logger.User($"{_subject} completed in {DateTime.Now.Subtract(_startTime):G}");
_logger.User($"{_subject} completed in {DateTime.Now.Subtract(_startTime):G}");
}
}
}

View File

@@ -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
/// <summary>
/// Logging object
/// </summary>
protected Logger logger = new Logger();
#endregion
#region Enums
/// <summary>
@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -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),

View File

@@ -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)

View File

@@ -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);

View File

@@ -10,9 +10,20 @@ namespace SabreTools
{
public class Program
{
// Private required variables
#region Static Variables
/// <summary>
/// Help object that determines available functionality
/// </summary>
private static Help _help;
/// <summary>
/// Logging object
/// </summary>
private static Logger logger = new Logger();
#endregion
/// <summary>
/// Entry point for the SabreTools application
/// </summary>
@@ -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<string>(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);
}