From 69918cdc73b1e23b407549b5b3006565b53cdfd0 Mon Sep 17 00:00:00 2001 From: Thibaud Chupin Date: Thu, 26 Nov 2026 20:22:11 +0100 Subject: [PATCH 1/3] Add GitLab Code Quality output format Add --output-format=gitlab-codequality, which writes findings as a GitLab Code Quality JSON array. Findings without a source location are skipped because GitLab requires a location. The existing warning hash is used as the fingerprint, with a location-based fallback when no token hash is available. --- Makefile | 10 +- cli/cmdlineparser.cpp | 5 +- cli/cppcheckexecutor.cpp | 16 ++- lib/cppcheck.vcxproj | 2 + lib/gitlabcodequalityreport.cpp | 115 ++++++++++++++++++ lib/gitlabcodequalityreport.h | 79 +++++++++++++ lib/settings.h | 2 +- oss-fuzz/Makefile | 4 + releasenotes.txt | 1 + test/cli/gitlab_code_quality_test.py | 47 ++++++++ test/testcmdlineparser.cpp | 10 +- test/testgitlabcodequalityreport.cpp | 170 +++++++++++++++++++++++++++ test/testrunner.vcxproj | 1 + 13 files changed, 457 insertions(+), 5 deletions(-) create mode 100644 lib/gitlabcodequalityreport.cpp create mode 100644 lib/gitlabcodequalityreport.h create mode 100644 test/cli/gitlab_code_quality_test.py create mode 100644 test/testgitlabcodequalityreport.cpp diff --git a/Makefile b/Makefile index 53c8b4c7aea..08085ce391a 100644 --- a/Makefile +++ b/Makefile @@ -246,6 +246,7 @@ LIBOBJ = $(libcppdir)/valueflow.o \ $(libcppdir)/findtoken.o \ $(libcppdir)/forwardanalyzer.o \ $(libcppdir)/fwdanalysis.o \ + $(libcppdir)/gitlabcodequalityreport.o \ $(libcppdir)/importproject.o \ $(libcppdir)/infer.o \ $(libcppdir)/keywords.o \ @@ -320,6 +321,7 @@ TESTOBJ = test/fixture.o \ test/testfrontend.o \ test/testfunctions.o \ test/testgarbage.o \ + test/testgitlabcodequalityreport.o \ test/testimportproject.o \ test/testincompletestatement.o \ test/testinternal.o \ @@ -616,6 +618,9 @@ $(libcppdir)/forwardanalyzer.o: lib/forwardanalyzer.cpp lib/analyzer.h lib/astut $(libcppdir)/fwdanalysis.o: lib/fwdanalysis.cpp lib/astutils.h lib/checkers.h lib/config.h lib/errortypes.h lib/fwdanalysis.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/fwdanalysis.cpp +$(libcppdir)/gitlabcodequalityreport.o: lib/gitlabcodequalityreport.cpp externals/picojson/picojson.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/gitlabcodequalityreport.h lib/json.h lib/refthunk.h lib/utils.h + $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/gitlabcodequalityreport.cpp + $(libcppdir)/importproject.o: lib/importproject.cpp externals/picojson/picojson.h externals/tinyxml2/tinyxml2.h lib/checkers.h lib/config.h lib/filesettings.h lib/importproject.h lib/json.h lib/library.h lib/mathlib.h lib/path.h lib/pathmatch.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h lib/xml.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/importproject.cpp @@ -703,7 +708,7 @@ frontend/frontend.o: frontend/frontend.cpp frontend/frontend.h lib/checkers.h li cli/cmdlineparser.o: cli/cmdlineparser.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/filelister.h externals/tinyxml2/tinyxml2.h lib/addoninfo.h lib/check.h lib/checkers.h lib/checks.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/importproject.h lib/library.h lib/mathlib.h lib/path.h lib/pathmatch.h lib/platform.h lib/refthunk.h lib/regex.h lib/rule.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h lib/xml.h $(CXX) ${INCLUDE_FOR_CLI} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ cli/cmdlineparser.cpp -cli/cppcheckexecutor.o: cli/cppcheckexecutor.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/cppcheckexecutor.h cli/executor.h cli/processexecutor.h cli/sehwrapper.h cli/signalhandler.h cli/singleexecutor.h cli/threadexecutor.h externals/picojson/picojson.h lib/analyzerinfo.h lib/check.h lib/checkers.h lib/checkersreport.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/json.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/sarifreport.h lib/settings.h lib/standards.h lib/suppressions.h lib/timer.h lib/utils.h +cli/cppcheckexecutor.o: cli/cppcheckexecutor.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/cppcheckexecutor.h cli/executor.h cli/processexecutor.h cli/sehwrapper.h cli/signalhandler.h cli/singleexecutor.h cli/threadexecutor.h externals/picojson/picojson.h lib/analyzerinfo.h lib/check.h lib/checkers.h lib/checkersreport.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/gitlabcodequalityreport.h lib/json.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/sarifreport.h lib/settings.h lib/standards.h lib/suppressions.h lib/timer.h lib/utils.h $(CXX) ${INCLUDE_FOR_CLI} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ cli/cppcheckexecutor.cpp cli/executor.o: cli/executor.cpp cli/executor.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h @@ -820,6 +825,9 @@ test/testfunctions.o: test/testfunctions.cpp lib/check.h lib/checkers.h lib/chec test/testgarbage.o: test/testgarbage.cpp lib/check.h lib/checkers.h lib/checks.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/standards.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h test/fixture.h test/helpers.h $(CXX) ${INCLUDE_FOR_TEST} ${CFLAGS_FOR_TEST} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ test/testgarbage.cpp +test/testgitlabcodequalityreport.o: test/testgitlabcodequalityreport.cpp externals/picojson/picojson.h lib/check.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/gitlabcodequalityreport.h lib/json.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/standards.h lib/utils.h test/fixture.h + $(CXX) ${INCLUDE_FOR_TEST} ${CFLAGS_FOR_TEST} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ test/testgitlabcodequalityreport.cpp + test/testimportproject.o: test/testimportproject.cpp lib/check.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/importproject.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/standards.h lib/suppressions.h lib/tokenize.h lib/tokenlist.h lib/utils.h test/fixture.h test/helpers.h test/redirect.h $(CXX) ${INCLUDE_FOR_TEST} ${CFLAGS_FOR_TEST} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ test/testimportproject.cpp diff --git a/cli/cmdlineparser.cpp b/cli/cmdlineparser.cpp index 6e2bc67cd10..b80c0a88ee9 100644 --- a/cli/cmdlineparser.cpp +++ b/cli/cmdlineparser.cpp @@ -1049,6 +1049,8 @@ CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const a mSettings.outputFormat = Settings::OutputFormat::text; else if (format == "sarif") mSettings.outputFormat = Settings::OutputFormat::sarif; + else if (format == "gitlab-codequality") + mSettings.outputFormat = Settings::OutputFormat::gitlabCodeQuality; else if (format == "xml") mSettings.outputFormat = Settings::OutputFormat::xml; else if (format == "xmlv2") { @@ -1058,7 +1060,7 @@ CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const a mSettings.outputFormat = Settings::OutputFormat::xml; mSettings.xml_version = 3; } else { - mLogger.printError("argument to '--output-format=' must be 'text', 'sarif', 'xml' (deprecated), 'xmlv2' or 'xmlv3'."); + mLogger.printError("argument to '--output-format=' must be 'text', 'sarif', 'gitlab-codequality', 'xml' (deprecated), 'xmlv2' or 'xmlv3'."); return Result::Fail; } mSettings.plistOutput = ""; @@ -1913,6 +1915,7 @@ void CmdLineParser::printHelp() const " Specify the output format. The available formats are:\n" " * text\n" " * sarif\n" + " * gitlab-codequality\n" " * xml (deprecated)\n" " * xmlv2\n" " * xmlv3\n" diff --git a/cli/cppcheckexecutor.cpp b/cli/cppcheckexecutor.cpp index d590b6c48d3..ee9e0679dc7 100644 --- a/cli/cppcheckexecutor.cpp +++ b/cli/cppcheckexecutor.cpp @@ -32,6 +32,7 @@ #include "errorlogger.h" #include "errortypes.h" #include "filesettings.h" +#include "gitlabcodequalityreport.h" #include "path.h" #include "sarifreport.h" #include "settings.h" @@ -117,8 +118,13 @@ namespace { } ~StdLogger() override { + // SARIF and GitlabCodeQuality reports are a JSON array. They cannot + // be written incrementally, but only when the full set of findings + // is available. if (mSettings.outputFormat == Settings::OutputFormat::sarif) { reportErr(mSarifReport.serialize(mSettings.cppcheckCfgProductName)); + } else if (mSettings.outputFormat == Settings::OutputFormat::gitlabCodeQuality) { + reportErr(mGitlabCodeQualityReport.serialize()); } delete mErrorOutput; } @@ -238,6 +244,11 @@ namespace { */ SarifReport mSarifReport; + /** + * GitLab Code Quality report generator + */ + GitlabCodeQualityReport mGitlabCodeQualityReport; + /** * Coding standard guideline mapping */ @@ -679,7 +690,8 @@ void StdLogger::reportErr(const ErrorMessage &msg) // Don't perform redundant reads for these formats, the code is not needed // for deduplication const bool noCode = mSettings.outputFormat == Settings::OutputFormat::xml || - mSettings.outputFormat == Settings::OutputFormat::sarif; + mSettings.outputFormat == Settings::OutputFormat::sarif || + mSettings.outputFormat == Settings::OutputFormat::gitlabCodeQuality; const std::string msgStr = msgCopy.toString(mSettings.verbose, mSettings.templateFormat, mSettings.templateLocation, noCode); @@ -690,6 +702,8 @@ void StdLogger::reportErr(const ErrorMessage &msg) if (mSettings.outputFormat == Settings::OutputFormat::sarif) { mSarifReport.addFinding(std::move(msgCopy)); + } else if (mSettings.outputFormat == Settings::OutputFormat::gitlabCodeQuality) { + mGitlabCodeQualityReport.addFinding(std::move(msgCopy)); } else if (mSettings.outputFormat == Settings::OutputFormat::xml) { reportErr(msgCopy.toXML()); } else { diff --git a/lib/cppcheck.vcxproj b/lib/cppcheck.vcxproj index c2484ebbcee..5c797006941 100644 --- a/lib/cppcheck.vcxproj +++ b/lib/cppcheck.vcxproj @@ -75,6 +75,7 @@ + @@ -152,6 +153,7 @@ + diff --git a/lib/gitlabcodequalityreport.cpp b/lib/gitlabcodequalityreport.cpp new file mode 100644 index 00000000000..d2c36d3b98a --- /dev/null +++ b/lib/gitlabcodequalityreport.cpp @@ -0,0 +1,115 @@ +/* + * Cppcheck - A tool for static C/C++ code analysis + * Copyright (C) 2007-2026 Cppcheck team. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "gitlabcodequalityreport.h" + +#include "errorlogger.h" +#include "errortypes.h" +#include "utils.h" + +#include +#include + +namespace { + std::string locationPath(const ErrorMessage::FileLocation& location) + { + std::string path = location.getfile(false); + while (startsWith(path, "./")) + path.erase(0, 2); + return path; + } + + picojson::object serializeLocation(const ErrorMessage::FileLocation& location) + { + picojson::object lines; + lines["begin"] = picojson::value(static_cast(location.line < 1 ? 1 : location.line)); + + picojson::object result; + result["path"] = picojson::value(locationPath(location)); + result["lines"] = picojson::value(lines); + return result; + } + + std::string fingerprint(const ErrorMessage& finding) + { + if (finding.hash != 0) { + return std::to_string(finding.hash); + } + + // Findings without token information have no warning hash. + const ErrorMessage::FileLocation& location = finding.callStack.back(); + return finding.id + ':' + finding.shortMessage() + ':' + locationPath(location) + ':' + + std::to_string(location.line); + } +} + +void GitlabCodeQualityReport::addFinding(ErrorMessage msg) +{ + mFindings.push_back(std::move(msg)); +} + +picojson::object GitlabCodeQualityReport::serializeFinding(const ErrorMessage& finding) +{ + const ErrorMessage::FileLocation& location = finding.callStack.back(); + + picojson::object result; + result["description"] = picojson::value(finding.shortMessage()); + result["check_name"] = picojson::value(finding.id); + result["fingerprint"] = picojson::value(fingerprint(finding)); + result["severity"] = picojson::value(codeQualitySeverity(finding)); + result["location"] = picojson::value(serializeLocation(location)); + return result; +} + +std::string GitlabCodeQualityReport::serialize() const +{ + picojson::array findings; + for (const ErrorMessage& finding : mFindings) { + // GitLab requires a location for every code quality finding. + if (finding.callStack.empty()) { + continue; + } + findings.emplace_back(serializeFinding(finding)); + } + + return picojson::value(findings).serialize(true); +} + +std::string GitlabCodeQualityReport::codeQualitySeverity(const ErrorMessage& finding) +{ + if (ErrorLogger::isCriticalErrorId(finding.id)) { + return "critical"; + } + + switch (finding.severity) { + case Severity::error: + return "critical"; + case Severity::warning: + return "major"; + case Severity::style: + case Severity::performance: + case Severity::portability: + return "minor"; + case Severity::information: + case Severity::internal: + case Severity::debug: + case Severity::none: + return "info"; + } + return "info"; +} diff --git a/lib/gitlabcodequalityreport.h b/lib/gitlabcodequalityreport.h new file mode 100644 index 00000000000..ae02b7d3cfe --- /dev/null +++ b/lib/gitlabcodequalityreport.h @@ -0,0 +1,79 @@ +/* + * Cppcheck - A tool for static C/C++ code analysis + * Copyright (C) 2007-2026 Cppcheck team. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef GITLAB_CODE_QUALITY_REPORT_H +#define GITLAB_CODE_QUALITY_REPORT_H + +#include "config.h" +#include "errorlogger.h" + +#include +#include + +#include "json.h" + +/** + * @brief Generates a GitLab Code Quality report. + * + * The report is a JSON array in the GitLab Code Quality report format. + * + * Each finding must contain: + * + * - description: human-readable description of the violation + * - check_name: unique name of the check or rule + * - fingerprint: unique fingerprint for the violation + * - severity: info, minor, major, critical, or blocker + * - location.path: repository-relative path to the source file + * - location.lines.begin (or location.positions.begin.line): line number + * + * Example: + * @code{.json} + * [ + * { + * "description": "Division by zero.", + * "check_name": "zerodiv", + * "fingerprint": "12532254259410460725", + * "severity": "critical", + * "location": { + * "path": "src/main.cpp", + * "lines": { + * "begin": 4 + * } + * } + * } + * ] + * @endcode + * + * @see https://docs.gitlab.com/ci/testing/code_quality/#code-quality-report-format + */ +class CPPCHECKLIB GitlabCodeQualityReport { +public: + GitlabCodeQualityReport() = default; + ~GitlabCodeQualityReport() = default; + + void addFinding(ErrorMessage msg); + std::string serialize() const; + +private: + static picojson::object serializeFinding(const ErrorMessage& finding); + static std::string codeQualitySeverity(const ErrorMessage& finding); + + std::vector mFindings; +}; + +#endif // GITLAB_CODE_QUALITY_REPORT_H diff --git a/lib/settings.h b/lib/settings.h index 52f20afb7c4..28a8ae42b01 100644 --- a/lib/settings.h +++ b/lib/settings.h @@ -349,7 +349,7 @@ class CPPCHECKLIB WARN_UNUSED Settings { /** @brief write results (--output-file=<file>) */ std::string outputFile; - enum class OutputFormat : std::uint8_t {text, plist, sarif, xml}; + enum class OutputFormat : std::uint8_t {text, plist, sarif, gitlabCodeQuality, xml}; OutputFormat outputFormat = OutputFormat::text; Platform platform; diff --git a/oss-fuzz/Makefile b/oss-fuzz/Makefile index a71b026618b..1ff4b260300 100644 --- a/oss-fuzz/Makefile +++ b/oss-fuzz/Makefile @@ -83,6 +83,7 @@ LIBOBJ = $(libcppdir)/valueflow.o \ $(libcppdir)/findtoken.o \ $(libcppdir)/forwardanalyzer.o \ $(libcppdir)/fwdanalysis.o \ + $(libcppdir)/gitlabcodequalityreport.o \ $(libcppdir)/importproject.o \ $(libcppdir)/infer.o \ $(libcppdir)/keywords.o \ @@ -285,6 +286,9 @@ $(libcppdir)/forwardanalyzer.o: ../lib/forwardanalyzer.cpp ../lib/analyzer.h ../ $(libcppdir)/fwdanalysis.o: ../lib/fwdanalysis.cpp ../lib/astutils.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/fwdanalysis.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/fwdanalysis.cpp +$(libcppdir)/gitlabcodequalityreport.o: ../lib/gitlabcodequalityreport.cpp ../externals/picojson/picojson.h ../lib/config.h ../lib/errorlogger.h ../lib/errortypes.h ../lib/gitlabcodequalityreport.h ../lib/json.h ../lib/refthunk.h ../lib/utils.h + $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/gitlabcodequalityreport.cpp + $(libcppdir)/importproject.o: ../lib/importproject.cpp ../externals/picojson/picojson.h ../externals/tinyxml2/tinyxml2.h ../lib/checkers.h ../lib/config.h ../lib/filesettings.h ../lib/importproject.h ../lib/json.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/pathmatch.h ../lib/platform.h ../lib/settings.h ../lib/standards.h ../lib/suppressions.h ../lib/utils.h ../lib/xml.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/importproject.cpp diff --git a/releasenotes.txt b/releasenotes.txt index 0212aab7a25..4eee6dcc31a 100644 --- a/releasenotes.txt +++ b/releasenotes.txt @@ -5,6 +5,7 @@ Options: - Rules: The PCRE library that we used is end-of-life. We have switched to PCRE2 instead. Existing rule files will hopefully work without changes. - The --clang option has been deprecated, it will be removed in Cppcheck 2.27 +- New output format: --output-format=gitlab-codequality for GitLab Code Quality reports. Major bug fixes & crashes: - diff --git a/test/cli/gitlab_code_quality_test.py b/test/cli/gitlab_code_quality_test.py new file mode 100644 index 00000000000..b52fa0b0fdf --- /dev/null +++ b/test/cli/gitlab_code_quality_test.py @@ -0,0 +1,47 @@ +# python -m pytest gitlab_code_quality_test.py + +import json + +from testutils import cppcheck + +TEST_CODE = """ +int main() +{ + int x = 0; + return 1 / x; +} +""" + + +def test_gitlab_code_quality(tmp_path): + (tmp_path / "test.cpp").write_text(TEST_CODE) + + exitcode, _, stderr = cppcheck( + ["--output-format=gitlab-codequality", "--enable=warning", "test.cpp"], + cwd=tmp_path) + + assert exitcode == 0 + findings = json.loads(stderr) + assert len(findings) == 1 + + finding = findings[0] + assert finding["description"] == "Division by zero." + assert finding["check_name"] == "zerodiv" + assert finding["fingerprint"] + assert finding["severity"] == "critical" + assert finding["location"]["path"] == "test.cpp" + assert finding["location"]["lines"]["begin"] == 5 + + +def test_gitlab_code_quality_output_file(tmp_path): + (tmp_path / "test.cpp").write_text(TEST_CODE) + + exitcode, _, stderr = cppcheck( + ["--output-format=gitlab-codequality", "--enable=warning", "--output-file=report.json", "test.cpp"], + cwd=tmp_path) + + assert exitcode == 0 + assert stderr == "" + findings = json.loads((tmp_path / "report.json").read_text()) + assert len(findings) == 1 + assert findings[0]["check_name"] == "zerodiv" diff --git a/test/testcmdlineparser.cpp b/test/testcmdlineparser.cpp index 6f963e07212..a6c9acaa381 100644 --- a/test/testcmdlineparser.cpp +++ b/test/testcmdlineparser.cpp @@ -243,6 +243,7 @@ class TestCmdlineParser : public TestFixture { TEST_CASE(maxConfigsTooSmall); TEST_CASE(outputFormatText); TEST_CASE(outputFormatSarif); + TEST_CASE(outputFormatGitlabCodeQuality); TEST_CASE(outputFormatXml); TEST_CASE(outputFormatXmlv2); TEST_CASE(outputFormatXmlv3); @@ -1474,6 +1475,13 @@ class TestCmdlineParser : public TestFixture { ASSERT_EQUALS_ENUM(Settings::OutputFormat::sarif, settings->outputFormat); } + void outputFormatGitlabCodeQuality() { + REDIRECT; + const char * const argv[] = {"cppcheck", "--output-format=gitlab-codequality", "file.cpp"}; + ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parseFromArgs(argv)); + ASSERT_EQUALS_ENUM(Settings::OutputFormat::gitlabCodeQuality, settings->outputFormat); + } + void outputFormatXml() { REDIRECT; const char * const argv[] = {"cppcheck", "--output-format=xml", "file.cpp"}; @@ -1501,7 +1509,7 @@ class TestCmdlineParser : public TestFixture { REDIRECT; const char * const argv[] = {"cppcheck", "--output-format=plist", "file.cpp"}; ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parseFromArgs(argv)); - ASSERT_EQUALS("cppcheck: error: argument to '--output-format=' must be 'text', 'sarif', 'xml' (deprecated), 'xmlv2' or 'xmlv3'.\n", logger->str()); + ASSERT_EQUALS("cppcheck: error: argument to '--output-format=' must be 'text', 'sarif', 'gitlab-codequality', 'xml' (deprecated), 'xmlv2' or 'xmlv3'.\n", logger->str()); } void outputFormatImplicitPlist() { diff --git a/test/testgitlabcodequalityreport.cpp b/test/testgitlabcodequalityreport.cpp new file mode 100644 index 00000000000..a7541d4f623 --- /dev/null +++ b/test/testgitlabcodequalityreport.cpp @@ -0,0 +1,170 @@ +/* + * Cppcheck - A tool for static C/C++ code analysis + * Copyright (C) 2007-2026 Cppcheck team. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "gitlabcodequalityreport.h" +#include "errorlogger.h" +#include "errortypes.h" +#include "fixture.h" + +#include +#include + +#include "json.h" + +class TestGitlabCodeQualityReport : public TestFixture +{ +public: + TestGitlabCodeQualityReport() : TestFixture("TestGitlabCodeQualityReport") + {} + +private: + void run() override + { + TEST_CASE(emptyReport); + TEST_CASE(singleError); + TEST_CASE(multipleErrors); + TEST_CASE(errorWithoutLocation); + TEST_CASE(severityMapping); + TEST_CASE(fingerprint); + TEST_CASE(pathWithoutDotSlash); + } + + static ErrorMessage createErrorMessage(const std::string& id, + Severity severity, + const std::string& msg, + const std::string& file = "test.cpp", + int line = 10) + { + ErrorMessage::FileLocation loc(file, line, 1); + return ErrorMessage({loc}, file, severity, msg, id, Certainty::normal); + } + + static bool parseJson(const std::string& data, picojson::value& root) + { + const std::string error = picojson::parse(root, data); + return error.empty() && root.is(); + } + + static const picojson::object& findingAt(const picojson::value& root, std::size_t index) + { + return root.get()[index].get(); + } + + std::string severityOf(Severity severity) + { + GitlabCodeQualityReport report; + report.addFinding(createErrorMessage("testError", severity, "Test error")); + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + return findingAt(json, 0).at("severity").get(); + } + + void emptyReport() + { + GitlabCodeQualityReport report; + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS(0U, json.get().size()); + } + + void singleError() + { + GitlabCodeQualityReport report; + report.addFinding(createErrorMessage("nullPointer", Severity::error, "Null pointer dereference", "src/test.cpp", 42)); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS(1U, json.get().size()); + + const picojson::object& finding = findingAt(json, 0); + ASSERT_EQUALS("Null pointer dereference", finding.at("description").get()); + ASSERT_EQUALS("nullPointer", finding.at("check_name").get()); + ASSERT_EQUALS("critical", finding.at("severity").get()); + ASSERT(!finding.at("fingerprint").get().empty()); + + const picojson::object& location = finding.at("location").get(); + ASSERT_EQUALS("src/test.cpp", location.at("path").get()); + const picojson::object& lines = location.at("lines").get(); + ASSERT_EQUALS(42, static_cast(lines.at("begin").get())); + } + + void multipleErrors() + { + GitlabCodeQualityReport report; + report.addFinding(createErrorMessage("error1", Severity::error, "Error 1", "file1.cpp", 10)); + report.addFinding(createErrorMessage("error2", Severity::warning, "Error 2", "file2.cpp", 20)); + report.addFinding(createErrorMessage("error3", Severity::style, "Error 3", "file3.cpp", 30)); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS(3U, json.get().size()); + } + + void errorWithoutLocation() + { + GitlabCodeQualityReport report; + report.addFinding(ErrorMessage({}, "test.cpp", Severity::error, "Error without location", "testError", Certainty::normal)); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS(0U, json.get().size()); + } + + void severityMapping() + { + ASSERT_EQUALS("critical", severityOf(Severity::error)); + ASSERT_EQUALS("major", severityOf(Severity::warning)); + ASSERT_EQUALS("minor", severityOf(Severity::style)); + ASSERT_EQUALS("minor", severityOf(Severity::performance)); + ASSERT_EQUALS("minor", severityOf(Severity::portability)); + ASSERT_EQUALS("info", severityOf(Severity::information)); + ASSERT_EQUALS("info", severityOf(Severity::debug)); + ASSERT_EQUALS("info", severityOf(Severity::none)); + + GitlabCodeQualityReport report; + report.addFinding(createErrorMessage("syntaxError", Severity::style, "Syntax error")); + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS("critical", findingAt(json, 0).at("severity").get()); + } + + void fingerprint() + { + ErrorMessage errorMessage = createErrorMessage("testError", Severity::error, "Test error"); + errorMessage.hash = 12345; + GitlabCodeQualityReport report; + report.addFinding(errorMessage); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS("12345", findingAt(json, 0).at("fingerprint").get()); + } + + void pathWithoutDotSlash() + { + GitlabCodeQualityReport report; + report.addFinding(createErrorMessage("testError", Severity::error, "Test error", "./src/test.cpp", 10)); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + const picojson::object& location = findingAt(json, 0).at("location").get(); + ASSERT_EQUALS("src/test.cpp", location.at("path").get()); + } +}; + +REGISTER_TEST(TestGitlabCodeQualityReport) diff --git a/test/testrunner.vcxproj b/test/testrunner.vcxproj index 2ce6a97d9c4..9b631fc0d10 100755 --- a/test/testrunner.vcxproj +++ b/test/testrunner.vcxproj @@ -69,6 +69,7 @@ + From 6e3abcfd0424f1419a3facb402d7f2ea28c2dda6 Mon Sep 17 00:00:00 2001 From: Thibaud Chupin Date: Thu, 26 Nov 2026 23:09:58 +0100 Subject: [PATCH 2/3] Warn about absolute GitLab report paths Track whether the GitLab Code Quality report contains an absolute location. Warn on stdout so the JSON report on stderr stays valid, even when --relative-paths was given but did not make the path relative. --- Makefile | 2 +- cli/cppcheckexecutor.cpp | 4 +++ lib/gitlabcodequalityreport.cpp | 4 +++ lib/gitlabcodequalityreport.h | 5 ++++ oss-fuzz/Makefile | 2 +- test/cli/gitlab_code_quality_test.py | 44 ++++++++++++++++++++++++++++ test/testgitlabcodequalityreport.cpp | 13 ++++++++ 7 files changed, 72 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 08085ce391a..17434fa4371 100644 --- a/Makefile +++ b/Makefile @@ -618,7 +618,7 @@ $(libcppdir)/forwardanalyzer.o: lib/forwardanalyzer.cpp lib/analyzer.h lib/astut $(libcppdir)/fwdanalysis.o: lib/fwdanalysis.cpp lib/astutils.h lib/checkers.h lib/config.h lib/errortypes.h lib/fwdanalysis.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/fwdanalysis.cpp -$(libcppdir)/gitlabcodequalityreport.o: lib/gitlabcodequalityreport.cpp externals/picojson/picojson.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/gitlabcodequalityreport.h lib/json.h lib/refthunk.h lib/utils.h +$(libcppdir)/gitlabcodequalityreport.o: lib/gitlabcodequalityreport.cpp externals/picojson/picojson.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/gitlabcodequalityreport.h lib/json.h lib/path.h lib/refthunk.h lib/standards.h lib/utils.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/gitlabcodequalityreport.cpp $(libcppdir)/importproject.o: lib/importproject.cpp externals/picojson/picojson.h externals/tinyxml2/tinyxml2.h lib/checkers.h lib/config.h lib/filesettings.h lib/importproject.h lib/json.h lib/library.h lib/mathlib.h lib/path.h lib/pathmatch.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h lib/xml.h diff --git a/cli/cppcheckexecutor.cpp b/cli/cppcheckexecutor.cpp index ee9e0679dc7..f8c93ecb407 100644 --- a/cli/cppcheckexecutor.cpp +++ b/cli/cppcheckexecutor.cpp @@ -124,6 +124,10 @@ namespace { if (mSettings.outputFormat == Settings::OutputFormat::sarif) { reportErr(mSarifReport.serialize(mSettings.cppcheckCfgProductName)); } else if (mSettings.outputFormat == Settings::OutputFormat::gitlabCodeQuality) { + if (mGitlabCodeQualityReport.hasAbsolutePath()) { + // Keep the JSON report on stderr free of warnings. + reportOut("cppcheck: warning: GitLab Code Quality requires repository-relative paths; use --relative-paths=."); + } reportErr(mGitlabCodeQualityReport.serialize()); } delete mErrorOutput; diff --git a/lib/gitlabcodequalityreport.cpp b/lib/gitlabcodequalityreport.cpp index d2c36d3b98a..990f8f4b71f 100644 --- a/lib/gitlabcodequalityreport.cpp +++ b/lib/gitlabcodequalityreport.cpp @@ -20,6 +20,7 @@ #include "errorlogger.h" #include "errortypes.h" +#include "path.h" #include "utils.h" #include @@ -60,6 +61,9 @@ namespace { void GitlabCodeQualityReport::addFinding(ErrorMessage msg) { + if (!msg.callStack.empty() && Path::isAbsolute(locationPath(msg.callStack.back()))) { + mHasAbsolutePath = true; + } mFindings.push_back(std::move(msg)); } diff --git a/lib/gitlabcodequalityreport.h b/lib/gitlabcodequalityreport.h index ae02b7d3cfe..37b0d5fc0de 100644 --- a/lib/gitlabcodequalityreport.h +++ b/lib/gitlabcodequalityreport.h @@ -69,11 +69,16 @@ class CPPCHECKLIB GitlabCodeQualityReport { void addFinding(ErrorMessage msg); std::string serialize() const; + bool hasAbsolutePath() const { + return mHasAbsolutePath; + } + private: static picojson::object serializeFinding(const ErrorMessage& finding); static std::string codeQualitySeverity(const ErrorMessage& finding); std::vector mFindings; + bool mHasAbsolutePath{}; }; #endif // GITLAB_CODE_QUALITY_REPORT_H diff --git a/oss-fuzz/Makefile b/oss-fuzz/Makefile index 1ff4b260300..248202a2599 100644 --- a/oss-fuzz/Makefile +++ b/oss-fuzz/Makefile @@ -286,7 +286,7 @@ $(libcppdir)/forwardanalyzer.o: ../lib/forwardanalyzer.cpp ../lib/analyzer.h ../ $(libcppdir)/fwdanalysis.o: ../lib/fwdanalysis.cpp ../lib/astutils.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/fwdanalysis.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/fwdanalysis.cpp -$(libcppdir)/gitlabcodequalityreport.o: ../lib/gitlabcodequalityreport.cpp ../externals/picojson/picojson.h ../lib/config.h ../lib/errorlogger.h ../lib/errortypes.h ../lib/gitlabcodequalityreport.h ../lib/json.h ../lib/refthunk.h ../lib/utils.h +$(libcppdir)/gitlabcodequalityreport.o: ../lib/gitlabcodequalityreport.cpp ../externals/picojson/picojson.h ../lib/config.h ../lib/errorlogger.h ../lib/errortypes.h ../lib/gitlabcodequalityreport.h ../lib/json.h ../lib/path.h ../lib/refthunk.h ../lib/standards.h ../lib/utils.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/gitlabcodequalityreport.cpp $(libcppdir)/importproject.o: ../lib/importproject.cpp ../externals/picojson/picojson.h ../externals/tinyxml2/tinyxml2.h ../lib/checkers.h ../lib/config.h ../lib/filesettings.h ../lib/importproject.h ../lib/json.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/pathmatch.h ../lib/platform.h ../lib/settings.h ../lib/standards.h ../lib/suppressions.h ../lib/utils.h ../lib/xml.h diff --git a/test/cli/gitlab_code_quality_test.py b/test/cli/gitlab_code_quality_test.py index b52fa0b0fdf..cd7ffeb8212 100644 --- a/test/cli/gitlab_code_quality_test.py +++ b/test/cli/gitlab_code_quality_test.py @@ -1,6 +1,7 @@ # python -m pytest gitlab_code_quality_test.py import json +import os from testutils import cppcheck @@ -45,3 +46,46 @@ def test_gitlab_code_quality_output_file(tmp_path): findings = json.loads((tmp_path / "report.json").read_text()) assert len(findings) == 1 assert findings[0]["check_name"] == "zerodiv" + + +def test_gitlab_code_quality_absolute_path_warning(tmp_path): + test_file = tmp_path / "test.cpp" + test_file.write_text(TEST_CODE) + + exitcode, stdout, stderr = cppcheck( + ["--output-format=gitlab-codequality", "--enable=warning", str(test_file)]) + + assert exitcode == 0 + assert "GitLab Code Quality requires repository-relative paths" in stdout + findings = json.loads(stderr) + assert len(findings) == 1 + assert os.path.isabs(findings[0]["location"]["path"]) + + +def test_gitlab_code_quality_absolute_path_warning_with_relative_paths(tmp_path): + test_file = tmp_path / "test.cpp" + test_file.write_text(TEST_CODE) + + exitcode, stdout, stderr = cppcheck( + ["--output-format=gitlab-codequality", "--enable=warning", "--relative-paths", str(test_file)]) + + assert exitcode == 0 + assert "GitLab Code Quality requires repository-relative paths" in stdout + findings = json.loads(stderr) + assert len(findings) == 1 + assert os.path.isabs(findings[0]["location"]["path"]) + + +def test_gitlab_code_quality_relative_paths(tmp_path): + test_file = tmp_path / "test.cpp" + test_file.write_text(TEST_CODE) + + exitcode, stdout, stderr = cppcheck( + ["--output-format=gitlab-codequality", "--enable=warning", + "--relative-paths=" + str(tmp_path), str(test_file)]) + + assert exitcode == 0 + assert "GitLab Code Quality requires repository-relative paths" not in stdout + findings = json.loads(stderr) + assert len(findings) == 1 + assert findings[0]["location"]["path"] == "test.cpp" diff --git a/test/testgitlabcodequalityreport.cpp b/test/testgitlabcodequalityreport.cpp index a7541d4f623..ec9fa9f331e 100644 --- a/test/testgitlabcodequalityreport.cpp +++ b/test/testgitlabcodequalityreport.cpp @@ -42,6 +42,7 @@ class TestGitlabCodeQualityReport : public TestFixture TEST_CASE(severityMapping); TEST_CASE(fingerprint); TEST_CASE(pathWithoutDotSlash); + TEST_CASE(absolutePath); } static ErrorMessage createErrorMessage(const std::string& id, @@ -165,6 +166,18 @@ class TestGitlabCodeQualityReport : public TestFixture const picojson::object& location = findingAt(json, 0).at("location").get(); ASSERT_EQUALS("src/test.cpp", location.at("path").get()); } + + void absolutePath() + { + GitlabCodeQualityReport report; + ASSERT(!report.hasAbsolutePath()); + + report.addFinding(createErrorMessage("testError", Severity::error, "Test error", "src/test.cpp", 10)); + ASSERT(!report.hasAbsolutePath()); + + report.addFinding(createErrorMessage("testError", Severity::error, "Test error", "/repo/src/test.cpp", 10)); + ASSERT(report.hasAbsolutePath()); + } }; REGISTER_TEST(TestGitlabCodeQualityReport) From 78f57a3a83adb7af0080fcb64b87f8c26341a65a Mon Sep 17 00:00:00 2001 From: Thibaud Chupin Date: Thu, 26 Nov 2026 23:32:37 +0100 Subject: [PATCH 3/3] Include CWE IDs in Code Quality descriptions Append the CWE ID to the finding description when available, matching the output of cppcheck-codequality. --- lib/gitlabcodequalityreport.cpp | 7 ++++++- lib/gitlabcodequalityreport.h | 2 +- test/cli/gitlab_code_quality_test.py | 2 +- test/testgitlabcodequalityreport.cpp | 14 ++++++++++++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/gitlabcodequalityreport.cpp b/lib/gitlabcodequalityreport.cpp index 990f8f4b71f..5f72b02ba2a 100644 --- a/lib/gitlabcodequalityreport.cpp +++ b/lib/gitlabcodequalityreport.cpp @@ -71,8 +71,13 @@ picojson::object GitlabCodeQualityReport::serializeFinding(const ErrorMessage& f { const ErrorMessage::FileLocation& location = finding.callStack.back(); + std::string description = finding.shortMessage(); + if (finding.cwe.id > 0) { + description += " (CWE-" + std::to_string(finding.cwe.id) + ")"; + } + picojson::object result; - result["description"] = picojson::value(finding.shortMessage()); + result["description"] = picojson::value(description); result["check_name"] = picojson::value(finding.id); result["fingerprint"] = picojson::value(fingerprint(finding)); result["severity"] = picojson::value(codeQualitySeverity(finding)); diff --git a/lib/gitlabcodequalityreport.h b/lib/gitlabcodequalityreport.h index 37b0d5fc0de..0cedf81e0f4 100644 --- a/lib/gitlabcodequalityreport.h +++ b/lib/gitlabcodequalityreport.h @@ -45,7 +45,7 @@ * @code{.json} * [ * { - * "description": "Division by zero.", + * "description": "Division by zero. (CWE-369)", * "check_name": "zerodiv", * "fingerprint": "12532254259410460725", * "severity": "critical", diff --git a/test/cli/gitlab_code_quality_test.py b/test/cli/gitlab_code_quality_test.py index cd7ffeb8212..006bc8f0ce2 100644 --- a/test/cli/gitlab_code_quality_test.py +++ b/test/cli/gitlab_code_quality_test.py @@ -26,7 +26,7 @@ def test_gitlab_code_quality(tmp_path): assert len(findings) == 1 finding = findings[0] - assert finding["description"] == "Division by zero." + assert finding["description"] == "Division by zero. (CWE-369)" assert finding["check_name"] == "zerodiv" assert finding["fingerprint"] assert finding["severity"] == "critical" diff --git a/test/testgitlabcodequalityreport.cpp b/test/testgitlabcodequalityreport.cpp index ec9fa9f331e..856f6b631a4 100644 --- a/test/testgitlabcodequalityreport.cpp +++ b/test/testgitlabcodequalityreport.cpp @@ -43,6 +43,7 @@ class TestGitlabCodeQualityReport : public TestFixture TEST_CASE(fingerprint); TEST_CASE(pathWithoutDotSlash); TEST_CASE(absolutePath); + TEST_CASE(cweDescription); } static ErrorMessage createErrorMessage(const std::string& id, @@ -178,6 +179,19 @@ class TestGitlabCodeQualityReport : public TestFixture report.addFinding(createErrorMessage("testError", Severity::error, "Test error", "/repo/src/test.cpp", 10)); ASSERT(report.hasAbsolutePath()); } + + void cweDescription() + { + ErrorMessage errorMessage = createErrorMessage("testError", Severity::error, "Test error"); + errorMessage.cwe = CWE(369); + + GitlabCodeQualityReport report; + report.addFinding(errorMessage); + + picojson::value json; + ASSERT(parseJson(report.serialize(), json)); + ASSERT_EQUALS("Test error (CWE-369)", findingAt(json, 0).at("description").get()); + } }; REGISTER_TEST(TestGitlabCodeQualityReport)