Python API tutorial 7: retrieving violations¶
The API can read any violation that appears in Understand's Violation Browser — CodeCheck violations, analysis errors, and warnings. That's useful for compliance reports and for finding high-risk areas of your code. This tutorial lists every file that contains a violation, along with the check IDs it triggers.
Populate the Violation Browser first¶
The API reads the same violations the Violation Browser shows, so those violations have to exist first:
- Choose Checks → Select Checks to open the Manage Configurations window and create a CodeCheck configuration — for example, all of SciTools' Recommended Checks. See Run your first CodeCheck.
- Turn on the configuration's option to run automatically in the background so results populate the Violation Browser, then analyze the project — see Run CodeCheck automatically in the background.
- Confirm with Checks → Browse Violations — see View & triage violations.
Or import results
You can also populate the Violation Browser by importing a SARIF file from another tool — see Import SARIF results.
The script¶
Starting from a script that simply lists project files, add a call to file.violations():
# Print each project file that has violations, with the check IDs it triggers
import understand
import sys
def fileList(db):
for file in db.ents("File"):
# Skip files from the standard library
if file.library() == "Standard":
continue
viols = file.violations()
if not viols:
continue
print(file.name(), "- violation count:", len(viols))
seen = []
for viol in viols:
if viol.check_id() not in seen:
seen.append(viol.check_id())
print("--> check ID:", viol.check_id())
if __name__ == "__main__":
db = understand.open(sys.argv[1])
fileList(db)
What changed from a plain file listing:
file.library()lets us skip standard-library files ("Standard").file.violations()returns the file's violations as a list ofunderstand.Violationobjects — an empty list if the file has none. (It returnsNoneonly when called on a non-file entity, which can't happen here since the loop is already filtered todb.ents("File").)viol.check_id()returns the unique ID of the triggering check — orUND_ERROR/UND_WARNINGfor analysis errors and warnings respectively. We de-duplicate so each check ID prints once per file.
Run it against a project whose Violation Browser is populated:
upython violations.py C:/projects/test.und
Explore the Violation class
A Violation also exposes its file(),
line(), column(), and text(), so you can build
detailed compliance output. Browse the full class under Help → Python API Documentation.
Series complete¶
That's the end of the tutorial series. From here:
- Write a plugin — package your scripts as GUI graphs, reports, checks, or metrics. To write your own CodeCheck checks with this API, see the CodeCheck API guide.
- Sample & solution scripts — ready-to-run scripts to copy from.
- Python API: getting started — the setup reference and links to the full in-product API documentation.