GithubHelp home page GithubHelp logo

platisd / clang-tidy-pr-comments Goto Github PK

View Code? Open in Web Editor NEW
38.0 4.0 18.0 135 KB

Turn clang-tidy warnings and fixes to comments in your pull request

License: MIT License

Python 95.00% Shell 3.65% CMake 1.17% C++ 0.18%
clang-tidy review-comments pull-requests cpp code-quality code-review

clang-tidy-pr-comments's Introduction

clang-tidy pull request comments

clang-tidy-8 support clang-tidy-9 support clang-tidy-10 support clang-tidy-11 support clang-tidy-12 support clang-tidy-13 support clang-tidy-14 support clang-tidy-15 support

A GitHub Action to post clang-tidy warnings and suggestions as review comments on your pull request.

action preview

What

platisd/clang-tidy-pr-comments is a GitHub Action that utilizes the exported fixes of clang-tidy for your C++ project and posts them as code review comments in the related pull request.

If clang-tidy has a concrete recommendation on how you should modify your code to fix the issue that's detected, then it will be presented as a suggested change that can be committed directly. Alternatively, the offending line will be highlighted along with a description of the warning.

The GitHub Action can be configured to request changes if clang-tidy warnings are found or merely leave a comment without blocking the pull request from being merged. It should fail only if it has been misconfigured by you, due to a bug (please contact me if that's the case) or the GitHub API acting up.

Please note the following:

  • It will not run clang-tidy for you. You are responsible for doing that and then supply the Action with the path to your generated report (see examples below). You can generate a YAML report that includes fixes for a pull request using the following methods:

    • Using the run-clang-tidy utility script with the -export-fixes argument. This script usually comes with the clang-tidy packages. You can use it to run checks for the entire codebase of a project at once.

    • Using the clang-tidy-diff utility script with the -export-fixes argument. This script also usually comes with the clang-tidy packages, and and it can be used to run checks only for code fragments that have been changed in a specific pull request.

    • Alternatively, you may use --export-fixes with clang-tidy itself in your own script.

    In any case, specify the path where you would like the report to be exported. The very same path should be supplied to this Action.

  • It will only comment on files and lines changed in the pull request. This is due to GitHub not allowing comments on other files outside the pull request diff. This means that there may be more warnings in your project. Make sure you fix them before starting to use this Action to ensure new warnings will not be introduced in the future.

  • This Action respects existing comments and doesn't repeat the same warnings for the same line (no spam).

  • This Action allows analysis to be performed separately from the posting of the analysis results (using separate workflows with different privileges), which allows you to safely analyze pull requests from forks (see example below).

Supported clang-tidy versions

YAML files containing generated fixes by the following clang-tidy versions are currently supported:

  • clang-tidy-8
  • clang-tidy-9
  • clang-tidy-10
  • clang-tidy-11
  • clang-tidy-12
  • clang-tidy-13
  • clang-tidy-14
  • clang-tidy-15

How

Since this action comments on files changed in pull requests, naturally, it can be only run on pull_request events. That being said, if it happens to be triggered in a different context, e.g. a push event, it will not run and fail softly by returning a success code.

Basic configuration example

A basic configuration for the platisd/clang-tidy-pr-comments action (for a CMake-based project using the clang-tidy-diff script) can be seen below:

name: Static analysis

on: pull_request

jobs:
  clang-tidy:
    runs-on: ubuntu-22.04
    permissions:
      pull-requests: write
      # OPTIONAL: auto-closing conversations requires the `contents` permission
      contents: write
    steps:
    - uses: actions/checkout@v4
      with:
        ref: ${{ github.event.pull_request.head.sha }}
        fetch-depth: 0
    - name: Fetch base branch
      run: |
        git remote add upstream "https://github.com/${{ github.event.pull_request.base.repo.full_name }}"
        git fetch --no-tags --no-recurse-submodules upstream "${{ github.event.pull_request.base.ref }}"
    - name: Install clang-tidy
      run: |
        sudo apt-get update
        sudo apt-get install -y clang-tidy
    - name: Prepare compile_commands.json
      run: |
        cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    - name: Create results directory
      run: |
        mkdir clang-tidy-result
    - name: Analyze
      run: |
        git diff -U0 "$(git merge-base HEAD "upstream/${{ github.event.pull_request.base.ref }}")" | clang-tidy-diff -p1 -path build -export-fixes clang-tidy-result/fixes.yml
    - name: Run clang-tidy-pr-comments action
      uses: platisd/clang-tidy-pr-comments@v1
      with:
        # The GitHub token (or a personal access token)
        github_token: ${{ secrets.GITHUB_TOKEN }}
        # The path to the clang-tidy fixes generated previously
        clang_tidy_fixes: clang-tidy-result/fixes.yml
        # Optionally set to true if you want the Action to request
        # changes in case warnings are found
        request_changes: true
        # Optionally set the number of comments per review
        # to avoid GitHub API timeouts for heavily loaded
        # pull requests
        suggestions_per_comment: 10

Triggering this Action manually

If you want to trigger this Action manually, i.e. by leaving a comment with a particular keyword in the pull request, then you can try the following:

name: Static analysis

# Don't trigger it on pull_request events but issue_comment instead
on: issue_comment

jobs:
  clang-tidy:
    # Trigger the job only when someone comments: run_clang_tidy
    if: ${{ github.event.issue.pull_request && contains(github.event.comment.body, 'run_clang_tidy') }}
    runs-on: ubuntu-22.04
    permissions:
      pull-requests: write
      # OPTIONAL: auto-closing conversations requires the `contents` permission
      contents: write
    steps:
    - uses: actions/checkout@v4
      with:
        ref: ${{ github.event.pull_request.head.sha }}
        fetch-depth: 0
    - name: Fetch base branch
      run: |
        git remote add upstream "https://github.com/${{ github.event.pull_request.base.repo.full_name }}"
        git fetch --no-tags --no-recurse-submodules upstream "${{ github.event.pull_request.base.ref }}"
    - name: Install clang-tidy
      run: |
        sudo apt-get update
        sudo apt-get install -y clang-tidy
    - name: Prepare compile_commands.json
      run: |
        cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    - name: Create results directory
      run: |
        mkdir clang-tidy-result
    - name: Analyze
      run: |
        git diff -U0 "$(git merge-base HEAD "upstream/${{ github.event.pull_request.base.ref }}")" | clang-tidy-diff -p1 -path build -export-fixes clang-tidy-result/fixes.yml
    - name: Run clang-tidy-pr-comments action
      uses: platisd/clang-tidy-pr-comments@v1
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        clang_tidy_fixes: clang-tidy-result/fixes.yml

Using this Action to safely perform analysis of pull requests from forks

If you want to trigger this Action using the workflow_run event to run analysis on pull requests from forks in a secure manner, then you can use the following combination of workflows:

# Insecure workflow with limited permissions that should provide analysis results through an artifact
name: Static analysis

on: pull_request

jobs:
  clang-tidy:
    runs-on: ubuntu-22.04
    steps:
    - uses: actions/checkout@v4
      with:
        ref: ${{ github.event.pull_request.head.sha }}
        fetch-depth: 0
    - name: Fetch base branch
      run: |
        git remote add upstream "https://github.com/${{ github.event.pull_request.base.repo.full_name }}"
        git fetch --no-tags --no-recurse-submodules upstream "${{ github.event.pull_request.base.ref }}"
    - name: Install clang-tidy
      run: |
        sudo apt-get update
        sudo apt-get install -y clang-tidy
    - name: Prepare compile_commands.json
      run: |
        cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    - name: Create results directory
      run: |
        mkdir clang-tidy-result
    - name: Analyze
      run: |
        git diff -U0 "$(git merge-base HEAD "upstream/${{ github.event.pull_request.base.ref }}")" | clang-tidy-diff -p1 -path build -export-fixes clang-tidy-result/fixes.yml
    - name: Save PR metadata
      run: |
        echo "${{ github.event.number }}" > clang-tidy-result/pr-id.txt
        echo "${{ github.event.pull_request.head.repo.full_name }}" > clang-tidy-result/pr-head-repo.txt
        echo "${{ github.event.pull_request.head.sha }}" > clang-tidy-result/pr-head-sha.txt
    - uses: actions/upload-artifact@v4
      with:
        name: clang-tidy-result
        path: clang-tidy-result/
# Secure workflow with access to repository secrets and GitHub token for posting analysis results
name: Post the static analysis results

on:
  workflow_run:
    workflows: [ "Static analysis" ]
    types: [ completed ]

jobs:
  clang-tidy-results:
    # Trigger the job only if the previous (insecure) workflow completed successfully
    if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-22.04
    permissions:
      pull-requests: write
      # OPTIONAL: auto-closing conversations requires the `contents` permission
      contents: write
    steps:
    - name: Download analysis results
      uses: actions/github-script@v7
      with:
        script: |
          const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{ github.event.workflow_run.id }},
          });
          const matchArtifact = artifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "clang-tidy-result"
          })[0];
          const download = await github.rest.actions.downloadArtifact({
              owner: context.repo.owner,
              repo: context.repo.repo,
              artifact_id: matchArtifact.id,
              archive_format: "zip",
          });
          const fs = require("fs");
          fs.writeFileSync("${{ github.workspace }}/clang-tidy-result.zip", Buffer.from(download.data));
    - name: Extract analysis results
      run: |
        mkdir clang-tidy-result
        unzip -j clang-tidy-result.zip -d clang-tidy-result
    - name: Set environment variables
      uses: actions/github-script@v7
      with:
        script: |
          const assert = require("node:assert").strict;
          const fs = require("fs");
          function exportVar(varName, fileName, regEx) {
              const val = fs.readFileSync("${{ github.workspace }}/clang-tidy-result/" + fileName, {
                  encoding: "ascii"
              }).trimEnd();
              assert.ok(regEx.test(val), "Invalid value format for " + varName);
              core.exportVariable(varName, val);
          }
          exportVar("PR_ID", "pr-id.txt", /^[0-9]+$/);
          exportVar("PR_HEAD_REPO", "pr-head-repo.txt", /^[-./0-9A-Z_a-z]+$/);
          exportVar("PR_HEAD_SHA", "pr-head-sha.txt", /^[0-9A-Fa-f]+$/);
    - uses: actions/checkout@v4
      with:
        repository: ${{ env.PR_HEAD_REPO }}
        ref: ${{ env.PR_HEAD_SHA }}
        persist-credentials: false
    - name: Redownload analysis results
      uses: actions/github-script@v7
      with:
        script: |
          const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{ github.event.workflow_run.id }},
          });
          const matchArtifact = artifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "clang-tidy-result"
          })[0];
          const download = await github.rest.actions.downloadArtifact({
              owner: context.repo.owner,
              repo: context.repo.repo,
              artifact_id: matchArtifact.id,
              archive_format: "zip",
          });
          const fs = require("fs");
          fs.writeFileSync("${{ github.workspace }}/clang-tidy-result.zip", Buffer.from(download.data));
    - name: Extract analysis results
      run: |
        mkdir clang-tidy-result
        unzip -j clang-tidy-result.zip -d clang-tidy-result
    - name: Run clang-tidy-pr-comments action
      uses: platisd/clang-tidy-pr-comments@v1
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        clang_tidy_fixes: clang-tidy-result/fixes.yml
        pull_request_id: ${{ env.PR_ID }}

