Skip to content

Commit 5977c76

Browse files
authored
resolves #24 (#32)
* update pre-commit envs; fix pylint warnings * change thread comments as suggested in #24 * introduce step-summary feature * add a unit test for LGTM comment * adjust test regex patterns (for sonar cloud linter notes) * rename step in doc-build.yml
1 parent 35e64f8 commit 5977c76

File tree

12 files changed

+100
-65
lines changed

12 files changed

+100
-65
lines changed

.github/workflows/build-docs.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ jobs:
1818
- name: Build docs
1919
run: sphinx-build docs docs/_build/html
2020

21-
- name: Deploy to gh-pages
21+
- name: upload docs build as artifact
2222
uses: actions/upload-artifact@v3
2323
with:
2424
name: "cpp-linter_docs"

.github/workflows/pre-commit-hooks.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ jobs:
1212
- uses: actions/checkout@v3
1313
- uses: actions/setup-python@v4
1414
with:
15-
python-version: '3.10'
15+
python-version: '3.x'
1616
- run: python3 -m pip install pre-commit
1717
- run: pre-commit run --all-files

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.3.0
3+
rev: v4.4.0
44
hooks:
55
- id: trailing-whitespace
66
- id: end-of-file-fixer
@@ -13,12 +13,12 @@ repos:
1313
- id: mixed-line-ending
1414
args: ["--fix=lf"]
1515
- repo: https://github.com/python/black
16-
rev: '22.6.0'
16+
rev: '23.3.0'
1717
hooks:
1818
- id: black
1919
args: ["--diff"]
2020
- repo: https://github.com/pycqa/pylint
21-
rev: v2.14.5
21+
rev: v3.0.0a6
2222
hooks:
2323
- id: pylint
2424
name: pylint (action code)

cpp_linter/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,10 @@ def make_headers(use_diff: bool = False) -> Dict[str, str]:
6161
class Globals:
6262
"""Global variables for re-use (non-constant)."""
6363

64-
PAYLOAD_TIDY: str = ""
64+
TIDY_COMMENT: str = ""
6565
"""The accumulated output of clang-tidy (gets appended to OUTPUT)"""
66-
OUTPUT: str = ""
66+
FORMAT_COMMENT: str = ""
67+
OUTPUT: str = "<!-- cpp linter action -->\n# Cpp-Linter Report "
6768
"""The accumulated body of the resulting comment that gets posted."""
6869
FILES: List[Dict[str, Any]] = []
6970
"""The responding payload containing info about changed files."""

cpp_linter/clang_tidy.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
"""Parse output from clang-tidy's stdout"""
22
from pathlib import Path, PurePath
3+
from textwrap import indent
34
import re
45
from typing import Tuple, Union, List, cast
56
from . import GlobalParser, CLANG_TIDY_STDOUT
67

7-
NOTE_HEADER = re.compile(r"^(.*):(\d+):(\d+):\s(\w+):(.*)\[(.*)\]$")
8+
NOTE_HEADER = re.compile(r"^(.+):(\d+):(\d+):\s(\w+):(.*)\[(.*)\]$")
89

910

