asanypath 2.7.1__tar.gz → 2.7.2__tar.gz

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.
Files changed (85) hide show
  1. {asanypath-2.7.1 → asanypath-2.7.2}/PKG-INFO +24 -10
  2. {asanypath-2.7.1 → asanypath-2.7.2}/README.md +22 -8
  3. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_version.py +2 -2
  4. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/asanypath.py +52 -14
  5. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/click.py +5 -1
  6. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/cloud.py +6 -2
  7. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/http.py +85 -4
  8. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/ssh.py +4 -7
  9. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_asanypath.py +196 -0
  10. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_backend_options.py +51 -0
  11. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_http.py +197 -0
  12. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_ssh.py +49 -0
  13. {asanypath-2.7.1 → asanypath-2.7.2}/.copilot/skills/async-python-lib/SKILL.md +0 -0
  14. {asanypath-2.7.1 → asanypath-2.7.2}/.copilot/skills/gitguro/SKILL.md +0 -0
  15. {asanypath-2.7.1 → asanypath-2.7.2}/.github/CODEOWNERS +0 -0
  16. {asanypath-2.7.1 → asanypath-2.7.2}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  17. {asanypath-2.7.1 → asanypath-2.7.2}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  18. {asanypath-2.7.1 → asanypath-2.7.2}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  19. {asanypath-2.7.1 → asanypath-2.7.2}/.github/dependabot.yml +0 -0
  20. {asanypath-2.7.1 → asanypath-2.7.2}/.github/workflows/publish.yml +0 -0
  21. {asanypath-2.7.1 → asanypath-2.7.2}/.github/workflows/unittests.yml +0 -0
  22. {asanypath-2.7.1 → asanypath-2.7.2}/.gitignore +0 -0
  23. {asanypath-2.7.1 → asanypath-2.7.2}/.pre-commit-config.yaml +0 -0
  24. {asanypath-2.7.1 → asanypath-2.7.2}/CODE_OF_CONDUCT.md +0 -0
  25. {asanypath-2.7.1 → asanypath-2.7.2}/CONTRIBUTING.md +0 -0
  26. {asanypath-2.7.1 → asanypath-2.7.2}/LICENSE +0 -0
  27. {asanypath-2.7.1 → asanypath-2.7.2}/asanypath.png +0 -0
  28. {asanypath-2.7.1 → asanypath-2.7.2}/compose.yml +0 -0
  29. {asanypath-2.7.1 → asanypath-2.7.2}/hatch_build.py +0 -0
  30. {asanypath-2.7.1 → asanypath-2.7.2}/pyproject.toml +0 -0
  31. {asanypath-2.7.1 → asanypath-2.7.2}/scripts/bench.py +0 -0
  32. {asanypath-2.7.1 → asanypath-2.7.2}/scripts/bench_rmtree.py +0 -0
  33. {asanypath-2.7.1 → asanypath-2.7.2}/scripts/bench_upload.py +0 -0
  34. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/__init__.py +0 -0
  35. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/__init__.pyi +0 -0
  36. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_backend_opts.py +0 -0
  37. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_credstore.py +0 -0
  38. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_prompt.py +0 -0
  39. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_resume.py +0 -0
  40. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/_transfer.py +0 -0
  41. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/artifactory.py +0 -0
  42. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/asanypath.pyi +0 -0
  43. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/azure.py +0 -0
  44. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/batcher.py +0 -0
  45. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/cache.py +0 -0
  46. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/cli.py +0 -0
  47. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/common.py +0 -0
  48. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/exceptions.py +0 -0
  49. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/ftp.py +0 -0
  50. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/gcs.py +0 -0
  51. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/local.py +0 -0
  52. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/options.py +0 -0
  53. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/py.typed +0 -0
  54. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/s3.py +0 -0
  55. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/sync.py +0 -0
  56. {asanypath-2.7.1 → asanypath-2.7.2}/src/asanypath/unsupported.py +0 -0
  57. {asanypath-2.7.1 → asanypath-2.7.2}/tests/__init__.py +0 -0
  58. {asanypath-2.7.1 → asanypath-2.7.2}/tests/conftest.py +0 -0
  59. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_artifactory.py +0 -0
  60. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_auth_errors.py +0 -0
  61. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_azure.py +0 -0
  62. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_batcher.py +0 -0
  63. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_cache.py +0 -0
  64. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_cli.py +0 -0
  65. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_click.py +0 -0
  66. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_cloudpathmixin.py +0 -0
  67. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_commonpathmixin.py +0 -0
  68. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_credstore.py +0 -0
  69. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_endpoints.py +0 -0
  70. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_ftp.py +0 -0
  71. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_gcs.py +0 -0
  72. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_http_auth.py +0 -0
  73. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_isolation.py +0 -0
  74. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_local.py +0 -0
  75. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_options.py +0 -0
  76. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_py_typed.py +0 -0
  77. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_resume.py +0 -0
  78. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_s3.py +0 -0
  79. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_scandir.py +0 -0
  80. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_ssh_hostkeys.py +0 -0
  81. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_sync.py +0 -0
  82. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_syncpath.py +0 -0
  83. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_transport_hardening.py +0 -0
  84. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_unsupported_path.py +0 -0
  85. {asanypath-2.7.1 → asanypath-2.7.2}/tests/test_upload.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: asanypath
3
- Version: 2.7.1
3
+ Version: 2.7.2
4
4
  Summary: Async pathlib for local and cloud storage
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -20,7 +20,7 @@ Classifier: Programming Language :: Python :: 3.15
20
20
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
21
  Requires-Python: >=3.10
22
22
  Requires-Dist: anyio>=4
23
- Requires-Dist: asanypath-native~=2.7.1
23
+ Requires-Dist: asanypath-native~=2.7.2
24
24
  Requires-Dist: msgspec>=0.22.0
25
25
  Requires-Dist: yarl>=1.2
26
26
  Provides-Extra: all
@@ -136,15 +136,15 @@ with path.open("rb") as f:
136
136
  chunk = f.read(512)