Who's using this action?

See the Action dependency graph.

clang-tidy-pr-comments's People

Contributors

caic99 avatar dependabot[bot] avatar oleg-derevenetz avatar platisd avatar pqn avatar renefritze avatar skrobinson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

clang-tidy-pr-comments's Issues

1.3.0 Seems to break warning without suggested replacement

Just noticed my actions are failing with the following message, my guess is that it breaks when there are no suggested replacements. I will try to make a minimal example if you need it.

Traceback (most recent call last):
  File "/action/run_action.py", line 4[12], in <module>
    sys.exit(main())
  File "/action/run_action.py", line 268, in main
    suggestion_end = suggestion_begin + diagnostic["ReplacementLength"]
KeyError: 'ReplacementLength'

Configuration examples not workng

To start using clang-tidy-pr-comments in a project, I copied the example code in "Using this Action to safely perform analysis of pull requests from forks". I kept getting fatal git errors in git diff -U0 HEAD^.

I found a solution that I hope will be added to the examples to help others. action/checkout@v2 (and v3) can use fetch-depth: 2 to enable enough context for git diff to work.

Avoid repeating comments

The tool currently does not care whether an identical comment already exists on the same line of code.
Check if there is already a comment before posting a new one.

multiline code-suggestions

Hi,

Might be that this request is not relevant or that the problem lies somewhere else. We (UltiMaker Cura) recently start using your GitHub action, for our custom-made linting tool. We wrote a small Python module which performs linting on a json file which contains definition for 3D printers used in Cura. Since we have a lot of community contributions we want provide the community contributors with some automatic feedback on their PR's

