Skip to content

Commit c89256c

Browse files
authored
Replace yapf Python formatter with black (#227)
1 parent 47369fb commit c89256c

35 files changed

+3745
-1863
lines changed

wpiformat/setup.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,12 @@
2626
"--count",
2727
# Includes previous year's commits in case one was merged after the
2828
# year incremented. Otherwise, the version wouldn't increment.
29-
"--after=\"main@{" + str(date.today().year - 1) + "-01-01}\"",
30-
"main"
29+
'--after="main@{' + str(date.today().year - 1) + '-01-01}"',
30+
"main",
3131
],
3232
stdout=subprocess.PIPE,
33-
stderr=subprocess.STDOUT)
33+
stderr=subprocess.STDOUT,
34+
)
3435
# If there is no main branch, the commit count defaults to 0
3536
if proc.returncode:
3637
commit_count = "0"
@@ -41,9 +42,8 @@
4142
version = str(date.today().year) + "." + commit_count.strip()
4243

4344
# Create the version.py file
44-
with open(version_file, 'w') as fp:
45-
fp.write("# Autogenerated by setup.py\n__version__ = \"{0}\"".format(
46-
version))
45+
with open(version_file, "w") as fp:
46+
fp.write('# Autogenerated by setup.py\n__version__ = "{0}"'.format(version))
4747

4848
if exists(version_file):
4949
with open(version_file, "r") as fp:
@@ -57,8 +57,7 @@
5757
setup(
5858
name="wpiformat",
5959
version=__version__,
60-
description=
61-
"Linters and formatters for ensuring WPILib's source code conforms to its style guide",
60+
description="Linters and formatters for ensuring WPILib's source code conforms to its style guide",
6261
long_description=long_description,
6362
author="WPILib",
6463
maintainer="Tyler Veness",
@@ -70,13 +69,16 @@
7069
zip_safe=True,
7170
setup_requires=["pytest-runner"],
7271
tests_require=["pytest"],
73-
install_requires=["regex==2021.11.10", "yapf==0.31.0"],
72+
install_requires=["regex==2021.11.10", "black==22.6.0"],
7473
license="BSD License",
7574
classifiers=[
7675
"Development Status :: 5 - Production/Stable",
77-
"Intended Audience :: Developers", "Intended Audience :: Education",
76+
"Intended Audience :: Developers",
77+
"Intended Audience :: Education",
7878
"License :: OSI Approved :: BSD License",
79-
"Operating System :: OS Independent", "Topic :: Scientific/Engineering",
80-
"Programming Language :: Python :: 3"
79+
"Operating System :: OS Independent",
80+
"Topic :: Scientific/Engineering",
81+
"Programming Language :: Python :: 3",
8182
],
82-
entry_points={"console_scripts": ["wpiformat = wpiformat:main"]})
83+
entry_points={"console_scripts": ["wpiformat = wpiformat:main"]},
84+
)

wpiformat/wpiformat/__init__.py

Lines changed: 37 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ def filter_ignored_files(names):
4141
proc = subprocess.run(
4242
["git", "check-ignore", "--no-index", "-n", "-v", "--stdin"],
4343
input=encoded_names,
44-
stdout=subprocess.PIPE)
44+
stdout=subprocess.PIPE,
45+
)
4546
if proc.returncode == 128:
4647
raise subprocess.CalledProcessError
4748