137
137
  ```
138
138
 
139
- Files smaller than the buffer size are fetched in one shot automatically.
140
- Supported on S3, GCS, Azure, and Artifactory.
139
+ The buffer size controls prefetch; smaller files may be fetched in one shot.
140
+ Supported on S3, GCS, Azure, Artifactory, and HTTP/HTTPS.
141
141
 
142
- HTTP and HTTPS paths also support read-only `open("rb")` and `open("r")`
143
- with both context-manager styles. These download the entire response on entry
144
- and return a seekable in-memory handle, so servers do not need to support HEAD
145
- or range requests. Text mode accepts `encoding`, `errors`, and `newline`.
146
- Existing HTTP authentication and read-cache settings apply; anonymous URLs
147
- require no token.
142
+ HTTP and HTTPS paths support read-only `open("rb")` and `open("r")` with both
143
+ context-manager styles. They use lazy range reads when a HEAD response supplies
144
+ the size, falling back to a full download when HEAD or ranges are unavailable.
145
+ If the download cache is enabled, `open()` uses it instead of range reads.
146
+ Text mode accepts `encoding`, `errors`, and `newline`. Existing HTTP
147
+ authentication settings apply; anonymous URLs require no token.
148
148
 
149
149
  ### Service endpoints
150
150
 
@@ -612,6 +612,20 @@ syntax. Transport-managed headers such as `Host` and
612
612
  visible in shell history or process listings, so use the HTTP auth environment
613
613
  variables for secrets.
614
614
 
615
+ For SSH copies, config aliases can be used as `alias:path` (relative to the
616
+ remote home) or `ssh://alias/absolute/path`. Source overrides use constructor
617
+ option names, not OpenSSH directive names, and each requires a separate flag:
618
+
619
+ ```sh
620
+ asanypath cp alias:logs/output.txt ./output.txt \
621
+ --src-option ssh.username=deploy \
622
+ --src-option ssh.port=2222 \
623
+ --src-option ssh.client_keys=/path/to/private-key
624
+ ```
625
+
626
+ These override the corresponding config values. Passwords and other secrets
627
+ passed on the command line may be visible in shell history or process listings.
628
+
615
629
  ### Shell Completions (Beta)
616
630
 
617
631
  Path completions are available for all subcommands that take cloud paths: `ls`, `cp`, `mv`, `rm`, `stat`, `cat`, `exists`, `touch`, `checksums`, `mkdir`, `presign`, and `sync`.
@@ -79,15 +79,15 @@ with path.open("rb") as f:
79
79
  chunk = f.read(512)
80
80
  ```
81
81
 
82
- Files smaller than the buffer size are fetched in one shot automatically.
83
- Supported on S3, GCS, Azure, and Artifactory.
82
+ The buffer size controls prefetch; smaller files may be fetched in one shot.
83
+ Supported on S3, GCS, Azure, Artifactory, and HTTP/HTTPS.
84
84
 
85
- HTTP and HTTPS paths also support read-only `open("rb")` and `open("r")`
86
- with both context-manager styles. These download the entire response on entry
87
- and return a seekable in-memory handle, so servers do not need to support HEAD
88
- or range requests. Text mode accepts `encoding`, `errors`, and `newline`.
89
- Existing HTTP authentication and read-cache settings apply; anonymous URLs
90
- require no token.
85
+ HTTP and HTTPS paths support read-only `open("rb")` and `open("r")` with both
86
+ context-manager styles. They use lazy range reads when a HEAD response supplies
87
+ the size, falling back to a full download when HEAD or ranges are unavailable.
88
+ If the download cache is enabled, `open()` uses it instead of range reads.
89
+ Text mode accepts `encoding`, `errors`, and `newline`. Existing HTTP
90
+ authentication settings apply; anonymous URLs require no token.
91
91
 
92
92
  ### Service endpoints
93
93
 
@@ -555,6 +555,20 @@ syntax. Transport-managed headers such as `Host` and
555
555
  visible in shell history or process listings, so use the HTTP auth environment
556
556
  variables for secrets.
557
557
 
558
+ For SSH copies, config aliases can be used as `alias:path` (relative to the
559
+ remote home) or `ssh://alias/absolute/path`. Source overrides use constructor
560
+ option names, not OpenSSH directive names, and each requires a separate flag:
561
+
562
+ ```sh
563
+ asanypath cp alias:logs/output.txt ./output.txt \
564
+ --src-option ssh.username=deploy \
565
+ --src-option ssh.port=2222 \
566
+ --src-option ssh.client_keys=/path/to/private-key
567
+ ```
568
+
569
+ These override the corresponding config values. Passwords and other secrets
570
+ passed on the command line may be visible in shell history or process listings.
571
+
558
572
  ### Shell Completions (Beta)
559
573
 
560
574
  Path completions are available for all subcommands that take cloud paths: `ls`, `cp`, `mv`, `rm`, `stat`, `cat`, `exists`, `touch`, `checksums`, `mkdir`, `presign`, and `sync`.
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '2.7.1'
22
- __version_tuple__ = version_tuple = (2, 7, 1)
21
+ __version__ = version = '2.7.2'
22
+ __version_tuple__ = version_tuple = (2, 7, 2)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -6,11 +6,13 @@
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import os
9
10
  from abc import ABC, abstractmethod
10
11
  from collections.abc import AsyncIterator, Callable
11
12
  from importlib import import_module
12
13
  from os import PathLike, stat_result
13
14
  from pathlib import Path, PurePosixPath
15
+ from threading import Lock
14
16
  from typing import TYPE_CHECKING, Any, TypeVar
15
17
  from urllib.parse import urlsplit
16
18
 
@@ -48,25 +50,60 @@ class _LazyDict(dict):
48
50
  def __init__(self) -> None:
49
51
  super().__init__()
50
52
  self._pending = dict(_BUILTIN_PROTOCOLS)
53
+ self._lock = Lock()
54
+ self._loading: dict[str, int] = {}
55
+ self._generation = 0
56
+
57
+ def _after_fork(self):
58
+ self._lock = Lock()
59
+ self._loading.clear()
60
+ self._generation += 1
51
61
 
52
62
  def _load(self, key) -> bool:
