示例#1
0
        /// <summary>Converts a tool log file represented as a stream into the SARIF format.</summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
        /// illegal values.</exception>
        /// <param name="toolFormat">The tool format of the input file.</param>
        /// <param name="inputStream">A stream that contains tool log contents.</param>
        /// <param name="outputStream">A stream to which the converted output should be written.</param>
        public void ConvertToStandardFormat(
            ToolFormat toolFormat,
            Stream inputStream,
            IResultLogWriter outputStream)
        {
            if (toolFormat == ToolFormat.PREfast)
            {
                throw new ArgumentException("Cannot convert PREfast XML from stream. Call ConvertPREfastToStandardFormat helper instead.");
            }
            ;

            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }
            ;
            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream");
            }
            ;

            Lazy <IToolFileConverter> converter;

            if (_converters.TryGetValue(toolFormat, out converter))
            {
                converter.Value.Convert(inputStream, outputStream);
            }
            else
            {
                throw new ArgumentException("Unrecognized tool specified: " + toolFormat.ToString(), "toolFormat");
            }
        }
示例#2
0
 /// <summary>Converts a tool log file to the SARIF format.</summary>
 /// <param name="toolFormat">The tool format of the input file.</param>
 /// <param name="inputFileName">The input log file name.</param>
 /// <param name="outputFileName">The name of the file to which the resulting SARIF log shall be
 /// written. This cannot be a directory.</param>
 public void ConvertToStandardFormat(
     ToolFormat toolFormat,
     string inputFileName,
     string outputFileName)
 {
     ConvertToStandardFormat(toolFormat, inputFileName, outputFileName, ToolFormatConversionOptions.None);
 }
示例#3
0
        /// <summary>Converts a tool log file into the SARIF format.</summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or
        /// illegal values.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        /// <param name="toolFormat">The tool format of the input file.</param>
        /// <param name="inputFileName">The input log file name.</param>
        /// <param name="outputFileName">The name of the file to which the resulting SARIF log shall be
        /// written. This cannot be a directory.</param>
        /// <param name="conversionOptions">Options for controlling the conversion.</param>
        public void ConvertToStandardFormat(
            ToolFormat toolFormat,
            string inputFileName,
            string outputFileName,
            ToolFormatConversionOptions conversionOptions)
        {
            if (toolFormat == ToolFormat.PREfast)
            {
                string sarif = ConvertPREfastToStandardFormat(inputFileName);
                File.WriteAllText(outputFileName, sarif);
            }

            if (inputFileName == null)
            {
                throw new ArgumentNullException("inputFileName");
            }
            ;
            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            ;

            if (Directory.Exists(outputFileName))
            {
                throw new ArgumentException("Specified file output path exists but is a directory.", "outputFileName");
            }

            if (!conversionOptions.HasFlag(ToolFormatConversionOptions.OverwriteExistingOutputFile) && File.Exists(outputFileName))
            {
                throw new InvalidOperationException("Output file already exists and option to overwrite was not specified.");
            }

            // FileMode settings here will results in an exception being raised if the input
            // file does not exist, and that an existing output file will be overwritten
            using (var input = File.OpenRead(inputFileName))
                using (var outputTextStream = File.Create(outputFileName))
                    using (var outputTextWriter = new StreamWriter(outputTextStream))
                        using (var outputJson = new JsonTextWriter(outputTextWriter))
                        {
                            if (conversionOptions.HasFlag(ToolFormatConversionOptions.PrettyPrint))
                            {
                                outputJson.Formatting = Formatting.Indented;
                            }

                            using (var output = new ResultLogJsonWriter(outputJson))
                            {
                                ConvertToStandardFormat(toolFormat, input, output);
                            }
                        }
        }
示例#4
0
        /// <summary>Converts a tool log file to the SARIF format.</summary>
        /// <param name="toolFormat">The tool format of the input file.</param>
        /// <param name="inputFileName">The input log file name.</param>
        /// <param name="outputFileName">The name of the file to which the resulting SARIF log shall be
        /// written. This cannot be a directory.</param>
        public void ConvertToStandardFormat(
            ToolFormat toolFormat,
            string inputFileName,
            string outputFileName)
        {
            if (toolFormat == ToolFormat.PREfast)
            {
                string sarif = ConvertPREfastToStandardFormat(inputFileName);
                File.WriteAllText(outputFileName, sarif);
                return;
            }

            ConvertToStandardFormat(toolFormat, inputFileName, outputFileName, ToolFormatConversionOptions.None);
        }
