|
| 1 | +require 'solargraph_test_coverage/version' |
| 2 | +require "json" |
| 3 | +require "solargraph" |
| 4 | + |
| 5 | +module SolargraphTestCoverage |
| 6 | + class Error < StandardError; end |
| 7 | + |
| 8 | + class TestCoverageReporter < Solargraph::Diagnostics::Base |
| 9 | + def diagnose(source, _api_map) |
| 10 | + return [] if source.code.empty? || !source.location.filename.include?("/app/") |
| 11 | + |
| 12 | + test_file = locate_test_file(source) |
| 13 | + return [] unless File.file?(test_file) |
| 14 | + |
| 15 | + test_file_content = File.read(test_file) |
| 16 | + return [] unless test_file_content.include? "SingleCov.covered" |
| 17 | + |
| 18 | + pid = Process.spawn("SINGLE_COV_GEN_REPORT=1 bundle exec rspec #{test_file}", out: "/dev/null") |
| 19 | + Process.wait(pid) |
| 20 | + |
| 21 | + results_file = source.location.filename.sub(%r{/app/.*}, "/coverage/.resultset_singlecov.json") |
| 22 | + results = JSON.parse(File.read(results_file)).dig("Minitest", "coverage", source.location.filename) |
| 23 | + |
| 24 | + results.map.with_index { |count, index| coverage_error(source, index) if count&.zero? } |
| 25 | + .compact |
| 26 | + end |
| 27 | + |
| 28 | + private |
| 29 | + |
| 30 | + def locate_test_file(source) |
| 31 | + source.location.filename.sub("/app/", "/spec/") |
| 32 | + .sub(".rb", "_spec.rb") |
| 33 | + end |
| 34 | + |
| 35 | + def coverage_error(source, index) |
| 36 | + { |
| 37 | + range: Solargraph::Range.from_to(index, 0, index, source.code.lines[index].length).to_hash, |
| 38 | + severity: Solargraph::Diagnostics::Severities::WARNING, |
| 39 | + source: 'TestCoverage', |
| 40 | + message: 'Line is not covered by spec' |
| 41 | + } |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + Solargraph::Diagnostics.register 'test_coverage', TestCoverageReporter |
| 46 | +end |
0 commit comments