53
- spec = self._pending.pop(key, None)
54
- if spec is None:
55
- return False
63
+ with self._lock:
64
+ if super().__contains__(key):
65
+ self._pending.pop(key, None)
66
+ return True
67
+ spec = self._pending.get(key)
68
+ if spec is None:
69
+ return False
70
+ self._loading[key] = self._loading.get(key, 0) + 1
71
+ generation = self._generation
72
+
73
+ unavailable = False
56
74
  try:
57
- klass = getattr(import_module(spec[0]), spec[1])
58
- except ImportError: # optional backend dependency not installed
59
- return False
60
- self.setdefault(key, klass)
61
- return True
75
+ # Do not hold the registry lock while Python's import locks are held.
76
+ try:
77
+ klass = getattr(import_module(spec[0]), spec[1])
78
+ except ImportError: # optional backend dependency not installed
79
+ unavailable = True
80
+ return False
81
+ with self._lock:
82
+ self.setdefault(key, klass)
83
+ if self._pending.get(key) == spec:
84
+ self._pending.pop(key)
85
+ return True
86
+ finally:
87
+ with self._lock:
88
+ if self._generation == generation:
89
+ remaining = self._loading[key] - 1
90
+ if remaining:
91
+ self._loading[key] = remaining
92
+ else:
93
+ del self._loading[key]
94
+ if unavailable and self._pending.get(key) == spec:
95
+ self._pending.pop(key)
62
96
 
63
97
  def _ensure(self):
64
- for key in list(self._pending):
98
+ with self._lock:
99
+ pending = list(self._pending)
100
+ for key in pending:
65
101
  self._load(key)
66
102
 
67
103
  def __setitem__(self, key, value):
68
- self._pending.pop(key, None)
69
- super().__setitem__(key, value)
104
+ with self._lock:
105
+ super().__setitem__(key, value)
106
+ self._pending.pop(key, None)
70
107
 
71
108
  def items(self):
72
109
  self._ensure()
@@ -97,12 +134,13 @@ class _LazyDict(dict):
97
134
  return super().get(key, default)
98
135
 
99
136
  def __missing__(self, key):
100
- if self._load(key):
101
- return self[key]
102
- return UnsupportedProtocolPath
137
+ self._load(key)
138
+ return super().get(key, UnsupportedProtocolPath)
103
139
 
104
140
 
105
141
  PROTOCOL_MAP = _LazyDict()
142
+ if hasattr(os, "register_at_fork"):
143
+ os.register_at_fork(after_in_child=PROTOCOL_MAP._after_fork)
106
144
 
107
145
  # Flavors whose abstract-method implementation has been validated once.
108
146
  _VALIDATED_FLAVORS: set[type] = set()
@@ -171,7 +171,11 @@ def _maybe_rewrite_scp_style(value: str) -> str:
171
171
  return value
172
172
  if not _discover_ssh_config():
173
173
  return value
174
- if _resolve_alias(host, None, None)[0] == host:
174
+ try:
175
+ resolved_host = _resolve_alias(host, None, None)[0]
176
+ except RuntimeError as exc:
177
+ raise click.ClickException(str(exc)) from exc
178
+ if resolved_host == host:
175
179
  # No Host block matched — leave alone (don't probe DNS).
176
180
  return value
177
181
  prefix = f"{user}@" if user else ""
@@ -1381,7 +1381,7 @@ class _CloudFile:
1381
1381
  self._range_read = range_read
1382
1382
  self._buf: IO[bytes] | None = None
1383
1383
  self._text_wrapper: io.TextIOWrapper | None = None
1384
- self._reader: io.BufferedReader | None = None
1384
+ self._reader: io.BufferedReader | io.RawIOBase | None = None
1385
1385
  self._closed = False
1386
1386
  self._sync = False
1387
1387
 
@@ -1415,11 +1415,12 @@ class _CloudFile:
1415
1415
 
1416
1416
  def _make_reader(self, size: int) -> io.IOBase:
1417
1417
  """Create a lazily-filled reader backed by range reads."""
1418
- raw = _CloudRawIO(self._path, size)
1418
+ raw = self._make_raw_reader(size)
1419
1419
  if self._buffering == 0:
1420
1420
  # Unbuffered: return raw directly (binary only)
1421
1421
  if "b" not in self._mode:
1422
1422
  raise ValueError("can't have unbuffered text I/O")
1423
+ self._reader = raw
1423
1424
  return raw
1424
1425
  reader = io.BufferedReader(raw, buffer_size=self._chunk_size)
1425
1426
  self._reader = reader
@@ -1432,6 +1433,9 @@ class _CloudFile:
1432
1433
  )
1433
1434
  return reader
1434
1435
 
1436
+ def _make_raw_reader(self, size: int) -> _CloudRawIO:
1437
+ return _CloudRawIO(self._path, size)
1438
+
1435
1439
  def _spool_for_upload(self) -> tuple[IO[bytes], int]:
1436
1440
  """Flush any text layer and rewind the spool; return ``(buffer, size)``."""
1437
1441
  if self._text_wrapper is not None:
@@ -29,7 +29,7 @@ from asanypath_native import (
29
29
  from yarl import URL
30
30
 
31
31
  from asanypath._transfer import RangeNotSupportedError
32
- from asanypath.cloud import CloudPathMixin, _CloudFile, _service_origin
32
+ from asanypath.cloud import CloudPathMixin, _CloudFile, _CloudRawIO, _service_origin
33
33
 
34
34
  logger = logging.getLogger(__name__)
35
35
 
@@ -483,8 +483,8 @@ class HTTPPath(CloudPathMixin):
483
483
  def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None):
484
484
  """Open a seekable read-only handle with sync or async context management.
485
485
 
486
- Downloads the response on context entry using read_bytes(), including
487
- its authentication and cache settings. No HEAD or range support is required.
486
+ Read ranges lazily when the server provides a usable size. Servers that
487
+ do not support HEAD or ranges fall back to a full download.
488
488
  """
489
489
  if mode not in ("r", "rt", "tr", "rb", "br"):
