core: move args.log to context.log (MR 2252)

Signed-off-by: Caleb Connolly <caleb@postmarketos.org>
This commit is contained in:
Caleb Connolly 2024-05-24 18:19:07 +02:00 committed by Oliver Smith
parent 838beb270d
commit 02f04ba3a8
No known key found for this signature in database
GPG key ID: 5AE7F5513E0885CB
6 changed files with 28 additions and 15 deletions

View file

@ -15,7 +15,8 @@ from .helpers import frontend
from .helpers import logging from .helpers import logging
from .helpers import mount from .helpers import mount
from .helpers import other from .helpers import other
from .core import Chroot from .core import Chroot, get_context
from .commands import run_command
# pmbootstrap version # pmbootstrap version
__version__ = "2.3.1" __version__ = "2.3.1"
@ -30,7 +31,8 @@ if version < (3, 9):
def print_log_hint() -> None: def print_log_hint() -> None:
log = config.get("log") context = get_context()
log = context.log
# Hints about the log file (print to stdout only) # Hints about the log file (print to stdout only)
log_hint = "Run 'pmbootstrap log' for details." log_hint = "Run 'pmbootstrap log' for details."
if not os.path.exists(log): if not os.path.exists(log):

View file

@ -160,7 +160,6 @@ defaults = {
# times on slower devices due to host systems being MUCH faster than the # times on slower devices due to host systems being MUCH faster than the
# target device (see issue #429). # target device (see issue #429).
"iter_time": "200", "iter_time": "200",
"log": "$WORK/log.txt",
} }
allowed_values = { allowed_values = {

View file

@ -3,13 +3,20 @@
"""Global runtime context""" """Global runtime context"""
import pmb.config
from pathlib import Path
class Context(): class Context():
details_to_stdout: bool details_to_stdout: bool
quiet: bool quiet: bool
command_timeout: float command_timeout: float
sudo_timer: bool sudo_timer: bool
log: Path
def __init__(self): def __init__(self):
self.details_to_stdout = False self.details_to_stdout = False
self.command_timeout = 0 self.command_timeout = 0
self.sudo_timer = False self.sudo_timer = False
self.log = pmb.config.work / "log.txt"
self.quiet = False

View file

@ -92,7 +92,7 @@ def replace_placeholders(args: PmbArgs):
setattr(args, key, old.replace("$WORK", str(pmb.config.work))) setattr(args, key, old.replace("$WORK", str(pmb.config.work)))
# Replace ~ (path variables only) # Replace ~ (path variables only)
for key in ["aports", "config", "log", "work"]: for key in ["aports", "config", "work"]:
if key in args: if key in args:
setattr(args, key, Path(getattr(args, key)).expanduser()) setattr(args, key, Path(getattr(args, key)).expanduser())

View file

@ -9,6 +9,7 @@ import sys
import pmb.config import pmb.config
from pmb.core.types import PmbArgs from pmb.core.types import PmbArgs
from pmb.core import get_context
class ReadlineTabCompleter: class ReadlineTabCompleter:
@ -128,7 +129,7 @@ def progress_print(args: PmbArgs, progress):
filled = "\u2588" * chars filled = "\u2588" * chars
empty = " " * (width - chars) empty = " " * (width - chars)
percent = int(progress * 100) percent = int(progress * 100)
if pmb.config.is_interactive and not args.details_to_stdout: if pmb.config.is_interactive and not get_context().details_to_stdout:
sys.stdout.write(f"\u001b7{percent:>3}% {filled}{empty}") sys.stdout.write(f"\u001b7{percent:>3}% {filled}{empty}")
sys.stdout.flush() sys.stdout.flush()
sys.stdout.write("\u001b8\u001b[0K") sys.stdout.write("\u001b8\u001b[0K")
@ -139,5 +140,5 @@ def progress_flush(args):
This will erase the line. Does nothing in non-interactive mode. This will erase the line. Does nothing in non-interactive mode.
""" """
if pmb.config.is_interactive and not args.details_to_stdout: if pmb.config.is_interactive and not get_context().details_to_stdout:
sys.stdout.flush() sys.stdout.flush()

View file

@ -5,6 +5,8 @@ import os
import sys import sys
from typing import TextIO from typing import TextIO
import pmb.config import pmb.config
from pmb.core import get_context
from pmb.core.context import Context
from pmb.core.types import PmbArgs from pmb.core.types import PmbArgs
logfd: TextIO logfd: TextIO
@ -21,19 +23,19 @@ VERBOSE = 5
class log_handler(logging.StreamHandler): class log_handler(logging.StreamHandler):
"""Write to stdout and to the already opened log file.""" """Write to stdout and to the already opened log file."""
_args: PmbArgs context: Context
def __init__(self, args: PmbArgs): def __init__(self):
super().__init__() super().__init__()
self._args = args self.context = get_context()
def emit(self, record): def emit(self, record):
try: try:
msg = self.format(record) msg = self.format(record)
# INFO or higher: Write to stdout # INFO or higher: Write to stdout
if (not self._args.details_to_stdout and if (not self.context.details_to_stdout and
not self._args.quiet and not self.context.quiet and
record.levelno >= logging.INFO): record.levelno >= logging.INFO):
stream = self.stream stream = self.stream
@ -106,18 +108,20 @@ def add_verbose_log_level():
def init(args: PmbArgs): def init(args: PmbArgs):
"""Set log format and add the log file descriptor to logfd, add the verbose log level.""" """Set log format and add the log file descriptor to logfd, add the verbose log level."""
global logfd global logfd
context = pmb.core.get_context()
# Set log file descriptor (logfd) # Set log file descriptor (logfd)
if args.details_to_stdout: if context.details_to_stdout:
logfd = sys.stdout logfd = sys.stdout
else: else:
# Require containing directory to exist (so we don't create the work # Require containing directory to exist (so we don't create the work
# folder and break the folder migration logic, which needs to set the # folder and break the folder migration logic, which needs to set the
# version upon creation) # version upon creation)
dir = os.path.dirname(args.log) dir = os.path.dirname(context.log)
if os.path.exists(dir): if os.path.exists(dir):
logfd = open(args.log, "a+") logfd = open(context.log, "a+")
else: else:
logfd = open(os.devnull, "a+") logfd = open(os.devnull, "a+")
# FIXME: what? surely this check shouldn't be needed!
if args.action != "init": if args.action != "init":
print(f"WARNING: Can't create log file in '{dir}', path" print(f"WARNING: Can't create log file in '{dir}', path"
" does not exist!") " does not exist!")
@ -135,7 +139,7 @@ def init(args: PmbArgs):
root_logger.setLevel(VERBOSE) root_logger.setLevel(VERBOSE)
# Add a custom log handler # Add a custom log handler
handler = log_handler(args) handler = log_handler()
handler.setFormatter(formatter) handler.setFormatter(formatter)
root_logger.addHandler(handler) root_logger.addHandler(handler)