swarmauri_tool_findfile 0.1.0.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- swarmauri_tool_findfile/FindFileTool.py +163 -0
- swarmauri_tool_findfile/__init__.py +17 -0
- swarmauri_tool_findfile/_filesystem.py +273 -0
- swarmauri_tool_findfile/_windows_fs.py +349 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/METADATA +185 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/RECORD +10 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/WHEEL +4 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/entry_points.txt +3 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/licenses/LICENSE +201 -0
- swarmauri_tool_findfile-0.1.0.dev1.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import fnmatch
|
|
2
|
+
import stat
|
|
3
|
+
from contextlib import closing
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, List, Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import Field
|
|
8
|
+
|
|
9
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
10
|
+
from swarmauri_base.tools.ToolBase import ToolBase
|
|
11
|
+
from swarmauri_standard.tools.Parameter import Parameter
|
|
12
|
+
|
|
13
|
+
from . import _filesystem
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@ComponentBase.register_type(ToolBase, "FindFileTool")
|
|
17
|
+
class FindFileTool(ToolBase):
|
|
18
|
+
"""Find files under a directory by name or wildcard pattern."""
|
|
19
|
+
|
|
20
|
+
version: str = "0.1.dev1"
|
|
21
|
+
allowed_roots: List[str] = Field(
|
|
22
|
+
default_factory=lambda: [str(Path.cwd())],
|
|
23
|
+
description="Trusted absolute directories set by the service owner.",
|
|
24
|
+
)
|
|
25
|
+
max_scanned_entries: int = Field(default=100_000, ge=1)
|
|
26
|
+
max_results: int = Field(default=10_000, ge=1)
|
|
27
|
+
max_return_bytes: int = Field(default=1024 * 1024, ge=1)
|
|
28
|
+
max_elapsed_seconds: float = Field(default=2.0, gt=0, allow_inf_nan=False)
|
|
29
|
+
max_depth: int = Field(default=64, ge=0)
|
|
30
|
+
max_pattern_length: int = Field(default=1024, ge=1)
|
|
31
|
+
parameters: List[Parameter] = Field(
|
|
32
|
+
default_factory=lambda: [
|
|
33
|
+
Parameter(
|
|
34
|
+
name="path",
|
|
35
|
+
input_type="string",
|
|
36
|
+
description=("Directory to search. A leading ~ is expanded."),
|
|
37
|
+
required=True,
|
|
38
|
+
),
|
|
39
|
+
Parameter(
|
|
40
|
+
name="pattern",
|
|
41
|
+
input_type="string",
|
|
42
|
+
description=(
|
|
43
|
+
"Shell-style wildcard matched case-insensitively "
|
|
44
|
+
"against each file name, for example *.log or report?.txt."
|
|
45
|
+
),
|
|
46
|
+
required=True,
|
|
47
|
+
),
|
|
48
|
+
Parameter(
|
|
49
|
+
name="recursive",
|
|
50
|
+
input_type="boolean",
|
|
51
|
+
description=(
|
|
52
|
+
"Also search subdirectories. Defaults to false, which "
|
|
53
|
+
"checks only the top level."
|
|
54
|
+
),
|
|
55
|
+
required=False,
|
|
56
|
+
),
|
|
57
|
+
]
|
|
58
|
+
)
|
|
59
|
+
name: str = "FindFileTool"
|
|
60
|
+
description: str = (
|
|
61
|
+
"Searches a directory for files whose name matches a shell-style "
|
|
62
|
+
"wildcard, case-insensitively, optionally walking subdirectories."
|
|
63
|
+
)
|
|
64
|
+
type: Literal["FindFileTool"] = "FindFileTool"
|
|
65
|
+
|
|
66
|
+
def __call__(
|
|
67
|
+
self, path: str, pattern: str, recursive: bool = False
|
|
68
|
+
) -> Dict[str, object]:
|
|
69
|
+
"""Find bounded regular-file matches through trusted directory handles.
|
|
70
|
+
|
|
71
|
+
Matching is case-insensitive against basenames. Symlinks and special
|
|
72
|
+
files are excluded in both modes. Failures return no partial matches.
|
|
73
|
+
"""
|
|
74
|
+
display = path if isinstance(path, str) else ""
|
|
75
|
+
try:
|
|
76
|
+
if not isinstance(path, str) or not path.strip():
|
|
77
|
+
raise ValueError("path must be a non-empty string")
|
|
78
|
+
if (
|
|
79
|
+
not isinstance(pattern, str)
|
|
80
|
+
or not pattern
|
|
81
|
+
or "\x00" in pattern
|
|
82
|
+
):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"pattern must be a non-empty string without NULs"
|
|
85
|
+
)
|
|
86
|
+
if len(pattern) > self.max_pattern_length:
|
|
87
|
+
raise ValueError("pattern exceeds the configured length limit")
|
|
88
|
+
if not isinstance(recursive, bool):
|
|
89
|
+
raise ValueError("recursive must be a boolean")
|
|
90
|
+
target = Path(path).expanduser().absolute()
|
|
91
|
+
display = str(target)
|
|
92
|
+
budget = _filesystem.Budget(
|
|
93
|
+
self.max_scanned_entries,
|
|
94
|
+
self.max_results,
|
|
95
|
+
self.max_return_bytes,
|
|
96
|
+
self.max_elapsed_seconds,
|
|
97
|
+
)
|
|
98
|
+
lowered = pattern.lower()
|
|
99
|
+
matches = []
|
|
100
|
+
|
|
101
|
+
def walk(descriptor, current, relative, depth):
|
|
102
|
+
with closing(
|
|
103
|
+
_filesystem.directory_entries(descriptor)
|
|
104
|
+
) as children:
|
|
105
|
+
for name, mode in children:
|
|
106
|
+
budget.visit()
|
|
107
|
+
if mode is None:
|
|
108
|
+
continue
|
|
109
|
+
if stat.S_ISREG(mode):
|
|
110
|
+
if fnmatch.fnmatchcase(name.lower(), lowered):
|
|
111
|
+
match = str(current / name)
|
|
112
|
+
budget.retain(match)
|
|
113
|
+
matches.append(match)
|
|
114
|
+
elif recursive and stat.S_ISDIR(mode):
|
|
115
|
+
if depth >= self.max_depth:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
"Scan exceeded the directory-depth limit"
|
|
118
|
+
)
|
|
119
|
+
with _filesystem.child_directory(
|
|
120
|
+
descriptor, name, root_fd, relative / name
|
|
121
|
+
) as child:
|
|
122
|
+
walk(
|
|
123
|
+
child,
|
|
124
|
+
current / name,
|
|
125
|
+
relative / name,
|
|
126
|
+
depth + 1,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
with _filesystem.open_directory(target, self.allowed_roots) as (
|
|
130
|
+
descriptor,
|
|
131
|
+
root_fd,
|
|
132
|
+
relative,
|
|
133
|
+
):
|
|
134
|
+
walk(descriptor, target, relative, 0)
|
|
135
|
+
matches.sort()
|
|
136
|
+
result = {
|
|
137
|
+
"path": display,
|
|
138
|
+
"pattern": pattern,
|
|
139
|
+
"count": len(matches),
|
|
140
|
+
"matches": matches,
|
|
141
|
+
}
|
|
142
|
+
budget.finish(result)
|
|
143
|
+
return result
|
|
144
|
+
except FileNotFoundError:
|
|
145
|
+
return self._failure(display, pattern, "Directory does not exist.")
|
|
146
|
+
except NotADirectoryError:
|
|
147
|
+
return self._failure(display, pattern, "Path is not a directory.")
|
|
148
|
+
except (OSError, ValueError, TypeError, RuntimeError) as exc:
|
|
149
|
+
return self._failure(
|
|
150
|
+
display, pattern, f"Could not read directory: {exc}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def _failure(self, target, pattern, message) -> Dict[str, object]:
|
|
154
|
+
return _filesystem.failure_response(
|
|
155
|
+
{
|
|
156
|
+
"path": str(target),
|
|
157
|
+
"pattern": pattern if isinstance(pattern, str) else "",
|
|
158
|
+
"count": 0,
|
|
159
|
+
"matches": [],
|
|
160
|
+
"error": message,
|
|
161
|
+
},
|
|
162
|
+
self.max_return_bytes,
|
|
163
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .FindFileTool import FindFileTool
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
__all__ = ["FindFileTool"]
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
# For Python 3.8 and newer
|
|
8
|
+
from importlib.metadata import version, PackageNotFoundError
|
|
9
|
+
except ImportError:
|
|
10
|
+
# For older Python versions, use the backport
|
|
11
|
+
from importlib_metadata import version, PackageNotFoundError
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = version("swarmauri_tool_findfile")
|
|
15
|
+
except PackageNotFoundError:
|
|
16
|
+
# If the package is not installed (for example, during development)
|
|
17
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Scan directories through held filesystem handles and bound the response."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import errno
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import sys
|
|
10
|
+
import stat
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
_RESOLVE_NO_SYMLINKS = 0x04
|
|
15
|
+
_RESOLVE_BENEATH = 0x08
|
|
16
|
+
_OPENAT2_ARCHES = {
|
|
17
|
+
"x86_64",
|
|
18
|
+
"amd64",
|
|
19
|
+
"i386",
|
|
20
|
+
"i686",
|
|
21
|
+
"aarch64",
|
|
22
|
+
"arm64",
|
|
23
|
+
"armv7l",
|
|
24
|
+
"riscv64",
|
|
25
|
+
"ppc64",
|
|
26
|
+
"ppc64le",
|
|
27
|
+
"s390x",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _OpenHow(ctypes.Structure):
|
|
32
|
+
_fields_ = [
|
|
33
|
+
("flags", ctypes.c_uint64),
|
|
34
|
+
("mode", ctypes.c_uint64),
|
|
35
|
+
("resolve", ctypes.c_uint64),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _directory_flags() -> int:
|
|
40
|
+
"""Refuse platforms without descriptor-relative, no-symlink traversal."""
|
|
41
|
+
if (
|
|
42
|
+
os.open not in os.supports_dir_fd
|
|
43
|
+
or not hasattr(os, "O_DIRECTORY")
|
|
44
|
+
or not hasattr(os, "O_NOFOLLOW")
|
|
45
|
+
or not hasattr(os, "O_CLOEXEC")
|
|
46
|
+
):
|
|
47
|
+
raise OSError(
|
|
48
|
+
errno.ENOTSUP,
|
|
49
|
+
"This platform lacks secure directory-relative file creation",
|
|
50
|
+
)
|
|
51
|
+
return os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _open_root(root: Path, directory_flags: int) -> int:
|
|
55
|
+
"""Anchor a trusted absolute root without following any symlink."""
|
|
56
|
+
descriptor = os.open(root.anchor, directory_flags)
|
|
57
|
+
try:
|
|
58
|
+
if root.parts[1:]:
|
|
59
|
+
opened = _open_root_beneath(
|
|
60
|
+
descriptor, Path(*root.parts[1:]), directory_flags
|
|
61
|
+
)
|
|
62
|
+
if opened is not None:
|
|
63
|
+
os.close(descriptor)
|
|
64
|
+
return opened
|
|
65
|
+
for part in root.parts[1:]:
|
|
66
|
+
child = os.open(part, directory_flags, dir_fd=descriptor)
|
|
67
|
+
os.close(descriptor)
|
|
68
|
+
descriptor = child
|
|
69
|
+
return descriptor
|
|
70
|
+
except BaseException:
|
|
71
|
+
os.close(descriptor)
|
|
72
|
+
raise
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _linux_openat2(root_fd: int, relative: Path, flags: int) -> int | None:
|
|
76
|
+
"""Use kernel-enforced resolution, or signal that it is unavailable."""
|
|
77
|
+
if (
|
|
78
|
+
sys.platform != "linux"
|
|
79
|
+
or platform.machine().lower() not in _OPENAT2_ARCHES
|
|
80
|
+
):
|
|
81
|
+
return None
|
|
82
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
83
|
+
syscall = libc.syscall
|
|
84
|
+
syscall.restype = ctypes.c_long
|
|
85
|
+
how = _OpenHow(
|
|
86
|
+
flags=flags,
|
|
87
|
+
mode=0,
|
|
88
|
+
resolve=_RESOLVE_BENEATH | _RESOLVE_NO_SYMLINKS,
|
|
89
|
+
)
|
|
90
|
+
result = syscall(
|
|
91
|
+
ctypes.c_long(437),
|
|
92
|
+
ctypes.c_int(root_fd),
|
|
93
|
+
ctypes.c_char_p(os.fsencode(relative)),
|
|
94
|
+
ctypes.byref(how),
|
|
95
|
+
ctypes.c_size_t(ctypes.sizeof(how)),
|
|
96
|
+
)
|
|
97
|
+
if result >= 0:
|
|
98
|
+
return int(result)
|
|
99
|
+
code = ctypes.get_errno()
|
|
100
|
+
if code in {errno.ENOSYS, errno.EINVAL, errno.E2BIG}:
|
|
101
|
+
return None
|
|
102
|
+
raise OSError(code, os.strerror(code), str(relative))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# Root establishment and operation lookup use the same kernel primitive.
|
|
106
|
+
_open_root_beneath = _linux_openat2
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _open_direct_child(root_fd: int, relative: Path, flags: int) -> int:
|
|
110
|
+
"""Use a single no-follow lookup when kernel containment is unavailable."""
|
|
111
|
+
if len(relative.parts) != 1:
|
|
112
|
+
raise OSError(errno.ENOTSUP, "Nested paths require Linux openat2")
|
|
113
|
+
return os.open(relative.name, flags, 0o666, dir_fd=root_fd)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@contextmanager
|
|
117
|
+
def open_directory(target: Path, allowed_roots: list[str]):
|
|
118
|
+
"""Open beneath a trusted root without following any symlink."""
|
|
119
|
+
if "\x00" in str(target) or ".." in target.parts:
|
|
120
|
+
raise ValueError("NUL characters and parent traversal are not allowed")
|
|
121
|
+
if not allowed_roots:
|
|
122
|
+
raise ValueError("allowed_roots must contain a trusted directory")
|
|
123
|
+
roots = []
|
|
124
|
+
for spelling in allowed_roots:
|
|
125
|
+
root = Path(spelling).expanduser()
|
|
126
|
+
if not root.is_absolute() or ".." in root.parts:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
"allowed_roots must be absolute without parent traversal"
|
|
129
|
+
)
|
|
130
|
+
if target.is_relative_to(root):
|
|
131
|
+
roots.append(root)
|
|
132
|
+
if not roots:
|
|
133
|
+
raise PermissionError("Path is outside configured allowed_roots")
|
|
134
|
+
root = max(roots, key=lambda candidate: len(candidate.parts))
|
|
135
|
+
relative = target.relative_to(root)
|
|
136
|
+
if os.name == "nt":
|
|
137
|
+
from . import _windows_fs
|
|
138
|
+
|
|
139
|
+
with _windows_fs.directory(
|
|
140
|
+
root.anchor, root.parts[1:] + relative.parts
|
|
141
|
+
) as handle:
|
|
142
|
+
yield handle, None, Path()
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
flags = _directory_flags()
|
|
146
|
+
root_fd = _open_root(root, flags)
|
|
147
|
+
try:
|
|
148
|
+
with _scan_posix(root_fd, relative) as descriptor:
|
|
149
|
+
yield descriptor, root_fd, relative
|
|
150
|
+
finally:
|
|
151
|
+
os.close(root_fd)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@contextmanager
|
|
155
|
+
def _scan_posix(root_fd: int, relative: Path):
|
|
156
|
+
"""Open and recheck each scanned directory against the original root."""
|
|
157
|
+
if not relative.parts:
|
|
158
|
+
yield root_fd
|
|
159
|
+
return
|
|
160
|
+
|
|
161
|
+
def lookup():
|
|
162
|
+
flags = _directory_flags()
|
|
163
|
+
descriptor = _linux_openat2(root_fd, relative, flags)
|
|
164
|
+
return (
|
|
165
|
+
_open_direct_child(root_fd, relative, flags)
|
|
166
|
+
if descriptor is None
|
|
167
|
+
else descriptor
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
descriptor = lookup()
|
|
171
|
+
try:
|
|
172
|
+
yield descriptor
|
|
173
|
+
current = lookup()
|
|
174
|
+
try:
|
|
175
|
+
if not os.path.samestat(os.fstat(descriptor), os.fstat(current)):
|
|
176
|
+
raise PermissionError("Directory changed during scan")
|
|
177
|
+
finally:
|
|
178
|
+
os.close(current)
|
|
179
|
+
finally:
|
|
180
|
+
os.close(descriptor)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@contextmanager
|
|
184
|
+
def child_directory(
|
|
185
|
+
parent_fd: int, name: str, root_fd: int | None, relative: Path
|
|
186
|
+
):
|
|
187
|
+
"""Open from the original POSIX root or the held Windows parent."""
|
|
188
|
+
if root_fd is not None:
|
|
189
|
+
with _scan_posix(root_fd, relative) as descriptor:
|
|
190
|
+
yield descriptor
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
from . import _windows_fs
|
|
194
|
+
|
|
195
|
+
handle = _windows_fs.child_directory(parent_fd, name)
|
|
196
|
+
try:
|
|
197
|
+
yield handle
|
|
198
|
+
finally:
|
|
199
|
+
_windows_fs.close_directory(handle)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def directory_entries(descriptor: int):
|
|
203
|
+
"""Yield entry names and types without following links."""
|
|
204
|
+
if os.name == "nt":
|
|
205
|
+
from . import _windows_fs
|
|
206
|
+
|
|
207
|
+
yield from _windows_fs.directory_entries(descriptor)
|
|
208
|
+
return
|
|
209
|
+
with os.scandir(descriptor) as children:
|
|
210
|
+
for child in children:
|
|
211
|
+
yield (
|
|
212
|
+
child.name,
|
|
213
|
+
stat.S_IFMT(child.stat(follow_symlinks=False).st_mode),
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Budget:
|
|
218
|
+
"""Bound entries, retained JSON output, and scan time."""
|
|
219
|
+
|
|
220
|
+
def __init__(self, scanned: int, results: int, size: int, seconds: float):
|
|
221
|
+
self.max_scanned = scanned
|
|
222
|
+
self.max_results = results
|
|
223
|
+
self.max_bytes = size
|
|
224
|
+
self.deadline = time.monotonic() + seconds
|
|
225
|
+
self.scanned = 0
|
|
226
|
+
self.results = 0
|
|
227
|
+
self.size = 0
|
|
228
|
+
|
|
229
|
+
def check(self) -> None:
|
|
230
|
+
if time.monotonic() > self.deadline:
|
|
231
|
+
raise ValueError("Scan exceeded the elapsed-time limit")
|
|
232
|
+
|
|
233
|
+
def visit(self) -> None:
|
|
234
|
+
self.check()
|
|
235
|
+
self.scanned += 1
|
|
236
|
+
if self.scanned > self.max_scanned:
|
|
237
|
+
raise ValueError("Scan exceeded the scanned-entry limit")
|
|
238
|
+
|
|
239
|
+
def retain(self, item: object) -> None:
|
|
240
|
+
self.check()
|
|
241
|
+
self.results += 1
|
|
242
|
+
self.size += (
|
|
243
|
+
len(json.dumps(item, ensure_ascii=True).encode("utf-8")) + 2
|
|
244
|
+
)
|
|
245
|
+
if self.results > self.max_results:
|
|
246
|
+
raise ValueError("Scan exceeded the result limit")
|
|
247
|
+
if self.size > self.max_bytes:
|
|
248
|
+
raise ValueError("Scan exceeded the returned-byte limit")
|
|
249
|
+
|
|
250
|
+
def finish(self, result: dict) -> None:
|
|
251
|
+
self.check()
|
|
252
|
+
if (
|
|
253
|
+
len(json.dumps(result, ensure_ascii=True).encode("utf-8"))
|
|
254
|
+
> self.max_bytes
|
|
255
|
+
):
|
|
256
|
+
raise ValueError("Scan exceeded the returned-byte limit")
|
|
257
|
+
self.check()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def failure_response(result: dict, limit: int) -> dict:
|
|
261
|
+
"""Bound echoed input and diagnostic output, retaining a useful error."""
|
|
262
|
+
# Keep room for a structured error even with tiny success budgets.
|
|
263
|
+
limit = max(256, min(limit, 4096))
|
|
264
|
+
for key, value in result.items():
|
|
265
|
+
if isinstance(value, str) and len(value) > limit:
|
|
266
|
+
result[key] = value[: limit - 3] + "..."
|
|
267
|
+
while len(json.dumps(result, ensure_ascii=True).encode("utf-8")) > limit:
|
|
268
|
+
key = max(
|
|
269
|
+
(key for key, value in result.items() if isinstance(value, str)),
|
|
270
|
+
key=lambda key: len(result[key]),
|
|
271
|
+
)
|
|
272
|
+
result[key] = result[key][: len(result[key]) // 2]
|
|
273
|
+
return result
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Open one Windows path component at a time from a held directory handle."""
|
|
2
|
+
|
|
3
|
+
import ctypes
|
|
4
|
+
import errno
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from ctypes import wintypes
|
|
7
|
+
|
|
8
|
+
_kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
9
|
+
_nt = ctypes.WinDLL("ntdll")
|
|
10
|
+
|
|
11
|
+
_DIRECTORY = 0x10
|
|
12
|
+
_DEVICE = 0x40
|
|
13
|
+
_REPARSE = 0x400
|
|
14
|
+
_READ_ATTRIBUTES = 0x80
|
|
15
|
+
_SYNCHRONIZE = 0x100000
|
|
16
|
+
_TRAVERSE = 0x20
|
|
17
|
+
_LIST_DIRECTORY = 0x01
|
|
18
|
+
_SHARE_READ_WRITE = 0x3 # Omit FILE_SHARE_DELETE on handles we hold.
|
|
19
|
+
_FILE_OPEN = 1
|
|
20
|
+
_FILE_CREATE = 2
|
|
21
|
+
_DIRECTORY_FILE = 1
|
|
22
|
+
_NON_DIRECTORY_FILE = 0x40
|
|
23
|
+
_SYNCHRONOUS_NONALERT = 0x20
|
|
24
|
+
_OPEN_REPARSE_POINT = 0x200000
|
|
25
|
+
_OBJ_CASE_INSENSITIVE = 0x40
|
|
26
|
+
_OBJ_DONT_REPARSE = 0x1000
|
|
27
|
+
_OPEN_EXISTING = 3
|
|
28
|
+
_BACKUP_SEMANTICS = 0x02000000
|
|
29
|
+
_WIN32_OPEN_REPARSE_POINT = 0x00200000
|
|
30
|
+
_INVALID_HANDLE = ctypes.c_void_p(-1).value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _UnicodeString(ctypes.Structure):
|
|
34
|
+
_fields_ = [
|
|
35
|
+
("Length", wintypes.USHORT),
|
|
36
|
+
("MaximumLength", wintypes.USHORT),
|
|
37
|
+
("Buffer", wintypes.LPWSTR),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _ObjectAttributes(ctypes.Structure):
|
|
42
|
+
_fields_ = [
|
|
43
|
+
("Length", wintypes.ULONG),
|
|
44
|
+
("RootDirectory", wintypes.HANDLE),
|
|
45
|
+
("ObjectName", ctypes.POINTER(_UnicodeString)),
|
|
46
|
+
("Attributes", wintypes.ULONG),
|
|
47
|
+
("SecurityDescriptor", wintypes.LPVOID),
|
|
48
|
+
("SecurityQualityOfService", wintypes.LPVOID),
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _IoStatusBlock(ctypes.Structure):
|
|
53
|
+
_fields_ = [
|
|
54
|
+
("StatusOrPointer", wintypes.LPVOID),
|
|
55
|
+
("Information", ctypes.c_size_t),
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _bind(library, name, result_type, *arg_types):
|
|
60
|
+
function = getattr(library, name)
|
|
61
|
+
function.argtypes = arg_types
|
|
62
|
+
function.restype = result_type
|
|
63
|
+
return function
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_get_volume = _bind(
|
|
67
|
+
_kernel,
|
|
68
|
+
"GetVolumeNameForVolumeMountPointW",
|
|
69
|
+
wintypes.BOOL,
|
|
70
|
+
wintypes.LPCWSTR,
|
|
71
|
+
wintypes.LPWSTR,
|
|
72
|
+
wintypes.DWORD,
|
|
73
|
+
)
|
|
74
|
+
_create_file = _bind(
|
|
75
|
+
_kernel,
|
|
76
|
+
"CreateFileW",
|
|
77
|
+
wintypes.HANDLE,
|
|
78
|
+
wintypes.LPCWSTR,
|
|
79
|
+
wintypes.DWORD,
|
|
80
|
+
wintypes.DWORD,
|
|
81
|
+
wintypes.LPVOID,
|
|
82
|
+
wintypes.DWORD,
|
|
83
|
+
wintypes.DWORD,
|
|
84
|
+
wintypes.HANDLE,
|
|
85
|
+
)
|
|
86
|
+
_close = _bind(_kernel, "CloseHandle", wintypes.BOOL, wintypes.HANDLE)
|
|
87
|
+
_file_type = _bind(_kernel, "GetFileType", wintypes.DWORD, wintypes.HANDLE)
|
|
88
|
+
_file_info = _bind(
|
|
89
|
+
_kernel,
|
|
90
|
+
"GetFileInformationByHandleEx",
|
|
91
|
+
wintypes.BOOL,
|
|
92
|
+
wintypes.HANDLE,
|
|
93
|
+
ctypes.c_int,
|
|
94
|
+
wintypes.LPVOID,
|
|
95
|
+
wintypes.DWORD,
|
|
96
|
+
)
|
|
97
|
+
_nt_create = _bind(
|
|
98
|
+
_nt,
|
|
99
|
+
"NtCreateFile",
|
|
100
|
+
wintypes.LONG,
|
|
101
|
+
ctypes.POINTER(wintypes.HANDLE),
|
|
102
|
+
wintypes.DWORD,
|
|
103
|
+
ctypes.POINTER(_ObjectAttributes),
|
|
104
|
+
ctypes.POINTER(_IoStatusBlock),
|
|
105
|
+
wintypes.LPVOID,
|
|
106
|
+
wintypes.ULONG,
|
|
107
|
+
wintypes.ULONG,
|
|
108
|
+
wintypes.ULONG,
|
|
109
|
+
wintypes.ULONG,
|
|
110
|
+
wintypes.LPVOID,
|
|
111
|
+
wintypes.ULONG,
|
|
112
|
+
)
|
|
113
|
+
_dos_error = _bind(
|
|
114
|
+
_nt,
|
|
115
|
+
"RtlNtStatusToDosError",
|
|
116
|
+
wintypes.ULONG,
|
|
117
|
+
wintypes.LONG,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def close_directory(handle: int) -> None:
|
|
122
|
+
"""Close a directory handle owned by the caller."""
|
|
123
|
+
if not _close(handle):
|
|
124
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _validate_handle(handle: int, *, directory: bool) -> None:
|
|
128
|
+
# FileAttributeTagInfo returns two DWORDs: attributes and reparse tag.
|
|
129
|
+
info = (wintypes.DWORD * 2)()
|
|
130
|
+
if not _file_info(handle, 9, info, ctypes.sizeof(info)):
|
|
131
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
132
|
+
attributes = info[0]
|
|
133
|
+
if attributes & _REPARSE:
|
|
134
|
+
raise PermissionError(
|
|
135
|
+
errno.EACCES, "Windows reparse points and symlinks are forbidden"
|
|
136
|
+
)
|
|
137
|
+
if bool(attributes & _DIRECTORY) != directory:
|
|
138
|
+
if directory:
|
|
139
|
+
raise NotADirectoryError(errno.ENOTDIR, "Expected a directory")
|
|
140
|
+
raise ValueError("Expected a regular file")
|
|
141
|
+
if attributes & _DEVICE or _file_type(handle) != 1: # FILE_TYPE_DISK
|
|
142
|
+
raise ValueError("Expected a disk file or directory")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _checked_handle(handle: int, *, directory: bool) -> int:
|
|
146
|
+
try:
|
|
147
|
+
_validate_handle(handle, directory=directory)
|
|
148
|
+
except BaseException:
|
|
149
|
+
close_directory(handle)
|
|
150
|
+
raise
|
|
151
|
+
return handle
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _open_volume(anchor: str, *, list_entries: bool) -> int:
|
|
155
|
+
if (
|
|
156
|
+
len(anchor) != 3
|
|
157
|
+
or anchor[0]
|
|
158
|
+
not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
159
|
+
or anchor[1:] != ":\\"
|
|
160
|
+
):
|
|
161
|
+
raise ValueError(
|
|
162
|
+
"Use an absolute drive-letter path on a local Windows volume"
|
|
163
|
+
)
|
|
164
|
+
volume = ctypes.create_unicode_buffer(64)
|
|
165
|
+
if not _get_volume(anchor, volume, len(volume)):
|
|
166
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
167
|
+
handle = _create_file(
|
|
168
|
+
volume.value,
|
|
169
|
+
_TRAVERSE
|
|
170
|
+
| _READ_ATTRIBUTES
|
|
171
|
+
| _SYNCHRONIZE
|
|
172
|
+
| (_LIST_DIRECTORY if list_entries else 0),
|
|
173
|
+
_SHARE_READ_WRITE,
|
|
174
|
+
None,
|
|
175
|
+
_OPEN_EXISTING,
|
|
176
|
+
_BACKUP_SEMANTICS | _WIN32_OPEN_REPARSE_POINT,
|
|
177
|
+
None,
|
|
178
|
+
)
|
|
179
|
+
if handle == _INVALID_HANDLE:
|
|
180
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
181
|
+
return _checked_handle(handle, directory=True)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _valid_component(name: str) -> bool:
|
|
185
|
+
# Win32 interprets these basenames as devices even with extensions.
|
|
186
|
+
stem = name.partition(".")[0].rstrip(" ").upper()
|
|
187
|
+
reserved = stem in {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"} or (
|
|
188
|
+
len(stem) == 4
|
|
189
|
+
and stem[:3] in {"COM", "LPT"}
|
|
190
|
+
and stem[3] in "123456789¹²³"
|
|
191
|
+
)
|
|
192
|
+
return not (
|
|
193
|
+
reserved
|
|
194
|
+
or not name
|
|
195
|
+
or name in {".", ".."}
|
|
196
|
+
or name.endswith((" ", "."))
|
|
197
|
+
or any(
|
|
198
|
+
character in '\\/:*?"<>|' or ord(character) < 32
|
|
199
|
+
for character in name
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _component_name(name: str) -> _UnicodeString:
|
|
205
|
+
if not _valid_component(name):
|
|
206
|
+
raise ValueError("Invalid Windows path component")
|
|
207
|
+
raw = name.encode("utf-16-le", errors="surrogatepass")
|
|
208
|
+
if len(raw) > 510:
|
|
209
|
+
raise ValueError("Windows path component exceeds 255 UTF-16 units")
|
|
210
|
+
# Pass counted UTF-16 directly, including non-BMP names.
|
|
211
|
+
buffer = ctypes.create_string_buffer(raw + b"\0\0")
|
|
212
|
+
return _UnicodeString(
|
|
213
|
+
len(raw), len(raw) + 2, ctypes.cast(buffer, wintypes.LPWSTR)
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _open_child(
|
|
218
|
+
parent: int,
|
|
219
|
+
name: str,
|
|
220
|
+
*,
|
|
221
|
+
directory: bool,
|
|
222
|
+
create: bool = False,
|
|
223
|
+
list_entries: bool = False,
|
|
224
|
+
) -> int:
|
|
225
|
+
text = _component_name(name)
|
|
226
|
+
attributes = _ObjectAttributes(
|
|
227
|
+
ctypes.sizeof(_ObjectAttributes),
|
|
228
|
+
parent,
|
|
229
|
+
ctypes.pointer(text),
|
|
230
|
+
_OBJ_CASE_INSENSITIVE | _OBJ_DONT_REPARSE,
|
|
231
|
+
None,
|
|
232
|
+
None,
|
|
233
|
+
)
|
|
234
|
+
access = _TRAVERSE if directory else (2 if create else 1)
|
|
235
|
+
if list_entries:
|
|
236
|
+
access |= _LIST_DIRECTORY
|
|
237
|
+
kind = (
|
|
238
|
+
_DIRECTORY_FILE
|
|
239
|
+
if directory
|
|
240
|
+
else (_NON_DIRECTORY_FILE if create else 0)
|
|
241
|
+
)
|
|
242
|
+
handle = wintypes.HANDLE()
|
|
243
|
+
status = _nt_create(
|
|
244
|
+
ctypes.byref(handle),
|
|
245
|
+
access | _READ_ATTRIBUTES | _SYNCHRONIZE,
|
|
246
|
+
ctypes.byref(attributes),
|
|
247
|
+
ctypes.byref(_IoStatusBlock()),
|
|
248
|
+
None,
|
|
249
|
+
0,
|
|
250
|
+
_SHARE_READ_WRITE,
|
|
251
|
+
_FILE_CREATE if create else _FILE_OPEN,
|
|
252
|
+
kind | _SYNCHRONOUS_NONALERT | _OPEN_REPARSE_POINT,
|
|
253
|
+
None,
|
|
254
|
+
0,
|
|
255
|
+
)
|
|
256
|
+
if status & 0xFFFFFFFF == 0xC000050B:
|
|
257
|
+
raise PermissionError(
|
|
258
|
+
errno.EACCES, "Windows reparse points are forbidden"
|
|
259
|
+
)
|
|
260
|
+
if status < 0:
|
|
261
|
+
error = _dos_error(status)
|
|
262
|
+
if error == 267: # ERROR_DIRECTORY
|
|
263
|
+
raise NotADirectoryError(
|
|
264
|
+
errno.ENOTDIR, "Expected a directory", name
|
|
265
|
+
)
|
|
266
|
+
raise ctypes.WinError(error)
|
|
267
|
+
return _checked_handle(handle.value, directory=directory)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@contextmanager
|
|
271
|
+
def _directories(anchor: str, parts: tuple[str, ...]):
|
|
272
|
+
"""Hold the volume and all traversed directories during the operation."""
|
|
273
|
+
handles = [_open_volume(anchor, list_entries=not parts)]
|
|
274
|
+
try:
|
|
275
|
+
for index, part in enumerate(parts):
|
|
276
|
+
handles.append(
|
|
277
|
+
_open_child(
|
|
278
|
+
handles[-1],
|
|
279
|
+
part,
|
|
280
|
+
directory=True,
|
|
281
|
+
list_entries=index == len(parts) - 1,
|
|
282
|
+
)
|
|
283
|
+
)
|
|
284
|
+
yield handles[-1]
|
|
285
|
+
finally:
|
|
286
|
+
for handle in reversed(handles):
|
|
287
|
+
_close(handle)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@contextmanager
|
|
291
|
+
def directory(anchor: str, parts: tuple[str, ...]):
|
|
292
|
+
"""Yield the held directory handle for an anchored scan."""
|
|
293
|
+
with _directories(anchor, parts) as handle:
|
|
294
|
+
yield handle
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def child_directory(parent: int, name: str) -> int:
|
|
298
|
+
"""Open a scanned directory by its name relative to the held parent."""
|
|
299
|
+
return _open_child(parent, name, directory=True, list_entries=True)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def directory_entries(handle: int):
|
|
303
|
+
"""Stream records from the directory handle in bounded batches."""
|
|
304
|
+
import stat
|
|
305
|
+
import struct
|
|
306
|
+
|
|
307
|
+
# FILE_FULL_DIR_INFO has an eight-byte aligned header and a UTF-16 name.
|
|
308
|
+
# Use a bounded, explicitly aligned buffer for the packed record chain.
|
|
309
|
+
buffer = (ctypes.c_uint64 * 8192)()
|
|
310
|
+
info_class = 15 # FileFullDirectoryRestartInfo
|
|
311
|
+
while _file_info(handle, info_class, buffer, ctypes.sizeof(buffer)):
|
|
312
|
+
data = memoryview(buffer).cast("B")
|
|
313
|
+
offset = 0
|
|
314
|
+
while True:
|
|
315
|
+
next_offset = struct.unpack_from("<I", data, offset)[0]
|
|
316
|
+
attributes, length = struct.unpack_from("<II", data, offset + 56)
|
|
317
|
+
name_start = offset + 68
|
|
318
|
+
end = offset + next_offset if next_offset else len(data)
|
|
319
|
+
if (
|
|
320
|
+
end > len(data)
|
|
321
|
+
or name_start + length > end
|
|
322
|
+
or length % 2
|
|
323
|
+
or (next_offset and next_offset % 8)
|
|
324
|
+
):
|
|
325
|
+
raise OSError(errno.EIO, "Invalid Windows directory record")
|
|
326
|
+
name = bytes(data[name_start : name_start + length]).decode(
|
|
327
|
+
"utf-16-le", errors="surrogatepass"
|
|
328
|
+
)
|
|
329
|
+
if name not in {".", ".."}:
|
|
330
|
+
if not _valid_component(name):
|
|
331
|
+
mode = None
|
|
332
|
+
elif attributes & (_REPARSE | _DEVICE):
|
|
333
|
+
mode = 0
|
|
334
|
+
else:
|
|
335
|
+
mode = (
|
|
336
|
+
stat.S_IFDIR
|
|
337
|
+
if attributes & _DIRECTORY
|
|
338
|
+
else stat.S_IFREG
|
|
339
|
+
)
|
|
340
|
+
yield name, mode
|
|
341
|
+
if not next_offset:
|
|
342
|
+
break
|
|
343
|
+
offset = end
|
|
344
|
+
info_class = (
|
|
345
|
+
14 # FileFullDirectoryInfo, continuing from the held cursor
|
|
346
|
+
)
|
|
347
|
+
error = ctypes.get_last_error()
|
|
348
|
+
if error not in {18, 38}: # ERROR_NO_MORE_FILES / ERROR_HANDLE_EOF
|
|
349
|
+
raise ctypes.WinError(error)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: swarmauri_tool_findfile
|
|
3
|
+
Version: 0.1.0.dev1
|
|
4
|
+
Summary: Swarmauri tool for finding files under a directory by shell-style wildcard name matching, case-insensitively, with optional recursion.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
License-File: NOTICE
|
|
8
|
+
Keywords: swarmauri,tool,findfile,find file,search files,glob,wildcard,pattern matching,case insensitive,recursive search,file system,agent tool
|
|
9
|
+
Author: Jacob Stewart
|
|
10
|
+
Author-email: jacob@swarmauri.com
|
|
11
|
+
Requires-Python: >=3.10,<3.15
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Natural Language :: English
|
|
14
|
+
Classifier: Development Status :: 1 - Planning
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
20
|
+
Classifier: Topic :: System :: Filesystems
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3
|
|
23
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
29
|
+
Requires-Dist: swarmauri_base
|
|
30
|
+
Requires-Dist: swarmauri_core
|
|
31
|
+
Requires-Dist: swarmauri_standard
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<a href="https://pypi.org/project/swarmauri_tool_findfile/">
|
|
38
|
+
<img src="https://img.shields.io/pypi/dm/swarmauri_tool_findfile" alt="PyPI - Downloads"/></a>
|
|
39
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_tool_findfile/">
|
|
40
|
+
<img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_tool_findfile.svg"/></a>
|
|
41
|
+
<a href="https://pypi.org/project/swarmauri_tool_findfile/">
|
|
42
|
+
<img src="https://img.shields.io/pypi/pyversions/swarmauri_tool_findfile" alt="PyPI - Python Version"/></a>
|
|
43
|
+
<a href="https://pypi.org/project/swarmauri_tool_findfile/">
|
|
44
|
+
<img src="https://img.shields.io/pypi/l/swarmauri_tool_findfile" alt="PyPI - License"/></a>
|
|
45
|
+
<a href="https://pypi.org/project/swarmauri_tool_findfile/">
|
|
46
|
+
<img src="https://img.shields.io/pypi/v/swarmauri_tool_findfile?label=swarmauri_tool_findfile&color=green" alt="PyPI - swarmauri_tool_findfile"/></a>
|
|
47
|
+
<a href="https://discord.gg/N4UpBuQv8T">
|
|
48
|
+
<img src="https://img.shields.io/badge/Discord-Join%20Chat-5865F2?logo=discord&logoColor=white" alt="Discord"/></a></p>
|
|
49
|
+
|
|
50
|
+
# Swarmauri Tool Find File
|
|
51
|
+
|
|
52
|
+
`swarmauri_tool_findfile` searches a directory for files whose name matches a
|
|
53
|
+
shell-style wildcard, case-insensitively, with optional recursion into
|
|
54
|
+
subdirectories.
|
|
55
|
+
|
|
56
|
+
## Features
|
|
57
|
+
|
|
58
|
+
- **Wildcard matching** with `*`, `?` and `[seq]`, matched against the file
|
|
59
|
+
name rather than the whole path.
|
|
60
|
+
- **Case-insensitive** on every platform, so `*.LOG` and `*.log` behave the
|
|
61
|
+
same wherever the code runs.
|
|
62
|
+
- **Optional recursion** via `recursive=True`; the default checks one level.
|
|
63
|
+
- **Never follows symbolic links**, so a link cycle cannot make the walk run
|
|
64
|
+
forever.
|
|
65
|
+
- **Returns files, not directories.** This answers "which files match", not
|
|
66
|
+
"what is here".
|
|
67
|
+
- **Reports problems instead of raising**, with the same result shape in every
|
|
68
|
+
case.
|
|
69
|
+
|
|
70
|
+
## Installation
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# With uv
|
|
74
|
+
uv add swarmauri_tool_findfile
|
|
75
|
+
|
|
76
|
+
# With pip
|
|
77
|
+
pip install swarmauri_tool_findfile
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Usage
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from pathlib import Path
|
|
84
|
+
|
|
85
|
+
from swarmauri_tool_findfile import FindFileTool
|
|
86
|
+
|
|
87
|
+
# Build a small tree so the example is reproducible.
|
|
88
|
+
Path("/tmp/logs/archive").mkdir(parents=True, exist_ok=True)
|
|
89
|
+
Path("/tmp/logs/app.log").write_text("x", encoding="utf-8")
|
|
90
|
+
Path("/tmp/logs/archive/old.log").write_text("x", encoding="utf-8")
|
|
91
|
+
|
|
92
|
+
tool = FindFileTool(allowed_roots=["/tmp/logs"])
|
|
93
|
+
|
|
94
|
+
tool(path="/tmp/logs", pattern="*.log")
|
|
95
|
+
# {"path": "/tmp/logs", "pattern": "*.log", "count": 1,
|
|
96
|
+
# "matches": ["/tmp/logs/app.log"]}
|
|
97
|
+
|
|
98
|
+
tool(path="/tmp/logs", pattern="*.log", recursive=True)
|
|
99
|
+
# {"count": 2, "matches": ["/tmp/logs/app.log", "/tmp/logs/archive/old.log"]}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Result keys
|
|
103
|
+
|
|
104
|
+
| Key | Type | Meaning |
|
|
105
|
+
| --- | --- | --- |
|
|
106
|
+
| `path` | `str` | Root directory that was searched |
|
|
107
|
+
| `pattern` | `str` | Pattern as supplied |
|
|
108
|
+
| `count` | `int` | Number of matching files |
|
|
109
|
+
| `matches` | `list[str]` | Absolute paths, sorted |
|
|
110
|
+
| `error` | `str` | Present only when the search could not run |
|
|
111
|
+
|
|
112
|
+
## Expected workflows
|
|
113
|
+
|
|
114
|
+
- **Locate by extension.** `*.csv` before loading a dataset.
|
|
115
|
+
- **Find a report by convention.** `report?.txt` or `2026-*.pdf`.
|
|
116
|
+
- **Scope a bulk action.** Gather matches, then act on the list.
|
|
117
|
+
|
|
118
|
+
## FAQ
|
|
119
|
+
|
|
120
|
+
> **Why case-insensitive by default rather than by flag?**
|
|
121
|
+
> The same tree yields different results on macOS and Linux otherwise, and a
|
|
122
|
+
> search that silently misses `Report.PDF` is the failure mode that hurts.
|
|
123
|
+
|
|
124
|
+
> **Does it follow symlinks?**
|
|
125
|
+
> No. Links are never traversed, so a directory that links back to its parent
|
|
126
|
+
> cannot produce an infinite walk.
|
|
127
|
+
|
|
128
|
+
> **Why does it only return files?**
|
|
129
|
+
> Directories are a different question with a different tool; mixing them makes
|
|
130
|
+
> every caller filter the result.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
## Trusted roots and resource limits
|
|
134
|
+
|
|
135
|
+
Configure `allowed_roots` on the tool from trusted service code. The default is
|
|
136
|
+
its construction-time working directory. Relative requests use the call-time
|
|
137
|
+
working directory and must still lie beneath a configured root. Empty roots
|
|
138
|
+
reject every request. Roots must be absolute; parent traversal and symlinks in
|
|
139
|
+
requested directory paths or root paths are rejected.
|
|
140
|
+
|
|
141
|
+
Where Linux `openat2` is available, lookups use beneath-root resolution.
|
|
142
|
+
If the syscall is unavailable, the POSIX fallback opens a single child of
|
|
143
|
+
the trusted root with a no-follow lookup. Nested directory lookups fail
|
|
144
|
+
with `ENOTSUP`. Policy denials such as `EPERM` or `EACCES` are returned as
|
|
145
|
+
errors, including when opening the configured root. Searching from the configured root
|
|
146
|
+
or a direct child is supported as long as the search need not open a
|
|
147
|
+
directory more than one level below the configured root. A search that
|
|
148
|
+
needs to open a deeper directory returns an error and discards partial
|
|
149
|
+
results.
|
|
150
|
+
|
|
151
|
+
The service must control the configured root, its ancestors, and mount
|
|
152
|
+
configuration. A root handle identifies the directory opened by the tool.
|
|
153
|
+
Filesystem permissions still govern concurrent changes to opened objects.
|
|
154
|
+
|
|
155
|
+
On POSIX, recursive directories are opened from the original root handle and
|
|
156
|
+
checked again by identity after enumeration. A detected move or replacement causes the scan to fail.
|
|
157
|
+
|
|
158
|
+
Service-owned defaults cap scans at 100,000 entries, results at 10,000, returned
|
|
159
|
+
JSON at 1 MiB, and elapsed scanning at two seconds. These constructor fields
|
|
160
|
+
(`max_scanned_entries`, `max_results`, `max_return_bytes`,
|
|
161
|
+
`max_elapsed_seconds`) are not agent-call parameters. Limit exhaustion returns
|
|
162
|
+
an explicit error and an empty result rather than successful partial data.
|
|
163
|
+
Time checks are cooperative and cannot interrupt a filesystem call blocked in
|
|
164
|
+
the kernel. Success responses obey `max_return_bytes`. Error responses truncate
|
|
165
|
+
echoed input and diagnostics to at most 4 KiB, or the configured byte budget
|
|
166
|
+
when smaller, with a 256-byte minimum to preserve a structured error envelope.
|
|
167
|
+
|
|
168
|
+
Both search modes return regular files only: symlinks, FIFOs, sockets, and other
|
|
169
|
+
special entries are excluded. Recursive directory opens are descriptor-relative
|
|
170
|
+
and never follow symlinks. `max_depth` defaults to 64 and
|
|
171
|
+
`max_pattern_length` to 1,024 characters; both are service-owned limits. Filename
|
|
172
|
+
matching remains case-insensitive, and results remain sorted absolute paths.
|
|
173
|
+
|
|
174
|
+
### Windows filesystem support
|
|
175
|
+
|
|
176
|
+
On Windows the backend opens the local drive by its volume identity and
|
|
177
|
+
opens each component relative to a held directory handle. It rejects junctions
|
|
178
|
+
and other reparse points and does not accept UNC or device paths, alternate data
|
|
179
|
+
streams, or ambiguous trailing dots or spaces, or reserved DOS basenames. Ancestors are
|
|
180
|
+
opened for traversal. Only a directory being enumerated requires listing access.
|
|
181
|
+
Volume and directory handles
|
|
182
|
+
deny delete sharing during traversal. Returned paths are descriptive snapshots.
|
|
183
|
+
Entries with names that ordinary Windows paths cannot represent are omitted.
|
|
184
|
+
A listed pathname conveys no permission to open its contents.
|
|
185
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
swarmauri_tool_findfile/FindFileTool.py,sha256=CwXpQoJy08a_n0LPAD7jf3HV87-hTpnPhH25uNo65Ow,6375
|
|
2
|
+
swarmauri_tool_findfile/__init__.py,sha256=bOXeKOr4hmm776tsIVYTf8pw6BI5MtmxJJCx6ikyPkw,491
|
|
3
|
+
swarmauri_tool_findfile/_filesystem.py,sha256=D5_M26nm0Rz5iJ8bCSZS2g1U7e68yH11xOvQ-Bom8tM,8444
|
|
4
|
+
swarmauri_tool_findfile/_windows_fs.py,sha256=42iN6a0s7Avc7xFvJFvn9IdiqYWmVVNAzSRKvQUy8Sg,10543
|
|
5
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/METADATA,sha256=z9KP1ZiH_SfTZPDzkxuUCMAe-yjfPm2qhXHjZ2E04iY,8602
|
|
6
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
7
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/entry_points.txt,sha256=js04wOQGbk8ZOkNuksY69d4Boi1ymyPZ5_wwFTsDZF8,82
|
|
8
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/licenses/LICENSE,sha256=djUXOlCxLVszShEpZXshZ7v33G-2qIC_j9KXpWKZSzQ,11359
|
|
9
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/licenses/NOTICE,sha256=VfAL5X7ziNvo-D3n5KC0OJscjJ6cHcF5CwRHzM3S9cc,150
|
|
10
|
+
swarmauri_tool_findfile-0.1.0.dev1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2025] [Jacob Stewart @ Swarmauri]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|