490
490
  raise ValueError("HTTPPath.open() supports only read modes ('r', 'rt', 'rb')")
@@ -492,7 +492,7 @@ class HTTPPath(CloudPathMixin):
492
492
  raise ValueError("binary mode doesn't take an encoding, errors or newline argument")
493
493
  if buffering == 0 and "b" not in mode:
494
494
  raise ValueError("can't have unbuffered text I/O")
495
- return _CloudFile(self, mode, buffering, encoding, errors, newline, range_read=False)
495
+ return _HTTPCloudFile(self, mode, buffering, encoding, errors, newline)
496
496
 
497
497
  async def _read_bytes_uncached(self) -> bytes:
498
498
  return await http_get(str(self), headers=self._merge_headers(None))
@@ -666,3 +666,84 @@ class HTTPSPath(HTTPPath):
666
666
  """Async path implementation for HTTPS."""
667
667
 
668
668
  protocol: str = "https"
669
+
670
+
671
+ class _HTTPRawIO(_CloudRawIO):
672
+ def __init__(self, path, size: int, etag: str | None, last_modified: str | None):
673
+ super().__init__(path, size)
674
+ self._etag = etag
675
+ self._last_modified = last_modified
676
+ self._whole_response: bytes | None = None
677
+
678
+ def readinto(self, b):
679
+ if self._pos >= self._size or not b:
680
+ return 0
681
+ end = min(self._pos + len(b), self._size)
682
+ if self._whole_response is None:
683
+ from asanypath.sync import _SyncRunner
684
+
685
+ try:
686
+ data = _SyncRunner.get().run(
687
+ self._path._range_read(
688
+ self._pos,
689
+ end - 1,
690
+ etag=self._etag,
691
+ last_modified=self._last_modified,
692
+ total_size=self._size,
693
+ )
694
+ )
695
+ except RangeNotSupportedError as error:
696
+ if len(error.data) != self._size:
697
+ raise OSError("Source changed during ranged read") from error
698
+ self._whole_response = error.data
699
+ data = error.data[self._pos : end]
700
+ else:
701
+ data = self._whole_response[self._pos : end]
702
+ b[: len(data)] = data
703
+ self._pos += len(data)
704
+ return len(data)
705
+
706
+
707
+ class _HTTPCloudFile(_CloudFile):
708
+ async def _range_metadata(self):
709
+ from asanypath.cache import cache_enabled
710
+
711
+ if cache_enabled(None) or http_request is None:
712
+ return None
713
+ response = await self._path.request("HEAD", headers={"accept-encoding": "identity"})
714
+ if response.status_code in (400, 401, 403, 404, 405, 501):
715
+ logger.debug("HTTP HEAD unavailable; falling back to a full read")
716
+ return None
717
+ if not response.ok:
718
+ raise RuntimeError(f"HTTP {response.status_code} during HEAD request")
719
+ headers = {key.lower(): value for key, value in response.headers.items()}
720
+ if headers.get("accept-ranges", "").lower() == "none":
721
+ return None
722
+ if headers.get("content-encoding", "identity").lower() != "identity":
723
+ return None
724
+ size = self._get_size(headers)
725
+ if size is None or size <= 0:
726
+ return None
727
+ return size, headers.get("etag"), headers.get("last-modified")
728
+
729
+ def _make_raw_reader(self, size: int) -> _CloudRawIO:
730
+ return _HTTPRawIO(self._path, size, self._etag, self._last_modified)
731
+
732
+ def __enter__(self):
733
+ from asanypath.sync import _SyncRunner
734
+
735
+ self._sync = True
736
+ runner = _SyncRunner.get()
737
+ metadata = runner.run(self._range_metadata())
738
+ if metadata is not None:
739
+ size, self._etag, self._last_modified = metadata
740
+ return self._make_reader(size)
741
+ return self._make_buffer(runner.run(self._path.read_bytes()))
742
+
743
+ async def __aenter__(self):
744
+ self._sync = False
745
+ metadata = await self._range_metadata()
746
+ if metadata is not None:
747
+ size, self._etag, self._last_modified = metadata
748
+ return self._make_reader(size)
749
+ return self._make_buffer(await self._path.read_bytes())
@@ -179,12 +179,9 @@ def _resolve_alias(
179
179
  cfg_paths = _discover_ssh_config()
180
180
  if not host or not cfg_paths:
181
181
  return host, port, user, None, None, None
182
- try:
183
- cfg_host, cfg_port, cfg_user, cfg_identity, cfg_strict, cfg_known = ssh_resolve_config(
184
- host, cfg_paths
185
- )
186
- except Exception: # noqa: BLE001
187
- return host, port, user, None, None, None
182
+ cfg_host, cfg_port, cfg_user, cfg_identity, cfg_strict, cfg_known = ssh_resolve_config(
183
+ host, cfg_paths
184
+ )
188
185
  resolved_host = cfg_host or host
189
186
  resolved_port = port or cfg_port
190
187
  resolved_user = user or cfg_user
@@ -356,7 +353,7 @@ class SSHPath(CloudPathMixin):
356
353
  # Auth precedence mirrors ssh: explicit password, then key file
357
354
  # (explicit kwarg/env, else ssh_config IdentityFile), else agent.
358
355
  keys = self._client_keys or ()
359
- key_path = keys[0] if keys else getattr(self, "_config_identity", None)
356
+ key_path = keys[0] if keys else self._expand_ssh_tokens(self._config_identity)
360
357
  if key_path is not None:
361
358
  key_path = str(Path(key_path).expanduser())
362
359
  if self._password is not None:
@@ -4,6 +4,7 @@
4
4
  # license that can be found in the LICENSE file or at
5
5
  # https://opensource.org/licenses/MIT.
6
6
 
7
+ import os
7
8
  import re
8
9
  from urllib.parse import urlparse
9
10
 
@@ -225,6 +226,201 @@ def test_register_overrides_builtin():
225
226
  assert out == "True"
226
227
 
227
228
 
229
+ def test_concurrent_https_and_local_dispatch_during_lazy_import(monkeypatch):
230
+ from concurrent.futures import ThreadPoolExecutor
231
+ from threading import Event
232
+
233
+ import asanypath.asanypath as factory
234
+ from asanypath.http import HTTPSPath
235
+ from asanypath.local import AsyncPath
236
+
237
+ registry = factory._LazyDict()
238
+ monkeypatch.setattr(factory, "PROTOCOL_MAP", registry)
239
+ original_import = factory.import_module
240
+ importing = Event()
241
+ resume = Event()
242
+
243
+ def blocked_import(name):
244
+ if name == "asanypath.local" and not importing.is_set():
245
+ importing.set()
246
+ if not resume.wait(5):
247
+ raise TimeoutError("local backend import was not released")
248
+ return original_import(name)
249
+
250
+ monkeypatch.setattr(factory, "import_module", blocked_import)
251
+ with ThreadPoolExecutor(max_workers=1) as executor:
252
+ https = executor.submit(AsAnyPath, "https://example.com/file")
253
+ try:
254
+ assert importing.wait(5)
255
+ local = AsAnyPath("/tmp/cfg.yaml")
256
+ finally:
257
+ resume.set()
258
+ assert isinstance(https.result(timeout=10), HTTPSPath)
259
+ assert isinstance(local, AsyncPath)
260
+ assert str(local) == "/tmp/cfg.yaml"
261
+
262
+
263
+ @pytest.mark.parametrize("import_fails", [False, True])
264
+ def test_register_while_lazy_import_is_in_progress(monkeypatch, import_fails):
265
+ from concurrent.futures import ThreadPoolExecutor
266
+ from threading import Event
267
+ from types import SimpleNamespace
268
+
269
+ import asanypath.asanypath as factory
270
+
271
+ class Builtin:
272
+ pass
273
+
274
+ class Override:
275
+ pass
276
+
277
+ registry = factory._LazyDict()
278
+ registry._pending = {"file": ("backend", "Builtin")}
279
+ importing = Event()
280
+ resume = Event()
281
+
282
+ def blocked_import(name):
283
+ importing.set()
284
+ if not resume.wait(5):
285
+ raise TimeoutError("backend import was not released")
286
+ if import_fails:
287
+ raise ImportError("optional backend unavailable")
288
+ return SimpleNamespace(Builtin=Builtin)
289
+
290
+ monkeypatch.setattr(factory, "import_module", blocked_import)
291
+ with ThreadPoolExecutor(max_workers=1) as executor:
292
+ lookup = executor.submit(registry.__getitem__, "file")
293
+ try:
294
+ assert importing.wait(5)
295
+ registry["file"] = Override
296
+ finally:
297
+ resume.set()
298
+ assert lookup.result(timeout=5) is Override
299
+ assert registry["file"] is Override
300
+
301
+
302
+ def test_failed_import_does_not_hide_another_import_in_progress(monkeypatch):
303
+ from concurrent.futures import ThreadPoolExecutor
304
+ from threading import Event
305
+ from types import SimpleNamespace
306
+
307
+ import asanypath.asanypath as factory
308
+
309
+ class Builtin:
310
+ pass
311
+
312
+ registry = factory._LazyDict()
313
+ registry._pending = {"file": ("backend", "Builtin")}
314
+ first_started, second_started = Event(), Event()
315
+ fail_first, finish_second = Event(), Event()
316
+
317
+ def blocked_import(name):
318
+ if not first_started.is_set():
319
+ first_started.set()
320
+ if not fail_first.wait(5):
321
+ raise TimeoutError("first import was not released")
322
+ raise ImportError("temporarily unavailable")
323
+ if not second_started.is_set():
324
+ second_started.set()
325
+ if not finish_second.wait(5):
326
+ raise TimeoutError("second import was not released")
327
+ return SimpleNamespace(Builtin=Builtin)
328
+
329
+ monkeypatch.setattr(factory, "import_module", blocked_import)
330
+ with ThreadPoolExecutor(max_workers=2) as executor:
331
+ first = executor.submit(registry.__getitem__, "file")
332
+ try:
333
+ assert first_started.wait(5)
334
+ second = executor.submit(registry.__getitem__, "file")
335
+ assert second_started.wait(5)
336
+ fail_first.set()
337
+ assert first.result(timeout=5) is UnsupportedProtocolPath
338
+ assert registry["file"] is Builtin
339
+ finally:
340
+ fail_first.set()
341
+ finish_second.set()
342
+ assert second.result(timeout=5) is Builtin
343
+
344
+
345
+ def test_missing_backend_is_not_reimported(monkeypatch):
346
+ import asanypath.asanypath as factory
347
+
348
+ registry = factory._LazyDict()
349
+ registry._pending = {"file": ("backend", "Builtin")}
350
+ attempts = []
351
+
352
+ def missing_import(name):
353
+ attempts.append(name)
354
+ raise ImportError("backend unavailable")
355
+
356
+ monkeypatch.setattr(factory, "import_module", missing_import)
357
+ assert registry["file"] is UnsupportedProtocolPath
358
+ assert registry["file"] is UnsupportedProtocolPath
359
+ assert attempts == ["backend"]
360
+
361
+
362
+ def test_in_progress_import_can_finish_after_fork_reset(monkeypatch):
363
+ from types import SimpleNamespace
364
+
365
+ import asanypath.asanypath as factory
366
+
367
+ class Builtin:
368
+ pass
369
+
370
+ registry = factory._LazyDict()
371
+ registry._pending = {"file": ("backend", "Builtin")}
372
+
373
+ def import_after_fork(name):
374
+ registry._after_fork()
375
+ return SimpleNamespace(Builtin=Builtin)
376
+
377
+ monkeypatch.setattr(factory, "import_module", import_after_fork)
378
+ assert registry["file"] is Builtin
379
+ assert registry["file"] is Builtin
380
+
381
+
382
+ @pytest.mark.skipif(not hasattr(os, "fork"), reason="requires fork")
383
+ def test_registry_lock_is_reinitialized_after_fork():
384
+ import multiprocessing
385
+ from concurrent.futures import ThreadPoolExecutor
386
+ from threading import Event
387
+
388
+ import asanypath.asanypath as factory
389
+ from asanypath.local import AsyncPath
390
+
391
+ ctx = multiprocessing.get_context("fork")
392
+ parent, child = ctx.Pipe(duplex=False)
393
+ locked, release = Event(), Event()
394
+
395
+ def hold_lock():
396
+ with factory.PROTOCOL_MAP._lock:
397
+ locked.set()
398
+ release.wait(10)
399
+
400
+ def child_lookup():
401
+ child.send(factory.PROTOCOL_MAP.get("file") is AsyncPath)
402
+ child.close()
403
+
404
+ with ThreadPoolExecutor(max_workers=1) as executor:
405
+ holder = executor.submit(hold_lock)
406
+ process = ctx.Process(target=child_lookup)
407
+ try:
408
+ assert locked.wait(5)
409
+ process.start()
410
+ assert parent.poll(5), "child blocked on the inherited registry lock"
411
+ assert parent.recv()
412
+ process.join(5)
413
+ assert process.exitcode == 0
414
+ finally:
415
+ release.set()
416
+ if process.pid is not None and process.is_alive():
417
+ process.terminate()
418
+ process.join()
419
+ holder.result(timeout=5)
420
+ parent.close()
421
+ child.close()
422
+
423
+
228
424
  def test_lazy_exports_and_dir():
229
425
  import asanypath
230
426
 
@@ -153,6 +153,57 @@ def test_cli_src_and_dst_options_are_scoped():
153
153
  assert by_path["s3://b/k"] == {"aws_region": "r0", "profile": "dst"}
154
154
 
155
155
 
156
+ def test_cli_ssh_alias_source_options(monkeypatch, tmp_path):
157
+ monkeypatch.setenv("SSH_CONFIG", str(tmp_path / "config"))
158
+ monkeypatch.setattr(
159
+ "asanypath.ssh.ssh_resolve_config",
160
+ lambda host, paths: ("real.example.com", 2222, "deploy", None, None, None),
161
+ )
162
+ calls = []
163
+
164
+ def fake(path, **kwargs):
165
+ calls.append((path, kwargs))
166
+ result = MagicMock()
167
+ result.exists = AsyncMock(return_value=True)
168
+ result.is_dir = AsyncMock(return_value=False)
169
+ result.copy = AsyncMock()
170
+ return result
171
+
172
+ with patch("asanypath.cli.AsAnyPath", side_effect=fake):
173
+ result = CliRunner().invoke(
174
+ cli,
175
+ [
176
+ "cp",
177
+ "alias:file",
178
+ str(tmp_path / "out"),
179
+ "--src-option",
180
+ "ssh.port=2223",
181
+ "--src-option",
182
+ "username=other",
183
+ "--src-option",
184
+ "client_keys=/keys/example",
185
+ ],
186
+ )
187
+ assert result.exit_code == 0, result.output
188
+ assert dict(calls)["ssh://alias/~/file"] == {
189
+ "port": 2223,
190
+ "username": "other",
191
+ "client_keys": "/keys/example",
192
+ }
193
+
194
+
195
+ def test_cli_scp_style_reports_config_parse_error(monkeypatch, tmp_path):
196
+ monkeypatch.setenv("SSH_CONFIG", str(tmp_path / "config"))
197
+
198
+ def fail(host, paths):
199
+ raise RuntimeError("ssh_config parse: invalid port")
200
+
201
+ monkeypatch.setattr("asanypath.ssh.ssh_resolve_config", fail)
202
+ result = CliRunner().invoke(cli, ["cp", "alias:file", str(tmp_path / "out")])
203
+ assert result.exit_code != 0
204
+ assert "ssh_config parse: invalid port" in result.output
205
+
206
+
156
207
  def test_cli_http_headers_are_repeatable_and_scoped():
157
208
  calls = []
158
209
 
@@ -486,6 +486,13 @@ async def test_not_implemented(method, args):
486
486
  await coro_or_gen
487
487
 
488
488
 
489
+ @pytest.fixture
490
+ def head_not_supported():
491
+ with patch(f"{_HTTP_NATIVE}.http_request", AsyncMock(return_value=(405, b"", {}))):
492
+ yield
493
+
494
+
495
+ @pytest.mark.usefixtures("head_not_supported")
489
496
  @pytest.mark.parametrize("path_type", [HTTPPath, HTTPSPath])
490
497
  @pytest.mark.parametrize("mode", ["rb", "br"])
491
498
  async def test_open_binary(path_type, mode):
@@ -502,6 +509,194 @@ async def test_open_binary(path_type, mode):
502
509
  get.assert_awaited_once_with(str(p), headers=p._merge_headers(None))
503
510
 
504
511
 
512
+ @pytest.mark.parametrize("path_type", [HTTPPath, HTTPSPath])
513
+ @pytest.mark.parametrize("sync", [False, True])
514
+ async def test_open_reads_http_ranges_lazily(path_type, sync):
515
+ data = b"0123456789abcdef"
516
+ path = path_type(f"{path_type.protocol}://example.com/file")
517
+ requests = []
518
+
519
+ async def request(method, url, *, body, headers):
520
+ requests.append((method, dict(headers or [])))
521
+ if method == "HEAD":
522
+ return (
523
+ 200,
524
+ b"",
525
+ {
526
+ "content-length": str(len(data)),
527
+ "accept-ranges": "bytes",
528
+ "etag": '"v1"',
529
+ },
530
+ )
531
+ headers = dict(headers)
532
+ start, end = map(int, headers["range"].removeprefix("bytes=").split("-"))
533
+ return 206, data[start : end + 1], {"content-range": f"bytes {start}-{end}/{len(data)}"}
534
+
535
+ get = AsyncMock(side_effect=AssertionError("unexpected full download"))
536
+ with (
537
+ patch(f"{_HTTP_NATIVE}.http_request", side_effect=request),
538
+ patch(f"{_HTTP_NATIVE}.http_get", get),
539
+ ):
540
+ context = path.open("rb", buffering=4)
541
+ if sync:
542
+ with context as f:
543
+ assert len(requests) == 1
544
+ assert f.read(2) == b"01"
545
+ f.seek(10)
546
+ assert f.read(2) == b"ab"
547
+ else:
548
+ async with context as f:
549
+ assert len(requests) == 1
550
+ assert f.read(2) == b"01"
551
+ f.seek(10)
552
+ assert f.read(2) == b"ab"
553
+
554
+ assert [method for method, _ in requests] == ["HEAD", "GET", "GET"]
555
+ assert [headers["range"] for _, headers in requests[1:]] == ["bytes=0-3", "bytes=10-13"]
556
+ assert all(headers["if-match"] == '"v1"' for _, headers in requests[1:])
557
+ get.assert_not_awaited()
558
+
559
+
560
+ def test_sync_adapter_uses_unbuffered_http_ranges(monkeypatch):
561
+ from asanypath.sync import AsAnyPath
562
+
563
+ data = b"0123456789abcdef"
564
+ requests = []
565
+ monkeypatch.delenv("HTTP_AUTH_USER", raising=False)
566
+ monkeypatch.delenv("HTTP_AUTH_PASSWORD", raising=False)
567
+ monkeypatch.setenv("HTTP_AUTH_URL", "https://example.com")
568
+ monkeypatch.setenv("HTTP_AUTH_HEADER", "User-Agent")
569
+ monkeypatch.setenv("HTTP_AUTH_TOKEN", "test-viewer")
570
+
571
+ async def request(method, url, *, body, headers):
572
+ headers = dict(headers)
573
+ requests.append((method, headers))
574
+ if method == "HEAD":
575
+ return 200, b"", {"content-length": str(len(data))}
576
+ start, end = map(int, headers["range"].removeprefix("bytes=").split("-"))
577
+ return 206, data[start : end + 1], {"content-range": f"bytes {start}-{end}/{len(data)}"}
578
+
579
+ with patch(f"{_HTTP_NATIVE}.http_request", side_effect=request):
580
+ with AsAnyPath("https://example.com/file").open("rb", buffering=0) as f:
581
+ assert f.read(2) == b"01"
582
+ f.seek(-2, 2)
583
+ assert f.read(2) == b"ef"
584
+ assert f.closed
585
+
586
+ assert [headers.get("range") for _, headers in requests] == [None, "bytes=0-1", "bytes=14-15"]
587
+ assert all(headers["User-Agent"] == "test-viewer" for _, headers in requests)
588
+
589
+
590
+ async def test_open_reuses_response_when_server_ignores_range():
591
+ data = b"0123456789abcdef"
592
+ path = _hp()
593
+ request = AsyncMock(
594
+ side_effect=[
595
+ (200, b"", {"content-length": str(len(data)), "accept-ranges": "bytes"}),
596
+ (200, data, {}),
597
+ ]
598
+ )
599
+ get = AsyncMock(side_effect=AssertionError("unexpected second download"))
600
+ with patch(f"{_HTTP_NATIVE}.http_request", request), patch(f"{_HTTP_NATIVE}.http_get", get):
601
+ async with path.open("rb", buffering=4) as f:
602
+ f.seek(6)
603
+ assert f.read(2) == b"67"
604
+ f.seek(0)
605
+ assert f.read() == data
606
+ assert request.await_count == 2
607
+ get.assert_not_awaited()
608
+
609
+
610
+ async def test_open_uses_full_read_when_range_unavailable_or_cache_enabled():
611
+ path = _hp()
612
+ get = AsyncMock(return_value=b"data")
613
+ head = AsyncMock(return_value=(200, b"", {"content-length": "4", "accept-ranges": "none"}))
614
+ with patch(f"{_HTTP_NATIVE}.http_request", head), patch(f"{_HTTP_NATIVE}.http_get", get):
615
+ async with path.open("rb") as f:
616
+ assert f.read() == b"data"
617
+ head.assert_awaited_once()
618
+ get.assert_awaited_once()
619
+
620
+ with (
621
+ patch("asanypath.cache.cache_enabled", return_value=True),
622
+ patch.object(path, "read_bytes", AsyncMock(return_value=b"cached")) as read,
623
+ patch(f"{_HTTP_NATIVE}.http_request", AsyncMock()) as head,
624
+ ):
625
+ async with path.open("rb") as f:
626
+ assert f.read() == b"cached"
627
+ read.assert_awaited_once()
628
+ head.assert_not_awaited()
629
+
630
+
631
+ async def test_open_rejects_changed_length_when_range_ignored():
632
+ request = AsyncMock(
633
+ side_effect=[
634
+ (200, b"", {"content-length": "16", "accept-ranges": "bytes"}),
635
+ (200, b"changed", {}),
636
+ ]
637
+ )
638
+ with patch(f"{_HTTP_NATIVE}.http_request", request):
639
+ async with _hp().open("rb", buffering=4) as f:
640
+ with pytest.raises(OSError, match="Source changed"):
641
+ f.read(2)
642
+
643
+
644
+ async def test_open_does_not_retry_rate_limited_head_as_full_get():
645
+ head = AsyncMock(return_value=(429, b"", {}))
646
+ get = AsyncMock()
647
+ with patch(f"{_HTTP_NATIVE}.http_request", head), patch(f"{_HTTP_NATIVE}.http_get", get):
648
+ with pytest.raises(RuntimeError, match="429"):
649
+ async with _hp().open("rb"):
650
+ pytest.fail("open must not succeed")
651
+ get.assert_not_awaited()
652
+
653
+
654
+ async def test_open_preserves_get_authentication_error_after_unauthorized_head():
655
+ from asanypath.exceptions import AuthenticationError
656
+
657
+ head = AsyncMock(return_value=(401, b"", {}))
658
+ get = AsyncMock(side_effect=AuthenticationError("rejected"))
659
+ with patch(f"{_HTTP_NATIVE}.http_request", head), patch(f"{_HTTP_NATIVE}.http_get", get):
660
+ with pytest.raises(AuthenticationError, match="rejected"):
661
+ async with _hp().open("rb"):
662
+ pytest.fail("open must not succeed")
663
+
664
+
665
+ @pytest.mark.parametrize(
666
+ "response",
667
+ [(412, b"", {}), (206, b"0123", {"content-range": "bytes 0-3/17"})],
668
+ )
669
+ async def test_open_propagates_invalid_range_response(response):
670
+ request = AsyncMock(
671
+ side_effect=[
672
+ (200, b"", {"content-length": "16", "etag": '"v1"'}),
673
+ response,
674
+ ]
675
+ )
676
+ with patch(f"{_HTTP_NATIVE}.http_request", request):
677
+ async with _hp().open("rb", buffering=4) as f:
678
+ with pytest.raises(OSError):
679
+ f.read(2)
680
+
681
+
682
+ async def test_open_text_uses_ranges():
683
+ data = b"first\nsecond\n"
684
+
685
+ async def request(method, url, *, body, headers):
686
+ if method == "HEAD":
687
+ return 200, b"", {"content-length": str(len(data))}
688
+ start, end = map(int, dict(headers)["range"].removeprefix("bytes=").split("-"))
689
+ end = min(end, len(data) - 1)
690
+ return 206, data[start : end + 1], {"content-range": f"bytes {start}-{end}/{len(data)}"}
691
+
692
+ with patch(f"{_HTTP_NATIVE}.http_request", side_effect=request):
693
+ async with _hp().open("r", buffering=4) as f:
694
+ assert f.readline() == "first\n"
695
+ assert f.readline() == "second\n"
696
+ assert f.closed
697
+
698
+
699
+ @pytest.mark.usefixtures("head_not_supported")
505
700
  @pytest.mark.parametrize("mode", ["r", "rt", "tr"])
506
701
  async def test_open_text(mode):
507
702
  p = _hp()
@@ -530,6 +725,7 @@ def test_open_rejects_unbuffered_text():
530
725
  _hp().open("r", buffering=0)
531
726
 
532
727
 
728
+ @pytest.mark.usefixtures("head_not_supported")
533
729
  async def test_open_propagates_download_error():
534
730
  with patch(f"{_HTTP_NATIVE}.http_get", AsyncMock(side_effect=PermissionError("HTTP 403"))):
535
731
  with pytest.raises(PermissionError, match="403"):
@@ -537,6 +733,7 @@ async def test_open_propagates_download_error():
537
733
  pytest.fail("open must not succeed")
538
734
 
539
735
 
736
+ @pytest.mark.usefixtures("head_not_supported")
540
737
  async def test_open_closes_on_error():
541
738
  with patch(f"{_HTTP_NATIVE}.http_get", AsyncMock(return_value=b"data")):
542
739
  with pytest.raises(RuntimeError, match="consumer error"):
@@ -14,8 +14,10 @@ from types import SimpleNamespace
14
14
  from unittest.mock import AsyncMock, MagicMock, patch
15
15
 
16
16
  import pytest
17
+ from click.testing import CliRunner
17
18
 
18
19
  from asanypath import AsAnyPath
20
+ from asanypath.cli import cli
19
21
  from asanypath.options import AccessGrant, AccessPolicyPatch
20
22
  from asanypath.ssh import SSHPath, disconnect_all
21
23
  from tests.conftest import classtest_factory
@@ -48,6 +50,41 @@ async def test_ssh_copy_uses_size_aware_parallel_ranges(ssh, tmp_path):
48
50
  ssh.read.assert_not_awaited()
49
51
 
50
52
 
53
+ def test_cli_copies_alias_to_local_with_source_options(ssh, tmp_path, monkeypatch):
54
+ monkeypatch.setenv("SSH_CONFIG", str(tmp_path / "config"))
55
+ monkeypatch.setattr(SSHPath, "_env_config", None)
56
+ monkeypatch.setattr(
57
+ "asanypath.ssh.ssh_resolve_config",
58
+ lambda host, paths: ("real.example.com", 2222, "deploy", None, "yes", None),
59
+ )
60
+ ssh.stat.return_value = _stat(size=7)
61
+ ssh.read.return_value = b"payload"
62
+ destination = tmp_path / "download"
63
+ result = CliRunner().invoke(
64
+ cli,
65
+ [
66
+ "cp",
67
+ "alias:file",
68
+ str(destination),
69
+ "--chunk-size",
70
+ "0",
71
+ "--src-option",
72
+ "ssh.port=2223",
73
+ "--src-option",
74
+ "ssh.username=other",
75
+ "--src-option",
76
+ "ssh.client_keys=/keys/example",
77
+ ],
78
+ )
79
+ assert result.exit_code == 0, result.output
80
+ assert destination.read_bytes() == b"payload"
81
+ assert ssh.read.await_args.kwargs["path"] == "./file"
82
+ assert ssh.read.await_args.kwargs["host"] == "real.example.com"
83
+ assert ssh.read.await_args.kwargs["port"] == 2223
84
+ assert ssh.read.await_args.kwargs["user"] == "other"
85
+ assert ssh.read.await_args.kwargs["key_path"] == "/keys/example"
86
+
87
+
51
88
  # ---------------------------------------------------------------------------
52
89
  # Mode constants
53
90
  # ---------------------------------------------------------------------------
@@ -605,6 +642,18 @@ def test_explicit_kwargs_override_alias(resolve_config):
605
642
  assert p._resolved_port == 9999
606
643
 
607
644
 
645
+ def test_config_identity_expands_connection_tokens(resolve_config):
646
+ resolve_config.return_value = ("real.example.com", 2222, "deploy", "/keys/%r-%h-%p", None, None)
647
+ p = SSHPath("ssh://myalias/x")
648
+ assert p._native_kwargs["key_path"] == "/keys/deploy-real.example.com-2222"
649
+
650
+
651
+ def test_config_parse_error_is_not_silently_ignored(resolve_config):
652
+ resolve_config.side_effect = RuntimeError("ssh_config parse: invalid port")
653
+ with pytest.raises(RuntimeError, match="ssh_config parse: invalid port"):
654
+ SSHPath("ssh://myalias/x")
655
+
656
+
608
657
  def test_no_ssh_config_means_no_resolution(monkeypatch):
609
658
  monkeypatch.setenv("SSH_CONFIG", "")
610
659
  SSHPath._env_config = None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes