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

github output #1049

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
45 changes: 26 additions & 19 deletions djlint/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from djlint.reformat import reformat_file
from djlint.settings import Config
from djlint.src import get_src
from djlint.github_output import print_github_output

if TYPE_CHECKING:
from djlint.types import ProcessResult
Expand Down Expand Up @@ -70,9 +71,7 @@
help="Indent spacing. [default: 4]",
show_default=False,
)
@click.option(
"--quiet", is_flag=True, help="Do not print diff when reformatting."
)
@click.option("--quiet", is_flag=True, help="Do not print diff when reformatting.")
@click.option(
"--profile",
type=str,
Expand All @@ -83,9 +82,7 @@
is_flag=True,
help="Only format or lint files that starts with a comment with the text 'djlint:on'",
)
@click.option(
"--lint", is_flag=True, help="Lint for common issues. [default option]"
)
@click.option("--lint", is_flag=True, help="Lint for common issues. [default option]")
@click.option(
"--use-gitignore",
is_flag=True,
Expand Down Expand Up @@ -133,9 +130,7 @@
help='Codes to include. ex: "H014,H017"',
show_default=False,
)
@click.option(
"--ignore-case", is_flag=True, help="Do not fix case on known html tags."
)
@click.option("--ignore-case", is_flag=True, help="Do not fix case on known html tags.")
@click.option(
"--ignore-blocks",
type=str,
Expand Down Expand Up @@ -215,9 +210,7 @@
@click.option(
"--indent-css", type=int, help="Set CSS indent level.", show_default=False
)
@click.option(
"--indent-js", type=int, help="Set JS indent level.", show_default=False
)
@click.option("--indent-js", type=int, help="Set JS indent level.", show_default=False)
@click.option(
"--close-void-tags",
is_flag=True,
Expand All @@ -244,6 +237,13 @@
help="Consolidate blank lines down to x lines. [default: 0]",
show_default=False,
)
@click.option(
"--github-output",
is_flag=True,
default=bool(os.getenv("GITHUB_ACTIONS")),
help="Output GitHub-compatible formatting.",
show_default=True,
)
@colorama_text(autoreset=True)
def main(
*,
Expand Down Expand Up @@ -287,8 +287,10 @@ def main(
no_function_formatting: bool,
no_set_formatting: bool,
max_blank_lines: int | None,
github_output: bool = False,
) -> None:
"""djLint · HTML template linter and formatter."""

config = Config(
src[0],
extension=extension,
Expand Down Expand Up @@ -383,7 +385,7 @@ def main(
Fore.GREEN + Style.BRIGHT,
Style.RESET_ALL + " ",
)
if not config.stdin and not config.quiet:
if not config.stdin and not config.quiet and not github_output:
echo()

progress_char = " »" if sys.platform == "win32" else "┈━"
Expand All @@ -409,13 +411,12 @@ def main(
colour="BLUE",
ascii=progress_char,
leave=False,
disable=github_output,
) as pbar:
for future in as_completed(futures):
file_errors.append(future.result())
pbar.update()
elapsed = pbar.format_interval(
pbar.format_dict["elapsed"]
)
elapsed = pbar.format_interval(pbar.format_dict["elapsed"])

finished_bar_message = f"{Fore.BLUE + Style.BRIGHT}{message}{Style.RESET_ALL} {Fore.GREEN + Style.BRIGHT}{{n_fmt}}/{{total_fmt}}{Style.RESET_ALL} {Fore.BLUE + Style.BRIGHT}files{Style.RESET_ALL} {{bar}} {Fore.GREEN + Style.BRIGHT}{elapsed}{Style.RESET_ALL} "

Expand All @@ -426,12 +427,11 @@ def main(
colour="GREEN",
ascii=progress_char,
leave=True,
disable=github_output,
):
pass
else:
file_errors = [
future.result() for future in as_completed(futures)
]
file_errors = [future.result() for future in as_completed(futures)]

if temp_file and (config.reformat or config.check):
# if using stdin, only give back formatted code.
Expand All @@ -448,6 +448,13 @@ def main(
finally:
Path(temp_file.name).unlink(missing_ok=True)

if (
github_output
and print_github_output(config, file_errors, len(file_list))
and not config.warn
):
sys.exit(1)

if print_output(config, file_errors, len(file_list)) and not config.warn:
sys.exit(1)

Expand Down
71 changes: 71 additions & 0 deletions djlint/github_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Build djLint GitHub workflow command output."""

from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from click import echo

if TYPE_CHECKING:
from collections.abc import Iterable, Mapping, Sequence
from djlint.settings import Config
from djlint.types import LintError, ProcessResult


def print_github_output(
config: Config, file_errors: Iterable[ProcessResult], file_count: int
) -> int:
"""Print results as GitHub workflow commands."""
lint_error_count = 0
format_error_count = 0

for error in sorted(
file_errors,
key=lambda x: next(iter(next(iter(x.values())))),
):
if error.get("format_message") and not config.stdin:
format_error_count += print_format_errors(error["format_message"], config)
if error.get("lint_message"):
lint_error_count += print_lint_errors(error["lint_message"], config)

return lint_error_count + format_error_count


def print_lint_errors(error: Mapping[str, Iterable[LintError]], config: Config) -> int:
"""Print lint errors in GitHub format."""
errors = sorted(
next(iter(error.values())),
key=lambda x: tuple(int(i) for i in x["line"].split(":")),
)
if not errors:
return 0

filename = build_relative_path(next(iter(error)), config.project_root)

for message_dict in errors:
line = message_dict["line"].split(":")[0]
level = "error" if message_dict["code"].startswith("E") else "warning"
echo(
f"::{level} file={filename},line={line}::{message_dict['code']} {message_dict['message']}"
)

return len(errors)


def print_format_errors(errors: Mapping[str, Sequence[str]], config: Config) -> int:
"""Print format errors in GitHub format."""
if not errors:
return 0

filename = build_relative_path(next(iter(errors)), config.project_root)
if bool(next(iter(errors.values()))):
echo(f"::error file={filename}::Formatting changes required")

return sum(1 for v in errors.values() if v)


def build_relative_path(url: str, project_root: Path) -> str:
"""Get path relative to project."""
url_path = Path(url)
if project_root != url_path and project_root in url_path.parents:
return str(url_path.relative_to(project_root))
return url
Loading