public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions = (CLIAnalyzeCmdOptions)commandOptions;
            AnalyzeResult        analyzeResult        = (AnalyzeResult)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 (cLIAnalyzeCmdOptions.SimpleTagsOnly)
            {
                List <string> keys = new List <string>(analyzeResult.Metadata.UniqueTags);
                keys.Sort();
                TagsFile tags = new TagsFile();
                tags.Tags = keys.ToArray();
                TextWriter.Write(JsonConvert.SerializeObject(tags, Formatting.Indented));
            }
            else
            {
                JsonSerializer jsonSerializer = new JsonSerializer();
                jsonSerializer.Formatting = Formatting.Indented;
                jsonSerializer.Serialize(TextWriter, analyzeResult);
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        /// <summary>
        /// Only AnalyzeResultsWriter supports an html option
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private static CommandResultsWriter GetAnalyzeWriter(CLIAnalyzeCmdOptions options)
        {
            CommandResultsWriter?writer;

            switch (options.OutputFileFormat.ToLower())
            {
            case "_dummy":
                writer = new AnalyzeDummyWriter();
                break;

            case "json":
                writer = new AnalyzeJsonWriter();
                break;

            case "text":
                writer = new AnalyzeTextWriter(options.TextOutputFormat);
                break;

            case "html":
                writer = new AnalyzeHtmlWriter();
                break;

            default:
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }

            //assign the stream as a file or console
            writer.OutputFileName = options.OutputFilePath;
            writer.TextWriter     = GetTextWriter(writer.OutputFileName);

            return(writer);
        }
Example #3
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));
        }
Example #4
0
        private static int RunAnalyzeCommand(CLIAnalyzeCmdOptions cliOptions)
        {
            AnalyzeResult.ExitCode exitCode = AnalyzeResult.ExitCode.CriticalError;

            AnalyzeCommand command = new AnalyzeCommand(new AnalyzeOptions()
            {
                SourcePath            = cliOptions.SourcePath ?? "",
                CustomRulesPath       = cliOptions.CustomRulesPath ?? "",
                IgnoreDefaultRules    = cliOptions.IgnoreDefaultRules,
                AllowDupTags          = cliOptions.AllowDupTags,
                ConfidenceFilters     = cliOptions.ConfidenceFilters,
                MatchDepth            = cliOptions.MatchDepth,
                FilePathExclusions    = cliOptions.FilePathExclusions,
                ConsoleVerbosityLevel = cliOptions.ConsoleVerbosityLevel,
                Log          = cliOptions.Log,
                SingleThread = cliOptions.SingleThread
            });;

            AnalyzeResult analyzeResult = command.GetResult();

            exitCode = analyzeResult.ResultCode;
            ResultsWriter.Write(analyzeResult, cliOptions);

            return((int)exitCode);
        }
Example #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));
        }
Example #6
0
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions = (CLIAnalyzeCmdOptions)commandOptions;
            AnalyzeResult        analyzeResult        = (AnalyzeResult)result;

            if (TextWriter is null)
            {
                throw new ArgumentNullException(nameof(TextWriter));
            }
            TextWriter.WriteLine("Results");

            WriteAppMeta(analyzeResult.Metadata);
            WriteDependencies(analyzeResult.Metadata);
            TextWriter.WriteLine(MakeHeading("Match Details"));

            foreach (MatchRecord match in analyzeResult.Metadata.Matches ?? new List <MatchRecord>())
            {
                WriteMatch(match);
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Example #7
0
 /// <summary>
 /// Responsible for returning the correct cmd and format writer for output of cmd results.  An an output
 /// file will be opened as a stream if provided otherwise the console.out stream is used
 /// A downcast is expected as the input param containing the common output format and filepath for simplifying
 /// the allocation to a single method and serves as a type selector but is also recast for command specific
 /// options in the writer as needed
 /// </summary>
 /// <param name="options"></param>
 /// <returns></returns>
 public CommandResultsWriter GetWriter(CLICommandOptions options)
 {
     return(options switch
     {
         CLIAnalyzeCmdOptions cliAnalyzeCmdOptions => GetAnalyzeWriter(cliAnalyzeCmdOptions),
         CLITagDiffCmdOptions cliTagDiffCmdOptions => GetTagDiffWriter(cliTagDiffCmdOptions),
         CLIExportTagsCmdOptions cliExportTagsCmdOptions => GetExportTagsWriter(cliExportTagsCmdOptions),
         CLIVerifyRulesCmdOptions cliVerifyRulesCmdOptions => GetVerifyRulesWriter(cliVerifyRulesCmdOptions),
         CLIPackRulesCmdOptions cliPackRulesCmdOptions => GetPackRulesWriter(cliPackRulesCmdOptions),
         _ => throw new OpException($"Unrecognized object type {options.GetType().Name} in writer request")
     });
Example #8
0
 /// <summary>
 /// This method gets a logging factory with Console disabled when the progress bar is enabled. Does not change the original options.
 /// </summary>
 /// <param name="cliOptions">The original options.</param>
 /// <returns>A logging factory with adjusted settings.</returns>
 private static ILoggerFactory GetAdjustedFactory(CLIAnalyzeCmdOptions cliOptions)
 {
     return(new LogOptions()
     {
         ConsoleVerbosityLevel = cliOptions.ConsoleVerbosityLevel,
         DisableLogFileOutput = cliOptions.DisableLogFileOutput,
         LogFileLevel = cliOptions.LogFileLevel,
         LogFilePath = cliOptions.LogFilePath,
         DisableConsoleOutput = cliOptions.NoShowProgressBar ? cliOptions.DisableConsoleOutput : false
     }.GetLoggerFactory());
 }
        private void WriteJsonResult()
        {
            //writes out json report for convenient link from report summary page(s)
            CLIAnalyzeCmdOptions jsonOptions = new CLIAnalyzeCmdOptions()
            {
                OutputFileFormat = "json",
                OutputFilePath   = "output.json"
            };

            //quiet normal write noise for json writter to just gen the file; then restore
            WriteOnce.ConsoleVerbosity saveVerbosity = WriteOnce.Verbosity;
            WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.None;
            AnalyzeJsonWriter jsonWriter = (AnalyzeJsonWriter)WriterFactory.GetWriter(jsonOptions);

            jsonWriter.WriteResults(_analyzeResult, jsonOptions);
            WriteOnce.Verbosity = saveVerbosity;
        }
Example #10
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));
        }
Example #11
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);
            }
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions = (CLIAnalyzeCmdOptions)commandOptions;
            AnalyzeResult        analyzeResult        = (AnalyzeResult)result;

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

            WriteOnce.Result("Results");

            if (cLIAnalyzeCmdOptions.SimpleTagsOnly)
            {
                List <string> keys = new List <string>(analyzeResult.Metadata.UniqueTags);
                keys.Sort();

                foreach (string tag in keys)
                {
                    WriteOnce.General(tag);
                }
            }
            else
            {
                WriteAppMeta(analyzeResult.Metadata);
                WriteDependencies(analyzeResult.Metadata);
                WriteOnce.General(MakeHeading("Match Details"));

                foreach (MatchRecord match in analyzeResult.Metadata.Matches)
                {
                    WriteMatch(match);
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions = (CLIAnalyzeCmdOptions)commandOptions;
            AnalyzeResult        analyzeResult        = (AnalyzeResult)result;

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

            WriteOnce.Result("Results");

            WriteAppMeta(analyzeResult.Metadata);
            WriteDependencies(analyzeResult.Metadata);
            WriteOnce.General(MakeHeading("Match Details"));

            foreach (MatchRecord match in analyzeResult.Metadata.Matches ?? new List <MatchRecord>())
            {
                WriteMatch(match);
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Example #14
0
        private static int RunAnalyzeCommand(CLIAnalyzeCmdOptions cliOptions)
        {
            // If the user manually specified -1 this means they also don't even want the snippet in sarif, so we respect that option
            // Otherwise if we are outputting sarif we don't use any of the context information so we set context to 0, if not sarif leave it alone.
            bool isSarif         = cliOptions.OutputFileFormat.Equals("sarif", StringComparison.InvariantCultureIgnoreCase);
            int  numContextLines = cliOptions.ContextLines == -1 ? cliOptions.ContextLines : isSarif ? 0 : cliOptions.ContextLines;
            // tagsOnly isn't compatible with sarif output, we choose to prioritize the choice of sarif.
            bool tagsOnly = !isSarif && cliOptions.TagsOnly;
            var  logger   = loggerFactory.CreateLogger("Program");

            if (!cliOptions.NoShowProgressBar)
            {
                logger.LogInformation("Progress bar is enabled so console output will be supressed. To receive log messages with the progress bar check the log file.");
            }
            ILoggerFactory adjustedFactory = GetAdjustedFactory(cliOptions);
            AnalyzeCommand command         = new(new AnalyzeOptions()
            {
                SourcePath = cliOptions.SourcePath ?? Array.Empty <string>(),
                CustomRulesPath = cliOptions.CustomRulesPath ?? "",
                CustomCommentsPath = cliOptions.CustomCommentsPath,
                CustomLanguagesPath = cliOptions.CustomLanguagesPath,
                IgnoreDefaultRules = cliOptions.IgnoreDefaultRules,
                ConfidenceFilters = cliOptions.ConfidenceFilters,
                FilePathExclusions = cliOptions.FilePathExclusions,
                SingleThread = cliOptions.SingleThread,
                NoShowProgress = cliOptions.NoShowProgressBar,
                FileTimeOut = cliOptions.FileTimeOut,
                ProcessingTimeOut = cliOptions.ProcessingTimeOut,
                ContextLines = numContextLines,
                ScanUnknownTypes = cliOptions.ScanUnknownTypes,
                TagsOnly = tagsOnly,
                NoFileMetadata = cliOptions.NoFileMetadata,
                AllowAllTagsInBuildFiles = cliOptions.AllowAllTagsInBuildFiles,
                MaxNumMatchesPerTag = cliOptions.MaxNumMatchesPerTag
            }, adjustedFactory);

            AnalyzeResult analyzeResult = command.GetResult();

            ResultsWriter writer = new(loggerFactory);

            if (cliOptions.NoShowProgressBar)
            {
                writer.Write(analyzeResult, cliOptions);
            }
            else
            {
                var done = false;

                _ = Task.Factory.StartNew(() =>
                {
                    writer.Write(analyzeResult, cliOptions);
                    done = true;
                });

                var options = new ProgressBarOptions
                {
                    ForegroundColor         = ConsoleColor.Yellow,
                    ForegroundColorDone     = ConsoleColor.DarkGreen,
                    BackgroundColor         = ConsoleColor.DarkGray,
                    BackgroundCharacter     = '\u2593',
                    DisableBottomPercentage = true
                };

                using (var pbar = new IndeterminateProgressBar("Writing Result Files.", options))
                {
                    while (!done)
                    {
                        Thread.Sleep(100);
                    }
                    pbar.Message = "Results written.";

                    pbar.Finished();
                }
                Console.Write(Environment.NewLine);
            }

            return((int)analyzeResult.ResultCode);
        }