Пример #1
0
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "PackRules"));
            RulesVerifier verifier = new RulesVerifier(_path);

            if (!verifier.Verify())//throws anyway
            {
                return((int)ExitCode.CriticalError);
            }

            List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.Formatting = (_indent) ? Formatting.Indented : Formatting.None;

            using (FileStream fs = File.Open(_outputfile, FileMode.Create, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(JsonConvert.SerializeObject(list, settings));
                sw.Close();
                fs.Close();
            }

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "PackRules"));
            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);

            return((int)ExitCode.NoIssues);
        }
        public void FlushAll()
        {
            if (_outputWriter != null)
            {
                _outputWriter.WriteApp(_appProfile);

                if (_outputWriter.TextWriter != null && _arg_fileFormat != "html")
                {
                    _outputWriter.FlushAndClose();//not required for html formal i.e. multiple files already closed
                    _outputWriter = null;

                    //Special case to avoid writing tmp file path to output file for TagTest,TagDiff or when called as a DLL since unnecessary
                    if (_arg_consoleVerbosityLevel.ToLower() != "none")
                    {
                        if (!String.IsNullOrEmpty(_arg_outputFile))
                        {
                            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                        }
                        else
                        {
                            WriteOnce.NewLine();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            bool issues = false;

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Verify Rules"));

            RulesVerifier verifier = new RulesVerifier(_arg_customRulesPath);

            if (!verifier.Verify())
            {
                return((int)ExitCode.NotVerified);
            }

            RuleSet rules = verifier.CompiledRuleset;

            //report each add
            foreach (Rule rule in rules)
            {
                WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
            }

            WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Verify Rules"));

            WriteOnce.FlushAll();
            if (!String.IsNullOrEmpty(_arg_outputFile))
            {
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
            }

            return(issues ? (int)ExitCode.NotVerified : (int)ExitCode.Verified);
        }
Пример #4
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("VerifyRulesCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "verifyrules"));

            ExitCode exitCode = ExitCode.CriticalError;

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();
                exitCode = ExitCode.Verified;

                RuleSet rules = verifier.CompiledRuleset;

                //report each add to console if desired
                foreach (Rule rule in rules)
                {
                    WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
                }

                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "verifyrules"));
                if (!String.IsNullOrEmpty(_arg_outputFile) && Utils.CLIExecutionContext)
                {
                    WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
                }
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)exitCode);
        }
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "packrules"));

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();

                List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.Formatting = (_arg_indent) ? Formatting.Indented : Formatting.None;

                using (FileStream fs = File.Open(_arg_outputfile, FileMode.Create, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(JsonConvert.SerializeObject(list, settings));
                    sw.Close();
                    fs.Close();
                }

                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "packrules"));
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)ExitCode.NoIssues);
        }
