Skip to content
Open
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions astrbot/core/utils/path_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@ def path_Mapping(mappings, srcPath: str) -> str:
has_replaced_processed = False
if srcPath.startswith("."):
# 相对路径处理。如果是相对路径,可能是Linux路径,也可能是Windows路径
sign = srcPath[1]
# 映射目标可能短到只是 "." 或 "..",此时没有后续字符,按需取以免越界
sign = srcPath[1] if len(srcPath) > 1 else ""
# 处理两个点的情况
if sign == ".":
sign = srcPath[2]
sign = srcPath[2] if len(srcPath) > 2 else ""
Comment on lines +58 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In Python, string slicing is safe from IndexError and returns an empty string if the index is out of bounds. We can leverage this to simplify the code and avoid verbose length checks by using srcPath[1:2] and srcPath[2:3].

Suggested change
sign = srcPath[1] if len(srcPath) > 1 else ""
# 处理两个点的情况
if sign == ".":
sign = srcPath[2]
sign = srcPath[2] if len(srcPath) > 2 else ""
sign = srcPath[1:2]
# 处理两个点的情况
if sign == '.':
sign = srcPath[2:3]

if sign == "/":
srcPath = srcPath.replace("\\", "/")
has_replaced_processed = True
Expand Down
19 changes: 19 additions & 0 deletions tests/test_path_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from astrbot.core.utils.path_util import path_Mapping


def test_path_mapping_target_single_dot_does_not_crash():
# A mapping whose target is "." reduces srcPath to "." (one character).
# The relative-path branch indexed srcPath[1] unconditionally and raised
# IndexError. path_Mapping is reachable from the respond stage, so a user
# configuring such a rule could crash message handling.
assert path_Mapping(["somepath:."], "somepath") == "."


def test_path_mapping_target_double_dot_does_not_crash():
# ".." is two characters, so the inner srcPath[2] access also overran.
assert path_Mapping(["somepath:.."], "somepath") == ".."


def test_path_mapping_relative_target_still_normalized():
# Regression: a normal relative target keeps its existing behaviour.
assert path_Mapping(["somepath:./sub"], "somepath") == "./sub"
Comment on lines +17 to +19

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add coverage for short relative targets like "./" and "../" to fully lock in the new index-guard logic.

Since the new logic guards srcPath[1] and srcPath[2], please add tests for "somepath:./" and "somepath:../" to cover the shortest relative targets and ensure the short vs normal relative boundary remains stable.

Loading