Skip to content

Commit d802afb

Browse files
committed
use pathlib.Path to open files
1 parent ac8b4f0 commit d802afb

File tree

3 files changed

+36
-35
lines changed

3 files changed

+36
-35
lines changed

cpp_linter/clang_tidy.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Parse output from clang-tidy's stdout"""
22
import os
3+
from pathlib import Path
34
import re
45
from typing import Tuple, Union, List, cast
56
from . import GlobalParser
@@ -97,18 +98,18 @@ def log_command(self) -> str:
9798
def parse_tidy_output() -> None:
9899
"""Parse clang-tidy output in a file created from stdout."""
99100
notification = None
100-
with open("clang_tidy_report.txt", "r", encoding="utf-8") as tidy_out:
101-
for line in tidy_out.readlines():
102-
match = re.match(NOTE_HEADER, line)
103-
if match is not None:
104-
notification = TidyNotification(
105-
cast(
106-
Tuple[str, Union[int, str], Union[int, str], str, str, str],
107-
match.groups(),
108-
)
101+
tidy_out = Path("clang_tidy_report.txt").read_text(encoding="utf-8")
102+
for line in tidy_out.splitlines():
103+
match = re.match(NOTE_HEADER, line)
104+
if match is not None:
105+
notification = TidyNotification(
106+
cast(
107+
Tuple[str, Union[int, str], Union[int, str], str, str, str],
108+
match.groups(),
109109
)
110-
GlobalParser.tidy_notes.append(notification)
111-
elif notification is not None:
112-
# append lines of code that are part of
113-
# the previous line's notification
114-
notification.fixit_lines.append(line)
110+
)
111+
GlobalParser.tidy_notes.append(notification)
112+
elif notification is not None:
113+
# append lines of code that are part of
114+
# the previous line's notification
115+
notification.fixit_lines.append(line)

cpp_linter/clang_tidy_yml.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Parse output from clang-tidy's YML format"""
22
import os
3+
from pathlib import Path
34
from typing import List
45
import yaml
56
from . import GlobalParser, get_line_cnt_from_cols, logger
@@ -102,9 +103,8 @@ def parse_tidy_suggestions_yml():
102103
"""Read a YAML file from clang-tidy and create a list of suggestions from it.
103104
Output is saved to [`tidy_advice`][cpp_linter.GlobalParser.tidy_advice].
104105
"""
105-
yml = {}
106-
with open("clang_tidy_output.yml", "r", encoding="utf-8") as yml_file:
107-
yml = yaml.safe_load(yml_file)
106+
yml_file = Path("clang_tidy_output.yml").read_text(encoding="utf-8")
107+
yml = yaml.safe_load(yml_file)
108108
fixit = YMLFixit(yml["MainSourceFile"])
109109
for diag_results in yml["Diagnostics"]:
110110
diag = TidyDiagnostic(diag_results["DiagnosticName"])

cpp_linter/run.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
GITHUB_TOKEN,
2828
GITHUB_SHA,
2929
API_HEADERS,
30+
IS_ON_RUNNER,
3031
log_response_msg,
3132
range_of_changed_lines,
3233
assemble_version_exec,
@@ -314,10 +315,12 @@ def filter_out_non_source_files(
314315
Globals.FILES = files
315316
else:
316317
cast(Dict[str, Any], Globals.FILES)["files"] = files
317-
if not os.getenv("CI"): # if not executed on a github runner
318-
with open(".changed_files.json", "w", encoding="utf-8") as temp:
319-
# dump altered json of changed files
320-
json.dump(Globals.FILES, temp, indent=2)
318+
if not IS_ON_RUNNER: # if not executed on a github runner
319+
# dump altered json of changed files
320+
Path(".changed_files.json").write_text(
321+
json.dumps(Globals.FILES, indent=2),
322+
encoding="utf-8",
323+
)
321324
else:
322325
logger.info("No source files need checking!")
323326
return False
@@ -344,8 +347,7 @@ def verify_files_are_present() -> None:
344347
Globals.response_buffer = requests.get(file["raw_url"])
345348
# retain the repo's original structure
346349
os.makedirs(os.path.split(file_name)[0], exist_ok=True)
347-
with open(file_name, "w", encoding="utf-8") as temp:
348-
temp.write(Globals.response_buffer.text)
350+
Path(file_name).write_text(Globals.response_buffer.text, encoding="utf-8")
349351

350352

351353
def list_source_files(
@@ -424,8 +426,8 @@ def run_clang_tidy(
424426
"""
425427
if checks == "-*": # if all checks are disabled, then clang-tidy is skipped
426428
# clear the clang-tidy output file and exit function
427-
with open("clang_tidy_report.txt", "wb") as f_out:
428-
return
429+
Path("clang_tidy_report.txt").write_bytes(b"")
430+
return
429431
filename = filename.replace("/", os.sep)
430432
cmds = [
431433
assemble_version_exec("clang-tidy", version),
@@ -446,12 +448,11 @@ def run_clang_tidy(
446448
logger.info("line_filter = %s", json.dumps([line_ranges]))
447449
cmds.append(f"--line-filter={json.dumps([line_ranges])}")
448450
cmds.append(filename)
449-
with open("clang_tidy_output.yml", "wb"):
450-
pass # clear yml file's content before running clang-tidy
451+
# clear yml file's content before running clang-tidy
452+
Path("clang_tidy_output.yml").write_bytes(b"")
451453
logger.info('Running "%s"', " ".join(cmds))
452454
results = subprocess.run(cmds, capture_output=True)
453-
with open("clang_tidy_report.txt", "wb") as f_out:
454-
f_out.write(results.stdout)
455+
Path("clang_tidy_report.txt").write_bytes(results.stdout)
455456
logger.debug("Output from clang-tidy:\n%s", results.stdout.decode())
456457
if os.path.getsize("clang_tidy_output.yml"):
457458
parse_tidy_suggestions_yml() # get clang-tidy fixes from yml
@@ -480,8 +481,8 @@ def run_clang_format(
480481
diff info.
481482
"""
482483
if not style: # if `style` == ""
483-
with open("clang_format_output.xml", "wb"):
484-
return # clear any previous output and exit
484+
Path("clang_format_output.xml").write_bytes(b"")
485+
return # clear any previous output and exit
485486
cmds = [
486487
assemble_version_exec("clang-format", version),
487488
f"-style={style}",
@@ -494,8 +495,7 @@ def run_clang_format(
494495
cmds.append(filename.replace("/", os.sep))
495496
logger.info('Running "%s"', " ".join(cmds))
496497
results = subprocess.run(cmds, capture_output=True)
497-
with open("clang_format_output.xml", "wb") as f_out:
498-
f_out.write(results.stdout)
498+
Path("clang_format_output.xml").write_bytes(results.stdout)
499499
if results.returncode:
500500
logger.debug(
501501
"%s raised the following error(s):\n%s", cmds[0], results.stderr.decode()
@@ -867,8 +867,8 @@ def main():
867867
os.chdir(args.repo_root)
868868

869869
if GITHUB_EVENT_PATH:
870-
# load event's json info about the workflow run
871-
Globals.EVENT_PAYLOAD = json.load(
870+
# load event's json info about the workflow run
871+
Globals.EVENT_PAYLOAD = json.loads(
872872
Path(GITHUB_EVENT_PATH).read_text(encoding="utf-8")
873873
)
874874
if logger.getEffectiveLevel() <= logging.DEBUG:

0 commit comments

Comments
 (0)