Пример #6
0
        public void FlushAll()
        {
            if (_outputWriter != null)
            {
                _outputWriter.WriteApp(_appProfile);

                if (_outputWriter.TextWriter != null && _arg_fileFormat != "html")
                {
                    _outputWriter.FlushAndClose();//not required for html formal i.e. multiple files already closed
                    _outputWriter = null;
                    if (!String.IsNullOrEmpty(_arg_outputFile))
                    {
                        WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile));
                    }
                    else
                    {
                        WriteOnce.NewLine();
                    }
                }
            }
        }
        //Main entry from CLI
        public override int Run()
        {
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Exporttags"));

            SortedDictionary <string, string> uniqueTags = new SortedDictionary <string, string>();

            foreach (Rule r in _rules)
            {
                //builds a list of unique tags
                foreach (string t in r.Tags)
                {
                    if (uniqueTags.ContainsKey(t))
                    {
                        continue;
                    }
                    else
                    {
                        uniqueTags.Add(t, t);
                    }
                }
            }

            //separate loop so results are sorted (Sorted type)
            foreach (string s in uniqueTags.Values)
            {
                WriteOnce.Result(s, true);
            }

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Exporttags"), true, WriteOnce.ConsoleVerbosity.Low);
            WriteOnce.FlushAll();
            if (!String.IsNullOrEmpty(_arg_outputFile))
            {
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
            }


            return((int)ExitCode.Success);
        }
        public void FlushAll()
        {
            if (_outputWriter != null)
            {
                _outputWriter.WriteApp(_appProfile);

                if (_outputWriter.TextWriter != null)
                {
                    if (_arg_fileFormat != "html")
                    {
                        _outputWriter.FlushAndClose();//not required for htmt formal i.e. already closed
                        _outputWriter    = null;
                        WriteOnce.Writer = null;

                        //Special case to avoid writing tmp file path to output file for TagTest,TagDiff or when called as a DLL since unnecessary
                        if (_arg_consoleVerbosityLevel.ToLower() != "none")
                        {
                            if (!String.IsNullOrEmpty(_arg_outputFile) && Utils.CLIExecutionContext)
                            {
                                WriteOnce.Info(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, WriteOnce.ConsoleVerbosity.Medium, false);
                            }
                            else
                            {
                                WriteOnce.NewLine();
                            }
                        }
                    }
                    else
                    {
                        if (!_arg_suppressBrowserOpen && Utils.CLIExecutionContext)
                        {
                            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, "output.html"), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
                        }
                    }
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            bool issues = false;

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Verify Rules"));

            //load [each] rules file separately to report out where a failure is happening
            RuleSet rules = new RuleSet(WriteOnce.Log);
            IEnumerable <string> fileListing = new List <string>();

            foreach (string rulePath in _rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    fileListing = Directory.EnumerateFiles(rulePath, "*.json", SearchOption.AllDirectories);
                }
                else if (File.Exists(rulePath) && Path.GetExtension(rulePath) == ".json")
                {
                    fileListing = new List <string>()
                    {
                        new string(rulePath)
                    }
                }
                ;
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }

                //test loading each file
                foreach (string filename in fileListing)
                {
                    try
                    {
                        rules.AddFile(filename);
                        WriteOnce.Info(string.Format("Rule file added {0}", filename), true, WriteOnce.ConsoleVerbosity.High);
                    }
                    catch (Exception e)
                    {
                        WriteOnce.Error(string.Format("Rule file add failed {0}", filename));
                        WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error);
                        issues = true;
                    }
                }
            }

            //option to write validating data
            if (_arg_consoleVerbosityLevel.ToLower() == "high")
            {
                WritePartialRuleDetails(rules);
            }

            //final status report
            if (issues)
            {
                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Verify Rules"));
            WriteOnce.FlushAll();
            if (!String.IsNullOrEmpty(_arg_outputFile))
            {
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
            }

            return(issues ? (int)ExitCode.NotVerified : (int)ExitCode.Verified);
        }
Пример #10
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "tagtest"));

            //init based on true or false present argument value
            bool testSuccess = true;

            //one file vs ruleset
            string tmp1 = Path.GetTempFileName();

            WriteOnce.ConsoleVerbosity saveVerbosity = WriteOnce.Verbosity;
            AnalyzeCommand.ExitCode    result        = AnalyzeCommand.ExitCode.CriticalError;

            //setup analyze call with silent option
            #region analyzesetup
            try
            {
                AnalyzeCommand cmd1 = new AnalyzeCommand(new AnalyzeCommandOptions
                {
                    SourcePath            = _arg_srcPath,
                    OutputFilePath        = tmp1,
                    OutputFileFormat      = "json",
                    CustomRulesPath       = _arg_customRulesPath,
                    IgnoreDefaultRules    = _arg_ignoreDefaultRules,
                    SimpleTagsOnly        = true,
                    AllowDupTags          = false,
                    FilePathExclusions    = "sample,example,test,docs,.vs,.git",
                    ConsoleVerbosityLevel = "None",
                    Log = _arg_logger
                });


                //quiet analysis commands
                result = (AnalyzeCommand.ExitCode)cmd1.Run();
            }
            catch (Exception e)
            {
                WriteOnce.Verbosity = saveVerbosity;
                throw e;
            }

            //restore
            WriteOnce.Verbosity = saveVerbosity;

            if (result == AnalyzeCommand.ExitCode.CriticalError)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_CRITICAL_FILE_ERR));
            }
            else if (result == AnalyzeCommand.ExitCode.NoMatches)
            {
                //results
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);
                if (_arg_tagTestType == TagTestType.RulesPresent)
                {
                    WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
                }
                else
                {
                    WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                }

                WriteOnce.FlushAll();
                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Tagtest"));

                return((int)ExitCode.CriticalError);
            }

            #endregion

            //assumed (result == AnalyzeCommand.ExitCode.MatchesFound)
            string file1TagsJson = File.ReadAllText(tmp1);
            var    file1TagsObj  = JsonConvert.DeserializeObject <TagsFile[]>(file1TagsJson);
            var    file1Tags     = file1TagsObj.First(); // here we have a single FileList object
            File.Delete(tmp1);

            foreach (Rule r in _rulesSet)
            {
                //supports both directions by generalizing
                string[] testList1 = _arg_tagTestType == TagTestType.RulesNotPresent ?
                                     r.Tags : file1Tags.Tags;

                string[] testList2 = _arg_tagTestType == TagTestType.RulesNotPresent ?
                                     file1Tags.Tags : r.Tags;

                foreach (string t in testList2)
                {
                    if (TagTest(testList1, t))
                    {
                        WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_FOUND, t), true, WriteOnce.ConsoleVerbosity.High);
                    }
                    else
                    {
                        testSuccess = false;
                        WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_MISSING, t), true, WriteOnce.ConsoleVerbosity.High);
                    }
                }
            }

            //results
            WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);
            if (testSuccess)
            {
                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }

            WriteOnce.FlushAll();
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Tagtest"));

            return(testSuccess ? (int)ExitCode.NoDiff : (int)ExitCode.DiffFound);
        }
