Ejemplo n.º 1
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                options.OutputFilePath = options.OutputFilePath ?? "output.html";
                string extensionCheck = Path.GetExtension(options.OutputFilePath);
                if (extensionCheck != ".html" && extensionCheck != ".htm")
                {
                    WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.ANALYZE_HTML_EXTENSION));
                }

                if (options.AllowDupTags) //fix #183; duplicates results for html format is not supported which causes filedialog issues
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                    throw new OpException(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                }

                if (options.SimpleTagsOnly) //won't work for html that expects full data for UI
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                }
            }

            CommonOutputChecks((CLICommandOptions)options);
            return(RunAnalyzeCommand(options));
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            VerifyRulesResult verifyRulesResult = (VerifyRulesResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            if (verifyRulesResult.ResultCode != VerifyRulesResult.ExitCode.Verified)
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }

            if (verifyRulesResult.RuleStatusList.Count > 0)
            {
                WriteOnce.Result("Rule status");
                foreach (RuleStatus ruleStatus in verifyRulesResult.RuleStatusList)
                {
                    WriteOnce.General(String.Format("Ruleid: {0}, Rulename: {1}, Status: {2}", ruleStatus.RulesId, ruleStatus.RulesName, ruleStatus.Verified));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 3
0
        private static int VerifyOutputArgsRun(CLIPackRulesCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            if (options.RepackDefaultRules && !string.IsNullOrEmpty(options.OutputFilePath))
            {
                WriteOnce.Info("output file argument ignored for -d option");
            }

            options.OutputFilePath = options.RepackDefaultRules ? Utils.GetPath(Utils.AppPath.defaultRulesPackedFile) : options.OutputFilePath;
            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
            }
            else
            {
                CommonOutputChecks(options);
            }

            return(RunPackRulesCommand(options));
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            TagDiffResult        tagDiffResult        = (TagDiffResult)result;
            CLITagDiffCmdOptions cLITagDiffCmdOptions = (CLITagDiffCmdOptions)commandOptions;

            TextWriter.WriteLine(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagDiffCmdOptions.TestType));

            if (tagDiffResult.ResultCode == TagDiffResult.ExitCode.TestFailed)
            {
                TextWriter.WriteLine(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL));
            }
            else
            {
                TextWriter.WriteLine(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS));
            }

            //Results list
            if (tagDiffResult.TagDiffList.Count > 0)
            {
                TextWriter.WriteLine("Differences");
                foreach (TagDiff tagDiff in tagDiffResult.TagDiffList)
                {
                    TextWriter.WriteLine(string.Format("Tag: {0}, Only found in file: {1}", tagDiff.Tag, tagDiff.Source));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 5
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            Logger logger = Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                if (!string.IsNullOrEmpty(options.OutputFilePath)) //dependent local files won't be there; TODO look into dir copy to target!
                {
                    WriteOnce.Info("-o output file argument ignored for html format");
                }

                options.OutputFilePath = "output.html";

                if (options.AllowDupTags) //fix #183; duplicates results for html format is not supported which causes filedialog issues

                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                    throw new OpException(MsgHelp.GetString(MsgHelp.ID.ANALYZE_NODUPLICATES_HTML_FORMAT));
                }

                if (options.SimpleTagsOnly) //won't work for html that expects full data for UI
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.ANALYZE_SIMPLETAGS_HTML_FORMAT));
                }
            }

            CommonOutputChecks((CLICommandOptions)options);
            return(RunAnalyzeCommand(options));
        }
        public static void Write(Result result, CLICommandOptions options)
        {
            CommandResultsWriter?writer = WriterFactory.GetWriter(options);
            string commandCompletedMsg;

            //perform type checking and assign final msg string
            if (result is TagTestResult)
            {
                commandCompletedMsg = "Tag Test";
            }
            else if (result is TagDiffResult)
            {
                commandCompletedMsg = "Tag Diff";
            }
            else if (result is ExportTagsResult)
            {
                commandCompletedMsg = "Export Tags";
            }
            else if (result is VerifyRulesResult)
            {
                commandCompletedMsg = "Verify Rules";
            }
            else if (result is PackRulesResult)
            {
                commandCompletedMsg = "Pack Rules";
            }
            else if (result is AnalyzeResult analyzeResult && options is CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions) //special handling for html format
            {
                commandCompletedMsg = "Analyze";

                //additional prechecks required for analyze html format
                if (cLIAnalyzeCmdOptions.OutputFileFormat == "html")
                {
                    int MAX_HTML_REPORT_FILE_SIZE = 1024 * 1000 * 3;  //warn about potential slow rendering

                    //prechecks
                    if (analyzeResult.ResultCode != AnalyzeResult.ExitCode.Success)
                    {
                        Finalize(writer, commandCompletedMsg);
                        return;
                    }

                    writer?.WriteResults(analyzeResult, cLIAnalyzeCmdOptions);

                    //post checks
                    if (File.Exists(options.OutputFilePath) && new FileInfo(options.OutputFilePath).Length > MAX_HTML_REPORT_FILE_SIZE)
                    {
                        WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.ANALYZE_REPORTSIZE_WARN));
                    }

                    if (!cLIAnalyzeCmdOptions.SuppressBrowserOpen)
                    {
                        Utils.OpenBrowser(cLIAnalyzeCmdOptions.OutputFilePath);
                    }

                    Finalize(writer, "Analyze");
                    return;
                }
            }
