fix rich autodetection of TTY, USE_COLOR, SHOW_PROGRESS

This commit is contained in:
Nick Sweeting 2024-09-24 19:37:29 -07:00
parent bde0bf8263
commit 0dffbf1bb4
No known key found for this signature in database
4 changed files with 32 additions and 17 deletions

View file

@ -41,6 +41,7 @@ import importlib.metadata
from pydantic_pkgr import SemVer from pydantic_pkgr import SemVer
from rich.progress import Progress from rich.progress import Progress
from rich.console import Console
import django import django
from django.db.backends.sqlite3.base import Database as sqlite3 from django.db.backends.sqlite3.base import Database as sqlite3
@ -55,8 +56,6 @@ from .config_stubs import (
) )
from .misc.logging import ( from .misc.logging import (
CONSOLE,
SHOW_PROGRESS,
DEFAULT_CLI_COLORS, DEFAULT_CLI_COLORS,
ANSI, ANSI,
COLOR_DICT, COLOR_DICT,
@ -1289,6 +1288,17 @@ if not CONFIG['CHECK_SSL_VALIDITY']:
########################### Config Validity Checkers ########################### ########################### Config Validity Checkers ###########################
if not CONFIG.USE_COLOR:
os.environ['NO_COLOR'] = '1'
if not CONFIG.SHOW_PROGRESS:
os.environ['TERM'] = 'dumb'
# recreate rich console obj based on new config values
CONSOLE = Console()
from .misc import logging
logging.CONSOLE = CONSOLE
INITIAL_STARTUP_PROGRESS = None INITIAL_STARTUP_PROGRESS = None
INITIAL_STARTUP_PROGRESS_TASK = 0 INITIAL_STARTUP_PROGRESS_TASK = 0

View file

@ -17,6 +17,9 @@ from typing import Any, Optional, List, Dict, Union, IO, TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from .index.schema import Link, ArchiveResult from .index.schema import Link, ArchiveResult
from rich import print
from rich.panel import Panel
from .system import get_dir_size from .system import get_dir_size
from .util import enforce_types from .util import enforce_types
from .config import ( from .config import (
@ -231,15 +234,20 @@ def progress_bar(seconds: int, prefix: str='') -> None:
def log_cli_command(subcommand: str, subcommand_args: List[str], stdin: Optional[str | IO], pwd: str): def log_cli_command(subcommand: str, subcommand_args: List[str], stdin: Optional[str | IO], pwd: str):
cmd = ' '.join(('archivebox', subcommand, *subcommand_args)) args = ' '.join(subcommand_args)
stderr('{black}[i] [{now}] ArchiveBox v{VERSION}: {cmd}{reset}'.format( version_msg = '[dark_magenta]\\[i] [{now}] ArchiveBox v{VERSION}: [/dark_magenta][green4]archivebox [green3]{subcommand}[green2] {args}[/green2]'.format(
now=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'), now=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'),
VERSION=VERSION, VERSION=VERSION,
cmd=cmd, subcommand=subcommand,
**ANSI, args=args,
)) )
stderr('{black} > {pwd}{reset}'.format(pwd=pwd, **ANSI)) # stderr()
stderr() # stderr('{black} > {pwd}{reset}'.format(pwd=pwd, **ANSI))
# stderr()
if SHOW_PROGRESS:
print(Panel(version_msg), file=sys.stderr)
else:
print(version_msg, file=sys.stderr)
### Parsing Stage ### Parsing Stage

View file

@ -2,7 +2,6 @@ __package__ = 'archivebox.misc'
# TODO: merge/dedupe this file with archivebox/logging_util.py # TODO: merge/dedupe this file with archivebox/logging_util.py
import os
import sys import sys
from typing import Optional, Union, Tuple, List from typing import Optional, Union, Tuple, List
from collections import defaultdict from collections import defaultdict
@ -11,12 +10,10 @@ from rich.console import Console
from ..config_stubs import ConfigDict from ..config_stubs import ConfigDict
SHOW_PROGRESS = None # SETUP RICH CONSOLE / TTY detection / COLOR / PROGRESS BARS
if os.environ.get('SHOW_PROGRESS', 'None') in ('True', '1', 'true', 'yes'): CONSOLE = Console()
SHOW_PROGRESS = True IS_TTY = CONSOLE.is_interactive
CONSOLE = Console(force_interactive=SHOW_PROGRESS)
SHOW_PROGRESS = CONSOLE.is_interactive if SHOW_PROGRESS is None else SHOW_PROGRESS
DEFAULT_CLI_COLORS = benedict( DEFAULT_CLI_COLORS = benedict(
{ {

View file

@ -147,7 +147,7 @@ class CheckUserIsNotRoot(BaseCheck):
hint=f'Run ArchiveBox as a non-root user with a UID greater than 500. (currently running as UID {os.getuid()}).', hint=f'Run ArchiveBox as a non-root user with a UID greater than 500. (currently running as UID {os.getuid()}).',
) )
) )
logger.debug('[√] UID is not root') # logger.debug('[√] UID is not root')
return errors return errors
@ -168,7 +168,7 @@ class CheckPipEnvironment(BaseCheck):
hint="Make sure the data dir is writable and make sure python3-pip and python3-venv are installed & available on the host.", hint="Make sure the data dir is writable and make sure python3-pip and python3-venv are installed & available on the host.",
) )
) )
logger.debug("[√] CheckPipEnvironment: data/lib/pip virtualenv is setup properly") # logger.debug("[√] CheckPipEnvironment: data/lib/pip virtualenv is setup properly")
return errors return errors