Skip to content

Commit c8371ef

Browse files
DingXuefeng2bndy5shenxianpeng
authored
[feat] Add ability to specify the compilation database (#42)
* add database option * Fix existing typos Co-authored-by: 2bndy5 <2bndy5@gmail.com> Co-authored-by: shenxianpeng <xianpeng.shen@gmail.com>
1 parent fe27528 commit c8371ef

File tree

5 files changed

+74
-26
lines changed

5 files changed

+74
-26
lines changed

.pylintrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ valid-metaclass-classmethod-first-arg=mcs
395395
[DESIGN]
396396

397397
# Maximum number of arguments for function / method
398-
max-args=5
398+
max-args=8
399399

400400
# Maximum number of attributes for a class (see R0902).
401401
# max-attributes=7

Dockerfile

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ LABEL com.github.actions.color="gray-dark"
1212
LABEL repository="https://github.com/shenxianpeng/cpp-linter-action"
1313
LABEL maintainer="shenxianpeng <20297606+shenxianpeng@users.noreply.github.com>"
1414

15-
RUN apt-get update
16-
RUN apt-get -y install python3-pip
17-
# RUN python3 -m pip install --upgrade pip
15+
RUN apt-get update && apt-get -y install python3-pip
1816

1917
COPY cpp_linter/ pkg/cpp_linter/
2018
COPY setup.py pkg/setup.py

README.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,12 +85,12 @@ jobs:
8585

8686
#### `lines-changed-only`
8787

88-
- **Description**: Set this option to true to only analyse changes in the event's diff.
88+
- **Description**: Set this option to true to only analyze changes in the event's diff.
8989
- Default: false
9090

9191
#### `files-changed-only`
9292

93-
- **Description**: Set this option to false to analyse any source files in the repo.
93+
- **Description**: Set this option to false to analyze any source files in the repo.
9494
- Default: true
9595

9696
#### `ignore`
@@ -106,7 +106,7 @@ jobs:
106106
- Prefix a path with a bang ('!') to make it explicitly _not_ ignored - order of
107107
multiple paths does _not_ take precedence. The '!' prefix can be applied to
108108
a submodule's path (if desired) but not hidden directories.
109-
- Glob patterns are not supported here. All asterick characters ('\*') are literal.
109+
- Glob patterns are not supported here. All asterisk characters ('\*') are literal.
110110
- Default: '.github'
111111

112112
#### `thread-comments`
@@ -116,6 +116,11 @@ jobs:
116116
variable. See [Authenticating with the GITHUB_TOKEN](https://docs.github.com/en/actions/reference/authentication-in-a-workflow)
117117
- Default: true
118118

119+
#### `database`
120+
121+
- **Description**: The directory containing compilation database (like compile_commands.json) file.
122+
- Default: ''
123+
119124
### Outputs
120125

121126
This action creates 1 output variable named `checks-failed`. Even if the linting checks fail for source files this action will still pass, but users' CI workflows can use this action's output to exit the workflow early if that is desired.
@@ -140,7 +145,7 @@ You can show C/C++ Lint Action status with a badge in your repository README
140145

141146
Example
142147

143-
```
148+
```markdown
144149
[![cpp-linter](https://github.com/shenxianpeng/cpp-linter-action/actions/workflows/cpp-linter.yml/badge.svg)](https://github.com/shenxianpeng/cpp-linter-action/actions/workflows/cpp-linter.yml)
145150
```
146151

action.yml

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,13 @@ inputs:
6363
- Prefix a path with a bang (`!`) to make it explicitly not ignored - order of
6464
multiple paths does take precedence. The `!` prefix can be applied to
6565
submodules if desired.
66-
- Glob patterns are not supported here. All asterick characters ('*') are literal.
66+
- Glob patterns are not supported here. All asterisk characters ('*') are literal.
6767
required: false
6868
default: ".github"
69+
database:
70+
description: The directory containing compile_commands.json file.
71+
required: false
72+
default: ""
6973
outputs:
7074
checks-failed:
7175
description: An integer that can be used as a boolean value to indicate if all checks failed.
@@ -82,5 +86,5 @@ runs:
8286
- --lines-changed-only=${{ inputs.lines-changed-only }}
8387
- --files-changed-only=${{ inputs.files-changed-only }}
8488
- --thread-comments=${{ inputs.thread-comments }}
85-
- --ignore
86-
- ${{ inputs.ignore }}
89+
- --ignore=${{ inputs.ignore }}
90+
- --database=${{ inputs.database }}

cpp_linter/run.py

Lines changed: 56 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
GITHUB_API_URL = os.getenv("GITHUB_API_URL", "https://api.github.com")
4040
GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY", "")
4141
GITHUB_EVENT_NAME = os.getenv("GITHUB_EVENT_NAME", "unknown")
42+
RUNNER_WORKSPACE = os.getenv("RUNNER_WORKSPACE", "")
4243

4344
# setup CLI args
4445
cli_arg_parser = argparse.ArgumentParser(
@@ -50,6 +51,19 @@
5051
default="10",
5152
help="The logging level. Defaults to level 20 (aka 'logging.INFO').",
5253
)
54+
cli_arg_parser.add_argument(
55+
"-p",
56+
"--database",
57+
default="",
58+
help="-p <build-path> is used to read a compile command database."
59+
"For example, it can be a CMake build directory in which a file named"
60+
"compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON"
61+
"CMake option to get this output). When no build path is specified,"
62+
"a search for compile_commands.json will be attempted through all"
63+
"parent paths of the first input file . See:"
64+
"https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an"
65+
"example of setting up Clang Tooling on a source tree.",
66+
)
5367
cli_arg_parser.add_argument(
5468
"-s",
5569
"--style",
@@ -145,7 +159,7 @@ def set_exit_code(override: int = None) -> int:
145159
def start_log_group(name: str) -> None:
146160
"""Begin a callapsable group of log statements.
147161
148-
Argrs:
162+
Args:
149163
name: The name of the callapsable group
150164
"""
151165
log_commander.fatal("::group::%s", name)
@@ -157,7 +171,7 @@ def end_log_group() -> None:
157171

158172

159173
def is_file_in_list(paths: list, file_name: str, prompt: str) -> bool:
160-
"""Detirmine if a file is specified in a list of paths and/or filenames.
174+
"""Determine if a file is specified in a list of paths and/or filenames.
161175
162176
Args:
163177
paths: A list of specified paths to compare with. This list can contain a
@@ -316,7 +330,7 @@ def list_source_files(ext_list: list, ignored_paths: list, not_ignored: list) ->
316330
submodules.read(".gitmodules")
317331
for module in submodules.sections():
318332
logger.info(
319-
"Apending submodule to ignored paths: %s", submodules[module]["path"]
333+
"Appending submodule to ignored paths: %s", submodules[module]["path"]
320334
)
321335
ignored_paths.append(submodules[module]["path"])
322336

@@ -354,7 +368,13 @@ def list_source_files(ext_list: list, ignored_paths: list, not_ignored: list) ->
354368

355369

356370
def run_clang_tidy(
357-
filename: str, file_obj: dict, version: str, checks: str, lines_changed_only: bool
371+
filename: str,
372+
file_obj: dict,
373+
version: str,
374+
checks: str,
375+
lines_changed_only: bool,
376+
database: str,
377+
repo_root: str,
358378
) -> None:
359379
"""Run clang-tidy on a certain file.
360380
@@ -378,6 +398,15 @@ def run_clang_tidy(
378398
cmds.append(f"-checks={checks}")
379399
cmds.append("--export-fixes=clang_tidy_output.yml")
380400
# cmds.append(f"--format-style={style}")
401+
if database:
402+
cmds.append("-p")
403+
if RUNNER_WORKSPACE:
404+
path_to_db = RUNNER_WORKSPACE
405+
if repo_root and repo_root != ".":
406+
path_to_db += os.sep + repo_root
407+
cmds.append(os.path.join(path_to_db, database))
408+
else:
409+
cmds.append(database)
381410
if lines_changed_only:
382411
logger.info("line_filter = %s", json.dumps(file_obj["line_filter"]["lines"]))
383412
cmds.append(f"--line-filter={json.dumps([file_obj['line_filter']])}")
@@ -431,7 +460,12 @@ def run_clang_format(
431460

432461

433462
def capture_clang_tools_output(
434-
version: str, checks: str, style: str, lines_changed_only: bool
463+
version: str,
464+
checks: str,
465+
style: str,
466+
lines_changed_only: bool,
467+
database: str,
468+
repo_root: str,
435469
):
436470
"""Execute and capture all output from clang-tidy and clang-format. This aggregates
437471
results in the [`OUTPUT`][cpp_linter.__init__.Globals.OUTPUT].
@@ -455,7 +489,9 @@ def capture_clang_tools_output(
455489
if not os.path.exists(file["filename"]):
456490
filename = os.path.split(file["raw_url"])[1]
457491
start_log_group(f"Performing checkup on {filename}")
458-
run_clang_tidy(filename, file, version, checks, lines_changed_only)
492+
run_clang_tidy(
493+
filename, file, version, checks, lines_changed_only, database, repo_root
494+
)
459495
run_clang_format(filename, file, version, style, lines_changed_only)
460496
end_log_group()
461497
if os.path.getsize("clang_tidy_report.txt"):
@@ -564,7 +600,7 @@ def post_diff_comments(base_url: str, user_id: int) -> bool:
564600
break
565601
if already_posted and comment_id is None:
566602
logger.info("comment %d already posted", i)
567-
continue # don't bother reposting the same comment
603+
continue # don't bother re-posting the same comment
568604

569605
# update ot create a review comment (in the diff)
570606
logger.debug("Payload %d body = %s", i, json.dumps(body))
@@ -669,7 +705,7 @@ def make_annotations(style: str) -> bool:
669705

670706

671707
def parse_ignore_option(paths: str):
672-
"""Parse a givven string of paths (separated by a '|') into `ignored` and
708+
"""Parse a given string of paths (separated by a '|') into `ignored` and
673709
`not_ignored` lists of strings.
674710
675711
Args:
@@ -726,14 +762,14 @@ def main():
726762
os.chdir(args.repo_root)
727763

728764
exit_early = False
765+
with open(GITHUB_EVEN_PATH, "r", encoding="utf-8") as payload:
766+
Globals.EVENT_PAYLOAD = json.load(payload)
767+
if logger.getEffectiveLevel() <= logging.DEBUG:
768+
start_log_group("Event json from the runner")
769+
logger.debug(json.dumps(Globals.EVENT_PAYLOAD))
770+
end_log_group()
729771
if args.files_changed_only:
730772
# load event's json info about the workflow run
731-
with open(GITHUB_EVEN_PATH, "r", encoding="utf-8") as payload:
732-
Globals.EVENT_PAYLOAD = json.load(payload)
733-
if logger.getEffectiveLevel() <= logging.DEBUG:
734-
start_log_group("Event json from the runner")
735-
logger.debug(json.dumps(Globals.EVENT_PAYLOAD))
736-
end_log_group()
737773
get_list_of_changed_files()
738774
exit_early = not filter_out_non_source_files(
739775
args.extensions,
@@ -750,7 +786,12 @@ def main():
750786
sys.exit(set_exit_code(0))
751787

752788
capture_clang_tools_output(
753-
args.version, args.tidy_checks, args.style, args.lines_changed_only
789+
args.version,
790+
args.tidy_checks,
791+
args.style,
792+
args.lines_changed_only,
793+
args.database,
794+
args.repo_root,
754795
)
755796

756797
start_log_group("Posting comment(s)")

0 commit comments

Comments
 (0)