Ejemplo n.º 7
0
        /// <summary>
        /// Checks that either output filepath is valid or console verbosity is not visible to ensure
        /// some output can be achieved...other command specific inputs that are relevant to both CLI
        /// and NuGet callers are checked by the commands themselves
        /// </summary>
        /// <param name="options"></param>
        private static void CommonOutputChecks(CLICommandOptions options)
        {
            //validate requested format
            string fileFormatArg = options.OutputFileFormat;

            string[] validFormats =
            {
                "html",
                "text",
                "json",
                "sarif"
            };

            string[] checkFormats;
            if (options is CLIAnalyzeCmdOptions cliAnalyzeOptions)
            {
                checkFormats  = validFormats;
                fileFormatArg = cliAnalyzeOptions.OutputFileFormat;
            }
            else if (options is CLIPackRulesCmdOptions cliPackRulesOptions)
            {
                checkFormats  = validFormats.Skip(2).Take(1).ToArray();
                fileFormatArg = cliPackRulesOptions.OutputFileFormat;
            }
            else
            {
                checkFormats = validFormats.Skip(1).Take(2).ToArray();
            }

            bool isValidFormat = checkFormats.Any(v => v.Equals(fileFormatArg.ToLower()));

            if (!isValidFormat)
            {
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
            }

            //validate output is not empty if no file output specified
            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                if (string.Equals(options.ConsoleVerbosityLevel, "none", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                }
                else if (string.Equals(options.ConsoleVerbosityLevel, "low", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.SafeLog("Verbosity set low.  Detailed output limited.", NLog.LogLevel.Info);
                }
            }
            else
            {
                ValidFileWritePath(options.OutputFilePath);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// CLI program entry point which defines command verbs and options to running
        /// </summary>
        /// <param name="args"></param>
        private static int Main(string[] args)
        {
            int finalResult = (int)Utils.ExitCode.CriticalError;

            Utils.CLIExecutionContext = true;//set manually at start from CLI

            WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.Medium;
            try
            {
                var argsResult = Parser.Default.ParseArguments <CLIAnalyzeCmdOptions,
                                                                CLITagDiffCmdOptions,
                                                                CLITagTestCmdOptions,
                                                                CLIExportTagsCmdOptions,
                                                                CLIVerifyRulesCmdOptions,
                                                                CLIPackRulesCmdOptions>(args)
                                 .MapResult(
                    (CLIAnalyzeCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLITagDiffCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLITagTestCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIExportTagsCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIVerifyRulesCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIPackRulesCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    errs => 1
                    );

                finalResult = argsResult;
            }
            catch (OpException)
            {
                //log, output file and console have already been written to ensure all are updated for NuGet and CLI callers
                //that may exit at different call points
            }
            catch (Exception e)
            {
                //unlogged exception so report out for CLI callers
                WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error);
            }

            //final exit msg to review log
            if (finalResult == (int)Utils.ExitCode.CriticalError)
            {
                if (!String.IsNullOrEmpty(Utils.LogFilePath))
                {
                    WriteOnce.Info(MsgHelp.FormatString(MsgHelp.ID.RUNTIME_ERROR_UNNAMED, Utils.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false);
                }
                else
                {
                    WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.RUNTIME_ERROR_PRELOG), true, WriteOnce.ConsoleVerbosity.Medium, false);
                }
            }

            return(finalResult);
        }
Ejemplo n.º 9
0
        private static int VerifyOutputArgsRun(CLIPackRulesCmdOptions options)
        {
            loggerFactory = options.GetLoggerFactory();
            ILogger logger = loggerFactory.CreateLogger("Program");

            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                logger.LogError(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.PACK_MISSING_OUTPUT_ARG));
            }
            else
            {
                CommonOutputChecks(options);
            }

            return(RunPackRulesCommand(options));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Checks that either output filepath is valid or console verbosity is not visible to ensure
        /// some output can be achieved...other command specific inputs that are relevant to both CLI
        /// and NuGet callers are checked by the commands themselves
        /// </summary>
        /// <param name="options"></param>
        private static bool CommonOutputChecks(CLICommandOptions options)
        {
            //validate requested format
            string fileFormatArg = options.OutputFileFormat;

            string[] validFormats =
            {
                "html",
                "text",
                "json",
                "sarif"
            };
            var logger = loggerFactory.CreateLogger("Program");

            string[] checkFormats;
            if (options is CLIAnalyzeCmdOptions cliAnalyzeOptions)
            {
                checkFormats  = validFormats;
                fileFormatArg = cliAnalyzeOptions.OutputFileFormat;
            }
            else if (options is CLIPackRulesCmdOptions cliPackRulesOptions)
            {
                checkFormats  = validFormats.Skip(2).Take(1).ToArray();
                fileFormatArg = cliPackRulesOptions.OutputFileFormat;
            }
            else
            {
                checkFormats = validFormats.Skip(1).Take(2).ToArray();
            }

            bool isValidFormat = checkFormats.Any(v => v.Equals(fileFormatArg.ToLower()));

            if (!isValidFormat)
            {
                logger.LogError(MsgHelp.GetString(MsgHelp.ID.CMD_INVALID_ARG_VALUE), "-f");
                return(false);
            }

            if (!string.IsNullOrEmpty(options.OutputFilePath) && !CanWritePath(options.OutputFilePath))
            {
                logger.LogError(MsgHelp.GetString(MsgHelp.ID.CMD_INVALID_LOG_PATH), options.OutputFilePath);
                return(false);
            }

            return(true);
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLITagTestCmdOptions cLITagTestCmdOptions = (CLITagTestCmdOptions)commandOptions;
            TagTestResult        tagTestResult        = (TagTestResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            WriteOnce.General(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagTestCmdOptions.TestType), false, WriteOnce.ConsoleVerbosity.Low);

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

            if (tagTestResult.TagsStatusList.Count > 0)
            {
                WriteOnce.Result("Test results:");

                foreach (TagStatus tag in tagTestResult.TagsStatusList)
                {
                    WriteOnce.General(string.Format("Tag: {0}, Detected: {1}", tag.Tag, tag.Detected));
                }
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 12
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            Logger logger = Common.Utils.SetupLogging(options, true);

            WriteOnce.Log = logger;
            options.Log   = logger;

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                options.OutputFilePath ??= "output.html";
                string extensionCheck = Path.GetExtension(options.OutputFilePath);
                if (extensionCheck is not ".html" and not ".htm")
                {
                    WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.ANALYZE_HTML_EXTENSION));
                }
            }

            CommonOutputChecks(options);
            return(RunAnalyzeCommand(options));
        }
Ejemplo n.º 13
0
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            TagDiffResult        tagDiffResult        = (TagDiffResult)result;
            CLITagDiffCmdOptions cLITagDiffCmdOptions = (CLITagDiffCmdOptions)commandOptions;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            WriteOnce.General(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagDiffCmdOptions.TestType), false, WriteOnce.ConsoleVerbosity.Low);

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

            //Results list
            if (tagDiffResult.TagDiffList.Count > 0)
            {
                WriteOnce.Result("Differences");
                foreach (TagDiff tagDiff in tagDiffResult.TagDiffList)
                {
                    WriteOnce.General(string.Format("Tag: {0}, Only found in file: {1}", tagDiff.Tag, tagDiff.Source));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 14
0
        private static int VerifyOutputArgsRun(CLIAnalyzeCmdOptions options)
        {
            loggerFactory = options.GetLoggerFactory();

            //analyze with html format limit checks
            if (options.OutputFileFormat == "html")
            {
                options.OutputFilePath ??= "output.html";
                string extensionCheck = Path.GetExtension(options.OutputFilePath);
                if (extensionCheck is not ".html" and not ".htm")
                {
                    loggerFactory.CreateLogger("Program").LogInformation(MsgHelp.GetString(MsgHelp.ID.ANALYZE_HTML_EXTENSION));
                }
            }
            if (CommonOutputChecks(options))
            {
                return(RunAnalyzeCommand(options));
            }
            else
            {
                return((int)Utils.ExitCode.CriticalError);
            }
        }