feat(libs): 新增 fileshare 共享目录访问 SDK(0.1.0)

按 UNC 目录列举文件并支持后缀筛选,复制选定文件到本地;支持当前 Windows 身份与显式账号密码,零第三方依赖。
This commit is contained in:
2026-11-26 09:28:22 +08:00
parent 49538fb2fd
commit 9c99bebc6d
7 changed files with 805 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
# fileshare
共享(UNC)文件访问 SDK:**按共享目录列出文件(可按后缀筛选)**,插件自己判断要哪个,
再让 SDK **复制到本地**。
只做「列」和「取」两件事,不含任何业务语义,任何插件都能用,共享地址作为参数传入。
## 快速开始
```python
import fileshare
# 可选:共享需要账号密码时才调;不调 = 用当前 Windows 登录身份
fileshare.configure(user=r"域\账号", password="***")
# 1) 传共享文件夹地址 + 后缀筛选,拿到文件清单(只读元数据,不下载)
files = fileshare.list_files(r"\\172.30.31.189\资料\人资\考勤月报封存检查", ".xlsx")
# [FileInfo(name='2026.11月报.xlsx', path='\\\\...', size=48213, mtime=datetime(...)), ...]
# 2) 插件自己判断要哪个(按名字/时间/大小随你),再让 SDK 复制过来
chosen = max(files, key=lambda f: f.mtime)
local = fileshare.copy_file(chosen, r"D:\工作\月报.xlsx")
```
`list_files` 默认按文件名升序;`sort="mtime", reverse=True` 即最新在前。
`copy_file` 传目录(已存在或以 `\` 结尾)时按源文件名落进去,传完整路径时父目录自动创建。
## API
| 函数 | 说明 |
|---|---|
| `list_files(folder, ext=None, pattern=None, recursive=False, sort="name", reverse=False)` | 列文件,返回 `list[FileInfo]`;空目录返回 `[]`,目录不存在/无权限抛 `RuntimeError` |
| `copy_file(src, dst, overwrite=True, skip_if_same=True, progress=None)` | 复制到本地,返回本地绝对路径;`src` 可传 `FileInfo` 或 UNC 路径 |
| `exists(path)` | 是否存在(不抛错) |
| `configure(user="", password="")` | 设置共享凭据;不调 = 当前 Windows 身份 |
| `mode()` | 当前访问模式,建议插件启动时打一行日志 |
| `close()` | 断开本进程建立的共享连接(进程退出自动调用) |
`FileInfo` 字段:`name` / `path`(完整 UNC)/ `size` / `mtime`(`datetime`)/ `ext` / `size_mb`。
## 后缀筛选写法
```python
list_files(folder, ".xlsx") # 单后缀
list_files(folder, "xlsx,xls") # 多后缀,逗号/分号/空格分隔
list_files(folder, [".xlsx", ".xls"]) # 列表
list_files(folder, ".xlsx", pattern="*2026.11*") # 通配 + 后缀取交集
```
大小写不敏感。
## 工程细节(都是为了避免踩坑)
- **用 `os.scandir` 而不是 `os.stat` 循环**:UNC 上每次 `stat` 是一次网络往返,
scandir 一次遍历就带齐 `size`/`mtime`,几十个文件也不会慢。
- **`.part` + 原子改名**:目标文件要么不存在、要么完整,不会让别的进程读到半个文件。
- **跳过重复**:目标已存在且大小、修改时间一致时直接返回,重复运行不重拉大文件;
复制成功后会把源 `mtime` 写回本地,保证下一轮判断有效。
- **1MB 流式复制**:大文件不进内存;`progress(done, total)` 可接壳子的进度上报。
- **错误码翻译**:`1326` 提示「填共享账号/密码」、`1219` 提示「凭据冲突」、
`53` 提示「主机不可达/445 被拦」、`5` 提示「无权限」,插件日志直接看得懂。
## 凭据与零依赖
- **零第三方依赖**:不装 pywin32、不装 smbprotocol。需要账号密码时用系统
`mpr.dll` 的 `WNetAddConnection2W`(标准库 `ctypes` 直接调),所以 `sdk.json.deps` 为空,
执行机不需要预装任何东西。
- 优先不填凭据:先用当前 Windows 登录身份访问,报 `1326`/`5` 时再去填账号密码。
- 凭据由插件配置提供(`plugin.json.fields` 里 `share_user` / `share_pass`,
密码字段用 `format: "password"`),SDK 不管配置来源。
## 已知限制
`WNetAddConnection2` 与 `net use` 是同一机制,连接是**登录会话级**的:
**同一台服务器不允许两套凭据**(会报 `1219`)。不同服务器 / 不同共享各自配置不受影响。
将来如果真出现「同一台服务器、不同插件、不同账号」的需求,再引入 `smbprotocol`
的进程级会话(插件每次运行是独立 python 子进程,天然隔离);届时它会变成一个
第三方依赖,需要走环境包预装或插件 `requirements.txt`,不能挂在 `sdk.json.deps` 上。
## 自测
```powershell
cd libs\fileshare
..\..\.venv\Scripts\python.exe -m fileshare._selftest
```
用本地临时目录模拟共享,不依赖真实网络环境。
+57
View File
@@ -0,0 +1,57 @@
{
"schema_version": 1,
"sdk_id": "fileshare",
"version": "0.1.0",
"modules": {
"fileshare": {
"exports": [
"FileInfo",
"configure",
"list_files",
"copy_file",
"exists",
"mode",
"close"
],
"all": [
"FileInfo",
"configure",
"list_files",
"copy_file",
"exists",
"mode",
"close"
],
"signatures": {
"FileInfo": "(name: 'str', path: 'str', size: 'int', mtime: 'datetime') -> None",
"configure": "(user: 'str' = '', password: 'str' = '') -> 'None'",
"list_files": "(folder: 'str', ext: 'Union[str, Sequence[str], None]' = None, pattern: 'Optional[str]' = None, recursive: 'bool' = False, sort: 'str' = 'name', reverse: 'bool' = False, retry: 'int' = 3) -> 'List[FileInfo]'",
"copy_file": "(src: 'Union[FileInfo, str]', dst: 'str', overwrite: 'bool' = True, skip_if_same: 'bool' = True, progress: 'Optional[Callable[[int, int], None]]' = None, retry: 'int' = 3) -> 'str'",
"exists": "(path: 'str') -> 'bool'",
"mode": "() -> 'str'",
"close": "() -> 'None'"
}
},
"fileshare._selftest": {
"exports": [
"TMP",
"annotations",
"build_share",
"fileshare",
"main",
"ok",
"os",
"shutil",
"sys",
"tempfile",
"time"
],
"all": [],
"signatures": {
"build_share": "() -> 'str'",
"main": "() -> 'int'",
"ok": "(cond: 'bool', msg: 'str') -> 'None'"
}
}
}
}
+457
View File
@@ -0,0 +1,457 @@
# -*- coding: utf-8 -*-
"""fileshare —— 共享(UNC)文件访问:列目录(可按后缀筛选)+ 复制到本地。
插件里只做两件事:先列,再取。
import fileshare
# 可选:共享需要账号密码时才调;不调 = 用当前 Windows 登录身份
fileshare.configure(user=r"域\账号", password="***")
# 1) 传共享文件夹地址 + 后缀筛选,拿到文件清单(不下载,只读元数据)
files = fileshare.list_files(r"\\172.30.31.189\资料\人资\考勤月报封存检查", ".xlsx")
# [FileInfo(name='2026.11月报.xlsx', path='\\\\...', size=48213, mtime=...), ...]
# 2) 插件自己判断要哪个,再让 SDK 复制过来
local = fileshare.copy_file(files[0], r"D:\工作\月报.xlsx")
设计要点
--------
- 只做「列」和「取」,不猜业务:不排序优先、不自动挑最新,判断权留给插件。
- 列目录用 ``os.scandir``:UNC 上逐文件 ``stat`` 是 N 次网络往返,scandir 一次遍历
就带齐 size/mtime(Windows 由 FindFirstFile/FindNextFile 完成),几十个文件也不会慢。
- 复制落盘用 ``.part`` + 原子改名:别的进程不会读到半个文件,中断也不留残缺目标。
- 同名 + 同大小 + 同时间戳默认跳过:同一插件重复运行不重复拉取大文件。
- 零第三方依赖:当前身份走标准库;需要账号密码时用系统 ``mpr.dll``
(``WNetAddConnection2W``),不依赖 pywin32 / smbprotocol。
已知限制
--------
``WNetAddConnection2`` 是登录会话级的(与 ``net use`` 同一机制),**同一台服务器
不允许两套凭据**(会报 1219)。不同服务器/不同共享各自配置账号不受影响;若将来确实
需要同机多凭据,再引入 smbprotocol 的进程级会话(见 README)。
"""
from __future__ import annotations
import atexit
import ctypes
import fnmatch
import os
import re
import shutil
import time
from dataclasses import dataclass
from datetime import datetime
from typing import Callable, List, Optional, Sequence, Tuple, Union
__version__ = "0.1.0"
__all__ = [
"FileInfo",
"configure",
"list_files",
"copy_file",
"exists",
"mode",
"close",
]
# ==================== 常量 ====================
_RETRY = 3 # 网络类错误重试次数(项目规范:最多 3 次)
_CHUNK = 1024 * 1024 # 复制缓冲 1MB,大文件不进内存
_MTIME_TOLERANCE = 2.0 # 跳过重复时允许的时间戳误差(秒,SMB 精度)
_RESOURCETYPE_DISK = 0x00000001
_CONNECT_TEMPORARY = 0x00000004
_ERROR_ALREADY_ASSIGNED = 85
# 访问模式缓存(进程内,一个插件一次运行一个进程)
_CREDS = {"user": "", "password": ""}
_CONNECTED: set = set()
# Win32 错误码 → 人话(凭据/网络类,插件日志直接看得懂)
_HINT = {
2: "路径不存在",
3: "路径不存在",
5: "拒绝访问:该账号没有此共享的权限",
53: "找不到网络路径:主机不可达,或 445 端口被防火墙拦截",
67: "找不到网络名:共享名写错或共享已被删除",
86: "账号或密码不正确",
1219: "凭据冲突:该服务器已用其它账号连接过(重启本机后再试,或统一用同一个共享账号)",
1272: "共享端禁止匿名/来宾访问,必须配置账号密码",
1326: "当前 Windows 身份未被共享接受,请填写共享账号/密码后重试",
}
# ==================== 数据结构 ====================
@dataclass(frozen=True)
class FileInfo:
"""共享里的一个文件。``name`` 是文件名,``path`` 是完整 UNC 路径。"""
name: str
path: str
size: int
mtime: datetime
def __str__(self) -> str: # 让 copy_file(files[0], ...) 和打印都直观
return self.path
@property
def ext(self) -> str:
return os.path.splitext(self.name)[1].lower()
@property
def size_mb(self) -> float:
return round(self.size / 1048576.0, 2)
# ==================== 凭据与连接 ====================
class _NETRESOURCEW(ctypes.Structure):
_fields_ = [
("dwScope", ctypes.c_uint32),
("dwType", ctypes.c_uint32),
("dwDisplayType", ctypes.c_uint32),
("dwUsage", ctypes.c_uint32),
("lpLocalName", ctypes.c_wchar_p),
("lpRemoteName", ctypes.c_wchar_p),
("lpComment", ctypes.c_wchar_p),
("lpProvider", ctypes.c_wchar_p),
]
def _mpr():
"""延迟加载 mpr.dll(非 Windows 或调用失败才抛,导入本模块不受影响)。"""
return ctypes.WinDLL("mpr.dll")
def configure(user: str = "", password: str = "") -> None:
"""设置共享访问凭据。**不调用 = 用当前 Windows 登录身份**。
Args:
user: 共享账号,``域\\账号`` 或 ``主机名\\账号`` 或裸账号;留空 = 当前身份。
password: 对应密码;账号留空时忽略。
"""
close() # 换凭据前先断开旧连接,避免 1219
_CREDS["user"] = (user or "").strip()
_CREDS["password"] = (password or "").strip()
def mode() -> str:
"""当前访问模式,插件启动时打一行日志,分布式排查时一眼看出走的哪条路。"""
if _CREDS["user"]:
return f"显式凭据({_CREDS['user']})"
return "当前 Windows 身份"
def _share_of(path: str) -> str:
"""从任意 UNC 路径截出共享根 ``\\\\host\\share``(WNet 只认到共享级)。"""
p = str(path).replace("/", "\\")
if not p.startswith("\\\\") or p.startswith("\\\\?\\"):
raise ValueError(f"不是合法的共享路径(需要 \\\\主机\\共享):{path}")
parts = [x for x in p.lstrip("\\").split("\\") if x]
if len(parts) < 2:
raise ValueError(f"不是合法的共享路径(需要 \\\\主机\\共享):{path}")
return "\\\\" + "\\".join(parts[:2])
def _forget(path: str) -> None:
"""访问失败后作废该共享的连接缓存(下次重连;本地路径忽略)。"""
try:
_CONNECTED.discard(_share_of(path))
except ValueError:
pass
def _wnet_connect(share: str, user: str, password: str) -> None:
"""用显式凭据建立共享连接(会话级,临时连接不落注册表)。"""
mpr = _mpr()
mpr.WNetAddConnection2W.argtypes = [
ctypes.POINTER(_NETRESOURCEW), ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32,
]
mpr.WNetAddConnection2W.restype = ctypes.c_uint32
nr = _NETRESOURCEW()
nr.dwType = _RESOURCETYPE_DISK
nr.lpRemoteName = share
rc = mpr.WNetAddConnection2W(ctypes.byref(nr), password, user, _CONNECT_TEMPORARY)
if rc in (0, _ERROR_ALREADY_ASSIGNED):
return
raise ctypes.WinError(rc)
def close() -> None:
"""断开本进程建立的共享连接(进程退出自动调用,不污染后续插件)。"""
if not _CONNECTED:
return
try:
mpr = _mpr()
mpr.WNetCancelConnection2W.argtypes = [ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_int]
mpr.WNetCancelConnection2W.restype = ctypes.c_uint32
for share in list(_CONNECTED):
mpr.WNetCancelConnection2W(share, 0, 1)
except Exception: # noqa: BLE001 清理失败不影响主流程
pass
finally:
_CONNECTED.clear()
def _ensure(path: str) -> None:
"""首次访问某共享时建立连接(无凭据/本地路径则什么也不做)。"""
if not _CREDS["user"]:
return
try:
share = _share_of(path)
except ValueError:
return # 本地路径不需要建连接
if share in _CONNECTED:
return
_wnet_connect(share, _CREDS["user"], _CREDS["password"])
_CONNECTED.add(share)
def _explain(err: BaseException, path: str = "") -> str:
code = getattr(err, "winerror", None) or getattr(err, "errno", None)
hint = _HINT.get(int(code)) if code else None
if hint is None:
hint = "共享访问失败"
where = f"({path})" if path else ""
return f"{hint}{where} → {type(err).__name__}: {err}"
# ==================== 路径与后缀 ====================
def _norm(path: str) -> str:
p = str(path).strip().strip('"')
if not p:
raise ValueError("路径为空")
return os.path.normpath(p)
def _normalize_ext(ext: Union[str, Sequence[str], None]) -> Optional[Tuple[str, ...]]:
"""后缀归一:``".xlsx"`` / ``"xlsx"`` / ``[".xlsx", ".xls"]`` / ``"xlsx,xls"`` 都认。"""
if not ext:
return None
if isinstance(ext, str):
parts = [p for p in re.split(r"[,;|\s]+", ext) if p]
else:
parts = [str(p) for p in ext]
out = []
for p in parts:
p = p.strip().lower()
if p:
out.append(p if p.startswith(".") else "." + p)
return tuple(out) or None
def _match(name: str, exts: Optional[Tuple[str, ...]], pattern: Optional[str]) -> bool:
lower = name.lower()
if exts and not lower.endswith(exts):
return False
if pattern and not fnmatch.fnmatch(lower, pattern.lower()):
return False
return True
# ==================== 列目录 ====================
def list_files(folder: str,
ext: Union[str, Sequence[str], None] = None,
pattern: Optional[str] = None,
recursive: bool = False,
sort: str = "name",
reverse: bool = False,
retry: int = _RETRY) -> List[FileInfo]:
"""列出共享文件夹里的文件(只读元数据,不下载)。
Args:
folder: 共享文件夹地址,如 ``\\\\172.30.31.189\\资料\\人资\\考勤月报封存检查``。
ext: 后缀筛选,``".xlsx"`` / ``"xlsx"`` / ``[".xlsx", ".xls"]`` / ``"xlsx,xls"``;
不传 = 全部文件。
pattern: 文件名通配(``fnmatch`` 语法),如 ``"*2026.11*"``;与 ext 同时生效(取交集)。
recursive: 是否递归子目录(默认只列当前层)。
sort: 排序字段,``"name"``(默认,按文件名)/ ``"mtime"``(修改时间)/ ``"size"``;
传 ``None``/``""`` 保持系统返回顺序。
reverse: 是否倒序(``sort="mtime", reverse=True`` 即最新在前)。
retry: 网络类错误重试次数。
Returns:
``FileInfo`` 列表;目录存在但没有匹配文件时返回空列表(不抛错)。
Raises:
RuntimeError: 目录不存在 / 无权限 / 需要凭据 / 主机不可达,消息里带可操作的提示。
"""
root = _norm(folder)
exts = _normalize_ext(ext)
items: List[FileInfo] = []
def _scan(cur: str):
with os.scandir(cur) as it:
for entry in it:
try:
if entry.is_dir(follow_symlinks=False):
if recursive:
yield ("dir", cur, entry)
continue
if entry.is_file(follow_symlinks=False):
yield ("file", cur, entry)
except OSError:
continue # 单个条目读不到不影响整批
last: Optional[BaseException] = None
for attempt in range(max(1, int(retry))):
try:
_ensure(root)
items.clear()
stack = [root]
while stack:
cur = stack.pop()
for kind, dirpath, entry in _scan(cur):
if kind == "dir":
stack.append(entry.path)
continue
if not _match(entry.name, exts, pattern):
continue
st = entry.stat()
items.append(FileInfo(
name=entry.name,
path=entry.path,
size=st.st_size,
mtime=datetime.fromtimestamp(st.st_mtime),
))
last = None
break
except OSError as err: # noqa: PERF203
last = err
_forget(root)
if getattr(err, "winerror", None) in _HINT:
break # 凭据/路径类错误重试无意义
if attempt + 1 < max(1, int(retry)):
time.sleep(1.0 * (attempt + 1))
if last is not None:
raise RuntimeError(_explain(last, root)) from last
key = (sort or "").lower()
if key == "mtime":
items.sort(key=lambda x: x.mtime, reverse=reverse)
elif key == "size":
items.sort(key=lambda x: x.size, reverse=reverse)
elif key == "name":
items.sort(key=lambda x: x.name.lower(), reverse=reverse)
return items
def exists(path: str) -> bool:
"""共享里该路径是否存在(不抛错,权限/网络问题一律 False)。"""
try:
p = _norm(path)
_ensure(p)
return os.path.exists(p)
except (OSError, ValueError):
return False
# ==================== 复制到本地 ====================
def _resolve_dst(src_path: str, dst: str) -> str:
d = str(dst).strip().strip('"')
if not d:
raise ValueError("目标路径为空")
if os.path.isdir(d) or d.endswith(("\\", "/")):
return os.path.join(d, os.path.basename(src_path))
return _norm(d)
def _try_remove(path: str) -> None:
try:
os.remove(path)
except OSError:
pass
def copy_file(src: Union[FileInfo, str],
dst: str,
overwrite: bool = True,
skip_if_same: bool = True,
progress: Optional[Callable[[int, int], None]] = None,
retry: int = _RETRY) -> str:
"""把共享里的一个文件复制到本地,返回本地路径。
Args:
src: ``list_files`` 返回的 ``FileInfo``,或完整的 UNC 文件路径。
dst: 本地目标。传**目录**(已存在或以 ``\\``/``/`` 结尾)时按源文件名落进去;
否则视为完整文件路径(父目录自动创建)。
overwrite: 目标已存在时是否覆盖;``False`` 且已存在则直接报错。
skip_if_same: 目标已存在且大小、修改时间一致时跳过(返回原路径,不重复下载)。
progress: 进度回调 ``fn(已复制字节, 总字节)``,大文件接壳子的进度上报。
retry: 网络类错误重试次数。
Returns:
本地文件的绝对路径。
Raises:
RuntimeError: 源不存在 / 无权限 / 需要凭据 / 网络中断,消息里带可操作的提示。
"""
if isinstance(src, FileInfo):
src_path = src.path
else:
src_path = _norm(src)
dst_path = _resolve_dst(src_path, dst)
parent = os.path.dirname(dst_path)
if parent:
os.makedirs(parent, exist_ok=True)
last: Optional[BaseException] = None
for attempt in range(max(1, int(retry))):
part = f"{dst_path}.part{os.getpid()}"
try:
_ensure(src_path)
st = os.stat(src_path)
if os.path.isdir(dst_path):
raise RuntimeError(f"目标是一个目录,不能当文件写:{dst_path}")
if os.path.isfile(dst_path):
if skip_if_same:
dst_st = os.stat(dst_path)
if (dst_st.st_size == st.st_size
and abs(dst_st.st_mtime - st.st_mtime) <= _MTIME_TOLERANCE):
return os.path.abspath(dst_path)
if not overwrite:
raise RuntimeError(f"目标已存在且 overwrite=False:{dst_path}")
total = 0
with open(src_path, "rb") as fsrc, open(part, "wb") as fdst:
while True:
buf = fsrc.read(_CHUNK)
if not buf:
break
fdst.write(buf)
total += len(buf)
if progress:
try:
progress(total, st.st_size)
except Exception: # noqa: BLE001 回调异常不影响复制
pass
os.replace(part, dst_path) # 原子落盘:不会出现半个文件
try:
os.utime(dst_path, (time.time(), st.st_mtime)) # 保留源时间戳,供下轮跳过判断
except OSError:
pass
return os.path.abspath(dst_path)
except OSError as err: # noqa: PERF203
last = err
_try_remove(part)
_forget(src_path)
if getattr(err, "winerror", None) in _HINT:
break
if attempt + 1 < max(1, int(retry)):
time.sleep(1.0 * (attempt + 1))
except RuntimeError:
_try_remove(part)
raise
raise RuntimeError(_explain(last, src_path)) from last
atexit.register(close)
+168
View File
@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
"""离线自测:本地临时目录模拟共享,验证列目录 / 后缀筛选 / 复制 / 跳过重复。
运行:
.venv\\Scripts\\python.exe -m fileshare._selftest
(或 cd libs\\fileshare; ..\\..\\.venv\\Scripts\\python.exe -m fileshare._selftest)
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import fileshare # noqa: E402
TMP = tempfile.mkdtemp(prefix="fileshare_selftest_")
_passed = 0
_progress_hits = []
def ok(cond: bool, msg: str) -> None:
global _passed
if not cond:
raise AssertionError(f"[FAIL] {msg}")
_passed += 1
print(f"[PASS] {msg}")
def build_share() -> str:
"""造一个「共享目录」:两层结构 + 多种后缀 + 不同时间戳。"""
root = os.path.join(TMP, "share", "资料", "考勤月报封存检查")
os.makedirs(os.path.join(root, "历史"), exist_ok=True)
files = {
"2026.09月报.xlsx": 1024,
"2026.10月报.xlsx": 2048,
"2026.11月报.xlsx": 4096,
"说明.txt": 128,
"旧表.xls": 512,
"历史/2025.12月报.xlsx": 256,
}
for i, (name, size) in enumerate(files.items()):
p = os.path.join(root, name)
with open(p, "wb") as f:
f.write(b"x" * size)
ts = time.time() - (100 - i) * 86400 # 越靠后越新
os.utime(p, (ts, ts))
return root
def main() -> int:
root = build_share()
# ---- 1. 内部工具:后缀归一 / 共享根解析 ----
ok(fileshare._normalize_ext(".xlsx") == (".xlsx",), "后缀归一:单字符串")
ok(fileshare._normalize_ext("xlsx,XLS") == (".xlsx", ".xls"), "后缀归一:逗号分隔 + 大小写")
ok(fileshare._normalize_ext([".xlsx", ".xls"]) == (".xlsx", ".xls"), "后缀归一:列表")
ok(fileshare._normalize_ext(None) is None, "后缀归一:None")
ok(fileshare._share_of(r"\\172.30.31.189\资料\人资\a.xlsx") == r"\\172.30.31.189\资料",
"共享根解析:截到共享级")
try:
fileshare._share_of(r"C:\temp\a.xlsx")
ok(False, "共享根解析:非 UNC 应报错")
except ValueError:
ok(True, "共享根解析:非 UNC 报错")
# ---- 2. 列目录:不带筛选 ----
all_files = fileshare.list_files(root)
ok(len(all_files) == 5, f"列当前层全部文件(不含子目录)→ {len(all_files)}")
# ---- 3. 后缀筛选 ----
xlsx = fileshare.list_files(root, ".xlsx")
ok(len(xlsx) == 3 and all(f.ext == ".xlsx" for f in xlsx), "后缀筛选:.xlsx → 3 个")
multi = fileshare.list_files(root, "xlsx,xls")
ok(len(multi) == 4, "后缀筛选:xlsx,xls → 4 个")
# ---- 4. 文件名通配(与后缀取交集)----
nov = fileshare.list_files(root, ".xlsx", pattern="*2026.11*")
ok(len(nov) == 1 and nov[0].name == "2026.11月报.xlsx", "通配 + 后缀交集 → 精确 1 个")
# ---- 5. 递归 ----
deep = fileshare.list_files(root, ".xlsx", recursive=True)
ok(len(deep) == 4, "递归:含历史子目录 → 4 个 xlsx")
# ---- 6. 排序 ----
by_name = fileshare.list_files(root, ".xlsx", sort="name")
ok([f.name for f in by_name] == sorted(f.name for f in by_name), "排序:按名称升序")
by_mtime = fileshare.list_files(root, ".xlsx", sort="mtime", reverse=True)
ok(by_mtime[0].name == "2026.11月报.xlsx", "排序:mtime 倒序 → 最新在前")
# ---- 7. 元数据 ----
f11 = fileshare.list_files(root, ".xlsx", pattern="*2026.11*")[0]
ok(f11.size == 4096, "元数据:size 正确")
ok(f11.mtime.year == time.localtime().tm_year, "元数据:mtime 是 datetime")
ok(str(f11) == f11.path, "元数据:str(FileInfo) 就是完整路径")
# ---- 8. 空目录 / 不存在目录 ----
empty = os.path.join(TMP, "share", "空目录")
os.makedirs(empty, exist_ok=True)
ok(fileshare.list_files(empty) == [], "空目录返回空列表(不抛错)")
try:
fileshare.list_files(os.path.join(TMP, "share", "不存在的目录"))
ok(False, "不存在目录应报错")
except RuntimeError as e:
ok("路径不存在" in str(e) or "共享访问失败" in str(e), f"不存在目录报可读错误:{e}")
# ---- 9. 复制到目录(自动拼文件名)----
out_dir = os.path.join(TMP, "out")
os.makedirs(out_dir, exist_ok=True)
local1 = fileshare.copy_file(f11, out_dir)
ok(os.path.isfile(local1) and os.path.basename(local1) == f11.name, "复制到目录:按源文件名落地")
ok(os.path.getsize(local1) == 4096, "复制到目录:内容完整")
# ---- 10. 复制到完整路径(父目录自动创建)+ 进度回调 ----
target = os.path.join(TMP, "deep", "nested", "月报副本.xlsx")
local2 = fileshare.copy_file(f11.path, target,
progress=lambda done, total: _progress_hits.append((done, total)))
ok(os.path.isfile(local2) and local2.endswith("月报副本.xlsx"), "复制到完整路径:父目录自动创建")
ok(bool(_progress_hits) and _progress_hits[-1][0] == _progress_hits[-1][1], "进度回调:走完且累计字节=总字节")
# ---- 11. 跳过重复 ----
_progress_hits.clear()
again = fileshare.copy_file(f11, out_dir, progress=lambda d, t: _progress_hits.append((d, t)))
ok(again == local1 and not _progress_hits, "跳过重复:同大小同时间戳不再下载")
# ---- 12. overwrite=False ----
try:
fileshare.copy_file(f11, local1, overwrite=False, skip_if_same=False)
ok(False, "overwrite=False 且已存在应报错")
except RuntimeError as e:
ok("overwrite=False" in str(e), "overwrite=False:明确报错")
# ---- 13. 原子落盘:不留 .part ----
leftovers = [n for n in os.listdir(out_dir) if ".part" in n]
ok(not leftovers, "原子落盘:目录里没有 .part 残留")
# ---- 14. 源不存在 ----
try:
fileshare.copy_file(os.path.join(root, "没有这个.xlsx"), out_dir)
ok(False, "源不存在应报错")
except RuntimeError as e:
ok(True, f"源不存在报可读错误:{e}")
# ---- 15. exists ----
ok(fileshare.exists(f11.path), "exists:共享内文件 → True")
ok(not fileshare.exists(os.path.join(root, "没有这个.xlsx")), "exists:不存在 → False")
# ---- 16. 模式 / 凭据 ----
ok("当前 Windows 身份" in fileshare.mode(), f"mode:默认走当前身份 → {fileshare.mode()}")
fileshare.configure(user=r"域\bot", password="***")
ok("显式凭据" in fileshare.mode(), "mode:配置后为显式凭据")
fileshare.configure() # 复原,避免影响后续用例
print(f"\n全部通过:{_passed} 项")
return 0
if __name__ == "__main__":
code = 1
try:
code = main()
finally:
fileshare.close()
shutil.rmtree(TMP, ignore_errors=True)
sys.exit(code)
+17
View File
@@ -0,0 +1,17 @@
[build-system]
requires = ["setuptools>=64"]
build-backend = "setuptools.build_meta"
[project]
name = "fileshare"
version = "0.1.0"
description = "共享目录文件访问:列文件(可按后缀筛选)+ 复制到本地(当前身份或显式账号)"
readme = "README.md"
requires-python = ">=3.9"
dependencies = []
[project.urls]
Repository = "https://github.com/37du/37duAutomation"
[tool.setuptools]
packages = ["fileshare"]
+3
View File
@@ -0,0 +1,3 @@
# fileshare 零第三方依赖(纯标准库:os / shutil / ctypes)。
# 需要账号密码的共享走系统 mpr.dll(WNetAddConnection2W),不依赖 pywin32 / smbprotocol。
# 因此本 SDK 的 sdk.json deps 为空,执行机不需要额外预装任何东西。
+15
View File
@@ -0,0 +1,15 @@
{
"schema_version": 1,
"id": "fileshare",
"name": "共享文件访问 SDK",
"version": "0.1.0",
"description": "按共享(UNC)目录列出文件并支持后缀筛选,再把选定文件复制到本地:支持当前 Windows 身份与显式账号密码,零第三方依赖",
"provides": [
"fileshare"
],
"deps": [],
"python": ">=3.9",
"minRuntimeVersion": "",
"selftest": "fileshare._selftest:main",
"api": "api.json"
}