Example #1
0
        /// <summary>
        /// Process args list based on current feature
        /// </summary>
        public virtual bool ProcessArgs(string[] args, FeatureSet help)
        {
            for (int i = 1; i < args.Length; i++)
            {
                // Verify that the current flag is proper for the feature
                if (!ValidateInput(args[i]))
                {
                    // Special precautions for files and directories
                    if (File.Exists(args[i]) || Directory.Exists(args[i]))
                    {
                        Inputs.Add(args[i]);
                    }

                    // Special precautions for wildcarded inputs (potential paths)
                    else if (args[i].Contains("*") || args[i].Contains("?"))
                    {
                        Inputs.Add(args[i]);
                    }

                    // Everything else isn't a file
                    else
                    {
                        logger.Error($"Invalid input detected: {args[i]}");
                        help.OutputIndividualFeature(this.Name);
                        LoggerImpl.Close();
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #2
0
        /// <summary>
        /// Seek to a specific point in the stream, if possible
        /// </summary>
        /// <param name="input">Input stream to try seeking on</param>
        /// <param name="offset">Optional offset to seek to</param>
        public static long SeekIfPossible(this Stream input, long offset = 0)
        {
            try
            {
                if (input.CanSeek)
                {
                    if (offset < 0)
                    {
                        return(input.Seek(offset, SeekOrigin.End));
                    }
                    else if (offset >= 0)
                    {
                        return(input.Seek(offset, SeekOrigin.Begin));
                    }
                }

                return(input.Position);
            }
            catch (NotSupportedException ex)
            {
                LoggerImpl.Verbose(ex, "Stream does not support seeking to starting offset. Stream position not changed");
            }
            catch (NotImplementedException ex)
            {
                LoggerImpl.Warning(ex, "Stream does not support seeking to starting offset. Stream position not changed");
            }

            return(-1);
        }
Example #3
0
        public static void LogError(string tag, string data)
        {
            if (!Logger.loggingEnabled)
            {
                return;
            }

            LoggerImpl.LogError(tag, data);
        }
        /// <summary>
        /// Retrieve a list of just directories from inputs
        /// </summary>
        /// <param name="inputs">List of strings representing directories and files</param>
        /// <param name="appendparent">True if the parent name should be included in the ParentablePath, false otherwise (default)</param>
        /// <returns>List of strings representing just directories from the inputs</returns>
        public static List <ParentablePath> GetDirectoriesOnly(List <string> inputs, bool appendparent = false)
        {
            List <ParentablePath> outputs = new List <ParentablePath>();

            for (int i = 0; i < inputs.Count; i++)
            {
                string input = inputs[i];

                // If we have a null or empty path
                if (string.IsNullOrEmpty(input))
                {
                    continue;
                }

                // If we have a wildcard
                string pattern = "*";
                if (input.Contains("*") || input.Contains("?"))
                {
                    pattern = Path.GetFileName(input);
                    input   = input.Substring(0, input.Length - pattern.Length);
                }

                // Get the parent path in case of appending
                string parentPath;
                try
                {
                    parentPath = Path.GetFullPath(input);
                }
                catch (Exception ex)
                {
                    LoggerImpl.Error(ex, $"An exception occurred getting the full path for '{input}'");
                    continue;
                }

                if (Directory.Exists(input))
                {
                    List <string> directories = GetDirectoriesOrdered(input, pattern);
                    foreach (string dir in directories)
                    {
                        try
                        {
                            outputs.Add(new ParentablePath(Path.GetFullPath(dir), appendparent ? parentPath : string.Empty));
                        }
                        catch (PathTooLongException ex)
                        {
                            LoggerImpl.Warning(ex, $"The path for '{dir}' was too long");
                        }
                        catch (Exception ex)
                        {
                            LoggerImpl.Error(ex, $"An exception occurred processing '{dir}'");
                        }
                    }
                }
            }

            return(outputs);
        }
Example #5
0
        public void Logger_SeverityLevelTest()
        {
            LoggerImpl target = LogManager.GetLogger("Test");

            Assert.Equal(Severity.Verbose, target.SeverityLevel);   //  "Default severity level not calculated correctly for runtime logger with no overrides"
            target.SetSeverityLevel(Severity.Verbose2);
            Assert.Equal(Severity.Verbose2, target.SeverityLevel);  //  "Custom severity level was not set properly"
            LogManager.SetRuntimeLogLevel(Severity.Warning);
            Assert.Equal(Severity.Verbose2, target.SeverityLevel);  //  "Severity level was re-calculated even though a custom value had been set"
        }
Example #6
0
        public static void LogError(string tag, string data)
        {
            //If logging is disabled
            if (!TextEditorCore.Instance.TextEditorSettings.CollectFeedback)
            {
                return;
            }

            LoggerImpl.LogError(tag, data);
        }
Example #7
0
 public void AddLogger(LoggerImpl logger)
 {
     if (_logger == null)
     {
         _logger = logger;
     }
     else
     {
         _logger += logger;
     }
 }
Example #8
0
            private static LoggerImpl _logger(string area = "")
            {
                if (_loggers.ContainsKey(area))
                {
                    return(_loggers[area]);
                }

                var logger = LoggerImpl.GetInstance(area);

                _loggers.Add(area, logger);
                return(logger);
            }
Example #9
0
        public void CallSiteShouldWorkEvenInlined()
        {
            Type loggerType = typeof(Logger);
            var  stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  index      = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
            var  logEvent   = new LogEventInfo(LogLevel.Error, "logger1", "message1");

            logEvent.SetStackTrace(stacktrace, index);
            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);

            Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite);
        }
Example #10
0
        public void CallSiteShouldWorkEvenInlined()
        {
            var  logEvent    = new LogEventInfo(LogLevel.Error, "logger1", "message1");
            Type loggerType  = typeof(Logger);
            var  stacktrace  = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  stackFrames = stacktrace.GetFrames();
            var  index       = LoggerImpl.FindCallingMethodOnStackTrace(stackFrames, loggerType) ?? 0;
            int? indexLegacy = LoggerImpl.SkipToUserStackFrameLegacy(stackFrames, index);

            logEvent.GetCallSiteInformationInternal().SetStackTrace(stacktrace, index, indexLegacy);
            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);

            Assert.Equal("NLog.UnitTests.LayoutRenderers.CallSiteTests.CallSiteShouldWorkEvenInlined", callSite);
        }
Example #11
0
        public async Task <string> GetAsyncCallSite()
        {
            Type loggerType = typeof(Logger);
            var  stacktrace = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  index      = LoggerImpl.FindCallingMethodOnStackTrace(stacktrace, loggerType);
            var  logEvent   = new LogEventInfo(LogLevel.Error, "logger1", "message1");

            logEvent.SetStackTrace(stacktrace, index);

            await Task.Delay(0);

            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);

            return(callSite);
        }
        internal PersistentStreamPullingManager(
            GrainId id,
            string strProviderName,
            IStreamProviderRuntime runtime,
            IStreamPubSub streamPubSub,
            IQueueAdapterFactory adapterFactory,
            IStreamQueueBalancer streamQueueBalancer,
            PersistentStreamProviderConfig config,
            IProviderConfiguration providerConfig)
            : base(id, runtime.ExecutingSiloAddress)
        {
            if (string.IsNullOrWhiteSpace(strProviderName))
            {
                throw new ArgumentNullException("strProviderName");
            }
            if (runtime == null)
            {
                throw new ArgumentNullException("runtime", "IStreamProviderRuntime runtime reference should not be null");
            }
            if (streamPubSub == null)
            {
                throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null");
            }
            if (streamQueueBalancer == null)
            {
                throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null");
            }

            queuesToAgentsMap      = new Dictionary <QueueId, PersistentStreamPullingAgent>();
            streamProviderName     = strProviderName;
            providerRuntime        = runtime;
            pubSub                 = streamPubSub;
            this.config            = config;
            this.providerConfig    = providerConfig;
            nonReentrancyGuarantor = new AsyncSerialExecutor();
            latestRingNotificationSequenceNumber = 0;
            latestCommandNumber = 0;
            queueBalancer       = streamQueueBalancer;
            this.adapterFactory = adapterFactory;

            queueAdapterCache = adapterFactory.GetQueueAdapterCache();
            logger            = LogManager.GetLogger(GetType().Name + "-" + streamProviderName, LoggerType.Provider);
            Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName);

            IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count);
        }
