From 73b1aa85a2e4b541cfd80cea304f82051a17bc6d Mon Sep 17 00:00:00 2001 From: Zanie Date: Fri, 12 Jan 2024 18:00:23 -0600 Subject: [PATCH] Defer import of traceback --- scripts/hookd/hookd.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/hookd/hookd.py b/scripts/hookd/hookd.py index 00378161c..f82fa1d2b 100755 --- a/scripts/hookd/hookd.py +++ b/scripts/hookd/hookd.py @@ -13,7 +13,6 @@ import errno import os import sys import time -import traceback from contextlib import ExitStack, contextmanager from functools import cache from typing import Any, Literal, Self, TextIO @@ -389,6 +388,9 @@ def send_error(file: TextIO, exc: HookdError): def send_traceback(file: TextIO, exc: BaseException): + # Defer import of traceback until an exception occurs + import traceback + tb = traceback.format_exception(exc) write_safe(file, "TRACEBACK", "\n".join(tb)) @@ -473,15 +475,17 @@ def run_once(stdin: TextIO, stdout: TextIO): """ -Optimized version of temporary file creation. -Implemenation based on CPython. +Optimized version of temporary file creation based on CPython's `NamedTemporaryFile`. -This implementation: +Profiling shows that temporary file creation for stdout and stderr is the most expensive +part of running a build hook. +Notable differences: - Uses UUIDs instead of the CPython random name generator - Finds a valid temporary directory at the same time as creating the temporary file - Avoids having to unlink a file created just to test if the directory is valid - Only finds the default temporary directory _once_ then caches it +- Does not manage deletion of the file """ _text_openflags = os.O_RDWR | os.O_CREAT | os.O_EXCL