@@ -51,7 +52,7 @@ def filter_ignored_files(names):
5152
# wraps names in quotes on Windows, and outputs "\n" line separators on all
5253
# platforms.
5354
return [
54-
name[2:].lstrip().strip("\"").replace("\\\\", "\\")
55+
name[2:].lstrip().strip('"').replace("\\\\", "\\")
5556
for name in output_list
5657
if name[0:2] == "::"
5758
]
@@ -260,33 +261,33 @@ def run_batch(task_pipeline, args, file_batches):
260261
def main():
261262
# Parse command-line arguments
262263
parser = argparse.ArgumentParser(
263-
description=
264-
"Runs all formatting tasks on the code base. This should be invoked from a directory within the project."
264+
description="Runs all formatting tasks on the code base. This should be invoked from a directory within the project."
265265
)
266266
parser.add_argument(
267267
"-v",
268268
dest="verbose1",
269269
action="store_true",
270-
help="verbosity level 1 (prints names of processed files)")
270+
help="verbosity level 1 (prints names of processed files)",
271+
)
271272
parser.add_argument(
272273
"-vv",
273274
dest="verbose2",
274275
action="store_true",
275-
help=
276-
"verbosity level 2 (prints names of processed files and tasks run on them)"
276+
help="verbosity level 2 (prints names of processed files and tasks run on them)",
277277
)
278278
list_files_group = parser.add_mutually_exclusive_group()
279279
list_files_group.add_argument(
280280
"-list-all-files",
281281
dest="list_all_files",
282282
action="store_true",
283-
help="list files to be processed instead of processing them")
283+
help="list files to be processed instead of processing them",
284+
)
284285
list_files_group.add_argument(
285286
"-list-changed-files",
286287
dest="list_changed_files",
287288
action="store_true",
288-
help=
289-
"same as list-all-files, but list only files changed from main branch")
289+
help="same as list-all-files, but list only files changed from main branch",
290+
)
290291
# mp.Pool() uses WaitForMultipleObjects() to wait for subprocess completion
291292
# on Windows. WaitForMultipleObjects() cannot wait on more then 64 events at
292293
# once, and mp uses a few internal events. Therefore, the maximum number of
@@ -297,51 +298,49 @@ def main():
297298
dest="jobs",
298299
type=int,
299300
default=cpu_count,
300-
help="number of jobs to run (default is number of cores)")
301+
help="number of jobs to run (default is number of cores)",
302+
)
301303
parser.add_argument(
302304
"-clang",
303305
dest="clang_version",
304306
type=str,
305307
default="",
306-
help=
307-
"version suffix for clang-format (invokes \"clang-format-CLANG_VERSION\" or \"clang-format\" if no suffix provided)"
308+
help='version suffix for clang-format (invokes "clang-format-CLANG_VERSION" or "clang-format" if no suffix provided)',
308309
)
309310
tidy_group = parser.add_mutually_exclusive_group()
310311
tidy_group.add_argument(
311312
"-tidy-changed",
312313
dest="tidy_changed",
313314
action="store_true",
314-
help=
315-
"also runs clang-tidy-CLANG_VERSION on changed files; this requires a compile_commands.json file"
315+
help="also runs clang-tidy-CLANG_VERSION on changed files; this requires a compile_commands.json file",
316316
)
317317
tidy_group.add_argument(
318318
"-tidy-all",
319319
dest="tidy_all",
320320
action="store_true",
321-
help=
322-
"also runs clang-tidy-CLANG_VERSION on all files (this takes a while); this requires a compile_commands.json file"
321+
help="also runs clang-tidy-CLANG_VERSION on all files (this takes a while); this requires a compile_commands.json file",
323322
)
324323
parser.add_argument(
325324
"-compile-commands",
326325
dest="compile_commands",
327326
type=str,
328327
default="",
329-
help=
330-
"path to directory containing compile_commands.json; if unset will search in parent paths"
328+
help="path to directory containing compile_commands.json; if unset will search in parent paths",
331329
)
332330
parser.add_argument(
333331
"-f",
334332
dest="file",
335333
type=str,
336334
default="",
337335
nargs="+",
338-
help=
339-
"file or directory names (can be path relative to python invocation directory or absolute path)"
336+
help="file or directory names (can be path relative to python invocation directory or absolute path)",
337+
)
338+
parser.add_argument(
339+
"-no-format",
340+
dest="no_format",
341+
action="store_true",
342+
help="disable formatting steps, only run linting",
340343
)
341-
parser.add_argument("-no-format",
342-
dest="no_format",
343-
action="store_true",
344-
help="disable formatting steps, only run linting")
345344
args = parser.parse_args()
346345

