pfig 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pfig/__init__.py +162 -0
- pfig/__main__.py +12 -0
- pfig/_remote_fs.py +327 -0
- pfig/ast_nodes.py +247 -0
- pfig/bundle.py +424 -0
- pfig/cli.py +1700 -0
- pfig/diff.py +583 -0
- pfig/execution.py +3536 -0
- pfig/fmt.py +1016 -0
- pfig/fs.py +202 -0
- pfig/helpers.py +45 -0
- pfig/includes.py +28 -0
- pfig/lexer.py +382 -0
- pfig/logging.py +147 -0
- pfig/lsp/__init__.py +130 -0
- pfig/lsp/__main__.py +26 -0
- pfig/lsp/analysis/__init__.py +0 -0
- pfig/lsp/analysis/pfig_adapter.py +196 -0
- pfig/lsp/analysis/pfig_validator.py +292 -0
- pfig/lsp/analysis/python_resolver.py +276 -0
- pfig/lsp/analysis/resolver.py +79 -0
- pfig/lsp/graph_plan_diff.py +583 -0
- pfig/lsp/graph_view_model.py +1678 -0
- pfig/lsp/server.py +1121 -0
- pfig/lsp/state.py +114 -0
- pfig/lsp_index.py +389 -0
- pfig/lsp_utils.py +106 -0
- pfig/parser.py +726 -0
- pfig/py.typed +0 -0
- pfig/replay/__init__.py +20 -0
- pfig/replay/git_restore.py +240 -0
- pfig/replay/report.py +105 -0
- pfig/replay/runner.py +135 -0
- pfig/replay/snapshot_loader.py +113 -0
- pfig/replay/validate.py +236 -0
- pfig/replay/venv.py +300 -0
- pfig/replay/workspace.py +306 -0
- pfig/rules/pfig-developer-guide.md +133 -0
- pfig/rules/pfig-friendly-python.md +152 -0
- pfig/rules/pfig-spec.md +108 -0
- pfig/snapshot.py +1147 -0
- pfig/utils.py +43 -0
- pfig/vis/__init__.py +7 -0
- pfig/vis/__main__.py +20 -0
- pfig/vis/assets/THIRD_PARTY_NOTICES.txt +747 -0
- pfig/vis/assets/assets/graph.js +85 -0
- pfig/vis/assets/assets/index.css +1 -0
- pfig/vis/assets/index.html +16 -0
- pfig/vis/server.py +292 -0
- pfig-0.1.0.dist-info/METADATA +208 -0
- pfig-0.1.0.dist-info/RECORD +55 -0
- pfig-0.1.0.dist-info/WHEEL +5 -0
- pfig-0.1.0.dist-info/entry_points.txt +3 -0
- pfig-0.1.0.dist-info/licenses/LICENSE +203 -0
- pfig-0.1.0.dist-info/top_level.txt +1 -0
pfig/__init__.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pfig - A tiny, strict DSL for declarative object configuration.
|
|
3
|
+
|
|
4
|
+
Built for ML: deterministic configs, shared vs fresh semantics, and snapshot/diff
|
|
5
|
+
for reproducible runs.
|
|
6
|
+
|
|
7
|
+
Main API Functions
|
|
8
|
+
------------------
|
|
9
|
+
run() - Execute a pfig config file (simplest API)
|
|
10
|
+
instantiate() - Instantiate specific bindings from a configuration
|
|
11
|
+
execute_pfig() - Execute a parsed pfig configuration
|
|
12
|
+
validate_pfig() - Validate a configuration without materialization
|
|
13
|
+
compile_pfig() - Compile without requiring an entrypoint (for tooling)
|
|
14
|
+
parse_pfig_source() - Parse pfig source code into an AST
|
|
15
|
+
parse_config_file() - Parse a pfig configuration file into an AST
|
|
16
|
+
get_materialized_bindings() - Get materialized objects for testing/debugging
|
|
17
|
+
|
|
18
|
+
Snapshot Functions
|
|
19
|
+
------------------
|
|
20
|
+
create_snapshot() - Create a snapshot of a run (IR graph + payload)
|
|
21
|
+
load_snapshot() - Load a snapshot from disk
|
|
22
|
+
build_ir_graph() - Build IR graph from compiled config
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
Simple execution::
|
|
26
|
+
|
|
27
|
+
from pfig import run
|
|
28
|
+
result = run("config.pfig") # Execute a config file
|
|
29
|
+
|
|
30
|
+
With more control::
|
|
31
|
+
|
|
32
|
+
from pfig import parse_pfig_source, execute_pfig
|
|
33
|
+
|
|
34
|
+
config = '''
|
|
35
|
+
from collections import OrderedDict
|
|
36
|
+
data = OrderedDict(a=1, b=2, c=3)
|
|
37
|
+
__entrypoint__ = @data.keys
|
|
38
|
+
'''
|
|
39
|
+
ast = parse_pfig_source(config)
|
|
40
|
+
result = execute_pfig(ast) # Returns odict_keys(['a', 'b', 'c'])
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
# AST node types for advanced usage
|
|
44
|
+
from .ast_nodes import ( # Top-level statements; Expressions; Utilities
|
|
45
|
+
BinaryOpExpr,
|
|
46
|
+
Binding,
|
|
47
|
+
BuiltinCallExpr,
|
|
48
|
+
CallExpr,
|
|
49
|
+
DictExpr,
|
|
50
|
+
DottedNameExpr,
|
|
51
|
+
Expr,
|
|
52
|
+
ExternalStmt,
|
|
53
|
+
FromImportStmt,
|
|
54
|
+
ImportStmt,
|
|
55
|
+
IncludeStmt,
|
|
56
|
+
ListExpr,
|
|
57
|
+
LiteralExpr,
|
|
58
|
+
OverrideStmt,
|
|
59
|
+
PathExpr,
|
|
60
|
+
PFigFile,
|
|
61
|
+
ProviderRefExpr,
|
|
62
|
+
TupleExpr,
|
|
63
|
+
UnaryOpExpr,
|
|
64
|
+
)
|
|
65
|
+
from .execution import (
|
|
66
|
+
ExecutionError,
|
|
67
|
+
ProfileSpec,
|
|
68
|
+
ValidationError,
|
|
69
|
+
ValidationIssue,
|
|
70
|
+
compile_pfig,
|
|
71
|
+
execute_pfig,
|
|
72
|
+
get_materialized_bindings,
|
|
73
|
+
instantiate,
|
|
74
|
+
run,
|
|
75
|
+
validate_pfig,
|
|
76
|
+
)
|
|
77
|
+
from .fmt import FormatError, FormatOptions, format_source
|
|
78
|
+
from .helpers import entrypoint
|
|
79
|
+
from .lexer import LexerError
|
|
80
|
+
|
|
81
|
+
# LSP API (for pfig-vscode-syntax)
|
|
82
|
+
from .lsp import (
|
|
83
|
+
DocumentIndex,
|
|
84
|
+
ParseResult,
|
|
85
|
+
index_from_ast,
|
|
86
|
+
node_at_position,
|
|
87
|
+
resolve_include_path,
|
|
88
|
+
resolve_provider_ref,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Core API exports
|
|
92
|
+
from .parser import ParseError, parse_config_file, parse_pfig_source
|
|
93
|
+
|
|
94
|
+
# Snapshot API
|
|
95
|
+
from .snapshot import (
|
|
96
|
+
IntrospectionInfo,
|
|
97
|
+
IntrospectionStatus,
|
|
98
|
+
OpaqueReasonCode,
|
|
99
|
+
build_ir_graph,
|
|
100
|
+
check_introspection_warnings,
|
|
101
|
+
create_snapshot,
|
|
102
|
+
load_snapshot,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# All public exports
|
|
106
|
+
__all__ = [
|
|
107
|
+
# Core functions
|
|
108
|
+
"run",
|
|
109
|
+
"parse_pfig_source",
|
|
110
|
+
"parse_config_file",
|
|
111
|
+
"index_from_ast",
|
|
112
|
+
"node_at_position",
|
|
113
|
+
"resolve_include_path",
|
|
114
|
+
"resolve_provider_ref",
|
|
115
|
+
"ParseResult",
|
|
116
|
+
"DocumentIndex",
|
|
117
|
+
"execute_pfig",
|
|
118
|
+
"compile_pfig",
|
|
119
|
+
"validate_pfig",
|
|
120
|
+
"get_materialized_bindings",
|
|
121
|
+
"instantiate",
|
|
122
|
+
"entrypoint",
|
|
123
|
+
# Snapshot functions
|
|
124
|
+
"create_snapshot",
|
|
125
|
+
"load_snapshot",
|
|
126
|
+
"build_ir_graph",
|
|
127
|
+
"check_introspection_warnings",
|
|
128
|
+
# Snapshot types
|
|
129
|
+
"IntrospectionStatus",
|
|
130
|
+
"IntrospectionInfo",
|
|
131
|
+
"OpaqueReasonCode",
|
|
132
|
+
# Formatter
|
|
133
|
+
"format_source",
|
|
134
|
+
"FormatOptions",
|
|
135
|
+
"FormatError",
|
|
136
|
+
# Exception types
|
|
137
|
+
"ParseError",
|
|
138
|
+
"ExecutionError",
|
|
139
|
+
"ValidationError",
|
|
140
|
+
"ValidationIssue",
|
|
141
|
+
"LexerError",
|
|
142
|
+
# AST nodes
|
|
143
|
+
"PFigFile",
|
|
144
|
+
"ImportStmt",
|
|
145
|
+
"FromImportStmt",
|
|
146
|
+
"IncludeStmt",
|
|
147
|
+
"ExternalStmt",
|
|
148
|
+
"OverrideStmt",
|
|
149
|
+
"Binding",
|
|
150
|
+
"Expr",
|
|
151
|
+
"LiteralExpr",
|
|
152
|
+
"ListExpr",
|
|
153
|
+
"TupleExpr",
|
|
154
|
+
"DictExpr",
|
|
155
|
+
"PathExpr",
|
|
156
|
+
"DottedNameExpr",
|
|
157
|
+
"ProviderRefExpr",
|
|
158
|
+
"CallExpr",
|
|
159
|
+
"BinaryOpExpr",
|
|
160
|
+
"UnaryOpExpr",
|
|
161
|
+
"BuiltinCallExpr",
|
|
162
|
+
]
|
pfig/__main__.py
ADDED
pfig/_remote_fs.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Remote filesystem operations for pfig — optional, requires ``pfig[remote]``.
|
|
2
|
+
|
|
3
|
+
Provides read/write/copy/existence operations over local paths, GCS (``gs://``),
|
|
4
|
+
S3 (``s3://``), and in-memory (``memory://``) URIs via fsspec. Import this
|
|
5
|
+
module only inside a try/except ImportError guard.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
import os
|
|
12
|
+
import random
|
|
13
|
+
import shutil
|
|
14
|
+
import tempfile
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from pathlib import Path, PurePosixPath
|
|
19
|
+
from typing import IO, Any, Callable, Iterator, TypeVar
|
|
20
|
+
|
|
21
|
+
import fsspec
|
|
22
|
+
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
# URI / filesystem helpers
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
SUPPORTED_PROTOCOLS = frozenset({"file", "gs", "s3", "memory"})
|
|
28
|
+
|
|
29
|
+
_SCHEME_TO_PROTO = {
|
|
30
|
+
"gs://": "gs",
|
|
31
|
+
"s3://": "s3",
|
|
32
|
+
"file://": "file",
|
|
33
|
+
"memory://": "memory",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
37
|
+
|
|
38
|
+
_MAX_RETRIES = 3
|
|
39
|
+
_BASE_DELAY = 0.5
|
|
40
|
+
_MAX_DELAY = 30.0
|
|
41
|
+
_RETRYABLE: tuple[type[Exception], ...] = (
|
|
42
|
+
ConnectionError,
|
|
43
|
+
TimeoutError,
|
|
44
|
+
BrokenPipeError,
|
|
45
|
+
ConnectionResetError,
|
|
46
|
+
ConnectionAbortedError,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
_fs_cache: dict[tuple[str, frozenset[tuple[str, Any]]], Any] = {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _split_uri(uri: str) -> tuple[str, str]:
|
|
53
|
+
uri = uri.strip()
|
|
54
|
+
for prefix, proto in _SCHEME_TO_PROTO.items():
|
|
55
|
+
if uri.startswith(prefix):
|
|
56
|
+
path = uri[len(prefix) :]
|
|
57
|
+
if proto == "file":
|
|
58
|
+
return (proto, str(Path(path).expanduser().resolve()))
|
|
59
|
+
return (proto, path.lstrip("/"))
|
|
60
|
+
if "://" in uri:
|
|
61
|
+
scheme = uri.split("://")[0]
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"Unsupported protocol: {scheme!r}. Supported: {sorted(SUPPORTED_PROTOCOLS)}"
|
|
64
|
+
)
|
|
65
|
+
return ("file", str(Path(uri).expanduser().resolve()))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _get_fs(protocol: str, **kwargs: Any) -> Any:
|
|
69
|
+
if protocol not in SUPPORTED_PROTOCOLS:
|
|
70
|
+
raise ValueError(f"Unsupported protocol: {protocol!r}")
|
|
71
|
+
cache_key = (protocol, frozenset(sorted(kwargs.items())))
|
|
72
|
+
if cache_key not in _fs_cache:
|
|
73
|
+
_fs_cache[cache_key] = fsspec.filesystem(protocol, **kwargs)
|
|
74
|
+
return _fs_cache[cache_key]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _url_to_fs(uri: str, **kwargs: Any) -> tuple[Any, str, str]:
|
|
78
|
+
protocol, path = _split_uri(uri)
|
|
79
|
+
return (_get_fs(protocol, **kwargs), path, protocol)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _make_uri(protocol: str, path: str) -> str:
|
|
83
|
+
if protocol in ("gs", "s3", "memory"):
|
|
84
|
+
return f"{protocol}://{path}"
|
|
85
|
+
return path
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _retry(
|
|
89
|
+
max_retries: int = _MAX_RETRIES,
|
|
90
|
+
base_delay: float = _BASE_DELAY,
|
|
91
|
+
max_delay: float = _MAX_DELAY,
|
|
92
|
+
retryable: tuple[type[Exception], ...] = _RETRYABLE,
|
|
93
|
+
) -> Callable[[F], F]:
|
|
94
|
+
def decorator(func: F) -> F:
|
|
95
|
+
@functools.wraps(func)
|
|
96
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
97
|
+
last: Exception | None = None
|
|
98
|
+
for attempt in range(max_retries + 1):
|
|
99
|
+
try:
|
|
100
|
+
return func(*args, **kwargs)
|
|
101
|
+
except retryable as exc:
|
|
102
|
+
last = exc
|
|
103
|
+
if attempt == max_retries:
|
|
104
|
+
raise
|
|
105
|
+
delay = min(base_delay * (2**attempt), max_delay)
|
|
106
|
+
time.sleep(delay + random.uniform(0, delay * 0.1))
|
|
107
|
+
if last:
|
|
108
|
+
raise last
|
|
109
|
+
|
|
110
|
+
return wrapper # type: ignore[return-value]
|
|
111
|
+
|
|
112
|
+
return decorator
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---------------------------------------------------------------------------
|
|
116
|
+
# Read
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@contextmanager
|
|
121
|
+
def open_file(uri: str, mode: str = "rb", **kwargs: Any) -> Iterator[IO[Any]]:
|
|
122
|
+
fs, path, _ = _url_to_fs(uri)
|
|
123
|
+
with fs.open(path, mode, **kwargs) as fh:
|
|
124
|
+
yield fh
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@_retry()
|
|
128
|
+
def read_bytes(uri: str, **kwargs: Any) -> bytes:
|
|
129
|
+
fs, path, _ = _url_to_fs(uri, **kwargs)
|
|
130
|
+
return fs.cat_file(path)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@_retry()
|
|
134
|
+
def read_text(uri: str, encoding: str = "utf-8", **kwargs: Any) -> str:
|
|
135
|
+
return read_bytes(uri, **kwargs).decode(encoding)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---------------------------------------------------------------------------
|
|
139
|
+
# Write
|
|
140
|
+
# ---------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _atomic_write_local(path: str, data: bytes, overwrite: bool) -> None:
|
|
144
|
+
target = Path(path)
|
|
145
|
+
if not overwrite and target.exists():
|
|
146
|
+
raise FileExistsError(f"File already exists: {path}")
|
|
147
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=".tmp_")
|
|
149
|
+
try:
|
|
150
|
+
os.write(fd, data)
|
|
151
|
+
os.close(fd)
|
|
152
|
+
os.replace(tmp, path)
|
|
153
|
+
except Exception:
|
|
154
|
+
try:
|
|
155
|
+
os.close(fd)
|
|
156
|
+
except OSError:
|
|
157
|
+
pass
|
|
158
|
+
if os.path.exists(tmp):
|
|
159
|
+
os.unlink(tmp)
|
|
160
|
+
raise
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _atomic_write_remote(fs: Any, path: str, data: bytes, overwrite: bool, uri: str) -> None:
|
|
164
|
+
if not overwrite and fs.exists(path):
|
|
165
|
+
raise FileExistsError(f"File already exists: {uri}")
|
|
166
|
+
parts = path.split("/", 1)
|
|
167
|
+
bucket = parts[0]
|
|
168
|
+
key = parts[1] if len(parts) > 1 else ""
|
|
169
|
+
parent = str(PurePosixPath(key).parent) if key else ""
|
|
170
|
+
tmp_key = f"{parent}/.tmp_{uuid.uuid4().hex}" if parent else f".tmp_{uuid.uuid4().hex}"
|
|
171
|
+
tmp_path = f"{bucket}/{tmp_key}"
|
|
172
|
+
try:
|
|
173
|
+
with fs.open(tmp_path, "wb") as f:
|
|
174
|
+
f.write(data)
|
|
175
|
+
fs.copy(tmp_path, path)
|
|
176
|
+
finally:
|
|
177
|
+
try:
|
|
178
|
+
fs.rm(tmp_path)
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@_retry()
|
|
184
|
+
def write_bytes(
|
|
185
|
+
uri: str,
|
|
186
|
+
data: bytes,
|
|
187
|
+
*,
|
|
188
|
+
overwrite: bool = True,
|
|
189
|
+
atomic: bool = True,
|
|
190
|
+
**kwargs: Any,
|
|
191
|
+
) -> None:
|
|
192
|
+
fs, path, protocol = _url_to_fs(uri, **kwargs)
|
|
193
|
+
if atomic:
|
|
194
|
+
if protocol == "file":
|
|
195
|
+
_atomic_write_local(path, data, overwrite)
|
|
196
|
+
elif protocol in ("gs", "s3"):
|
|
197
|
+
_atomic_write_remote(fs, path, data, overwrite, uri)
|
|
198
|
+
else:
|
|
199
|
+
if not overwrite and fs.exists(path):
|
|
200
|
+
raise FileExistsError(f"File already exists: {uri}")
|
|
201
|
+
with fs.open(path, "wb") as f:
|
|
202
|
+
f.write(data)
|
|
203
|
+
else:
|
|
204
|
+
if not overwrite and fs.exists(path):
|
|
205
|
+
raise FileExistsError(f"File already exists: {uri}")
|
|
206
|
+
if protocol == "file":
|
|
207
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
with fs.open(path, "wb") as f:
|
|
209
|
+
f.write(data)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@_retry()
|
|
213
|
+
def write_text(
|
|
214
|
+
uri: str,
|
|
215
|
+
text: str,
|
|
216
|
+
encoding: str = "utf-8",
|
|
217
|
+
*,
|
|
218
|
+
overwrite: bool = True,
|
|
219
|
+
atomic: bool = True,
|
|
220
|
+
**kwargs: Any,
|
|
221
|
+
) -> None:
|
|
222
|
+
write_bytes(uri, text.encode(encoding), overwrite=overwrite, atomic=atomic, **kwargs)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ---------------------------------------------------------------------------
|
|
226
|
+
# Existence
|
|
227
|
+
# ---------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@_retry()
|
|
231
|
+
def exists(uri: str, **kwargs: Any) -> bool:
|
|
232
|
+
fs, path, _ = _url_to_fs(uri, **kwargs)
|
|
233
|
+
return fs.exists(path)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@_retry()
|
|
237
|
+
def is_file(uri: str, **kwargs: Any) -> bool:
|
|
238
|
+
fs, path, _ = _url_to_fs(uri, **kwargs)
|
|
239
|
+
return fs.isfile(path)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@_retry()
|
|
243
|
+
def is_dir(uri: str, **kwargs: Any) -> bool:
|
|
244
|
+
fs, path, _ = _url_to_fs(uri, **kwargs)
|
|
245
|
+
return fs.isdir(path)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# ---------------------------------------------------------------------------
|
|
249
|
+
# Directory ops
|
|
250
|
+
# ---------------------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def mkdirs(uri: str, exist_ok: bool = True, **kwargs: Any) -> None:
|
|
254
|
+
fs, path, protocol = _url_to_fs(uri, **kwargs)
|
|
255
|
+
if protocol in ("gs", "s3"):
|
|
256
|
+
return # directories are virtual on object stores
|
|
257
|
+
fs.makedirs(path, exist_ok=exist_ok)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# ---------------------------------------------------------------------------
|
|
261
|
+
# Copy
|
|
262
|
+
# ---------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _copy_streaming(src_uri: str, dst_uri: str, **kwargs: Any) -> None:
|
|
266
|
+
chunk = 8 * 1024 * 1024
|
|
267
|
+
with open_file(src_uri, "rb", **kwargs) as src:
|
|
268
|
+
with open_file(dst_uri, "wb", **kwargs) as dst:
|
|
269
|
+
shutil.copyfileobj(src, dst, length=chunk)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _copy_recursive(src_dir: str, dst_dir: str, *, overwrite: bool = True, **kwargs: Any) -> None:
|
|
273
|
+
src_fs, src_path, src_proto = _url_to_fs(src_dir, **kwargs)
|
|
274
|
+
src_path = src_path.rstrip("/")
|
|
275
|
+
first_root: str | None = None
|
|
276
|
+
for root, _dirs, files in src_fs.walk(src_path):
|
|
277
|
+
if first_root is None:
|
|
278
|
+
first_root = root
|
|
279
|
+
rel_root = ""
|
|
280
|
+
elif root == first_root:
|
|
281
|
+
rel_root = ""
|
|
282
|
+
else:
|
|
283
|
+
rel_root = root[len(first_root) + 1 :]
|
|
284
|
+
for filename in files:
|
|
285
|
+
src_file = _make_uri(src_proto, f"{root}/{filename}")
|
|
286
|
+
raw_dst = f"{dst_dir}/{rel_root}/{filename}" if rel_root else f"{dst_dir}/{filename}"
|
|
287
|
+
dst_proto, dst_norm = _split_uri(raw_dst)
|
|
288
|
+
cp(
|
|
289
|
+
src_file,
|
|
290
|
+
_make_uri(dst_proto, dst_norm),
|
|
291
|
+
recursive=False,
|
|
292
|
+
overwrite=overwrite,
|
|
293
|
+
**kwargs,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
@_retry()
|
|
298
|
+
def cp(
|
|
299
|
+
src: str,
|
|
300
|
+
dst: str,
|
|
301
|
+
*,
|
|
302
|
+
recursive: bool = False,
|
|
303
|
+
overwrite: bool = True,
|
|
304
|
+
**kwargs: Any,
|
|
305
|
+
) -> None:
|
|
306
|
+
src_fs, src_path, src_proto = _url_to_fs(src, **kwargs)
|
|
307
|
+
dst_fs, dst_path, dst_proto = _url_to_fs(dst, **kwargs)
|
|
308
|
+
|
|
309
|
+
if not src_fs.exists(src_path):
|
|
310
|
+
raise FileNotFoundError(f"No such file or directory: {src}")
|
|
311
|
+
if not overwrite and dst_fs.exists(dst_path):
|
|
312
|
+
raise FileExistsError(f"Destination already exists: {dst}")
|
|
313
|
+
|
|
314
|
+
if src_fs.isdir(src_path):
|
|
315
|
+
if not recursive:
|
|
316
|
+
raise IsADirectoryError(f"Source is a directory (use recursive=True): {src}")
|
|
317
|
+
_copy_recursive(src, dst, overwrite=overwrite, **kwargs)
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
if src_proto == dst_proto and src_proto != "memory":
|
|
321
|
+
if dst_proto == "file":
|
|
322
|
+
Path(dst_path).parent.mkdir(parents=True, exist_ok=True)
|
|
323
|
+
src_fs.copy(src_path, dst_path)
|
|
324
|
+
else:
|
|
325
|
+
if dst_proto == "file":
|
|
326
|
+
Path(dst_path).parent.mkdir(parents=True, exist_ok=True)
|
|
327
|
+
_copy_streaming(src, dst, **kwargs)
|