Example #13
0
        public async Task <string> GetAsyncCallSite()
        {
            var logEvent = new LogEventInfo(LogLevel.Error, "logger1", "message1");

#if !NETSTANDARD1_5
            Type loggerType  = typeof(Logger);
            var  stacktrace  = StackTraceUsageUtils.GetWriteStackTrace(loggerType);
            var  stackFrames = stacktrace.GetFrames();
            var  index       = LoggerImpl.FindCallingMethodOnStackTrace(stackFrames, loggerType) ?? 0;
            int? indexLegacy = LoggerImpl.SkipToUserStackFrameLegacy(stackFrames, index);
            logEvent.GetCallSiteInformationInternal().SetStackTrace(stacktrace, index, indexLegacy);
#endif
            await Task.Delay(0);

            Layout l        = "${callsite}";
            var    callSite = l.Render(logEvent);
            return(callSite);
        }
Example #14
0
 /// <summary>
 /// Log an item ignoring the ColectFeedback settings
 /// This method must not be used for anything except insturmentation
 /// on/off reporting without explicit permission from the user
 /// Uses of this method must be approved by TL + Legal
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="data"></param>
 public static void FORCE_Log(string tag, string data)
 {
     LoggerImpl.FORCE_Log(tag, data);
 }
Example #15
0
        /// <summary>
        /// Retrieve file information for a single file
        /// </summary>
        /// <param name="input">Filename to get information from</param>
        /// <param name="size">Size of the input stream</param>
        /// <param name="hashes">Hashes to include in the information</param>
        /// <param name="keepReadOpen">True if the underlying read stream should be kept open, false otherwise</param>
        /// <returns>Populated BaseFile object if success, empty one on error</returns>
        public static BaseFile GetInfo(Stream input, long size = -1, Hash hashes = Hash.Standard, bool keepReadOpen = false)
        {
            // If we want to automatically set the size
            if (size == -1)
            {
                size = input.Length;
            }

            try
            {
                // Get a list of hashers to run over the buffer
                List <Hasher> hashers = new List <Hasher>();

                if (hashes.HasFlag(Hash.CRC))
                {
                    hashers.Add(new Hasher(Hash.CRC));
                }
                if (hashes.HasFlag(Hash.MD5))
                {
                    hashers.Add(new Hasher(Hash.MD5));
                }
                if (hashes.HasFlag(Hash.SHA1))
                {
                    hashers.Add(new Hasher(Hash.SHA1));
                }
                if (hashes.HasFlag(Hash.SHA256))
                {
                    hashers.Add(new Hasher(Hash.SHA256));
                }
                if (hashes.HasFlag(Hash.SHA384))
                {
                    hashers.Add(new Hasher(Hash.SHA384));
                }
                if (hashes.HasFlag(Hash.SHA512))
                {
                    hashers.Add(new Hasher(Hash.SHA512));
                }
                if (hashes.HasFlag(Hash.SpamSum))
                {
                    hashers.Add(new Hasher(Hash.SpamSum));
                }

                // Initialize the hashing helpers
                var    loadBuffer = new ThreadLoadBuffer(input);
                int    buffersize = 3 * 1024 * 1024;
                byte[] buffer0    = new byte[buffersize];
                byte[] buffer1    = new byte[buffersize];

                /*
                 * Please note that some of the following code is adapted from
                 * RomVault. This is a modified version of how RomVault does
                 * threaded hashing. As such, some of the terminology and code
                 * is the same, though variable names and comments may have
                 * been tweaked to better fit this code base.
                 */

                // Pre load the first buffer
                long refsize = size;
                int  next    = refsize > buffersize ? buffersize : (int)refsize;
                input.Read(buffer0, 0, next);
                int current = next;
                refsize -= next;
                bool bufferSelect = true;

                while (current > 0)
                {
                    // Trigger the buffer load on the second buffer
                    next = refsize > buffersize ? buffersize : (int)refsize;
                    if (next > 0)
                    {
                        loadBuffer.Trigger(bufferSelect ? buffer1 : buffer0, next);
                    }

                    byte[] buffer = bufferSelect ? buffer0 : buffer1;

                    // Run hashes in parallel
                    Parallel.ForEach(hashers, Globals.ParallelOptions, h => h.Process(buffer, current));

                    // Wait for the load buffer worker, if needed
                    if (next > 0)
                    {
                        loadBuffer.Wait();
                    }

                    // Setup for the next hashing step
                    current      = next;
                    refsize     -= next;
                    bufferSelect = !bufferSelect;
                }

                // Finalize all hashing helpers
                loadBuffer.Finish();
                Parallel.ForEach(hashers, Globals.ParallelOptions, h => h.Terminate());

                // Get the results
                BaseFile baseFile = new BaseFile()
                {
                    Size    = size,
                    CRC     = hashes.HasFlag(Hash.CRC) ? hashers.First(h => h.HashType == Hash.CRC).GetHash() : null,
                    MD5     = hashes.HasFlag(Hash.MD5) ? hashers.First(h => h.HashType == Hash.MD5).GetHash() : null,
                    SHA1    = hashes.HasFlag(Hash.SHA1) ? hashers.First(h => h.HashType == Hash.SHA1).GetHash() : null,
                    SHA256  = hashes.HasFlag(Hash.SHA256) ? hashers.First(h => h.HashType == Hash.SHA256).GetHash() : null,
                    SHA384  = hashes.HasFlag(Hash.SHA384) ? hashers.First(h => h.HashType == Hash.SHA384).GetHash() : null,
                    SHA512  = hashes.HasFlag(Hash.SHA512) ? hashers.First(h => h.HashType == Hash.SHA512).GetHash() : null,
                    SpamSum = hashes.HasFlag(Hash.SpamSum) ? hashers.First(h => h.HashType == Hash.SpamSum).GetHash() : null,
                };

                // Dispose of the hashers
                loadBuffer.Dispose();
                hashers.ForEach(h => h.Dispose());

                return(baseFile);
            }
            catch (IOException ex)
            {
                LoggerImpl.Warning(ex, "An exception occurred during hashing.");
                return(new BaseFile());
            }
            finally
            {
                if (!keepReadOpen)
                {
                    input.Dispose();
                }
                else
                {
                    input.SeekIfPossible();
                }
            }
        }
