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

Improve width logic #57

Merged
merged 1 commit into from
Sep 21, 2023
Merged
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
52 changes: 38 additions & 14 deletions src/pip4a/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

from __future__ import annotations

import decimal
import logging
import os
import shutil
import sys
import textwrap

Expand All @@ -18,6 +19,40 @@


T = TypeVar("T", bound="Level")
GOLDEN_RATIO = 1.61803398875


def round_half_up(number: float) -> int:
"""Round a number to the nearest integer with ties going away from zero.

This is different the round() where exact halfway cases are rounded to the nearest
even result instead of away from zero. (e.g. round(2.5) = 2, round(3.5) = 4).

This will always round based on distance from zero. (e.g round(2.5) = 3, round(3.5) = 4).

:param number: The number to round
:returns: The rounded number as an it
"""
rounded = decimal.Decimal(number).quantize(
decimal.Decimal("1"),
rounding=decimal.ROUND_HALF_UP,
)
return int(rounded)


def console_width() -> int:
"""Get a console width based on common screen widths.

:returns: The console width
"""
medium = 80
wide = 132
width = shutil.get_terminal_size().columns
if width <= medium:
return width
if width <= wide:
return max(80, round_half_up(width / GOLDEN_RATIO))
return wide


class Color:
Expand Down Expand Up @@ -284,18 +319,7 @@ def log(self: Output, msg: str, level: Level = Level.ERROR) -> None:
if self.log_to_file:
self.logger.log(level.log_level, msg, stacklevel=3)

try:
width = float(os.get_terminal_size()[0])
except OSError:
width = 80
narrow = 80
wide = 120
if width <= narrow:
set_width = width - 2
elif wide >= width >= narrow:
set_width = width * 0.9
elif width > wide:
set_width = width * 0.8
set_width = console_width()

debug = 2
info = 1
Expand All @@ -306,7 +330,7 @@ def log(self: Output, msg: str, level: Level = Level.ERROR) -> None:

lines = Msg(message=msg, prefix=level).to_lines(
color=self.term_features.color,
width=int(set_width),
width=set_width,
with_prefix=True,
)
if level in (Level.CRITICAL, Level.ERROR):
Expand Down