Пример #11
0
        /// <summary>
        /// Main entry point to start analysis; handles setting up rules, directory enumeration
        /// file type detection and handoff
        /// Pre: All Configure Methods have been called already and we are ready to SCAN
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("AnalyzeCommand::Run", LogLevel.Trace);

            DateTime start = DateTime.Now;

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Analyze"));

            _appProfile.MetaData.TotalFiles = _srcfileList.Count();//updated for zipped files later

            // Iterate through all files and process against rules
            foreach (string filename in _srcfileList)
            {
                ArchiveFileType archiveFileType;
                try //fix for #146
                {
                    archiveFileType = MiniMagic.DetectFileType(filename);
                }
                catch (Exception e)
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_FILE_TYPE_OPEN, filename));
                }

                if (archiveFileType == ArchiveFileType.UNKNOWN)//not a known zipped file type
                {
                    ProcessAsFile(filename);
                }
                else
                {
                    UnZipAndProcess(filename, archiveFileType);
                }
            }

            WriteOnce.General("\r" + ErrMsg.FormatString(ErrMsg.ID.ANALYZE_FILES_PROCESSED_PCNT, 100));
            WriteOnce.Operation(ErrMsg.GetString(ErrMsg.ID.CMD_PREPARING_REPORT));

            //Prepare report results
            _appProfile.MetaData.LastUpdated = LastUpdated.ToString();
            _appProfile.DateScanned          = DateScanned.ToString();
            _appProfile.PrepareReport();
            TimeSpan timeSpan = start - DateTime.Now;

            WriteOnce.SafeLog(String.Format("Processing time: seconds:{0}", timeSpan.TotalSeconds * -1), LogLevel.Trace);
            FlushAll();

            //wrapup result status
            if (_appProfile.MetaData.TotalFiles == _appProfile.MetaData.FilesSkipped)
            {
                WriteOnce.Error(ErrMsg.GetString(ErrMsg.ID.ANALYZE_NOSUPPORTED_FILETYPES));
            }
            else if (_appProfile.MatchList.Count == 0)
            {
                WriteOnce.Error(ErrMsg.GetString(ErrMsg.ID.ANALYZE_NOPATTERNS));
            }
            else
            {
                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Analyze"));
                if (!_arg_autoBrowserOpen)
                {
                    WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, "output.html"));
                }
            }

            return(_appProfile.MatchList.Count() == 0 ? (int)ExitCode.NoMatches :
                   (int)ExitCode.Success);
        }
Пример #12
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("TagTestCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "tagtest"));

            //init based on true or false present argument value
            ExitCode exitCode = ExitCode.CriticalError;

            WriteOnce.ConsoleVerbosity saveVerbosity    = WriteOnce.Verbosity;
            AnalyzeCommand.ExitCode    analyzeCmdResult = AnalyzeCommand.ExitCode.CriticalError;

            try
            {
                //one file vs ruleset
                string tmp1 = Path.GetTempFileName();

                //setup analyze call with silent option
                AnalyzeCommand cmd1 = new AnalyzeCommand(new AnalyzeCommandOptions
                {
                    SourcePath            = _arg_srcPath,
                    OutputFilePath        = tmp1,
                    OutputFileFormat      = "json",
                    IgnoreDefaultRules    = true,
                    CustomRulesPath       = _arg_customRulesPath,
                    FilePathExclusions    = _arg_fileExclusionList,
                    SimpleTagsOnly        = true,
                    ConsoleVerbosityLevel = "None",
                    Log = _arg_logger
                });


                //get and perform initial analyze on results
                analyzeCmdResult = (AnalyzeCommand.ExitCode)cmd1.Run();

                //must be done here to avoid losing our handle from analyze command overwriting WriteOnce.Writer
                ConfigureFileOutput();

                //restore
                WriteOnce.Verbosity = saveVerbosity;

                if (analyzeCmdResult == AnalyzeCommand.ExitCode.CriticalError)
                {
                    throw new Exception(ErrMsg.GetString(ErrMsg.ID.CMD_CRITICAL_FILE_ERR));
                }
                else if (analyzeCmdResult == AnalyzeCommand.ExitCode.NoMatches)
                {
                    WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);
                    if (_arg_tagTestType == TagTestType.RulesPresent)
                    {
                        WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
                    }
                    else
                    {
                        WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                    }

                    WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "tagtest"));

                    exitCode = _arg_tagTestType == TagTestType.RulesPresent ? ExitCode.TestFailed : ExitCode.TestPassed;
                }
                else //assumed (result == AnalyzeCommand.ExitCode.MatchesFound)
                {
                    string file1TagsJson = File.ReadAllText(tmp1);
                    var    file1Tags     = JsonConvert.DeserializeObject <TagsFile>(file1TagsJson);
                    File.Delete(tmp1);

                    exitCode = ExitCode.TestPassed;
                    foreach (Rule r in _rulesSet)
                    {
                        //supports both directions by generalizing
                        string[] testList1 = _arg_tagTestType == TagTestType.RulesNotPresent ?
                                             r.Tags : file1Tags.Tags;

                        string[] testList2 = _arg_tagTestType == TagTestType.RulesNotPresent ?
                                             file1Tags.Tags : r.Tags;

                        foreach (string t in testList2)
                        {
                            if (TagTest(testList1, t))
                            {
                                WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_FOUND, t), true, WriteOnce.ConsoleVerbosity.High);
                            }
                            else
                            {
                                exitCode = ExitCode.TestFailed;
                                WriteOnce.Result(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TAGS_MISSING, t), true, WriteOnce.ConsoleVerbosity.High);
                            }

                            if (exitCode != ExitCode.TestPassed)
                            {
                                break;
                            }
                        }

                        if (exitCode != ExitCode.TestPassed)
                        {
                            break;
                        }
                    }

                    //results
                    WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.TAGTEST_RESULTS_TEST_TYPE, _arg_tagTestType.ToString()), false, WriteOnce.ConsoleVerbosity.Low);

                    if (exitCode == ExitCode.TestFailed)
                    {
                        WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
                    }
                    else
                    {
                        WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                    }

                    WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Tagtest"));
                    if (!String.IsNullOrEmpty(_arg_outputFile) && Utils.CLIExecutionContext)
                    {
                        WriteOnce.Info(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, WriteOnce.ConsoleVerbosity.Low, false);
                    }

                    WriteOnce.FlushAll();
                }
            }
            catch (Exception e)
            {
                WriteOnce.Verbosity = saveVerbosity;
                if (analyzeCmdResult == AnalyzeCommand.ExitCode.Success) //then error was not previously logged
                {
                    WriteOnce.Error(e.Message);
                }
                else
                {
                    WriteOnce.Error(e.Message, true, WriteOnce.ConsoleVerbosity.Low, false);
                }

                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)exitCode);
        }