The output of this linting tool follows the same scheme as clang-tidy. See the example below:

Diagnostics:
-   DiagnosticMessage:
        FileOffset: 238
        FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
        Message: 'Overriding machine_nozzle_offset_x with the same value (0.0) as defined in parent definition: fdmextruder'
        Replacements:
        -   FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
            Length: 52
            Offset: 246
            ReplacementText: ''
    DiagnosticName: diagnostic-definition-redundant-override
    Level: Warning
-   DiagnosticMessage:
        FileOffset: 299
        FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
        Message: 'Overriding machine_nozzle_offset_y with the same value (0.0) as defined in parent definition: fdmextruder'
        Replacements:
        -   FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
            Length: 52
            Offset: 307
            ReplacementText: ''
    DiagnosticName: diagnostic-definition-redundant-override
    Level: Warning
-   DiagnosticMessage:
        FileOffset: 360
        FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
        Message: 'Overriding machine_nozzle_size with the same value (0.4) as defined in parent definition: fdmextruder'
        Replacements:
        -   FilePath: /home/jspijker/cura_wp/Cura/resources/extruders/koonovo_kn5_extruder_1.def.json
            Length: 48
            Offset: 368
            ReplacementText: ''

However some of our suggested fixes are fixes over multiple lines, which this Action seems to have some trouble with, at least when we use it in conjunction with our custom printer-linter. It could be that the fixes suggested by clang-tidy are always confined to a single line so it isn't an issue for normal usage. But it would really help us if this action handles multi line suggestion comments

