Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support multiple cargo subprojects #247

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions language_formatters_pre_commit_hooks/pre_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@

def _is_command_success(
*command_args: str,
print_if_ok:bool=False,
print_command_exec=False,
) -> bool:
exit_status, _, _ = run_command(*command_args)
exit_status, _, _ = run_command(
*command_args, print_if_ok=print_if_ok, print_command_exec=print_command_exec
)
return exit_status == 0


Expand Down Expand Up @@ -80,8 +84,8 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int:


rust_required = _ToolRequired(
tool_name="rustfmt",
check_command=(lambda _: _is_command_success("cargo", "fmt", "--", "--version")),
tool_name="cargo",
check_command=(lambda _: _is_command_success("cargo", "fmt", "--version")),
download_install_url="https://github.com/rust-lang-nursery/rustfmt#quick-start",
)

Expand Down
49 changes: 40 additions & 9 deletions language_formatters_pre_commit_hooks/pretty_format_rust.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import argparse
import os.path
import sys
import typing

Expand All @@ -17,29 +18,59 @@ def pretty_format_rust(argv: typing.Optional[typing.List[str]] = None) -> int:
help="Automatically fixes encountered not-pretty-formatted files",
)
parser.add_argument(
"--manifest-path",
default="Cargo.toml",
dest="manifest_path",
help="The cargo manifest file location (Default: %(default)s)",
"--manifest-root",
action="append",
dest="manifest_root",
help="The cargo manifest file location.",
)
parser.add_argument(
'--format-verbose',
action="store_true",
dest='print_command_exec',
help="Output tool execution messages",
)

parser.add_argument("filenames", nargs="*", help="Filenames to fix")
args = parser.parse_args(argv)

if not args.manifest_root:
pretty_format_rust_internal(args.autofix, None, args.filenames, print_command_exec=args.print_command_exec)

for manifest_root in args.manifest_root:
manifest_path = os.path.join(manifest_root, 'Cargo.toml')

# TODO: properly filter filenames
filenames = list(filter(lambda filename: filename.startswith(manifest_root), args.filenames))
pretty_format_rust_internal(args.autofix, manifest_path, filenames,
print_command_exec=args.print_command_exec)

def pretty_format_rust_internal(autofix: bool, manifest_path: str|None, filenames:
list[str], *, print_command_exec: bool):
# Check
status_code, output, _ = run_command("cargo", "fmt", "--manifest-path", args.manifest_path, "--", "--check", *args.filenames)
if autofix:
check_args = []
else:
check_args = ['--check']

if manifest_path:
manifest_path_args = ["--manifest-path", manifest_path]
else:
manifest_path_args = []

status_code, output, _ = run_command(
"cargo", "fmt", *manifest_path_args, *check_args, "--", *filenames,
print_if_ok=False, print_command_exec=print_command_exec
)
not_well_formatted_files = sorted(line.split()[2] for line in output.splitlines() if line.startswith("Diff in "))
if not_well_formatted_files:
print(
"{}: {}".format(
"The following files have been fixed by cargo format" if args.autofix else "The following files are not properly formatted",
"The following files have been fixed by rustfmt" if autofix else "The following files are not properly formatted",
", ".join(not_well_formatted_files),
),
)
if args.autofix:
run_command("cargo", "fmt", "--manifest-path", args.manifest_path, "--", *not_well_formatted_files)
elif status_code != 0:
print("Detected not valid rust source files among {}".format("\n".join(sorted(args.filenames))))
print("Detected not valid rust source files among {}".format("\n".join(sorted(filenames))))

return 1 if status_code != 0 or not_well_formatted_files else 0

Expand Down
26 changes: 14 additions & 12 deletions language_formatters_pre_commit_hooks/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,26 @@
import requests


def run_command(*command: str) -> typing.Tuple[int, str, str]:
print(
"[cwd={cwd}] Run command: {command}".format(
command=command,
cwd=os.getcwd(),
),
file=sys.stderr,
)
def run_command(*command: str, print_if_ok=True, print_command_exec=True) -> typing.Tuple[int, str, str]:
if print_command_exec:
print(
"[cwd={cwd}] Run command: {command}".format(
command=command,
cwd=os.getcwd(),
),
file=sys.stderr,
)

result = subprocess.run(command, capture_output=True) # nosec: disable=B603
return_code = result.returncode
stdout = result.stdout.decode("utf-8")
stderr = result.stderr.decode("utf-8")

print(
"[return_code={return_code}] | {output}\n\tstderr: {err}".format(return_code=return_code, output=stdout, err=stderr),
file=sys.stderr,
)
if return_code != 0 or print_if_ok:
print(
"[return_code={return_code}] | {output}\n\tstderr: {err}".format(return_code=return_code, output=stdout, err=stderr),
file=sys.stderr,
)
return return_code, stdout, stderr


Expand Down
Loading