I’m building a new Rust project and I want to do it right, so I’m interested in complexity and code smells and want to get that automatically via my github CI into SonarCloud. Not too much to ask you’d think?
Personally, I’m a fan of SonarCloud for bringing code analysis and coverage together, and so I find it a bit frustrating that SonarCloud GitHub Action doesn’t support rust out of the box yet in 2022.
If you integrate the sonarcloud scanner and run it, you just end with a new project in SonarCloud but it has no analysis. The message “The main branch of this project is empty” is what you get instead.
Unfortunately, we can’t fix this message completely, but we can get some stats into SonarCloud – namely the code analysis via clippy alongside cargo-sonar. These need to be installed and configured on your action as follows.
N.B. I’m also showing you how to integrate llvm-cov for code coverage – even though the upload to sonarcloud doesn’t appear to work yet.
Essentially this is a four-step process
- Install rustup and clippy and llvm-cov
- Run clippy and convert file to JSON output format
- Run llvm-cov to generate coverage output
- Run the sonarcloud runner to upload the output files generated in the previous steps.
Here’s the excerpt from my github action yaml:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Install Rust
run: rustup update stable
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@cargo-llvm-cov
- name: Install Clippy
run: rustup component add clippy
- name: Install cargo-sonar and run Clippy
run: |
cargo install cargo-sonar
cargo clippy --message-format json > my-clippy-report.json
cargo sonar --issues clippy --clippy-path my-clippy-report.json
- name: Generate code coverage
run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: >
-Dsonar.externalIssuesReportPaths=sonar-issues.json
-Dcommunity.rust.lcov.reportPaths=lcov.info
Assuming your sonar.properties is set up correctly you should then get some statistics uploaded to Sonarcloud. As mentioned, you won’t get code coverage, but I’ll cover how to do that on codecov in another blog post.
The potentially better news is that if you’re running your own SonarQube instance then you can use the sonar-rust plugin to do both clippy and llvm-cov analysis and upload.
Let me know how you get on.