From 965e8893a3b81d831a665acfd4f5498bbfbbdfdb Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sat, 16 May 2026 08:55:20 +0000 Subject: [PATCH] Optimize path containment checks in is_in_dir Co-authored-by: thirdeyenation <133812267+thirdeyenation@users.noreply.github.com> --- .jules/bolt.md | 4 ++++ helpers/files.py | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 .jules/bolt.md diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000000..a82bf23efb --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,4 @@ + +## 2024-05-24 - Optimize path containment checks +**Learning:** `os.path.commonpath` is a significant bottleneck for frequent path containment checks due to internal list allocations and path splitting overhead. +**Action:** Use `os.path.abspath` and `str.startswith()` instead, conditionally appending a trailing `os.sep` to the absolute directory before comparison to prevent path traversal bugs (e.g., `abs_path == abs_dir or abs_path.startswith(abs_dir + ('' if abs_dir.endswith(os.sep) else os.sep))`). diff --git a/helpers/files.py b/helpers/files.py index c77ab54cf1..cd5d763c8c 100644 --- a/helpers/files.py +++ b/helpers/files.py @@ -653,7 +653,8 @@ def is_in_dir(path: str, dir: str): # check if the given path is within the directory abs_path = os.path.abspath(path) abs_dir = os.path.abspath(dir) - return os.path.commonpath([abs_path, abs_dir]) == abs_dir + # ⚡ Bolt Optimization: Use string prefix matching instead of commonpath to avoid list allocations and path splitting overhead + return abs_path == abs_dir or abs_path.startswith(abs_dir + ('' if abs_dir.endswith(os.sep) else os.sep)) def get_subdirectories(