Skip to content

Commit 6affda8

Browse files
committed
Add in black formatter
Currently this is not enforced in any CI checks yet. Next step is to apply the formatter fix, and then enforce the format check after that. Example usage: ``` // Check with both black and flake8 ramble style // Only check black ramble style -t black // Apply black fix for all relevant files ramble style -t black -a -f ```
1 parent 909663f commit 6affda8

File tree

4 files changed

+63
-27
lines changed

4 files changed

+63
-27
lines changed

lib/ramble/ramble/cmd/style.py

+34-26
Original file line numberDiff line numberDiff line change
@@ -89,16 +89,13 @@ def is_application(f):
8989
pattern_exemptions = dict(
9090
(
9191
re.compile(file_pattern),
92-
dict(
93-
(code, [re.compile(p) for p in patterns])
94-
for code, patterns in error_dict.items()
95-
),
92+
dict((code, [re.compile(p) for p in patterns]) for code, patterns in error_dict.items()),
9693
)
9794
for file_pattern, error_dict in pattern_exemptions.items()
9895
)
9996

100-
101-
tool_names = ["flake8"]
97+
# Tools run in the given order, with flake8 as the last check.
98+
tool_names = ["black", "flake8"]
10299

103100
tools = {}
104101

@@ -221,9 +218,17 @@ def setup_parser(subparser):
221218
action="append",
222219
help="specify tools to skip (choose from %s)" % ",".join(tool_names),
223220
)
224-
subparser.add_argument(
225-
"files", nargs=argparse.REMAINDER, help="specific files to check"
226-
)
221+
subparser.add_argument("files", nargs=argparse.REMAINDER, help="specific files to check")
222+
223+
224+
def print_tool_header(tool, file_list):
225+
print("=======================================================")
226+
print(f"{tool}: running {tool} checks on ramble.")
227+
print()
228+
print("Modified files:")
229+
for filename in file_list:
230+
print(f" {filename.strip()}")
231+
print("=======================================================")
227232

228233

229234
def print_tool_result(tool, returncode):
@@ -241,9 +246,7 @@ def print_output(output, args):
241246
# print results relative to current working directory
242247
def cwd_relative(path):
243248
return "{0}: [".format(
244-
os.path.relpath(
245-
os.path.join(ramble.paths.prefix, path.group(1)), os.getcwd()
246-
)
249+
os.path.relpath(os.path.join(ramble.paths.prefix, path.group(1)), os.getcwd())
247250
)
248251

249252
for line in output.split("\n"):
@@ -335,13 +338,7 @@ def run_flake8(flake8_cmd, file_list, args):
335338
temp = tempfile.mkdtemp()
336339
returncode = 1
337340
try:
338-
print("=======================================================")
339-
print("flake8: running flake8 code checks on ramble.")
340-
print()
341-
print("Modified files:")
342-
for filename in file_list:
343-
print(f" {filename.strip()}")
344-
print("=======================================================")
341+
print_tool_header("flake8", file_list)
345342

346343
# run flake8 on the temporary tree, once for core, once for apps
347344
application_file_list = [f for f in file_list if is_application(f)]
@@ -413,12 +410,27 @@ def run_flake8(flake8_cmd, file_list, args):
413410
return returncode
414411

415412

413+
@tool("black")
414+
def run_black(black_cmd, file_list, args):
415+
print_tool_header("black", file_list)
416+
black_args = ("--config", os.path.join(ramble.paths.prefix, "pyproject.toml"))
417+
if not args.fix:
418+
black_args += ("--check", "--diff")
419+
black_args += tuple(file_list)
420+
421+
output = black_cmd(*black_args, fail_on_error=False, output=str, error=str)
422+
returncode = black_cmd.returncode
423+
print_output(output, args)
424+
print_tool_result("black", returncode)
425+
return returncode
426+
427+
416428
def validate_toolset(arg_value):
417429
"""Validate --tool and --skip arguments (sets of optionally comma-separated tools)."""
418430
tools = set(",".join(arg_value).split(",")) # allow args like 'black,flake8'
419431
for tool in tools:
420432
if tool not in tool_names:
421-
print(f"Invaild tool: {tool}, choose from: {', '.join(tool_names)}")
433+
print(f"Invalid tool: {tool}, choose from: {', '.join(tool_names)}")
422434
return tools
423435

424436

@@ -427,9 +439,7 @@ def style(parser, args):
427439
if file_list:
428440

429441
def prefix_relative(path):
430-
return os.path.relpath(
431-
os.path.abspath(os.path.realpath(path)), ramble.paths.prefix
432-
)
442+
return os.path.relpath(os.path.abspath(os.path.realpath(path)), ramble.paths.prefix)
433443

434444
file_list = [prefix_relative(p) for p in file_list]
435445

@@ -469,9 +479,7 @@ def prefix_relative(path):
469479

470480
for tool_name in tools_to_run:
471481
print(f"Running {tool_name} check")
472-
returncode |= tools[tool_name](
473-
which(tool_name, required=True), file_list, args
474-
)
482+
returncode |= tools[tool_name](which(tool_name, required=True), file_list, args)
475483

476484
if returncode != 0:
477485
print("style checks found errors.")

pyproject.toml

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[tool.black]
2+
line-length = 99
3+
target-version = ["py36", "py37", "py38", "py39", "py310", "py311"]
4+
include = '''
5+
\.pyi?$
6+
'''
7+
force-exclude = '''
8+
/(
9+
\.git
10+
| etc
11+
| share
12+
| var
13+
| lib/ramble/external
14+
| lib/ramble/spack
15+
| lib/ramble/llnl
16+
| __pycache__
17+
)/
18+
'''

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pytest
22
flake8
3+
black
34
google-cloud-storage # for gcs fetch test
45
google-api-core # for gcs fetch error .execptions
56
coverage

share/ramble/ramble-completion.bash

+10-1
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ _ramble() {
267267
then
268268
RAMBLE_COMPREPLY="-h --help -H --all-help --color -c --config -C --config-scope -d --debug --disable-passthrough -N --disable-logger -P --disable-progress-bar --timestamp --pdb -w --workspace -D --workspace-dir -W --no-workspace --use-workspace-repo -k --insecure -l --enable-locks -L --disable-locks -m --mock -p --profile --sorted-profile --lines -v --verbose --stacktrace -V --version --print-shell-vars"
269269
else
270-
RAMBLE_COMPREPLY="attributes clean commands config debug deployment edit flake8 help info license list mirror mods on python repo results software-definitions unit-test workspace"
270+
RAMBLE_COMPREPLY="attributes clean commands config debug deployment edit flake8 help info license list mirror mods on python repo results software-definitions style unit-test workspace"
271271
fi
272272
}
273273

@@ -643,6 +643,15 @@ _ramble_software_definitions() {
643643
RAMBLE_COMPREPLY="-h --help -s --summary -c --conflicts -e --error-on-conflict"
644644
}
645645

646+
_ramble_style() {
647+
if $list_options
648+
then
649+
RAMBLE_COMPREPLY="-h --help -b --base -a --all -o --output -r --root-relative -U --no-untracked -f --fix -k --keep-temp -t --tool -s --skip"
650+
else
651+
RAMBLE_COMREPLY=""
652+
fi
653+
}
654+
646655
_ramble_unit_test() {
647656
if $list_options
648657
then

0 commit comments

Comments
 (0)