image
The suggestion in the image would result in an ill-formed json

Ambiguous expression in example workflow config

# Optionally set the number of comments per review
# to avoid GitHub API timeouts for heavily loaded
# pull requests
suggestions_per_comment: 10

Here, the comment says this is "the number of comments per review", but the variable name gives us "suggestions per comment". I suppose the latter one is actually what you mean.

Bug: warnings not correctly recognized

In this build, clang-tidy found some warnings (and fixes):

Run cat /home/runner/work/industrial_ci/industrial_ci/.work/clang-tidy-fixes.yml
Diagnostics:
- DiagnosticName: readability-identifier-naming
  FileOffset: 26
  FilePath: /home/runner/work/industrial_ci/industrial_ci/.work/target_ws/src/test_clang_tidy/src/test_clang_tidy.cpp
  Message: invalid case style for variable 'a'
  Replacements:
  - {FilePath: /home/runner/work/industrial_ci/industrial_ci/.work/target_ws/src/test_clang_tidy/src/test_clang_tidy.cpp,
    Length: 1, Offset: 26, ReplacementText: A}
MainSourceFile: ''

but the action reports:
No warnings found in files changed in this pull request

How to contribute to this project?

Hello, thank you for developing this project!
Although I just started to take a look at this, it looks so nice. ๐Ÿ˜„

So I'd like to contribute to this project and I believe I can contribute mainly 3 points.
How should I contribute? Could I send PRs for these?

1. Release Management

By adding CI scripts like this, if I push a tag,
image

this CI will run,
https://github.com/kenji-miyake/clang-tidy-pr-comments/runs/5168564498?check_suite_focus=true

and a new release is prepared,
image

and after I publish it, the major version tag is created as well.
https://github.com/kenji-miyake/clang-tidy-pr-comments/runs/5168578795?check_suite_focus=true
image

Why doing so is here:
https://github.com/actions/toolkit/blob/2f164000dcd42fb08287824a3bc3030dbed33687/docs/action-versioning.md

2. Other CI scripts

It seems some files are not properly formatted.
image

By installing pre-commit.ci and other tools, this can be improved and it will reduce your maintenance cost.

Please see this project for more details: https://github.com/autowarefoundation/autoware-github-actions/

3. Bug investigations/fixes

While I'm testing this action, it seems I caught a bug. I can investigate the cause and fix it.
https://github.com/kenji-miyake/autoware.universe/runs/5168447074?check_suite_focus=true
image