1011
class TidyNotification:
@@ -56,17 +57,11 @@ def __repr__(self) -> str:
5657
PurePath(self.filename).suffix.lstrip("."),
5758
"\n".join(self.fixit_lines),
5859
)
59-
return (
60-
"<details open>\n<summary><strong>{}:{}:{}:</strong> {}: [{}]"
61-
"\n\n> {}\n</summary><p>\n\n{}</p>\n</details>\n\n".format(
62-
self.filename,
63-
self.line,
64-
self.cols,
65-
self.note_type,
66-
self.diagnostic,
67-
self.note_info,
68-
concerned_code,
69-
)
60+
return indent(
61+
f"<strong>{self.filename}:{self.line}:{self.cols}:</strong> "
62+
+ f"{self.note_type}: [{self.diagnostic}]\n> {self.note_info}"
63+
+ f"\n\n{concerned_code}\n",
64+
" "
7065
)
7166

7267
def log_command(self) -> str:

cpp_linter/cli.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,16 @@
180180
disabled because the GitHub REST API behaves
181181
differently for thread comments on a private repository.
182182
183+
Defaults to ``%(default)s``.""",
184+
)
185+
cli_arg_parser.add_argument(
186+
"-w",
187+
"--step-summary",
188+
default="false",
189+
type=lambda input: input.lower() == "true",
190+
help="""Set this option to true or false to enable or disable the use of
191+
a workflow step summary when the run has concluded.
192+
183193
Defaults to ``%(default)s``.""",
184194
)
185195
cli_arg_parser.add_argument(

cpp_linter/git.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,14 +112,14 @@ def parse_diff(full_diff: str) -> List[Dict[str, Any]]:
112112
if filename_match is None:
113113
continue
114114
filename = filename_match.groups(0)[0]
115-
file_objects.append(dict(filename=filename))
115+
file_objects.append({"filename": filename})
116116
if first_hunk is None:
117117
continue
118118
ranges, additions = parse_patch(diff[first_hunk.start() :])
119-
file_objects[-1]["line_filter"] = dict(
120-
diff_chunks=ranges,
121-
lines_added=consolidate_list_to_ranges(additions),
122-
)
119+
file_objects[-1]["line_filter"] = {
120+
"diff_chunks": ranges,
121+
"lines_added": consolidate_list_to_ranges(additions),
122+
}
123123
return file_objects
124124

125125

cpp_linter/run.py

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ def list_source_files(
249249
if not is_file_in_list(
250250
ignored_paths, file_path, "ignored"
251251
) or is_file_in_list(not_ignored, file_path, "not ignored"):
252-
Globals.FILES.append(dict(filename=file_path))
252+
Globals.FILES.append({"filename": file_path})
253253

254254
if Globals.FILES:
255255
logger.info(
@@ -318,9 +318,10 @@ def run_clang_tidy(
318318
if not PurePath(database).is_absolute():
319319
database = str(Path(RUNNER_WORKSPACE, repo_root, database).resolve())
320320
cmds.append(database)
321-
line_ranges = dict(
322-
name=filename, lines=range_of_changed_lines(file_obj, lines_changed_only, True)
323-
)
321+
line_ranges = {
322+
"name": filename,
323+
"lines": range_of_changed_lines(file_obj, lines_changed_only, True),
324+
}
324325
if line_ranges["lines"]:
325326
# logger.info("line_filter = %s", json.dumps([line_ranges]))
326327
cmds.append(f"--line-filter={json.dumps([line_ranges])}")
@@ -405,16 +406,13 @@ def create_comment_body(
405406
if CLANG_TIDY_STDOUT.exists() and CLANG_TIDY_STDOUT.stat().st_size:
406407
parse_tidy_output() # get clang-tidy fixes from stdout
407408
comment_output = ""
408-
if Globals.PAYLOAD_TIDY:
409-
Globals.PAYLOAD_TIDY += "<hr></details>"
410409
for fix in GlobalParser.tidy_notes:
411410
if lines_changed_only and fix.line not in ranges:
412411
continue
413412
comment_output += repr(fix)
414413
tidy_notes.append(fix)
415414
if comment_output:
416-
Globals.PAYLOAD_TIDY += f"<details><summary>{filename}</summary><br>\n"
417-
Globals.PAYLOAD_TIDY += comment_output
415+
Globals.TIDY_COMMENT += f"- {filename}\n\n{comment_output}"
418416
GlobalParser.tidy_notes.clear() # empty list to avoid duplicated output
419417

420418
if CLANG_FORMAT_XML.exists() and CLANG_FORMAT_XML.stat().st_size:
@@ -430,10 +428,7 @@ def create_comment_body(
430428
should_comment = True
431429
break
432430
if should_comment:
433-
if not Globals.OUTPUT:
434-
Globals.OUTPUT = "<!-- cpp linter action -->\n## :scroll: "
435-
Globals.OUTPUT += "Run `clang-format` on the following files\n"
436-
Globals.OUTPUT += f"- [ ] {file_obj['filename']}\n"
431+
Globals.FORMAT_COMMENT += f"- {file_obj['filename']}\n"
437432

438433

439434
def capture_clang_tools_output(
@@ -480,13 +475,25 @@ def capture_clang_tools_output(
480475

481476
create_comment_body(filename, file, lines_changed_only, tidy_notes)
482477

483-
if Globals.PAYLOAD_TIDY:
484-
if not Globals.OUTPUT:
485-
Globals.OUTPUT = "<!-- cpp linter action -->\n"
486-
else:
487-
Globals.OUTPUT += "\n---\n"
488-
Globals.OUTPUT += "## :speech_balloon: Output from `clang-tidy`\n"
489-
Globals.OUTPUT += Globals.PAYLOAD_TIDY
478+
if Globals.FORMAT_COMMENT or Globals.TIDY_COMMENT:
479+
Globals.OUTPUT += ":warning:\nSome files did not pass the configured checks!\n"
480+
if Globals.FORMAT_COMMENT:
481+
Globals.OUTPUT += (
482+
"\n<details><summary>clang-format reports: <strong>"
483+
+ f"{len(GlobalParser.format_advice)} file(s) not formatted</strong>"
484+
+ f"</summary>\n\n{Globals.FORMAT_COMMENT}\n\n</details>"
485+
)
486+
if Globals.TIDY_COMMENT:
487+
Globals.OUTPUT += (
488+
f"\n<details><summary>clang-tidy reports: <strong>{len(tidy_notes)} "
489+
+ f"concern(s)</strong></summary>\n\n{Globals.TIDY_COMMENT}\n\n"
490+
+ "</details>"
491+
)
492+
else:
493+
Globals.OUTPUT += ":heavy_check_mark:\nNo problems need attention."
494+
Globals.OUTPUT += "\n\nHave any feedback or feature suggestions? [Share it here.]"
495+
Globals.OUTPUT += "(https://github.com/cpp-linter/cpp-linter-action/issues)"
496+
490497
GlobalParser.tidy_notes = tidy_notes[:] # restore cache of notifications
491498

492499

@@ -814,6 +821,9 @@ def main():
814821
)
815822
if args.thread_comments and thread_comments_allowed:
816823
post_results(False) # False is hard-coded to disable diff comments.
824+
if args.step_summary and "GITHUB_STEP_SUMMARY" in os.environ:
825+
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
826+
summary.write(f"\n{Globals.OUTPUT}\n")
817827
set_exit_code(
818828
int(
819829
make_annotations(args.style, args.file_annotations, args.lines_changed_only)

cpp_linter/thread_comments.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -105,13 +105,13 @@ def aggregate_tidy_advice(lines_changed_only: int) -> List[Dict[str, Any]]:
105105
body += suggestion
106106

107107
results.append(
108-
dict(
109-
body=body,
110-
commit_id=GITHUB_SHA,
111-
line=diag.line,
112-
path=fixit.filename,
113-
side="RIGHT",
114-
)
108+
{
109+
"body": body,
110+
"commit_id": GITHUB_SHA,
111+
"line": diag.line,
112+
"path": fixit.filename,
113+
"side": "RIGHT",
114+
}
115115
)
116116
return results
117117

@@ -162,13 +162,13 @@ def aggregate_format_advice(lines_changed_only: int) -> List[Dict[str, Any]]:
162162

163163
# create a suggestion from clang-format advice
164164
results.append(
165-
dict(
166-
body=body,
167-
commit_id=GITHUB_SHA,
168-
line=fixed_line.line,
169-
path=fmt_advice.filename,
170-
side="RIGHT",
171-
)
165+
{
166+
"body": body,
167+
"commit_id": GITHUB_SHA,
168+
"line": fixed_line.line,
169+
"path": fmt_advice.filename,
170+
"side": "RIGHT",
171+
}
172172
)
173173
return results
174174

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ min-public-methods = 1
356356

357357
[tool.pylint.exceptions]
358358
# Exceptions that will emit a warning when caught.
359-
overgeneral-exceptions = ["Exception"]
359+
overgeneral-exceptions = ["builtins.Exception"]
360360

361361
[tool.pylint.format]
362362
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.

0 commit comments

Comments
 (0)