示例#5
0
        public static void ProcessLogFile(string filePath, ToolFormat toolFormat = ToolFormat.None)
        {
            SarifLog log;

            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                ContractResolver = SarifContractResolver.Instance,
            };

            string logText;

            if (toolFormat == ToolFormat.None)
            {
                logText = File.ReadAllText(filePath);
            }
            else if (toolFormat == ToolFormat.PREfast)
            {
                logText = ToolFormatConverter.ConvertPREfastToStandardFormat(filePath);
            }
            else
            {
                // We have conversion to do
                var converter = new ToolFormatConverter();
                var sb = new StringBuilder();

                using (var input = new MemoryStream(File.ReadAllBytes(filePath)))
                {
                    var outputTextWriter = new StringWriter(sb);
                    var outputJson = new JsonTextWriter(outputTextWriter);
                    var output = new ResultLogJsonWriter(outputJson);

                    input.Seek(0, SeekOrigin.Begin);
                    converter.ConvertToStandardFormat(toolFormat, input, output);

                    // This is serving as a flush mechanism
                    output.Dispose();

                    logText = sb.ToString();
                }
            }

            log = JsonConvert.DeserializeObject<SarifLog>(logText, settings);
            ProcessSarifLog(log, filePath);
        }
        public static void ProcessLogFile(string filePath, ToolFormat toolFormat = ToolFormat.None)
        {
            SarifLog log;

            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                ContractResolver = SarifContractResolver.Instance,
            };

            string logText;

            if (toolFormat == ToolFormat.None)
            {
                logText = File.ReadAllText(filePath);
            }
            else if (toolFormat == ToolFormat.PREfast)
            {
                logText = ToolFormatConverter.ConvertPREfastToStandardFormat(filePath);
            }
            else
            {
                // We have conversion to do
                var converter = new ToolFormatConverter();
                var sb        = new StringBuilder();

                using (var input = new MemoryStream(File.ReadAllBytes(filePath)))
                {
                    var outputTextWriter = new StringWriter(sb);
                    var outputJson       = new JsonTextWriter(outputTextWriter);
                    var output           = new ResultLogJsonWriter(outputJson);

                    input.Seek(0, SeekOrigin.Begin);
                    converter.ConvertToStandardFormat(toolFormat, input, output);

                    // This is serving as a flush mechanism
                    output.Dispose();

                    logText = sb.ToString();
                }
            }

            log = JsonConvert.DeserializeObject <SarifLog>(logText, settings);
            ProcessSarifLog(log);
        }
        private void RunConverter(StringBuilder sb, ToolFormat toolFormat, string inputFileName, TestMode testMode)
        {
            string expectedFileName = inputFileName + ".sarif";
            string generatedFileName = inputFileName + ".actual.sarif";

            try
            {
                this.converter.ConvertToStandardFormat(toolFormat, inputFileName, generatedFileName, ToolFormatConversionOptions.OverwriteExistingOutputFile | ToolFormatConversionOptions.PrettyPrint);
            }
            catch (Exception ex)
            {
                sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "The converter {0} threw an exception for input \"{1}\".", toolFormat, inputFileName));
                sb.AppendLine(ex.ToString());
                return;
            }

            string expectedSarif = File.ReadAllText(expectedFileName);
            string actualSarif = File.ReadAllText(generatedFileName);

            if (expectedSarif == actualSarif)
            {
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ContractResolver = SarifContractResolver.Instance,
                    Formatting = Formatting.Indented
                };

                // Make sure we can successfully deserialize what was just generated
                SarifLog actualLog = JsonConvert.DeserializeObject<SarifLog>(actualSarif, settings);

                actualSarif = JsonConvert.SerializeObject(actualLog, settings);

                bool success;
                switch (testMode)
                {
                    case TestMode.CompareFileContents:
                        success = expectedSarif == actualSarif;
                        break;

                    case TestMode.CompareObjectModels:
                        SarifLog expectedLog = JsonConvert.DeserializeObject<SarifLog>(expectedSarif, settings);
                        success = SarifLogEqualityComparer.Instance.Equals(expectedLog, actualLog);
                        break;

                    default:
                        throw new ArgumentException($"Invalid test mode: {testMode}", nameof(testMode));
                }

                if (success)
                {
                    return;
                }
                else
                {
                    File.WriteAllText(generatedFileName, actualSarif);
                }
            }

            string errorMessage = "The output of the {0} converter did not match for input {1}.";
            sb.AppendLine(string.Format(CultureInfo.CurrentCulture, errorMessage, toolFormat, inputFileName));
            sb.AppendLine("Check differences with:");
            sb.AppendLine(GenerateDiffCommand(expectedFileName, generatedFileName));
        }
        private void BatchRunConverter(ToolFormat tool, string inputFilter, TestMode testMode)
        {
            var sb = new StringBuilder();

            string toolName = Enum.GetName(typeof(ToolFormat), tool);
            string testDirectory = SarifConverterTests.TestDirectory + "\\" + toolName;
            string[] testFiles = Directory.GetFiles(testDirectory, inputFilter);

            foreach (string file in testFiles)
            {
                RunConverter(sb, tool, file, testMode);
            }

            sb.Length.Should().Be(0, FormatFailureReason(sb, toolName));
        }
 private void BatchRunConverter(ToolFormat tool, TestMode testMode)
 {
     BatchRunConverter(tool, "*.xml", testMode);
 }
