You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Github Actions中Sonar Scanner无法解析lcov.info文件路径

SonarQube扫描无法识别nyc生成的lcov覆盖率文件问题

问题背景

已尝试所有公开可查的同类问题解决方案均未生效,场景存在特殊情况。
当前操作目标为将mocha测试通过nyc生成的lcov.info覆盖率数据上传至自有SonarQube实例,无论如何调整配置,sonar-scanner始终无法定位lcov文件中标记的对应文件,报错信息如下:

WARN: Could not resolve 7 file paths in [/github/workspace/coverage/lcov.info]
WARN: First unresolved path: config/file:config/config.ts

现有配置

  • yarn test执行命令:
    nyc --reporter=lcovonly --reporter=text-summary mocha -r ts-node/register 'tests/run.test.ts'

  • SonarScanner Github Actions工作流配置:

name: Build
on:
  push:
      branches: [ master ]
  pull_request:
      types: [opened, synchronize, reopened]
      branches: [ master ]
jobs:
  sonarqube:
    name: sonarqube
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Install dependencies
        run: yarn
      - name: Run Tests
        run: yarn test

      ## 此前尝试的修复方案:移除路径前缀,将绝对路径改为相对路径
      - name: Fix coverage report
        run: sed -i "s+/home/runner/work/rest-api/rest-api/++g" coverage/lcov.info

      - name: Run SonarQube Scan
        uses: sonarsource/sonarqube-scan-action@master
        with:
          ## 开启sonarqube-scan-action调试模式
          args: >
            -Dsonar.verbose=true
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
  • sonar-project.properties配置:
sonar.language=ts
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.sources=.
sonar.tests=tests/
sonar.coverage.exclusions=tests/**
sonar.test.inclusions=tests/**
sonar.projectKey=<PROJECT-KEY>

问题根因

报错中出现的config/file:config/config.ts属于异常路径:正常lcov文件的SF字段应为纯文件路径,路径中混入file:前缀,是nyc搭配ts-node处理TypeScript源码路径时,未正确转换source map返回的file协议路径导致的。此前使用sed替换绝对路径的方案未命中该异常格式,因此路径始终无法被SonarScanner识别。

修复方案

按以下步骤调整配置即可解决问题:

  1. 调整nyc执行参数,新增--cwd ./和--exclude-after-remap=false参数,从源头避免生成错误路径,修改后的test命令为:
    nyc --reporter=lcovonly --reporter=text-summary --cwd ./ --exclude-after-remap=false mocha -r ts-node/register 'tests/run.test.ts'
  2. 修改覆盖率文件修复步骤的命令,在原有绝对路径替换逻辑基础上,新增file:前缀替换逻辑,修改后的命令如下:
# 移除绝对路径前缀
sed -i "s+/home/runner/work/rest-api/rest-api/++g" coverage/lcov.info
# 移除残留的file协议前缀
sed -i "s+file:++g" coverage/lcov.info
  1. 调整sonar-project.properties中的源码路径配置,明确指定源码根目录为当前路径,避免相对路径匹配偏差:
    将sonar.sources=.修改为sonar.sources=./即可。

内容的提问来源于stack exchange,提问作者Mavial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:33:08