347346
# tidy requires compile_commands.json
@@ -350,7 +349,8 @@ def main():
350349
if not os.path.exists(ccloc):
351350
print(
352351
f"error: clang-tidy: {ccloc} not found (try -compile-commands)",
353-
file=sys.stderr)
352+
file=sys.stderr,
353+
)
354354
sys.exit(1)
355355

356356
# All discovered files are relative to Git repo root directory, so find the
@@ -373,9 +373,7 @@ def main():
373373
os.remove(f)
374374

375375
# Recursively create list of files in given directory
376-
files = [
377-
os.path.join(dp, f) for dp, dn, fn in os.walk(root_path) for f in fn
378-
]
376+
files = [os.path.join(dp, f) for dp, dn, fn in os.walk(root_path) for f in fn]
379377

380378
if not files:
381379
print("Error: no files found to format", file=sys.stderr)
@@ -385,11 +383,9 @@ def main():
385383
for name in args.file:
386384
# If a directory was specified, recursively expand it
387385
if os.path.isdir(name):
388-
files.extend([
389-
os.path.join(dp, f)
390-
for dp, dn, fn in os.walk(name)
391-
for f in fn
392-
])
386+
files.extend(
387+
[os.path.join(dp, f) for dp, dn, fn in os.walk(name) for f in fn]
388+
)
393389
else:
394390
files.append(name)
395391

@@ -412,8 +408,9 @@ def main():
412408
branch_options = ["master", "main"]
413409
main_branch = ""
414410
for branch in branch_options:
415-
proc = subprocess.run(["git", "rev-parse", "-q", "--verify", branch],
416-
stdout=subprocess.DEVNULL)
411+
proc = subprocess.run(
412+
["git", "rev-parse", "-q", "--verify", branch], stdout=subprocess.DEVNULL
413+
)
417414
if proc.returncode == 0:
418415
main_branch = branch
419416
break
@@ -426,10 +423,9 @@ def main():
426423

427424
# Create list of all changed files
428425
output_list = subprocess.check_output(
429-
["git", "diff", "--name-only", main_branch], encoding="ascii").split()
430-
changed_file_list = [
431-
root_path + os.sep + line.strip() for line in output_list
432-
]
426+
["git", "diff", "--name-only", main_branch], encoding="ascii"
427+
).split()
428+
changed_file_list = [root_path + os.sep + line.strip() for line in output_list]
433429

434430
# Don't run tasks on modifiable or generated files
435431
work = []
@@ -461,9 +457,7 @@ def main():
461457

462458
# Prepare file batches for batch tasks
463459
chunksize = math.ceil(len(files) / args.jobs)
464-
file_batches = [
465-
files[i:i + chunksize] for i in range(0, len(files), chunksize)
466-
]
460+
file_batches = [files[i : i + chunksize] for i in range(0, len(files), chunksize)]
467461

468462
if args.no_format:
469463
# Only run Lint

wpiformat/wpiformat/bracecomment.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99

1010
class BraceComment(Task):
11-
1211
@staticmethod
1312
def should_process_file(config_file, name):
1413
return config_file.is_c_file(name) or config_file.is_cpp_file(name)
@@ -21,9 +20,14 @@ def run_pipeline(self, config_file, name, lines):
2120
brace_postfix = r"[ \t]*/(/|\*)[^\r\n]*"
2221

2322
brace_regex = regex.compile(
24-
r"/\*|\*/|//|\\\\|\\\"|\"|\\'|'|" + linesep + r"|" + \
25-
r"(" + brace_prefix + r"\s*)?{|" # "{" with optional prefix
26-
r"}(" + brace_postfix + r")?") # "}" with optional comment postfix
23+
r"/\*|\*/|//|\\\\|\\\"|\"|\\'|'|"
24+
+ linesep
25+
+ r"|"
26+
+ r"("
27+
+ brace_prefix
28+
+ r"\s*)?{|" # "{" with optional prefix
29+
r"}(" + brace_postfix + r")?"
30+
) # "}" with optional comment postfix
2731

