Skip to content

ACPFileSystem

Base classes

Name Children Inherits
BaseAsyncFileSystem
upathtools.filesystems.base.basefilesystem
Async filesystem base with parallelized directory traversal.

â‹” Inheritance diagram

graph TD
  95970868417008["filesystem.ACPFileSystem"]
  95970842055616["basefilesystem.BaseAsyncFileSystem"]
  95970841239696["asyn.AsyncFileSystem"]
  95970839306576["spec.AbstractFileSystem"]
  125067848591872["builtins.object"]
  95970835676112["typing.Generic"]
  95970842055616 --> 95970868417008
  95970841239696 --> 95970842055616
  95970839306576 --> 95970841239696
  125067848591872 --> 95970839306576
  95970835676112 --> 95970842055616
  125067848591872 --> 95970835676112

🛈 DocStrings

Bases: BaseAsyncFileSystem[ACPPath, AcpInfo]

Async filesystem for ACP sessions.

Source code in src/aclientp/filesystem.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
class ACPFileSystem(BaseAsyncFileSystem[ACPPath, AcpInfo]):
    """Async filesystem for ACP sessions."""

    protocol = "acp"
    sep = "/"
    upath_cls = ACPPath

    def __init__(
        self,
        client: Client,
        session_id: str,
        *,
        use_cli_find: bool = True,
        **kwargs: Any,
    ) -> None:
        """Initialize ACP filesystem.

        Args:
            client: ACP client for operations
            session_id: Session identifier
            use_cli_find: Use CLI find command for _find/_glob operations.
                When True (default), uses a single `find` command for recursive
                file discovery, which is much more efficient over the protocol
                barrier than walking the tree with multiple ls calls.
            **kwargs: Additional filesystem options
        """
        super().__init__(**kwargs)
        self.client = client
        self.session_id = session_id
        self.requests = ACPRequests(client, session_id)
        self.notifications = ACPNotifications(client, session_id)
        self.command_provider = get_os_command_provider()
        self.use_cli_find = use_cli_find

    async def _cat_file(
        self, path: str, start: int | None = None, end: int | None = None, **kwargs: Any
    ) -> bytes:
        """Read file content via ACP session.

        Args:
            path: File path to read
            start: Start byte position (not supported by ACP)
            end: End byte position (not supported by ACP)
            **kwargs: Additional options

        Returns:
            File content as bytes

        Raises:
            NotImplementedError: If byte range is requested (ACP doesn't support
                partial reads)
        """
        if start is not None or end is not None:
            raise NotImplementedError("ACP filesystem does not support byte range reads")

        mime_type = guess_type(path)

        if not is_binary_mime(mime_type):
            # Text (or unknown) file - use read_text_file directly
            try:
                content = await self.requests.read_text_file(path)
                return content.encode("utf-8")
            except Exception as e:
                raise FileNotFoundError(f"Could not read file {path}: {e}") from e

        # Binary file - use base64 encoding via terminal command
        try:
            b64_cmd = self.command_provider.get_command("base64_encode")
            cmd_str = b64_cmd.create_command(path)
            output, exit_code = await self.requests.run_command(cmd_str, timeout_seconds=30)

            if exit_code != 0:
                raise FileNotFoundError(f"Could not read binary file {path}: {output}")  # noqa: TRY301

            return b64_cmd.parse_command(output)
        except Exception as e:
            raise FileNotFoundError(f"Could not read file {path}: {e}") from e

    cat_file = sync_wrapper(_cat_file)

    async def _put_file(
        self, lpath: str, rpath: str, mode: str = "overwrite", **kwargs: Any
    ) -> None:
        """Upload a local file to the remote ACP filesystem.

        Args:
            lpath: Local filesystem path to read from
            rpath: Remote path to write to (protocol prefix already stripped)
            mode: Write mode
            **kwargs: Additional options
        """
        content = Path(lpath).read_bytes()
        try:
            await self.requests.write_text_file(rpath, content.decode("utf-8"))
        except Exception as e:
            raise OSError(f"Could not write {lpath} to {rpath}: {e}") from e

    put_file = sync_wrapper(_put_file)

    async def _pipe_file(
        self,
        path: str,
        value: bytes,
        mode: str = "overwrite",
        **kwargs: Any,
    ) -> None:
        """Write bytes directly to a file path.

        This is the fsspec standard method for writing data to a file.
        Wraps _put_file for compatibility.

        Args:
            path: File path to write
            value: Bytes to write
            mode: Write mode, either 'overwrite' or 'append'
            **kwargs: Additional options
        """
        val = value.decode() if isinstance(value, bytes) else value
        try:
            await self.requests.write_text_file(path, val)
        except Exception as e:
            raise OSError(f"Could not write file {path}: {e}") from e

    pipe_file = sync_wrapper(_pipe_file)

    @overload
    async def _ls(self, path: str, detail: Literal[True] = ..., **kwargs: Any) -> list[AcpInfo]: ...

    @overload
    async def _ls(self, path: str, detail: Literal[False], **kwargs: Any) -> list[str]: ...

    async def _ls(self, path: str, detail: bool = True, **kwargs: Any) -> list[AcpInfo] | list[str]:
        """List directory contents via terminal command.

        Uses 'ls -la' command through ACP terminal to get directory listings.

        Args:
            path: Directory path to list
            detail: Whether to return detailed file information
            **kwargs: Additional options

        Returns:
            List of file information dictionaries or file names
        """
        # Use OS-specific command to list directory contents
        list_cmd = self.command_provider.get_command("list_directory")
        ls_cmd = list_cmd.create_command(path)

        try:
            output, exit_code = await self.requests.run_command(ls_cmd, timeout_seconds=10)

            if exit_code != 0:
                raise FileNotFoundError(f"Error listing directory {path!r}: {output}")  # noqa: TRY301

            result = list_cmd.parse_command(output, path)
            if detail:
                return [
                    AcpInfo(
                        name=item.path,  # fsspec expects full path in 'name'
                        type="file" if item.type == "link" else item.type,
                        size=item.size,
                        islink=item.type == "link",
                        timestamp=item.timestamp,
                        permissions=item.permissions,
                    )
                    for item in result
                ]
            return [item.path for item in result]  # Return full paths for consistency

        except Exception as e:
            raise FileNotFoundError(f"Could not list directory {path}: {e}") from e

    ls = sync_wrapper(_ls)

    async def _info(self, path: str, **kwargs: Any) -> AcpInfo:
        """Get file information via stat command.

        Args:
            path: File path to get info for
            **kwargs: Additional options

        Returns:
            File information dictionary
        """
        info_cmd = self.command_provider.get_command("file_info")
        stat_cmd = info_cmd.create_command(path)

        try:
            output, exit_code = await self.requests.run_command(stat_cmd, timeout_seconds=5)

            if exit_code != 0:
                raise FileNotFoundError(f"File not found: {path}")
            file_info = info_cmd.parse_command(output.strip(), path)
            return AcpInfo(
                name=file_info.path,
                type="file" if file_info.type == "link" else file_info.type,
                size=file_info.size,
                islink=file_info.type == "link",
                timestamp=file_info.timestamp,
                permissions=file_info.permissions,
            )

        except (OSError, ValueError) as e:
            # Fallback: try to get basic info from ls
            try:
                ls_result = await self._ls(str(Path(path).parent), detail=True)
                filename = Path(path).name

                for item in ls_result:
                    if Path(item["name"]).name == filename:
                        return AcpInfo(
                            name=path,  # fsspec expects full path in 'name'
                            type=item["type"],
                            size=item["size"],
                            islink=item.get("islink", False),
                            timestamp=item.get("timestamp"),
                            permissions=item.get("permissions"),
                        )

                raise FileNotFoundError(f"File not found: {path}")
            except (OSError, ValueError):
                raise FileNotFoundError(f"Could not get file info for {path}: {e}") from e

    info = sync_wrapper(_info)

    async def _exists(self, path: str, **kwargs: Any) -> bool:
        """Check if file exists via test command.

        Args:
            path: File path to check
            **kwargs: Additional options

        Returns:
            True if file exists, False otherwise
        """
        exists_cmd = self.command_provider.get_command("exists")
        test_cmd = exists_cmd.create_command(path)

        try:
            output, exit_code = await self.requests.run_command(test_cmd, timeout_seconds=5)
        except (OSError, ValueError):
            return False
        else:
            return exists_cmd.parse_command(output, exit_code if exit_code is not None else 1)

    exists = sync_wrapper(_exists)

    async def _isdir(self, path: str, **kwargs: Any) -> bool:
        """Check if path is a directory via test command.

        Args:
            path: Path to check
            **kwargs: Additional options

        Returns:
            True if path is a directory, False otherwise
        """
        isdir_cmd = self.command_provider.get_command("is_directory")
        test_cmd = isdir_cmd.create_command(path)

        try:
            output, exit_code = await self.requests.run_command(test_cmd, timeout_seconds=5)
        except (OSError, ValueError):
            return False
        else:
            return isdir_cmd.parse_command(output, exit_code if exit_code is not None else 1)

    isdir = sync_wrapper(_isdir)

    async def _isfile(self, path: str, **kwargs: Any) -> bool:
        """Check if path is a file via test command.

        Args:
            path: Path to check
            **kwargs: Additional options

        Returns:
            True if path is a file, False otherwise
        """
        isfile_cmd = self.command_provider.get_command("is_file")
        test_cmd = isfile_cmd.create_command(path)

        try:
            output, exit_code = await self.requests.run_command(test_cmd, timeout_seconds=5)
        except (OSError, ValueError):
            return False
        else:
            return isfile_cmd.parse_command(output, exit_code if exit_code is not None else 1)

    isfile = sync_wrapper(_isfile)

    async def _makedirs(self, path: str, exist_ok: bool = False, **kwargs: Any) -> None:
        """Create directories via mkdir command.

        Args:
            path: Directory path to create
            exist_ok: Don't raise error if directory already exists
            **kwargs: Additional options
        """
        create_cmd = self.command_provider.get_command("create_directory")
        mkdir_cmd = create_cmd.create_command(path, parents=exist_ok)

        try:
            output, exit_code = await self.requests.run_command(mkdir_cmd, timeout_seconds=5)
            success = create_cmd.parse_command(output, exit_code if exit_code is not None else 1)
            if not success:
                raise OSError(f"Error creating directory {path}: {output}")  # noqa: TRY301
        except Exception as e:
            raise OSError(f"Could not create directory {path}: {e}") from e

    makedirs = sync_wrapper(_makedirs)

    async def _cp_file(self, path1: str, path2: str, **kwargs: Any) -> None:
        """Copy a file from path1 to path2.

        Uses CLI cp/copy command for efficiency - single round-trip and
        native binary file support without base64 encoding overhead.

        Args:
            path1: Source file path
            path2: Destination file path
            **kwargs: Additional options
        """
        copy_cmd = self.command_provider.get_command("copy_path")
        cmd_str = copy_cmd.create_command(path1, path2, recursive=False)

        try:
            output, exit_code = await self.requests.run_command(cmd_str, timeout_seconds=30)
            success = copy_cmd.parse_command(output, exit_code if exit_code is not None else 1)
            if not success:
                raise OSError(f"Error copying {path1} to {path2}: {output}")  # noqa: TRY301
        except Exception as e:
            raise OSError(f"Could not copy {path1} to {path2}: {e}") from e

    cp_file = sync_wrapper(_cp_file)

    async def _rm(
        self,
        path: str,
        recursive: bool = False,
        batch_size: int | None = None,
        maxdepth: int | None = None,
        **kwargs: Any,
    ) -> None:
        """Remove file or directory via rm command.

        Args:
            path: Path to remove
            recursive: Remove directories recursively
            batch_size: Batch size when removing directories (recursively)
            maxdepth: Maximum recursion depth (not supported by the remote rm command)
            **kwargs: Additional options
        """
        if recursive and maxdepth is not None:
            raise NotImplementedError("Depth-limited recursive removal is not supported")
        remove_cmd = self.command_provider.get_command("remove_path")
        rm_cmd = remove_cmd.create_command(path, recursive=recursive)

        try:
            output, exit_code = await self.requests.run_command(rm_cmd, timeout_seconds=10)
            success = remove_cmd.parse_command(output, exit_code if exit_code is not None else 1)
            if not success:
                raise OSError(f"Error removing {path}: {output}")  # noqa: TRY301
        except Exception as e:
            raise OSError(f"Could not remove {path}: {e}") from e

    rm = sync_wrapper(_rm)

    @overload
    async def _find(
        self,
        path: str,
        maxdepth: int | None = None,
        withdirs: bool = False,
        *,
        detail: Literal[False] = False,
        **kwargs: Any,
    ) -> list[str]: ...

    @overload
    async def _find(
        self,
        path: str,
        maxdepth: int | None = None,
        withdirs: bool = False,
        *,
        detail: Literal[True],
        **kwargs: Any,
    ) -> dict[str, AcpInfo]: ...

    async def _find(
        self,
        path: str,
        maxdepth: int | None = None,
        withdirs: bool = False,
        **kwargs: Any,
    ) -> list[str] | dict[str, AcpInfo]:
        """Find files recursively.

        When use_cli_find is enabled, uses a single CLI find command instead of
        walking the directory tree with multiple ls calls. This is much more
        efficient over the protocol barrier.

        Args:
            path: Root path to search from
            maxdepth: Maximum depth to descend (None for unlimited)
            withdirs: Include directories in results
            **kwargs: Additional options (detail=True returns dict with info)

        Returns:
            List of paths, or dict mapping paths to info if detail=True
        """
        if not self.use_cli_find:
            # Fall back to default fsspec implementation (walks tree with _ls)
            return await super()._find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs)  # type: ignore[no-any-return]

        detail = kwargs.get("detail", False)
        stripped = self._strip_protocol(path)
        search_path = stripped if isinstance(stripped, str) else stripped[0]

        # Determine file_type filter
        file_type: Literal["file", "directory", "all"] = "all" if withdirs else "file"

        # Use anyenv find command
        find_cmd = self.command_provider.get_command("find")
        cmd_str = find_cmd.create_command(
            search_path, maxdepth=maxdepth, file_type=file_type, with_stats=detail
        )

        try:
            output, exit_code = await self.requests.run_command(cmd_str, timeout_seconds=60)

            if exit_code != 0:
                # If find fails, fall back to default implementation
                logger.warning("CLI find failed, falling back to walk: %s", output)
                return await super()._find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs)  # type: ignore[no-any-return]

            entries = find_cmd.parse_command(output, search_path)

            if detail:
                # Return dict with info from find output
                return {
                    entry.path: AcpInfo(
                        name=entry.path,
                        type="file" if entry.type == "link" else entry.type,
                        size=entry.size,
                        islink=entry.type == "link",
                        timestamp=entry.timestamp,
                        permissions=entry.permissions,
                    )
                    for entry in entries
                    if entry.name not in (".", "..")
                }
            return [entry.path for entry in entries if entry.name not in (".", "..")]

        except Exception as e:  # noqa: BLE001
            logger.warning("CLI find error, falling back to walk: %s", e)
            return await super()._find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs)  # type: ignore[no-any-return]

    find = sync_wrapper(_find)  # pyright: ignore[reportAssignmentType]

    def open(
        self,
        path: str,
        mode: str = "rb",
        block_size: int | None = None,
        cache_options: dict[str, Any] | None = None,
        compression: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> ACPFile:
        """Open file for reading or writing.

        Args:
            path: File path to open
            mode: File mode ('rb', 'wb', 'ab', 'xb')
            block_size: Block size for reading/writing
            cache_options: Cache options for reading/writing
            compression: Compression options for reading/writing
            **kwargs: Additional options

        Returns:
            File-like object
        """
        # Convert text modes to binary modes for fsspec compatibility
        match mode:
            case "r":
                mode = "rb"
            case "w":
                mode = "wb"
            case "a":
                mode = "ab"
            case "x":
                mode = "xb"

        return ACPFile(self, path, mode, **kwargs)

__init__

__init__(client: Client, session_id: str, *, use_cli_find: bool = True, **kwargs: Any) -> None

Initialize ACP filesystem.

Parameters:

Name Type Description Default
client Client

ACP client for operations

required
session_id str

Session identifier

required
use_cli_find bool

Use CLI find command for _find/_glob operations. When True (default), uses a single find command for recursive file discovery, which is much more efficient over the protocol barrier than walking the tree with multiple ls calls.

True
**kwargs Any

Additional filesystem options

{}
Source code in src/aclientp/filesystem.py
def __init__(
    self,
    client: Client,
    session_id: str,
    *,
    use_cli_find: bool = True,
    **kwargs: Any,
) -> None:
    """Initialize ACP filesystem.

    Args:
        client: ACP client for operations
        session_id: Session identifier
        use_cli_find: Use CLI find command for _find/_glob operations.
            When True (default), uses a single `find` command for recursive
            file discovery, which is much more efficient over the protocol
            barrier than walking the tree with multiple ls calls.
        **kwargs: Additional filesystem options
    """
    super().__init__(**kwargs)
    self.client = client
    self.session_id = session_id
    self.requests = ACPRequests(client, session_id)
    self.notifications = ACPNotifications(client, session_id)
    self.command_provider = get_os_command_provider()
    self.use_cli_find = use_cli_find

open

open(
    path: str,
    mode: str = "rb",
    block_size: int | None = None,
    cache_options: dict[str, Any] | None = None,
    compression: dict[str, Any] | None = None,
    **kwargs: Any,
) -> ACPFile

Open file for reading or writing.

Parameters:

Name Type Description Default
path str

File path to open

required
mode str

File mode ('rb', 'wb', 'ab', 'xb')

'rb'
block_size int | None

Block size for reading/writing

None
cache_options dict[str, Any] | None

Cache options for reading/writing

None
compression dict[str, Any] | None

Compression options for reading/writing

None
**kwargs Any

Additional options

{}

Returns:

Type Description
ACPFile

File-like object

Source code in src/aclientp/filesystem.py
def open(
    self,
    path: str,
    mode: str = "rb",
    block_size: int | None = None,
    cache_options: dict[str, Any] | None = None,
    compression: dict[str, Any] | None = None,
    **kwargs: Any,
) -> ACPFile:
    """Open file for reading or writing.

    Args:
        path: File path to open
        mode: File mode ('rb', 'wb', 'ab', 'xb')
        block_size: Block size for reading/writing
        cache_options: Cache options for reading/writing
        compression: Compression options for reading/writing
        **kwargs: Additional options

    Returns:
        File-like object
    """
    # Convert text modes to binary modes for fsspec compatibility
    match mode:
        case "r":
            mode = "rb"
        case "w":
            mode = "wb"
        case "a":
            mode = "ab"
        case "x":
            mode = "xb"

    return ACPFile(self, path, mode, **kwargs)

:fa-brands-github: Show source on GitHub