-> clang_tidy_fixes should be under the checked-out workspace?

A more strict regex extracting diff info is required

One of my test failed with an index out of range error (see logs here).
The patches include changes on something like this:

+    // @@@@@@@
+    // test
+    // @@@@@@@
+    /*

And the regex at

git_line_tags = re.findall(r"@@.*?@@", pull_request_file["patch"])
# The result is something like ['@@ -101,8 +102,11 @@', '@@ -123,9 +127,7 @@']
# We need to get it to a state like this: ['102,11', '127,7']

matches this pattern, not giving out diff info, resulting in error.
I suggest replacing it with a more strict regex match, maybe like @@ -\d+,\d+ \+\d+,\d+ @@.

The logic of searching for consecutive replacements is broken

The current logic here:

replacements_are_consecutive = True
for i in range(len(diagnostic["DiagnosticMessage"]["Replacements"]) - 1):
current_offset = diagnostic["DiagnosticMessage"]["Replacements"][i][
"Offset"
]
current_length = diagnostic["DiagnosticMessage"]["Replacements"][i][
"Length"
]
next_offset = diagnostic["DiagnosticMessage"]["Replacements"][i + 1][
"Offset"
]
if current_offset + current_length < next_offset - 1:
replacements_are_consecutive = False
break
if replacements_are_consecutive:

is problematic. Consider the following fixes.yml:

Diagnostics:
- BuildDirectory: /home/runner/work/fheroes2/fheroes2/build/src/fheroes2
  DiagnosticMessage:
    FileOffset: 7837
    FilePath: /home/runner/work/fheroes2/fheroes2/src/fheroes2/kingdom/kingdom.cpp
    Message: return type 'const EventsDate' (aka 'const list<EventDate>') is 'const'-qualified
      at the top level, which may reduce code readability without improving const
      correctness
    Ranges:
    - FileOffset: 7837
      FilePath: /home/runner/work/fheroes2/fheroes2/src/fheroes2/kingdom/kingdom.cpp
      Length: 5
    Replacements:
    - FilePath: /home/runner/work/fheroes2/fheroes2/src/fheroes2/kingdom/kingdom.cpp
      Length: 6
      Offset: 7837
      ReplacementText: ''
    - FilePath: /home/runner/work/fheroes2/fheroes2/src/fheroes2/kingdom/kingdom.h
      Length: 6
      Offset: 4838
      ReplacementText: ''
  DiagnosticName: readability-const-return-type
  Level: Warning
MainSourceFile: ''

First of all, these replacements are for different files with different FilePaths in each replacement, but this is not taken into account when checking for continuity. Second, even though these replacements are not consecutive, they are still considered as such, because 7837 + 6 is not less than 4838 - 1.

Add support form many fixes files

I would like to use this action in my projects.
It is not clear to me if it allows many files or a directory path in the clang_tidy_fixes input.

I am using CMake to create the YAML fixes-reports for the project.
CMake create many report files as explained here .

Enhancing this action to take a directory or many files as input to create the comments and reviews will be great.
Also if is already possible to input many fixes files to the action, will be nice to make it clearer on the Readme.

Approve PR when issues have been fixed

Thanks for making this action!

It's working well in the sense that it's requesting changes when clang-tidy has issues, but even once those issues have been fixed by the submitter, it will forever remain in a "changes requested" state, preventing merging of the PR without administrator override.

This could be fixed by simply having the action submit an "approved" review when there are no changes to make, or otherwise, dismissing its previous review.

Wrong suggestions

Sometimes I get incorrect suggestions. For example, for this PR the suggestion is:

-	auto findIteratorFor = [](const InterfaceState* state, const Interface& interface) {
+	auto findItfind_iterator_forconst InterfaceState* state, const Interface& interface) {

instead of the following one, which is correctly produced by clang-apply-replacements from the provided fixes file:

-	auto findIteratorFor = [](const InterfaceState* state, const Interface& interface) {
+	auto find_iterator_for = [](const InterfaceState* state, const Interface& interface) {

Looks like the replacement is shifted by 6 characters in the suggestion.

Error appending replacements in multi-line comments

With #38, suggestions including multiple replacements where tried to be tackled. However, right now, replacements text is only concatenated and the length is being summed, which is a bit too simple, resulting in potentially unusable comments.

Consider the following example:
Screenshot 2022-12-12 at 16 50 26

Diagnostics:
- BuildDirectory: /home/runner/work/orbitprofiler/orbitprofiler/build/src/DataViews
  DiagnosticMessage:
    FileOffset: 1269
    FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
    Message: invalid case style for local variable 'resultingColumns_'
    Replacements:
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1269
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1292
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1335
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1420
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1503
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1581
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1663
      ReplacementText: resulting_columns
    - FilePath: /home/runner/work/orbitprofiler/orbitprofiler/src/DataViews/CallstackDataView.cpp
      Length: 17
      Offset: 1762
      ReplacementText: resulting_columns
  DiagnosticName: readability-identifier-naming
  Level: Warning
MainSourceFile: ''

Clang tidy action failing to post comments.

The clang-tidy-pr-comments action is failing to post comment with the following assert

Processing 'cppcoreguidelines-pro-type-member-init' at lines 340-340 of libbinlogevents/include/compression/payload_event_buffer_istream.h...
    sys.exit(main())
             ^^^^^^
  File "/home/runner/work/_actions/platisd/clang-tidy-pr-comments/v1/run_action.py", line 623, in main
    post_review_comments(
  File "/home/runner/work/_actions/platisd/clang-tidy-pr-comments/v1/run_action.py", line 433, in post_review_comments
    assert result.status_code in (
           ^^^^^^^^^^^^^^^^^^^^^^^

The workflow file can be found at https://github.com/percona/percona-server/blob/testing/.github/workflows/main.yml.
The workflow is configured with the following permissions.

permissions:
      issues: write
      pull-requests: write

Also, pull request ID is being passed through properly

Run ${GITHUB_ACTION_PATH}/action_launcher.bash
  ${GITHUB_ACTION_PATH}/action_launcher.bash
  shell: /usr/bin/bash -l {0}
  env:
    UBUNTU_CODE_NAME: jammy
    COMPILER_VERSION: 17
    BOOST_VERSION: 1_77_0
    BOOST_DIR: /home/runner/my_boost
    INPUT_GITHUB_TOKEN: ***
    INPUT_CLANG_TIDY_FIXES: clang-tidy-result/fixes.yml
    INPUT_PULL_REQUEST_ID: 5241
    INPUT_REQUEST_CHANGES: true
    INPUT_SUGGESTIONS_PER_COMMENT: 10
    INPUT_REPO_PATH_PREFIX: /home/runner/work

For more info, check out percona/percona-server#5241

Failed Assertion `run_action.py:244`

My repo is failing this assertion

assert all(path == file_paths[0] for path in file_paths)
My Workflow yml
name: idf

on:
  pull_request:
  push:
    branches:
      - main

jobs:
  clang-tidy:
    runs-on: ubuntu-latest
    container:
      image: espressif/idf:release-v5.1
    steps:
      - uses: actions/checkout@v2
        with:
          submodules: true

      - name: Install tools
        run: |
          . $IDF_PATH/export.sh
          idf_tools.py install esp-clang
          pip install --upgrade pyclang

      - name: Run clang-tidy
        run: |
          . $IDF_PATH/export.sh
          idf.py clang-check --run-clang-tidy-options "-export-fixes build/fixes.yml -header-filter=main/.*" --exclude-paths managed_components

      - name: Run clang-tidy-pr-comments action
        uses: platisd/clang-tidy-pr-comments@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          clang_tidy_fixes: build/fixes.yml
          request_changes: true
          suggestions_per_comment: 10
          repo_path_prefix: "/__w"

      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: fixes
          path: build/fixes.yml
My build/fixes.yml (`head -n 50` -- full version attached)
Diagnostics:
- BuildDirectory: /__w/mainframe-tester/mainframe-tester/build
  DiagnosticMessage:
    FileOffset: 95
    FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.hpp
    Message: invalid case style for global constant 'kDut3_3V'
    Replacements:
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.hpp
      Length: 8
      Offset: 95
      ReplacementText: kDut33V
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.cpp
      Length: 8
      Offset: 82
      ReplacementText: kDut33V
  DiagnosticName: readability-identifier-naming
  Level: Warning
- BuildDirectory: /__w/mainframe-tester/mainframe-tester/build
  DiagnosticMessage:
    FileOffset: 1481
    FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.hpp
    Message: invalid case style for global function 'initGpio'
    Replacements:
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.hpp
      Length: 8
      Offset: 1481
      ReplacementText: InitGpio
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/GPIO.cpp
      Length: 8
      Offset: 46
      ReplacementText: InitGpio
  DiagnosticName: readability-identifier-naming
  Level: Warning
- BuildDirectory: /__w/mainframe-tester/mainframe-tester/build
  DiagnosticMessage:
    FileOffset: 35
    FilePath: /__w/mainframe-tester/mainframe-tester/main/NVS.hpp
    Message: invalid case style for global function 'initNvs'
    Replacements:
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/NVS.hpp
      Length: 7
      Offset: 35
      ReplacementText: InitNvs
  DiagnosticName: readability-identifier-naming
  Level: Warning
- BuildDirectory: /__w/mainframe-tester/mainframe-tester/build
  DiagnosticMessage:
    FileOffset: 52
    FilePath: /__w/mainframe-tester/mainframe-tester/main/NVS.hpp
    Message: invalid case style for global function 'swap_servo_direction'

fixes.yml.zip

Nothing seems out of place in my paths. The __w part is because I'm indeed running clang-tidy inside docker, but seems like that is what the repo_path_prefix is meant to handle.

I added a simple bit of printing to my fork before the assert:

for path in file_paths:                
    print(f"{path} == {file_paths[0]}")

And I see this in the logs:

main/mainframe-tester.cpp == main/mainframe-tester.cpp
main/ADC.hpp == main/mainframe-tester.cpp

So it would seem that the assertion failure is coming from this replacement:

- BuildDirectory: /__w/mainframe-tester/mainframe-tester/build
  DiagnosticMessage:
    FileOffset: 5
    FilePath: /__w/mainframe-tester/mainframe-tester/main/ADC.hpp
    Message: invalid case style for global function 'initAdc'
    Replacements:
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/mainframe-tester.cpp
      Length: 7
      Offset: 4544
      ReplacementText: InitAdc
    - FilePath: /__w/mainframe-tester/mainframe-tester/main/ADC.hpp
      Length: 7
      Offset: 5
      ReplacementText: InitAdc
  DiagnosticName: readability-identifier-naming
  Level: Warning

This replacement seems valid, since it's changing a method name in both the header where it's defined and in a .cpp file where it's used.

It appears the code in its current state assumes that each replacement is only in a single file, which seems to not necessarily be the case, at least in clang-tidy 15.

Should "fixed" review requests get dismissed

I've noticed that when I fix a tidy issue the associated change request is not dismissed.

I've set up an MWE here
where I first add a commit that introduces an issue and a second commit that doesn't have tidy complain.

Since no fixes files is now created, it looks like the action skips out early

Is that expected behavior, a potential bug? Did I misconfigure the action maybe?

Note I'm not using the clang-tidy-diff script because I'm currently limited to clang >= 17 in my real application and it's just not currently distributed with the python wrapper I'm using.

Failed to match codes between repo and `fixes.yml`.

In my action, the running log shows that "No warnings found in files changed in this pull request". This error also happened in #17 .

@kenji-miyake All file paths in your fixes.yaml begin with /__w/... (probably because clang-tidy is running self-hosted) while this action expects the GitHub directory layout (/home/runner/...), so it can't normalize paths and is not able to find all these files from your PR.
Originally posted by @oleg-derevenetz in #17 (comment)

Thanks @oleg-derevenetz points out that there is another file system in a custom actions container.

I wonder is there a proper way to avoid modifications on fixes.yaml? Maybe GitHub environment variable GITHUB_WORKSPACE helps, creating a symlink from from /home/runner/... to /__w/... .

non-docker option

I'm loving the functionality the action provides, but I need to be able to run it from a job that runs on a windows host.
I've had a brief look at the implementation, and it seems to me it could be refactored into a composite action that sets up python, installs deps from requirements and then runs the script.
I'm keen to know if that has been considered and dismissed, and if not, whether a contribution to effect such a refactor would be of interest.

Example projects using clang-tidy-pr-comments

Great project!
Are there any real life example project on github which are using this github action?
If yes please add them to the readme it would help developers to decide if they want to use it and promote this tool more.
Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.