mirror of
https://github.com/CodeSeeed/sbackup.git
synced 2026-10-05 02:42:58 +08:00
fix: 简化 hooks 跨平台命令解析,改进测试兼容性
This commit is contained in:
1 parent
14ae82e311
commit
8f3c6dbc85
2 files changed
+17
-7
No files matched your search
+5
-3
@@ -69,13 +69,15 @@ class HookRunner:
|
|||||||
start = time.monotonic()
|
start = time.monotonic()
|
||||||
try:
|
try:
|
||||||
# 跨平台命令解析
|
# 跨平台命令解析
|
||||||
if sys.platform == "win32":
|
# posix=True(默认):剥离引号,各平台行为一致
|
||||||
|
# Windows 上 shlex.split 可能对某些命令格式报 ValueError,回退到 [command]
|
||||||
try:
|
try:
|
||||||
args_list = shlex.split(command, posix=False)
|
args_list = shlex.split(command)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
|
if sys.platform == "win32":
|
||||||
args_list = [command]
|
args_list = [command]
|
||||||
else:
|
else:
|
||||||
args_list = shlex.split(command)
|
raise
|
||||||
|
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
args_list,
|
args_list,
|
||||||
|
|||||||
@@ -10,13 +10,21 @@ from sbackup.hooks import HookResult, HookRunner
|
|||||||
|
|
||||||
|
|
||||||
def _make_python_cmd(script: str) -> str:
|
def _make_python_cmd(script: str) -> str:
|
||||||
"""创建跨平台的 Python 命令,避免引号转义问题"""
|
"""创建跨平台的 Python 命令
|
||||||
return f"{sys.executable} -c {script}"
|
|
||||||
|
将可执行文件路径用双引号包裹,确保 shlex.split 在 posix 模式下
|
||||||
|
不会将 Windows 路径中的反斜杠解释为转义字符。
|
||||||
|
"""
|
||||||
|
return f'"{sys.executable}" -c {script}'
|
||||||
|
|
||||||
|
|
||||||
|
# 命令中不包含空格或分号,确保 shlex.split 正确解析
|
||||||
_echo_cmd = _make_python_cmd("print(42)")
|
_echo_cmd = _make_python_cmd("print(42)")
|
||||||
_fail_cmd = _make_python_cmd("raise SystemExit(1)")
|
_fail_cmd = _make_python_cmd("exit(1)")
|
||||||
_sleep_cmd = _make_python_cmd("__import__('time').sleep(10)")
|
# 超时命令使用 ping(无引号/分号问题):
|
||||||
|
# Windows: ping -n 11 127.0.0.1 (~10s)
|
||||||
|
# Unix: ping -c 11 127.0.0.1 (~10s)
|
||||||
|
_sleep_cmd = "ping -n 11 127.0.0.1" if sys.platform == "win32" else "sleep 10"
|
||||||
|
|
||||||
|
|
||||||
class TestHookResult(unittest.TestCase):
|
class TestHookResult(unittest.TestCase):
|
||||||
|
|||||||
Reference in new issue
Block a user