Last Updated: February 25, 2016
·
975
· julias-shaw

XML Formatter for SimpleCov

module SimpleCov
  module Formatter
    class XMLFormatter
      RESULT_FILE_NAME = "coverage.xml"

      def format(result)
        xml = "<SimpleCov>\n"

        xml << "  <summary percent_covered=\"#{result.covered_percent.round.to_s}\" "
        xml << "relevant_lines=\"#{result.total_lines}\" "
        xml << "lines_covered=\"#{result.covered_lines}\" "
        xml << "lines_missed=\"#{result.missed_lines}\" />\n"
        xml << "  <files>\n"
        result.files.each do |file|
          xml << "    <file name=\"#{shortened_filename file}\" "
          xml << "percent_covered=\"#{file.covered_percent.round.to_s}\" "
          xml << "lines=\"#{file.lines.count}\" "
          xml << "relevant_lines=\"#{file.covered_lines.count + file.missed_lines.count}\" "
          xml << "lines_covered=\"#{file.covered_lines.count}\" "
          xml << "lines_missed=\"#{file.missed_lines.count}\" />\n"
        end
        xml << "  <files>\n"
        xml << "</SimpleCov>"

        result_file_path = File.join( SimpleCov.coverage_path, SimpleCov::Formatter::XMLFormatter.result_file_name )
        File.open( result_file_path, "w" ) do |file_result|
          file_result.write xml
        end
        puts "Coverage report generated for #{result.command_name} to #{result_file_path}"

        return xml
      end

      private

      def shortened_filename(source_file)
        source_file.filename.gsub(SimpleCov.root, '.')
      end

      def self.result_file_name
        SimpleCov::Formatter::XMLFormatter::RESULT_FILE_NAME
      end
    end
  end
end