示例#10
0
 private static void CreateConverterRecord <T>(IDictionary <ToolFormat, Lazy <IToolFileConverter> > dict, ToolFormat format)
     where T : IToolFileConverter, new()
 {
     dict.Add(format, new Lazy <IToolFileConverter>(() => new T(), LazyThreadSafetyMode.ExecutionAndPublication));
 }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            OleMenuCommand      menuCommand      = (OleMenuCommand)sender;
            OleMenuCmdEventArgs menuCmdEventArgs = (OleMenuCmdEventArgs)e;

            string inputFile = menuCmdEventArgs.InValue as String;
            string logFile   = null;

            if (!String.IsNullOrWhiteSpace(inputFile))
            {
                // If the input file is a URL, download the file.
                if (Uri.IsWellFormedUriString(inputFile, UriKind.Absolute))
                {
                    TryDownloadFile(inputFile, out logFile);
                }
                else
                {
                    // Verify if the input file is valid. i.e. it exists and has a valid file extension.
                    string logFileExtension = Path.GetExtension(inputFile);

                    // Since we don't have a tool format, only accept *.sarif and *.json files as command input files.
                    if (logFileExtension.Equals(".sarif", StringComparison.OrdinalIgnoreCase) || logFileExtension.Equals(".json", StringComparison.OrdinalIgnoreCase))
                    {
                        if (File.Exists(inputFile))
                        {
                            logFile = inputFile;
                        }
                    }
                }
            }

            ToolFormat toolFormat = ToolFormat.None;

            if (logFile == null)
            {
                string title  = "Open Static Analysis Results Interchange Format (SARIF) file";
                string filter = "SARIF files (*.sarif;*.sarif.json)|*.sarif;*.sarif.json";

                switch (menuCommand.CommandID.ID)
                {
                // These constants expressed in our VSCT
                case OpenSarifFileCommandId:
                {
                    // Native SARIF. All our defaults above are fine
                    break;
                }

                case OpenPREfastFileCommandId:
                {
                    toolFormat = ToolFormat.PREfast;
                    title      = "Open PREfast XML log file";
                    filter     = "PREfast log files (*.xml)|*.xml";
                    break;
                }

                case OpenFxCopFileCommandId:
                {
                    // FxCop. TODO. We need project file support. FxCop
                    // fullMessages look broken.
                    toolFormat = ToolFormat.FxCop;
                    title      = "Open FxCop XML log file";
                    filter     = "FxCop report and project files (*.xml)|*.xml";
                    break;
                }

                case OpenCppCheckFileCommandId:
                {
                    toolFormat = ToolFormat.CppCheck;
                    title      = "Open CppCheck XML log file";
                    filter     = "CppCheck log files (*.xml)|*.xml";
                    break;
                }

                case OpenClangFileCommandId:
                {
                    toolFormat = ToolFormat.ClangAnalyzer;
                    title      = "Open Clang XML log file";
                    filter     = "Clang log files (*.xml)|*.xml";
                    break;
                }

                case OpenAndroidStudioFileCommandId:
                {
                    toolFormat = ToolFormat.AndroidStudio;
                    title      = "Open Android Studio XML log file";
                    filter     = "Android Studio log files (*.xml)|*.xml";
                    break;
                }
                }

                OpenFileDialog openFileDialog = new OpenFileDialog();

                openFileDialog.Title            = title;
                openFileDialog.Filter           = filter;
                openFileDialog.RestoreDirectory = true;

                if (!String.IsNullOrWhiteSpace(inputFile))
                {
                    openFileDialog.FileName         = Path.GetFileName(inputFile);
                    openFileDialog.InitialDirectory = Path.GetDirectoryName(inputFile);
                }

                if (openFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                logFile = openFileDialog.FileName;
            }

            ErrorListService.ProcessLogFile(logFile, toolFormat);
        }