Skip to content

Commit

Permalink
Fix unicode character map error in Windows OS and some linux distribu…
Browse files Browse the repository at this point in the history
…tions with non native unicode support
  • Loading branch information
cavearr committed Apr 28, 2024
1 parent 6ca3ce2 commit 7d70644
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
9 changes: 4 additions & 5 deletions apio/managers/scons.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,7 @@ def _execute_scons(self, command: str, variables: list, board: str) -> int:
click.echo(f"[{date_time_str}] Processing {board_color}")

# -- Print a horizontal line
click.secho("" * terminal_width, bold=True)
click.secho("-" * terminal_width, bold=True)

# -- Command to execute: scons -Q apio_cmd flags
scons_command = ["scons"] + ["-Q", command] + variables
Expand All @@ -975,7 +975,7 @@ def _execute_scons(self, command: str, variables: list, board: str) -> int:
summary_text = f" Took {duration:.2f} seconds "

# -- Half line
half_line = "" * int(((terminal_width - len(summary_text) - 10) / 2))
half_line = "=" * int(((terminal_width - len(summary_text) - 10) / 2))

# -- Status message
status = (
Expand All @@ -985,9 +985,8 @@ def _execute_scons(self, command: str, variables: list, board: str) -> int:
)

# -- Print all the information!
click.echo(
f"{half_line} [{status}]{summary_text}{half_line}",
err=is_error,
util.safe_click(
f"{half_line} [{status}]{summary_text}{half_line}", err=is_error
)

# -- Return the exit code
Expand Down
18 changes: 18 additions & 0 deletions apio/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,3 +885,21 @@ def context_settings():
# Per https://click.palletsprojects.com/en/8.1.x/documentation/
# #help-parameter-customization
return {"help_option_names": ["-h", "--help"]}


def safe_click(text, *args, **kwargs):
"""Prints text to the console handling potential Unicode errors,
forwarding any additional arguments to click.echo. This permits
avoid the need of setting encode environment variables for utf-8"""

error_flag = kwargs.pop("err", False)

try:
click.echo(text, err=error_flag, *args, **kwargs)
except UnicodeEncodeError:
cleaned_text = text.encode("ascii", errors="replace").decode("ascii")
# if encoding fails, after retry without errors , bad characters are
# replaced by '?' character, and is better replace for = because is the
# most common character error
cleaned_text = "".join([ch if ord(ch) < 128 else "=" for ch in text])
click.echo(cleaned_text, err=error_flag, *args, **kwargs)

0 comments on commit 7d70644

Please sign in to comment.