How to get the top 500 files in a project sorted by cognitive complexity (using the REST API)? The intent is to export the metric for use with another tool.
On a current SonarQube (8.2, though this would work with earlier versions as well, according to documentation), and presuming your instance is on localhost:9000 and the project's name is project1, this bash script curls SonarQube for top 500 files and their cognitive complexity values, sorted by cognitive complexity, then pretty prints it with jq, and displays it in less:
#!/bin/bash
curl \
"localhost:9000"\
"/api/measures/component_tree?"\
"component=project1&"\
"strategy=leaves&"\
"metricKeys=cognitive_complexity&"\
"s=metric&"\
"metricSort=cognitive_complexity&"\
"asc=false&"\
"ps=500" \
| jq "[.components[] | {path: .path, cognitive_complexity: .measures[0].value}]" \
| less
Above script produces output as such:
[
{
"path": "desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java",
"cognitive_complexity": "319"
}
{
"path": "desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java",
"cognitive_complexity": "304"
}
{
"path": "p2p/src/main/java/bisq/network/p2p/network/Connection.java",
"cognitive_complexity": "228"
}
{
"path": "desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java",
"cognitive_complexity": "225"
}
{
"path": "desktop/src/main/java/bisq/desktop/util/GUIUtil.java",
"cognitive_complexity": "192"
}
...