asanypath 2.6.0__tar.gz → 2.7.0__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.6.0 → asanypath-2.7.0}/.github/workflows/publish.yml +6 -6
  2. {asanypath-2.6.0 → asanypath-2.7.0}/.github/workflows/unittests.yml +2 -2
  3. {asanypath-2.6.0 → asanypath-2.7.0}/PKG-INFO +28 -4
  4. {asanypath-2.6.0 → asanypath-2.7.0}/README.md +26 -2
  5. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_version.py +2 -2
  6. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/artifactory.py +2 -2
  7. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/asanypath.pyi +1 -0
  8. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/cloud.py +102 -60
  9. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/common.py +3 -2
  10. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/local.py +2 -1
  11. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/sync.py +13 -1
  12. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_auth_errors.py +83 -1
  13. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_cloudpathmixin.py +293 -0
  14. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_scandir.py +5 -2
  15. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_sync.py +64 -1
  16. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_syncpath.py +38 -0
  17. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_upload.py +8 -2
  18. {asanypath-2.6.0 → asanypath-2.7.0}/.copilot/skills/async-python-lib/SKILL.md +0 -0
  19. {asanypath-2.6.0 → asanypath-2.7.0}/.copilot/skills/gitguro/SKILL.md +0 -0
  20. {asanypath-2.6.0 → asanypath-2.7.0}/.github/CODEOWNERS +0 -0
  21. {asanypath-2.6.0 → asanypath-2.7.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  22. {asanypath-2.6.0 → asanypath-2.7.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  23. {asanypath-2.6.0 → asanypath-2.7.0}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  24. {asanypath-2.6.0 → asanypath-2.7.0}/.github/dependabot.yml +0 -0
  25. {asanypath-2.6.0 → asanypath-2.7.0}/.gitignore +0 -0
  26. {asanypath-2.6.0 → asanypath-2.7.0}/.pre-commit-config.yaml +0 -0
  27. {asanypath-2.6.0 → asanypath-2.7.0}/CODE_OF_CONDUCT.md +0 -0
  28. {asanypath-2.6.0 → asanypath-2.7.0}/CONTRIBUTING.md +0 -0
  29. {asanypath-2.6.0 → asanypath-2.7.0}/LICENSE +0 -0
  30. {asanypath-2.6.0 → asanypath-2.7.0}/asanypath.png +0 -0
  31. {asanypath-2.6.0 → asanypath-2.7.0}/compose.yml +0 -0
  32. {asanypath-2.6.0 → asanypath-2.7.0}/hatch_build.py +0 -0
  33. {asanypath-2.6.0 → asanypath-2.7.0}/pyproject.toml +0 -0
  34. {asanypath-2.6.0 → asanypath-2.7.0}/scripts/bench.py +0 -0
  35. {asanypath-2.6.0 → asanypath-2.7.0}/scripts/bench_rmtree.py +0 -0
  36. {asanypath-2.6.0 → asanypath-2.7.0}/scripts/bench_upload.py +0 -0
  37. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/__init__.py +0 -0
  38. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/__init__.pyi +0 -0
  39. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_backend_opts.py +0 -0
  40. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_credstore.py +0 -0
  41. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_prompt.py +0 -0
  42. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_resume.py +0 -0
  43. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/_transfer.py +0 -0
  44. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/asanypath.py +0 -0
  45. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/azure.py +0 -0
  46. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/batcher.py +0 -0
  47. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/cache.py +0 -0
  48. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/cli.py +0 -0
  49. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/click.py +0 -0
  50. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/exceptions.py +0 -0
  51. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/ftp.py +0 -0
  52. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/gcs.py +0 -0
  53. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/http.py +0 -0
  54. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/options.py +0 -0
  55. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/py.typed +0 -0
  56. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/s3.py +0 -0
  57. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/ssh.py +0 -0
  58. {asanypath-2.6.0 → asanypath-2.7.0}/src/asanypath/unsupported.py +0 -0
  59. {asanypath-2.6.0 → asanypath-2.7.0}/tests/__init__.py +0 -0
  60. {asanypath-2.6.0 → asanypath-2.7.0}/tests/conftest.py +0 -0
  61. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_artifactory.py +0 -0
  62. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_asanypath.py +0 -0
  63. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_azure.py +0 -0
  64. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_backend_options.py +0 -0
  65. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_batcher.py +0 -0
  66. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_cache.py +0 -0
  67. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_cli.py +0 -0
  68. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_click.py +0 -0
  69. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_commonpathmixin.py +0 -0
  70. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_credstore.py +0 -0
  71. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_endpoints.py +0 -0
  72. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_ftp.py +0 -0
  73. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_gcs.py +0 -0
  74. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_http.py +0 -0
  75. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_http_auth.py +0 -0
  76. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_isolation.py +0 -0
  77. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_local.py +0 -0
  78. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_options.py +0 -0
  79. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_py_typed.py +0 -0
  80. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_resume.py +0 -0
  81. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_s3.py +0 -0
  82. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_ssh.py +0 -0
  83. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_ssh_hostkeys.py +0 -0
  84. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_transport_hardening.py +0 -0
  85. {asanypath-2.6.0 → asanypath-2.7.0}/tests/test_unsupported_path.py +0 -0
@@ -44,7 +44,7 @@ jobs:
44
44
  - os: macos-15-intel
45
45
  target: x86_64
46
46
  manylinux: off
47
- - os: macos-14
47
+ - os: macos-15
48
48
  target: aarch64
49
49
  manylinux: off
50
50
  - os: windows-latest
@@ -71,7 +71,7 @@ jobs:
71
71
  # macOS and Windows build against the runner's.
72
72
  - name: Set up Python interpreters
73
73
  if: runner.os != 'Linux'
74
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
74
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
75
75
  with:
76
76
  python-version: |
77
77
  3.10
@@ -116,7 +116,7 @@ jobs:
116
116
  rm rust/Cargo.toml.bak
117
117
 
118
118
  - name: Set up uv
119
- uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0
119
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
120
120
  with:
121
121
  enable-cache: false
122
122
 
@@ -142,7 +142,7 @@ jobs:
142
142
  persist-credentials: false
143
143
 
144
144
  - name: Set up uv
145
- uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0
145
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
146
146
  with:
147
147
  enable-cache: false
148
148
 
@@ -179,7 +179,7 @@ jobs:
179
179
  merge-multiple: true
180
180
 
181
181
  - name: Publish native distribution
182
- uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
182
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
183
183
  with:
184
184
  packages-dir: dist
185
185
 
@@ -199,6 +199,6 @@ jobs:
199
199
  path: dist
200
200
 
201
201
  - name: Publish Python distribution
202
- uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
202
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
203
203
  with:
204
204
  packages-dir: dist
@@ -39,12 +39,12 @@ jobs:
39
39
  persist-credentials: false
40
40
 
41
41
  - name: Set up Python
42
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
42
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
43
43
  with:
44
44
  python-version: ${{ matrix.python-version }}
45
45
 
46
46
  - name: Set up uv
47
- uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0
47
+ uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
48
48
 
49
49
  - name: Ruff checks
50
50
  run: uvx ruff check src tests && uvx ruff format --check src tests
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: asanypath
3
- Version: 2.6.0
3
+ Version: 2.7.0
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.6.0
23
+ Requires-Dist: asanypath-native~=2.7.0
24
24
  Requires-Dist: msgspec>=0.22.0
25
25
  Requires-Dist: yarl>=1.2
26
26
  Provides-Extra: all
@@ -187,19 +187,38 @@ anonymous, which is enough for repositories open to anonymous reads. A
187
187
  configured token is always sent: an expired one fails instead of falling back
188
188
  to anonymous access.
189
189
 
190
+ Artifactory `exists()`, `is_file()` and `is_dir()` return `False` for missing
191
+ paths, but propagate authentication and permission errors. CLI source checks
192
+ report those errors rather than claiming the file does not exist.
193
+
190
194
  ### Copy and recursive delete
191
195
 
192
196
  ```python
193
197
  # Copy a single file (cross-backend supported)
194
198
  await src.copy(dst)
195
199
 
196
- # Copy entire directory tree
200
+ # Copy entire directory tree (cloud sources copy files concurrently)
197
201
  await src.copy(dst, recursive=True)
198
202
 
203
+ # Tune recursive cloud-copy concurrency, or use 1 for sequential copying
204
+ await src.copy(dst, recursive=True, concurrency=16)
205
+
199
206
  # Remove directory and all its contents
200
207
  await path.rmdir(recursive=True)
201
208
  ```
202
209
 
210
+ Recursive copies from S3, GCS, Azure, Artifactory and HTTP/HTTPS reuse
211
+ directory-listing metadata where available instead of probing each entry's
212
+ type. The default file concurrency is `min(12, os.cpu_count() or 1)`. A bounded
213
+ queue feeds the file workers, so a large tree does not create one task per
214
+ file. `concurrency=1` restores sequential file copying. Local, SSH and FTP
215
+ source backends are unchanged.
216
+ Progress callbacks remain serialized with cumulative byte totals, but files
217
+ may finish in any order. If a listing, transfer or callback fails, outstanding
218
+ workers are cancelled and awaited before the error is raised and `on_done`
219
+ is called. Some files may already have been copied (or moved); recursive
220
+ copies are not transactional.
221
+
203
222
  On S3, GCS and Azure a recursive delete lists the prefix once at every depth
204
223
  and deletes each key below it, directory marker objects included, in bulk: S3
205
224
  with one `DeleteObjects` request per 1,000 keys, GCS with JSON batch requests
@@ -267,7 +286,12 @@ for child in p.parent.iterdir(): # yields synchronously
267
286
  ```
268
287
 
269
288
  Local paths (`file://` or bare `/path`) bypass the proxy entirely and use
270
- `pathlib.Path` directly — zero threading overhead.
289
+ `SyncPath`, a wrapper around `pathlib.Path` — zero threading overhead.
290
+ These local path objects can be pickled and passed to spawned multiprocessing
291
+ workers.
292
+
293
+ Cloud paths share a background event loop per process. After `fork`, the child
294
+ resets the inherited runner and starts its own loop lazily on the next sync call.
271
295
 
272
296
  ### Large uploads stream automatically
273
297
 
@@ -130,19 +130,38 @@ anonymous, which is enough for repositories open to anonymous reads. A
130
130
  configured token is always sent: an expired one fails instead of falling back
131
131
  to anonymous access.
132
132
 
133
+ Artifactory `exists()`, `is_file()` and `is_dir()` return `False` for missing
134
+ paths, but propagate authentication and permission errors. CLI source checks
135
+ report those errors rather than claiming the file does not exist.
136
+
133
137
  ### Copy and recursive delete
134
138
 
135
139
  ```python
136
140
  # Copy a single file (cross-backend supported)
137
141
  await src.copy(dst)
138
142
 
139
- # Copy entire directory tree
143
+ # Copy entire directory tree (cloud sources copy files concurrently)
140
144
  await src.copy(dst, recursive=True)
141
145
 
146
+ # Tune recursive cloud-copy concurrency, or use 1 for sequential copying
147
+ await src.copy(dst, recursive=True, concurrency=16)
148
+
142
149
  # Remove directory and all its contents
143
150
  await path.rmdir(recursive=True)
144
151
  ```
145
152
 
153
+ Recursive copies from S3, GCS, Azure, Artifactory and HTTP/HTTPS reuse
154
+ directory-listing metadata where available instead of probing each entry's
155
+ type. The default file concurrency is `min(12, os.cpu_count() or 1)`. A bounded
156
+ queue feeds the file workers, so a large tree does not create one task per
157
+ file. `concurrency=1` restores sequential file copying. Local, SSH and FTP
158
+ source backends are unchanged.
159
+ Progress callbacks remain serialized with cumulative byte totals, but files
160
+ may finish in any order. If a listing, transfer or callback fails, outstanding
161
+ workers are cancelled and awaited before the error is raised and `on_done`
162
+ is called. Some files may already have been copied (or moved); recursive
163
+ copies are not transactional.
164
+
146
165
  On S3, GCS and Azure a recursive delete lists the prefix once at every depth
147
166
  and deletes each key below it, directory marker objects included, in bulk: S3
148
167
  with one `DeleteObjects` request per 1,000 keys, GCS with JSON batch requests
@@ -210,7 +229,12 @@ for child in p.parent.iterdir(): # yields synchronously
210
229
  ```
211
230
 
212
231
  Local paths (`file://` or bare `/path`) bypass the proxy entirely and use
213
- `pathlib.Path` directly — zero threading overhead.
232
+ `SyncPath`, a wrapper around `pathlib.Path` — zero threading overhead.
233
+ These local path objects can be pickled and passed to spawned multiprocessing
234
+ workers.
235
+
236
+ Cloud paths share a background event loop per process. After `fork`, the child
237
+ resets the inherited runner and starts its own loop lazily on the next sync call.
214
238
 
215
239
  ### Large uploads stream automatically
216
240
 
@@ -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.6.0'
22
- __version_tuple__ = version_tuple = (2, 6, 0)
21
+ __version__ = version = '2.7.0'
22
+ __version_tuple__ = version_tuple = (2, 7, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -330,7 +330,7 @@ class ArtifactoryPath(CloudPathMixin, ServiceEndpointMixin):
330
330
  info = await self._storage_info()
331
331
  self._is_folder = "children" in info
332
332
  return self._is_folder
333
- except (FileNotFoundError, PermissionError):
333
+ except FileNotFoundError:
334
334
  return False
335
335
 
336
336
  async def is_file(self) -> bool:
@@ -340,7 +340,7 @@ class ArtifactoryPath(CloudPathMixin, ServiceEndpointMixin):
340
340
  info = await self._storage_info()
341
341
  self._is_folder = "children" in info
342
342
  return not self._is_folder
343
- except (FileNotFoundError, PermissionError):
343
+ except FileNotFoundError:
344
344
  return False
345
345
 
346
346
  async def _list_entries(self, *, stat: bool = False, fresh: bool = False) -> list[DirEntry]:
@@ -136,6 +136,7 @@ class AsAnyPath(AsAnyPurePath):
136
136
  dst: PathPart,
137
137
  *,
138
138
  recursive: bool = False,
139
+ concurrency: int = ...,
139
140
  remove_src: bool = False,
140
141
  force: bool = False,
141
142
  atomic: bool = False,
@@ -988,6 +988,7 @@ class CloudPathMixin(CommonPurePathMixin):
988
988
  dst,
989
989
  *,
990
990
  recursive: bool = False,
991
+ concurrency: int = min(12, os.cpu_count() or 1),
991
992
  remove_src: bool = False,
992
993
  force: bool = False,
993
994
  atomic: bool = False,
@@ -1000,13 +1001,18 @@ class CloudPathMixin(CommonPurePathMixin):
1000
1001
  """Copy this path to *dst*.
1001
1002
 
1002
1003
  *dst* can be any path type (cross-backend supported).
1003
- With ``recursive=True``, copies entire directory tree.
1004
+ With ``recursive=True``, copies entire directory tree with up to
1005
+ ``concurrency`` file transfers in flight (default: CPU count, capped at
1006
+ 12, or 1 if unknown; pass 1 for sequential).
1007
+ Progress callbacks are serialized, but files may finish in any order.
1004
1008
  With ``remove_src=True``, deletes source after copy (move semantics).
1005
1009
  Returns the destination path.
1006
1010
  """
1007
1011
  from asanypath import AsAnyPath
1008
1012
 
1009
1013
  _validate_chunk_size(chunk_size)
1014
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
1015
+ raise ValueError("concurrency must be a positive integer")
1010
1016
  dst = dst if has_async_transfer_api(dst) else AsAnyPath(str(dst))
1011
1017
  same_native = self._can_server_side_copy(dst)
1012
1018
  if atomic and getattr(dst, "protocol", None) != "file" and not same_native:
@@ -1027,15 +1033,17 @@ class CloudPathMixin(CommonPurePathMixin):
1027
1033
  )
1028
1034
  transferred = 0
1029
1035
  error: BaseException | None = None
1036
+ progress_lock = asyncio.Lock()
1030
1037
 
1031
1038
  async def _emit_progress(delta: int) -> None:
1032
1039
  nonlocal transferred
1033
1040
  if on_progress is None or delta <= 0: # pragma: no cover
1034
1041
  return
1035
- transferred += delta
1036
- maybe = on_progress(delta, transferred, self, dst)
1037
- if inspect.isawaitable(maybe): # pragma: no cover
1038
- await maybe
1042
+ async with progress_lock:
1043
+ transferred += delta
1044
+ maybe = on_progress(delta, transferred, self, dst)
1045
+ if inspect.isawaitable(maybe): # pragma: no cover
1046
+ await maybe
1039
1047
 
1040
1048
  async def _emit_done() -> None:
1041
1049
  if on_done is None: # pragma: no cover
@@ -1044,66 +1052,101 @@ class CloudPathMixin(CommonPurePathMixin):
1044
1052
  if inspect.isawaitable(maybe): # pragma: no cover
1045
1053
  await maybe
1046
1054
 
1047
- async def _copy_recursive(src_node: Self, dst_node: Self) -> None:
1048
- if await src_node.is_dir():
1049
- await dst_node.mkdir(parents=True, exist_ok=True)
1050
- async for child in src_node.iterdir():
1051
- await _copy_recursive(child, dst_node / child.name)
1052
- else:
1055
+ async def _copy_leaf(src_node: Self, dst_node: Any) -> None:
1056
+ if getattr(dst_node, "protocol", None) == "file":
1057
+ # copy_from owns destination checks, atomic writes and source removal.
1058
+ await dst_node.copy_from(
1059
+ src_node,
1060
+ remove_src=remove_src,
1061
+ force=force,
1062
+ atomic=atomic,
1063
+ chunk_size=chunk_size,
1064
+ on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1065
+ )
1066
+ return
1053
1067
 
1054
- async def _copy_leaf() -> int:
1055
- if not needs_copy:
1056
- return 0
1057
- if src_node._can_server_side_copy(dst_node):
1058
- return await src_node._server_side_copy(
1059
- dst_node,
1060
- want_size=on_progress is not None,
1061
- destination_backend_options=destination_backend_options,
1062
- )
1063
- if getattr(dst_node, "protocol", None) == "file":
1064
- await dst_node.copy_from(
1065
- src_node,
1066
- force=force,
1067
- atomic=atomic,
1068
- chunk_size=chunk_size,
1069
- on_progress=lambda delta, transferred, _src, _dst: _emit_progress(
1070
- delta
1071
- ),
1072
- )
1073
- return 0
1074
- await dst_node.parent.mkdir(parents=True, exist_ok=True)
1075
- return await src_node._copy_to_remote(
1068
+ async def _copy_file() -> int:
1069
+ if not needs_copy:
1070
+ return 0
1071
+ if src_node._can_server_side_copy(dst_node):
1072
+ return await src_node._server_side_copy(
1076
1073
  dst_node,
1077
- chunk_size=chunk_size,
1078
- backend_options=destination_backend_options,
1074
+ want_size=on_progress is not None,
1075
+ destination_backend_options=destination_backend_options,
1079
1076
  )
1080
-
1081
- needs_copy, same_path, destination_exists = await async_destination_state(
1082
- src_node, dst_node
1077
+ await dst_node.parent.mkdir(parents=True, exist_ok=True)
1078
+ return await src_node._copy_to_remote(
1079
+ dst_node,
1080
+ chunk_size=chunk_size,
1081
+ backend_options=destination_backend_options,
1083
1082
  )
1084
- if not needs_copy:
1085
- if same_path:
1086
- return
1087
- elif destination_exists and not force:
1088
- require_force(force, dst_node)
1089
1083
 
1090
- await run_transfer_async(
1091
- src=src_node,
1092
- dst=dst_node,
1093
- copy_fn=_copy_leaf,
1094
- remove_fn=src_node.unlink,
1095
- remove_src=remove_src and not same_path,
1096
- on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1097
- on_done=None,
1098
- )
1084
+ needs_copy, same_path, destination_exists = await async_destination_state(
1085
+ src_node, dst_node
1086
+ )
1087
+ if not needs_copy:
1088
+ if same_path:
1089
+ return
1090
+ elif destination_exists and not force:
1091
+ require_force(force, dst_node)
1092
+
1093
+ await run_transfer_async(
1094
+ src=src_node,
1095
+ dst=dst_node,
1096
+ copy_fn=_copy_file,
1097
+ remove_fn=src_node.unlink,
1098
+ remove_src=remove_src and not same_path,
1099
+ on_progress=lambda delta, transferred, _src, _dst: _emit_progress(delta),
1100
+ on_done=None,
1101
+ )
1102
+
1103
+ async def _copy_tree() -> None:
1104
+ queue: asyncio.Queue[tuple[Self, Any] | None] = asyncio.Queue(maxsize=concurrency)
1105
+
1106
+ async def produce(src_node: Self, dst_node: Any) -> None:
1107
+ await dst_node.mkdir(parents=True, exist_ok=True)
1108
+ async for entry in src_node.scandir():
1109
+ target = dst_node / entry.path.name
1110
+ is_dir = entry.is_dir
1111
+ if is_dir is None:
1112
+ is_dir = await entry.path.is_dir()
1113
+ if is_dir:
1114
+ await produce(entry.path, target)
1115
+ elif concurrency == 1:
1116
+ await _copy_leaf(entry.path, target)
1117
+ else:
1118
+ await queue.put((entry.path, target))
1119
+
1120
+ if concurrency == 1:
1121
+ await produce(self, dst)
1122
+ return
1123
+
1124
+ async def producer() -> None:
1125
+ await produce(self, dst)
1126
+ for _ in range(concurrency):
1127
+ await queue.put(None)
1128
+
1129
+ async def worker() -> None:
1130
+ while (item := await queue.get()) is not None:
1131
+ await _copy_leaf(*item)
1132
+
1133
+ tasks = [asyncio.create_task(producer())]
1134
+ tasks.extend(asyncio.create_task(worker()) for _ in range(concurrency))
1135
+ try:
1136
+ await asyncio.gather(*tasks)
1137
+ finally:
1138
+ for task in tasks:
1139
+ task.cancel()
1140
+ await asyncio.gather(*tasks, return_exceptions=True)
1099
1141
 
1100
1142
  try:
1101
- if recursive and await self.is_dir():
1143
+ is_directory = await self.is_dir()
1144
+ if recursive and is_directory:
1102
1145
  same_path = str(self) == str(dst)
1103
- await _copy_recursive(self, dst)
1146
+ await _copy_tree()
1104
1147
  if remove_src and not same_path:
1105
1148
  await self.rmdir()
1106
- elif await self.is_dir():
1149
+ elif is_directory:
1107
1150
  raise IsADirectoryError(21, f"Is a directory: '{self}' (use recursive=True)")
1108
1151
  else:
1109
1152
 
@@ -1206,17 +1249,16 @@ class CloudPathMixin(CommonPurePathMixin):
1206
1249
  directory prefixes need no per-entry probes.
1207
1250
  ``follow_symlinks`` is accepted for API parity; cloud objects have no symlinks.
1208
1251
  """
1252
+ dirs: list[Self] = []
1253
+ files: list[Self] = []
1209
1254
  try:
1210
- entries = [entry async for entry in self.scandir()]
1255
+ async for entry in self.scandir():
1256
+ (dirs if entry.is_dir else files).append(entry.path)
1211
1257
  except OSError as e:
1212
1258
  if on_error is not None:
1213
1259
  on_error(e)
1214
1260
  return
1215
1261
  raise
1216
- dirs: list[Self] = []
1217
- files: list[Self] = []
1218
- for entry in entries:
1219
- (dirs if entry.is_dir else files).append(entry.path)
1220
1262
  if top_down:
1221
1263
  yield self, [d.name for d in dirs], [f.name for f in files]
1222
1264
  for d in dirs:
@@ -14,12 +14,13 @@ from datetime import datetime
14
14
  from email.utils import parsedate_to_datetime
15
15
  from os import PathLike, getenv, sep
16
16
  from pathlib import Path, PurePath, PurePosixPath
17
- from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar
17
+ from typing import TYPE_CHECKING, Any, TypeVar
18
18
  from urllib.parse import urlsplit
19
19
 
20
20
  if TYPE_CHECKING:
21
21
  from typing import Self
22
22
 
23
+ import msgspec
23
24
  from anyio import Path as AioPath
24
25
  from yarl import URL
25
26
 
@@ -34,7 +35,7 @@ OS_SEP = sep
34
35
  _FILL_CONCURRENCY = 32
35
36
 
36
37
 
37
- class DirEntry(NamedTuple):
38
+ class DirEntry(msgspec.Struct, frozen=True):
38
39
  """One directory listing entry with the metadata the backend reported.
39
40
 
40
41
  ``None`` means the field is unknown: the listing did not include it and
@@ -201,7 +201,8 @@ class SyncPath(CommonPurePathMixin):
201
201
  return str(self._path)
202
202
 
203
203
  def __getattr__(self, name):
204
- return getattr(self._path, name)
204
+ # Pickle probes __setstate__ before restoring _path.
205
+ return getattr(object.__getattribute__(self, "_path"), name)
205
206
 
206
207
  def iterdir(self) -> Generator[S]:
207
208
  for entry in self._path.iterdir():
@@ -23,6 +23,7 @@ from __future__ import annotations
23
23
 
24
24
  import asyncio
25
25
  import inspect
26
+ import os
26
27
  import threading
27
28
  from abc import ABC
28
29
  from collections.abc import AsyncIterator
@@ -74,6 +75,15 @@ class _SyncRunner:
74
75
  return
75
76
 
76
77
 
78
+ def _reset_after_fork() -> None:
79
+ _SyncRunner._instance = None
80
+ _SyncRunner._lock = threading.Lock()
81
+
82
+
83
+ if hasattr(os, "register_at_fork"):
84
+ os.register_at_fork(after_in_child=_reset_after_fork)
85
+
86
+
77
87
  class _SyncProxy:
78
88
  """Transparent sync proxy around an async path instance."""
79
89
 
@@ -155,12 +165,14 @@ class _SyncProxy:
155
165
  if inspect.isasyncgenfunction(attr): # pragma: no cover
156
166
 
157
167
  def _sync_iter_method(*args, **kwargs): # pragma: no cover
168
+ from msgspec.structs import replace
169
+
158
170
  from asanypath.common import DirEntry
159
171
 
160
172
  async_it = attr(*args, **kwargs)
161
173
  for item in _SyncRunner.get().iter(async_it): # pragma: no cover
162
174
  if isinstance(item, DirEntry):
163
- yield item._replace(path=_wrap(item.path))
175
+ yield replace(item, path=_wrap(item.path))
164
176
  else:
165
177
  yield _wrap(item) if _is_path(item) else item
166
178
 
@@ -43,7 +43,14 @@ def server():
43
43
  pass
44
44
 
45
45
  def do_GET(self):
46
- status, body = (403, S3_403) if self.path == "/denied" else (401, ARTIFACTORY_401)
46
+ if self.path.endswith("/denied"):
47
+ status, body = 403, S3_403
48
+ elif self.path.endswith("/missing"):
49
+ status, body = 404, b"{}"
50
+ elif self.path.endswith("/present"):
51
+ status, body = 200, b'{"size": "1"}'
52
+ else:
53
+ status, body = 401, ARTIFACTORY_401
47
54
  self.send_response(status)
48
55
  self.send_header("Content-Length", str(len(body)))
49
56
  self.end_headers()
@@ -55,6 +62,81 @@ def server():
55
62
  srv.shutdown()
56
63
 
57
64
 
65
+ @pytest.mark.parametrize("operation", ["exists", "is_dir", "is_file", "cli_source_check"])
66
+ @pytest.mark.parametrize(
67
+ "name,error",
68
+ [("unauthorized", AuthenticationError), ("denied", PermissionError)],
69
+ )
70
+ async def test_artifactory_source_checks_preserve_auth_errors(
71
+ server, monkeypatch, operation, name, error
72
+ ):
73
+ path = ArtifactoryPath(
74
+ f"art://{server.removeprefix('http://')}/artifactory/repo/{name}", token="invalid"
75
+ )
76
+ monkeypatch.setattr(path, "_endpoint_url", f"{server}/artifactory")
77
+ if operation == "cli_source_check":
78
+ from asanypath.cli import _exists_or_virtual_dir
79
+
80
+ check = _exists_or_virtual_dir(path)
81
+ else:
82
+ check = getattr(path, operation)()
83
+ with pytest.raises(error):
84
+ await check
85
+
86
+
87
+ @pytest.mark.parametrize("operation", ["exists", "is_dir", "is_file", "cli_source_check"])
88
+ @pytest.mark.parametrize("name", ["missing", "present"])
89
+ async def test_artifactory_source_checks_distinguish_missing_files(
90
+ server, monkeypatch, operation, name
91
+ ):
92
+ path = ArtifactoryPath(
93
+ f"art://{server.removeprefix('http://')}/artifactory/repo/{name}", token="invalid"
94
+ )
95
+ monkeypatch.setattr(path, "_endpoint_url", f"{server}/artifactory")
96
+ present = name == "present"
97
+ if operation == "cli_source_check":
98
+ from asanypath.cli import _exists_or_virtual_dir
99
+
100
+ assert await _exists_or_virtual_dir(path) == (present, False)
101
+ else:
102
+ assert await getattr(path, operation)() == (present and operation != "is_dir")
103
+
104
+
105
+ @pytest.mark.parametrize(
106
+ "name,message",
107
+ [("unauthorized", "Authentication failed"), ("denied", "Permission denied")],
108
+ )
109
+ def test_artifactory_cp_reports_auth_errors(server, monkeypatch, tmp_path, name, message):
110
+ from click.testing import CliRunner
111
+
112
+ import asanypath.cli as cli_module
113
+
114
+ base = f"{server.removeprefix('http://')}/artifactory"
115
+ monkeypatch.setenv("ARTIFACTORY_BASE_URL", base)
116
+ monkeypatch.setenv("ARTIFACTORY_IDENTITY_TOKEN", "sdf")
117
+ make_path = cli_module._make_path
118
+
119
+ def local_http_path(*args, **kwargs):
120
+ path = make_path(*args, **kwargs)
121
+ if isinstance(path, ArtifactoryPath):
122
+ assert path._token == "sdf"
123
+ path._endpoint_url = f"{server}/artifactory"
124
+ return path
125
+
126
+ monkeypatch.setattr(cli_module, "_make_path", local_http_path)
127
+ destination = tmp_path / "model.bin"
128
+ result = CliRunner().invoke(
129
+ cli_module.cli, ["cp", "-vv", f"art://repo/{name}", str(destination)]
130
+ )
131
+ assert result.exit_code == 2
132
+ assert message in result.output
133
+ assert "No such file or directory" not in result.output
134
+ if name == "unauthorized":
135
+ assert "Props Authentication Token not found" in result.output
136
+ assert "ARTIFACTORY_IDENTITY_TOKEN" in result.output
137
+ assert not destination.exists()
138
+
139
+
58
140
  async def test_401_is_an_authentication_error_with_the_reason(server):
59
141
  uri = f"{server}/artifactory/repo/model.bin"
60
142
  with pytest.raises(AuthenticationError) as info: