public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            VerifyRulesResult verifyRulesResult = (VerifyRulesResult)result;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                TextWriter.WriteLine("Results");
            }

            if (verifyRulesResult.ResultCode != VerifyRulesResult.ExitCode.Verified)
            {
                TextWriter.WriteLine(MsgHelp.ID.TAGTEST_RESULTS_FAIL);
            }
            else
            {
                TextWriter.WriteLine(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS);
            }

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

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        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();
            }
        }
Exemple #3
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();
            }
        }
Exemple #4
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 static CommandResultsWriter?GetWriter(CLICommandOptions options)
        {
            CommandResultsWriter?writer;

            //allocate the right writer by cmd (options) type
            if (options is CLIAnalyzeCmdOptions cliAnalyzeCmdOptions)
            {
                writer = GetAnalyzeWriter(cliAnalyzeCmdOptions);
            }
            else if (options is CLITagDiffCmdOptions cliTagDiffCmdOptions)
            {
                writer = GetTagDiffWriter(cliTagDiffCmdOptions);
            }
            else if (options is CLIExportTagsCmdOptions cliExportTagsCmdOptions)
            {
                writer = GetExportTagsWriter(cliExportTagsCmdOptions);
            }
            else if (options is CLIVerifyRulesCmdOptions cliVerifyRulesCmdOptions)
            {
                writer = GetVerifyRulesWriter(cliVerifyRulesCmdOptions);
            }
            else if (options is CLIPackRulesCmdOptions cliPackRulesCmdOptions)
            {
                writer = GetPackRulesWriter(cliPackRulesCmdOptions);
            }
            else
            {
                throw new Exception("Unrecognized object type in writer request");
            }

            return(writer);
        }
Exemple #5
0
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            if (TextWriter is null)
            {
                throw new ArgumentNullException(nameof(TextWriter));
            }

            ExportTagsResult exportTagsResult = (ExportTagsResult)result;

            if (exportTagsResult.TagsList.Count > 0)
            {
                TextWriter.WriteLine("Results");

                foreach (string tag in exportTagsResult.TagsList)
                {
                    TextWriter.WriteLine(tag);
                }
            }
            else
            {
                TextWriter.WriteLine("No tags found");
            }

            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;

            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();
            }
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            ExportTagsResult exportTagsResult = (ExportTagsResult)result;

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

            if (exportTagsResult.TagsList.Count > 0)
            {
                WriteOnce.Result("Results");

                foreach (string tag in exportTagsResult.TagsList)
                {
                    WriteOnce.General(tag);
                }
            }
            else
            {
                WriteOnce.General("No tags found");
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        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();
            }
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            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");
            }

            JsonSerializer jsonSerializer = new();

            jsonSerializer.Formatting = Formatting.Indented;
            if (TextWriter != null)
            {
                jsonSerializer.Serialize(TextWriter, analyzeResult);
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        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;
                }
            }
        /// <summary>
        /// Pre: AnalyzeCommand GetResults created and populated from RulesEngine
        /// </summary>
        /// <param name="result"></param>
        /// <param name="cLICommandOptions"></param>
        /// <param name="autoClose"></param>
        public override void WriteResults(Result result, CLICommandOptions cLICommandOptions, bool autoClose = true)
        {
            //recover metadata results from prior analyzecommand GetResults()
            _analyzeResult = (AnalyzeResult)result;
            _appMetaData   = _analyzeResult.Metadata;

            PopulateTagGroups();
            WriteHtmlResult();
        }
Exemple #12
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);
            }
        }
Exemple #13
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")
     });
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            AnalyzeResult analyzeResult = (AnalyzeResult)result;

            JsonSerializer jsonSerializer = new();

            jsonSerializer.Formatting = Formatting.Indented;
            if (TextWriter != null)
            {
                jsonSerializer.Serialize(TextWriter, analyzeResult);
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Exemple #15
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();
            }
        }
Exemple #17
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();
            }
        }
        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();
            }
        }
 public abstract void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true);
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            if (TextWriter is null)
            {
                throw new ArgumentNullException(nameof(TextWriter));
            }
            string?basePath = null;

            if (commandOptions is CLIAnalyzeCmdOptions cLIAnalyzeCmdOptions)
            {
                basePath = cLIAnalyzeCmdOptions.BasePath;

                if (result is AnalyzeResult analyzeResult)
                {
                    SarifLog     log          = new();
                    SarifVersion sarifVersion = SarifVersion.Current;
                    log.SchemaUri = sarifVersion.ConvertToSchemaUri();
                    log.Version   = sarifVersion;
                    log.Runs      = new List <Run>();
                    var run = new Run();

                    if (Uri.TryCreate(cLIAnalyzeCmdOptions.RepositoryUri, UriKind.RelativeOrAbsolute, out Uri? uri))
                    {
                        run.VersionControlProvenance = new List <VersionControlDetails>()
                        {
                            new VersionControlDetails()
                            {
                                RepositoryUri = uri,
                                RevisionId    = cLIAnalyzeCmdOptions.CommitHash
                            }
                        };
                    }

                    var artifacts = new List <Artifact>();
                    run.Tool = new Tool
                    {
                        Driver = new ToolComponent
                        {
                            Name           = $"Application Inspector",
                            InformationUri = new Uri("https://github.com/microsoft/ApplicationInspector/"),
                            Organization   = "Microsoft",
                            Version        = Helpers.GetVersionString(),
                        }
                    };
                    var reportingDescriptors = new List <ReportingDescriptor>();
                    run.Results = new List <CodeAnalysis.Sarif.Result>();
                    foreach (var match in analyzeResult.Metadata.Matches)
                    {
                        var sarifResult = new CodeAnalysis.Sarif.Result();

                        if (match.Rule is not null)
                        {
                            if (!reportingDescriptors.Any(r => r.Id == match.Rule.Id))
                            {
                                ReportingDescriptor reportingDescriptor = new()
                                {
                                    FullDescription = new MultiformatMessageString()
                                    {
                                        Text = match.Rule.Description
                                    },
                                    Id   = match.Rule.Id,
                                    Name = match.Rule.Name,
                                    DefaultConfiguration = new ReportingConfiguration()
                                    {
                                        Level = GetSarifFailureLevel(match.Rule.Severity)
                                    }
                                };
                                reportingDescriptor.Tags.AddRange(match.Rule.Tags);
                                reportingDescriptors.Add(reportingDescriptor);
                            }

                            sarifResult.Level  = GetSarifFailureLevel(match.Rule.Severity);
                            sarifResult.RuleId = match.Rule.Id;
                            sarifResult.Tags.AddRange(match.Rule.Tags);
                            sarifResult.Message = new Message()
                            {
                                Text = match.Rule.Description
                            };

                            if (match.FileName is not null)
                            {
                                string fileName = match.FileName;
                                if (basePath is not null)
                                {
                                    fileName = Path.GetRelativePath(basePath, fileName);
                                }
                                if (Uri.TryCreate(fileName, UriKind.RelativeOrAbsolute, out Uri? outUri))
                                {
                                    int artifactIndex = artifacts.FindIndex(a => a.Location.Uri.Equals(outUri));
                                    if (artifactIndex == -1)
                                    {
                                        Artifact artifact = new()
                                        {
                                            Location = new ArtifactLocation()
                                            {
                                                Index = artifacts.Count,
                                                Uri   = outUri
                                            },
                                        };
                                        artifactIndex = artifact.Location.Index;
                                        artifact.Tags.AddRange(match.Rule.Tags);
                                        if (Language.FromFileNameOut(fileName, out LanguageInfo languageInfo))
                                        {
                                            artifact.SourceLanguage = languageInfo.Name;
                                        }
                                        artifacts.Add(artifact);
                                    }
                                    else
                                    {
                                        artifacts[artifactIndex].Tags.AddRange(match.Rule.Tags);
                                    }
                                    sarifResult.Locations = new List <Location>()
                                    {
                                        new Location()
                                        {
                                            PhysicalLocation = new PhysicalLocation()
                                            {
                                                ArtifactLocation = new ArtifactLocation()
                                                {
                                                    Index = artifactIndex
                                                },
                                                Region = new Region()
                                                {
                                                    StartLine   = match.StartLocationLine,
                                                    StartColumn = match.StartLocationColumn,
                                                    EndLine     = match.EndLocationLine,
                                                    EndColumn   = match.EndLocationColumn,
                                                    Snippet     = new ArtifactContent()
                                                    {
                                                        Text = match.Sample
                                                    }
                                                }
                                            }
                                        }
                                    };
                                }
                            }
                        }

                        run.Artifacts         = artifacts;
                        run.Tool.Driver.Rules = reportingDescriptors;
                        run.Results.Add(sarifResult);
                    }

                    log.Runs.Add(run);
                    JsonSerializerSettings serializerSettings = new();
                    var serializer = new JsonSerializer();
                    serializer.Serialize(TextWriter, log);
                    FlushAndClose();
                }
                else
                {
                    throw new ArgumentException("This writer can only write Analyze results.", nameof(result));
                }
            }
            else
            {
                throw new ArgumentException("This writer requires a CLIAnalyzeCmdOptions options argument.", nameof(commandOptions));
            }
        }
Exemple #22
0
 public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
 {
     throw new System.NotImplementedException();
 }