2832
name_stack = []
2933
brace_count = 0
@@ -52,9 +56,9 @@ def run_pipeline(self, config_file, name, lines):
5256
# Tokens processed after this branch are ignored if they are in
5357
# comments
5458
continue
55-
elif token == "\\\"":
59+
elif token == '\\"':
5660
continue
57-
elif token == "\"":
61+
elif token == '"':
5862
if not in_char:
5963
in_string = not in_string
6064
elif token == "\\'":
@@ -72,12 +76,14 @@ def run_pipeline(self, config_file, name, lines):
7276
elif "{" in token:
7377
brace_count += 1
7478
elif token.startswith("}"):
75-
output += lines[extract_location:match.start()]
76-
if len(name_stack) > 0 and name_stack[len(name_stack) -
77-
1][0] == brace_count:
79+
output += lines[extract_location : match.start()]
80+
if (
81+
len(name_stack) > 0
82+
and name_stack[len(name_stack) - 1][0] == brace_count
83+
):
7884
output += "} // " + name_stack.pop()[1]
7985
else:
80-
output += lines[match.start():match.end()]
86+
output += lines[match.start() : match.end()]
8187
extract_location = match.end()
8288
brace_count -= 1
8389

wpiformat/wpiformat/cidentlist.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@
66

77

88
class CIdentList(Task):
9-
109
@staticmethod
1110
def __print_failure(name):
12-
print("Error: " + name + ": unmatched curly braces when scanning for "
13-
"C identifier lists. If the code compiles, this is a bug in "
14-
"wpiformat.")
11+
print(
12+
"Error: " + name + ": unmatched curly braces when scanning for "
13+
"C identifier lists. If the code compiles, this is a bug in "
14+
"wpiformat."
15+
)
1516

1617
@staticmethod
1718
def should_process_file(config_file, name):
@@ -44,9 +45,15 @@ def run_pipeline(self, config_file, name, lines):
4445
extern_str = r"(?P<ext_decl>extern \"C(\+\+)?\")\s+(?P<ext_brace>\{)?|"
4546
braces_str = r"\{|\}|;|def\s+\w+|\w+\s+\w+\s*(?P<paren>\(\))"
4647
postfix_str = r"(?=\s*(;|\{))"
47-
token_regex = regex.compile(preproc_str + comment_str + string_str +
48-
char_str + extern_str + braces_str +
49-
postfix_str)
48+
token_regex = regex.compile(
49+
preproc_str
50+
+ comment_str
51+
+ string_str
52+
+ char_str
53+
+ extern_str
54+
+ braces_str
55+
+ postfix_str
56+
)
5057

5158
EXTRA_POP_OFFSET = 2
5259

@@ -95,9 +102,9 @@ def run_pipeline(self, config_file, name, lines):
95102
# Tokens processed after this branch are ignored if they are in
96103
# comments
97104
continue
98-
elif token == "\\\"":
105+
elif token == '\\"':
99106
continue
100-
elif token == "\"":
107+
elif token == '"':
101108
if not in_char:
102109
in_string = not in_string
103110
elif token == "\\'":
@@ -146,14 +153,13 @@ def run_pipeline(self, config_file, name, lines):
146153
extern_brace_indices.append(is_c + EXTRA_POP_OFFSET)
147154

148155
# Change language based on extern declaration
149-
if match.group("ext_decl") == "extern \"C\"":
156+
if match.group("ext_decl") == 'extern "C"':
150157
is_c = True
151158
else:
152159
is_c = False
153-
elif match.group(
154-
"paren") and "return " not in match.group() and is_c:
160+
elif match.group("paren") and "return " not in match.group() and is_c:
155161
# Replaces () with (void)
156-
output += lines[pos:match.span("paren")[0]] + "(void)"
162+
output += lines[pos : match.span("paren")[0]] + "(void)"
157163
pos = match.span("paren")[0] + len("()")
158164

159165
# Write rest of file if it wasn't all processed

0 commit comments

Comments
 (0)