Example #16
0
 public static void Init(string logDirectory)
 {
     Impl = new LoggerImpl(logDirectory);
 }
Example #17
0
        /// <summary>
        /// Populate the dictionary from an INI file
        /// </summary>
        /// <param name="ini">Path to INI file to populate from</param>
        /// <remarks>
        /// The INI file format that is supported here is not exactly the same
        /// as a traditional one. This expects a MAME extras format, which usually
        /// doesn't contain key value pairs and always at least contains one section
        /// called `ROOT_FOLDER`. If that's the name of a section, then we assume
        /// the value is boolean. If there's another section name, then that is set
        /// as the value instead.
        /// </remarks>
        public bool PopulateFromFile(string ini)
        {
            // Prepare all intenral variables
            IniReader ir = new IniReader(ini)
            {
                ValidateRows = false
            };
            bool foundRootFolder = false;

            // If we got a null reader, just return
            if (ir == null)
            {
                return(false);
            }

            // Otherwise, read the file to the end
            try
            {
                while (!ir.EndOfStream)
                {
                    // Read in the next line and process
                    ir.ReadNextLine();

                    // We don't care about whitespace or comments
                    if (ir.RowType == IniRowType.None || ir.RowType == IniRowType.Comment)
                    {
                        continue;
                    }

                    // If we have a section, just read it in
                    if (ir.RowType == IniRowType.SectionHeader)
                    {
                        // If we've found the start of the extras, set the flag
                        if (string.Equals(ir.Section, "ROOT_FOLDER", StringComparison.OrdinalIgnoreCase))
                        {
                            foundRootFolder = true;
                        }

                        continue;
                    }

                    // If we have a value, then we start populating the dictionary
                    else if (foundRootFolder)
                    {
                        // Get the value and machine name
                        string value       = ir.Section;
                        string machineName = ir.CurrentLine.Trim();

                        // If the section is "ROOT_FOLDER", then we use the value "true" instead.
                        // This is done because some INI files use the name of the file as the
                        // category to be assigned to the items included.
                        if (value == "ROOT_FOLDER")
                        {
                            value = "true";
                        }

                        // Add the new mapping
                        Mappings[machineName] = value;
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerImpl.Warning(ex, $"Exception found while parsing '{ini}'");
                return(false);
            }

            ir.Dispose();
            return(true);
        }
Example #18
0
 public App()
 {
     Logger = new LoggerImpl();
 }
Example #19
0
 public Log(IClock clock)
 {
     entries    = new List <LogEntry>();
     Logger     = new LoggerImpl(this, clock);
     AllEntries = new ReadOnlyCollection <LogEntry>(entries);
 }
Example #20
0
 private static void InitLogger()
 {
     Logger = new LoggerImpl(InitNlog(), InitRollbar());
 }
Example #21
0
        /// <summary>
        /// Entry point for the SabreTools application
        /// </summary>
        /// <param name="args">String array representing command line parameters</param>
        public static void Main(string[] args)
        {
            // Perform initial setup and verification
            LoggerImpl.SetFilename(Path.Combine(PathTool.GetRuntimeDirectory(), "logs", "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();

            // Credits take precidence over all
            if ((new List <string>(args)).Contains("--credits"))
            {
                _help.OutputCredits();
                LoggerImpl.Close();
                return;
            }

            // If there's no arguments, show help
            if (args.Length == 0)
            {
                _help.OutputGenericHelp();
                LoggerImpl.Close();
                return;
            }

            // Get the first argument as a feature flag
            string featureName = args[0];

            // TODO: Remove this block once trimming is no longer needed
            // TODO: Update wiki documentation ONLY after this reaches stable
            // TODO: Re-evaluate feature flags with this change in mind
            featureName = featureName.TrimStart('-');
            if (args[0].StartsWith("-"))
            {
                logger.User($"Feature flags no longer require leading '-' characters");
            }

            // Verify that the flag is valid
            if (!_help.TopLevelFlag(featureName))
            {
                logger.User($"'{featureName}' is not valid feature flag");
                _help.OutputIndividualFeature(featureName);
                LoggerImpl.Close();
                return;
            }

            // Get the proper name for the feature
            featureName = _help.GetFeatureName(featureName);

            // Get the associated feature
            BaseFeature feature = _help[featureName] as BaseFeature;

            // If we had the help feature first
            if (featureName == DisplayHelp.Value || featureName == DisplayHelpDetailed.Value)
            {
                feature.ProcessArgs(args, _help);
                LoggerImpl.Close();
                return;
            }

            // Now verify that all other flags are valid
            if (!feature.ProcessArgs(args, _help))
            {
                LoggerImpl.Close();
                return;
            }

            // Set the new log level based on settings
            LoggerImpl.LowestLogLevel = feature.LogLevel;

            // If output is being redirected or we are in script mode, don't allow clear screens
            if (!Console.IsOutputRedirected && feature.ScriptMode)
            {
                Console.Clear();
                Prepare.SetConsoleHeader("SabreTools");
            }

            // Now process the current feature
            Dictionary <string, Feature> features = _help.GetEnabledFeatures();
            bool success = false;

            switch (featureName)
            {
            // No-op as these should be caught
            case DisplayHelp.Value:
            case DisplayHelpDetailed.Value:
                break;

            // Require input verification
            case Batch.Value:
            case DatFromDir.Value:
            case Extract.Value:
            case Restore.Value:
            case Split.Value:
            case Stats.Value:
            case Update.Value:
            case Verify.Value:
                VerifyInputs(feature.Inputs, feature);
                success = feature.ProcessFeatures(features);
                break;

            // Requires no input verification
            case Sort.Value:
                success = feature.ProcessFeatures(features);
                break;

            // If nothing is set, show the help
            default:
                _help.OutputGenericHelp();
                break;
            }

            // If the feature failed, output help
            if (!success)
            {
                logger.Error("An error occurred during processing!");
                _help.OutputIndividualFeature(featureName);
            }

            LoggerImpl.Close();
            return;
        }
Example #22
0
        /// <summary>
        /// Entry point for the SabreTools application
        /// </summary>
        /// <param name="args">String array representing command line parameters</param>
        public static void Main(string[] args)
        {
            // Perform initial setup and verification
            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();

            // Get the location of the script tag, if it exists
            int scriptLocation = (new List <string>(args)).IndexOf("--script");

            // If output is being redirected or we are in script mode, don't allow clear screens
            if (!Console.IsOutputRedirected && scriptLocation == -1)
            {
                Console.Clear();
                Prepare.SetConsoleHeader("SabreTools");
            }

            // Now we remove the script tag because it messes things up
            if (scriptLocation > -1)
            {
                List <string> newargs = new List <string>(args);
                newargs.RemoveAt(scriptLocation);
                args = newargs.ToArray();
            }

            // Credits take precidence over all
            if ((new List <string>(args)).Contains("--credits"))
            {
                _help.OutputCredits();
                LoggerImpl.Close();
                return;
            }

            // If there's no arguments, show help
            if (args.Length == 0)
            {
                _help.OutputGenericHelp();
                LoggerImpl.Close();
                return;
            }

            // Get the first argument as a feature flag
            string featureName = args[0];

            // Verify that the flag is valid
            if (!_help.TopLevelFlag(featureName))
            {
                logger.User($"'{featureName}' is not valid feature flag");
                _help.OutputIndividualFeature(featureName);
                LoggerImpl.Close();
                return;
            }

            // Get the proper name for the feature
            featureName = _help.GetFeatureName(featureName);

            // Get the associated feature
            BaseFeature feature = _help[featureName] as BaseFeature;

            // If we had the help feature first
            if (featureName == DisplayHelp.Value || featureName == DisplayHelpDetailed.Value)
            {
                feature.ProcessArgs(args, _help);
                LoggerImpl.Close();
                return;
            }

            // Now verify that all other flags are valid
            if (!feature.ProcessArgs(args, _help))
            {
                LoggerImpl.Close();
                return;
            }

            // Now process the current feature
            Dictionary <string, Feature> features = _help.GetEnabledFeatures();

            switch (featureName)
            {
            // No-op as these should be caught
            case DisplayHelp.Value:
            case DisplayHelpDetailed.Value:
            case Script.Value:
                break;

            // Require input verification
            case Batch.Value:
            case DatFromDir.Value:
            case Extract.Value:
            case Restore.Value:
            case Split.Value:
            case Stats.Value:
            case Update.Value:
            case Verify.Value:
                VerifyInputs(feature.Inputs, featureName);
                feature.ProcessFeatures(features);
                break;

            // Requires no input verification
            case Sort.Value:
                feature.ProcessFeatures(features);
                break;

            // If nothing is set, show the help
            default:
                _help.OutputGenericHelp();
                break;
            }

            LoggerImpl.Close();
            return;
        }
Example #23
0
        /// <summary>
        /// Entry class for the RombaSharp application
        /// </summary>
        public static void Main(string[] args)
        {
            // Perform initial setup and verification
            LoggerImpl.SetFilename(Path.Combine(PathTool.GetRuntimeDirectory(), "logs", "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();

            // Credits take precidence over all
            if ((new List <string>(args)).Contains("--credits"))
            {
                _help.OutputCredits();
                LoggerImpl.Close();
                return;
            }

            // If there's no arguments, show help
            if (args.Length == 0)
            {
                _help.OutputGenericHelp();
                LoggerImpl.Close();
                return;
            }

            // Get the first argument as a feature flag
            string featureName = args[0];

            // Verify that the flag is valid
            if (!_help.TopLevelFlag(featureName))
            {
                logger.User($"'{featureName}' is not valid feature flag");
                _help.OutputIndividualFeature(featureName);
                LoggerImpl.Close();
                return;
            }

            // Get the proper name for the feature
            featureName = _help.GetFeatureName(featureName);

            // Get the associated feature
            BaseFeature feature = _help[featureName] as BaseFeature;

            // If we had the help feature first
            if (featureName == DisplayHelp.Value || featureName == DisplayHelpDetailed.Value)
            {
                feature.ProcessArgs(args, _help);
                LoggerImpl.Close();
                return;
            }

            // Now verify that all other flags are valid
            if (!feature.ProcessArgs(args, _help))
            {
                LoggerImpl.Close();
                return;
            }

            // Set the new log level based on settings
            LoggerImpl.LowestLogLevel = feature.LogLevel;

            // If output is being redirected or we are in script mode, don't allow clear screens
            if (!Console.IsOutputRedirected && feature.ScriptMode)
            {
                Console.Clear();
                Prepare.SetConsoleHeader("SabreTools");
            }

            // Now process the current feature
            Dictionary <string, Feature> features = _help.GetEnabledFeatures();
            bool success = false;

            switch (featureName)
            {
            case DisplayHelpDetailed.Value:
            case DisplayHelp.Value:
                // No-op as this should be caught
                break;

            // Require input verification
            case Archive.Value:
            case Build.Value:
            case DatStats.Value:
            case Fixdat.Value:
            case Import.Value:
            case Lookup.Value:
            case Merge.Value:
            case Miss.Value:
            case RescanDepots.Value:
                VerifyInputs(feature.Inputs, featureName);
                success = feature.ProcessFeatures(features);
                break;

            // Requires no input verification
            case Cancel.Value:
            case DbStats.Value:
            case Diffdat.Value:
            case Dir2Dat.Value:
            case EDiffdat.Value:
            case Export.Value:
            case Memstats.Value:
            case Progress.Value:
            case PurgeBackup.Value:
            case PurgeDelete.Value:
            case RefreshDats.Value:
            case Shutdown.Value:
            case Features.Version.Value:
                success = feature.ProcessFeatures(features);
                break;

            // If nothing is set, show the help
            default:
                _help.OutputGenericHelp();
                break;
            }

            // If the feature failed, output help
            if (!success)
            {
                logger.Error("An error occurred during processing!");
                _help.OutputIndividualFeature(featureName);
            }

            LoggerImpl.Close();
            return;
        }
Example #24
0
 public static void CancelProcessing()
 {
     LoggerImpl.CancelProcessing();
 }