datadouble-files 0.0.3__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.
@@ -0,0 +1,21 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ __pycache__/
5
+ *.py[cod]
6
+ .venv/
7
+ .env
8
+ .coverage
9
+ .coverage.*
10
+ coverage.xml
11
+ .reports/
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ dist/
16
+ site/
17
+ .cache/
18
+
19
+ # The default work directory of `datadouble run`.
20
+ .datadouble/
21
+ node_modules/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026- Tight Line LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: datadouble-files
3
+ Version: 0.0.3
4
+ Summary: File tree engine adapter for Datadouble
5
+ Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
+ Project-URL: Source, https://github.com/datadouble/datadouble
7
+ Author: Tight Line LLC
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Topic :: Database
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Requires-Dist: datadouble
19
+ Description-Content-Type: text/markdown
20
+
21
+ # datadouble-files
22
+
23
+ The file tree engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
24
+
25
+ It copies a spec's `files`: the uploads, documents and other files a
26
+ database's rows refer to, as a second image beside the database's, in the
27
+ same generation and image groups.
28
+
29
+ ```yaml
30
+ files:
31
+ connection:
32
+ root: /srv/uploads # the tree, as Datadouble sees it
33
+ accept_inconsistent: true # copy each file as it is when read
34
+ select: # find tests for each top-level directory
35
+ avatars: -mtime -30
36
+ documents: -false # none of its own: only what paths_from names
37
+ exclude: [tmp, cache]
38
+ paths_from: # the files the chosen rows name
39
+ table: customer_documents
40
+ path: '{url}' # a template over the row's columns
41
+ match: '^https://cdn[.]example[.]com/uploads/([^?]+)' # group 1 is the path
42
+ cleanup: # shell, run in the copy's root
43
+ - find . -name '*.log' -delete
44
+ - exiftool -all= -overwrite_original -r ./avatars
45
+ image: vendor/exiftool:13 # the image cleanup runs in; Debian by default
46
+ ```
47
+
48
+ Each top-level directory is a table whose rows are its regular files, keyed
49
+ by their path from the root. Every top-level directory must be selected or
50
+ excluded, so a new directory fails the plan rather than being copied unseen
51
+ or left out unnoticed. Selection tests are GNU `find` tests; tests that act
52
+ (`-exec`, `-delete`, printing) or follow symbolic links are refused, and only
53
+ regular files are copied. `:as_of` in a test stands for the plan's anchor
54
+ time, as in `-newermt :as_of`.
55
+
56
+ `paths_from` specifies how file paths come from the source's selected rows, by a path
57
+ relative to the root. `path` is a template over a table's columns, such as
58
+ `documents/{customer_id}/{file_name}`, and `match`, if given, a regular
59
+ expression whose first group is the path, for values such as URLs or keys
60
+ with a prefix. `paths_from: customer_documents.path` is short for a column
61
+ that holds the path itself. The values are read inside the source's
62
+ snapshot, and those files are copied too. A path that leaves the tree, or
63
+ names no file, is skipped; values the pattern does not match are counted in
64
+ a warning, since they usually mean the pattern is wrong.
65
+
66
+ Cleanup is not proof: the PII scan reads every copied file's path and the
67
+ runs of printable text in its bytes, which includes a photo's EXIF fields
68
+ and similar metadata, and fails the image if it finds personal data.
69
+
70
+ A consistent copy needs a filesystem snapshot (btrfs, ZFS or LVM), which this
71
+ version does not take, so the extract runs only with `accept_inconsistent:
72
+ true`, and images record that their files were copied as they were when read.
@@ -0,0 +1,52 @@
1
+ # datadouble-files
2
+
3
+ The file tree engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
4
+
5
+ It copies a spec's `files`: the uploads, documents and other files a
6
+ database's rows refer to, as a second image beside the database's, in the
7
+ same generation and image groups.
8
+
9
+ ```yaml
10
+ files:
11
+ connection:
12
+ root: /srv/uploads # the tree, as Datadouble sees it
13
+ accept_inconsistent: true # copy each file as it is when read
14
+ select: # find tests for each top-level directory
15
+ avatars: -mtime -30
16
+ documents: -false # none of its own: only what paths_from names
17
+ exclude: [tmp, cache]
18
+ paths_from: # the files the chosen rows name
19
+ table: customer_documents
20
+ path: '{url}' # a template over the row's columns
21
+ match: '^https://cdn[.]example[.]com/uploads/([^?]+)' # group 1 is the path
22
+ cleanup: # shell, run in the copy's root
23
+ - find . -name '*.log' -delete
24
+ - exiftool -all= -overwrite_original -r ./avatars
25
+ image: vendor/exiftool:13 # the image cleanup runs in; Debian by default
26
+ ```
27
+
28
+ Each top-level directory is a table whose rows are its regular files, keyed
29
+ by their path from the root. Every top-level directory must be selected or
30
+ excluded, so a new directory fails the plan rather than being copied unseen
31
+ or left out unnoticed. Selection tests are GNU `find` tests; tests that act
32
+ (`-exec`, `-delete`, printing) or follow symbolic links are refused, and only
33
+ regular files are copied. `:as_of` in a test stands for the plan's anchor
34
+ time, as in `-newermt :as_of`.
35
+
36
+ `paths_from` specifies how file paths come from the source's selected rows, by a path
37
+ relative to the root. `path` is a template over a table's columns, such as
38
+ `documents/{customer_id}/{file_name}`, and `match`, if given, a regular
39
+ expression whose first group is the path, for values such as URLs or keys
40
+ with a prefix. `paths_from: customer_documents.path` is short for a column
41
+ that holds the path itself. The values are read inside the source's
42
+ snapshot, and those files are copied too. A path that leaves the tree, or
43
+ names no file, is skipped; values the pattern does not match are counted in
44
+ a warning, since they usually mean the pattern is wrong.
45
+
46
+ Cleanup is not proof: the PII scan reads every copied file's path and the
47
+ runs of printable text in its bytes, which includes a photo's EXIF fields
48
+ and similar metadata, and fails the image if it finds personal data.
49
+
50
+ A consistent copy needs a filesystem snapshot (btrfs, ZFS or LVM), which this
51
+ version does not take, so the extract runs only with `accept_inconsistent:
52
+ true`, and images record that their files were copied as they were when read.
@@ -0,0 +1,38 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ [project]
5
+ name = "datadouble-files"
6
+ # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
+ # sets it at release time.
8
+ version = "0.0.3"
9
+ description = "File tree engine adapter for Datadouble"
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Tight Line LLC" }]
14
+ requires-python = ">=3.13"
15
+ dependencies = ["datadouble"]
16
+ classifiers = [
17
+ "Development Status :: 2 - Pre-Alpha",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
22
+ "Topic :: Database",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://datadouble.tightlinesoftware.com/"
28
+ Source = "https://github.com/datadouble/datadouble"
29
+
30
+ [project.entry-points."datadouble.engines"]
31
+ files = "datadouble_files:engine"
32
+
33
+ [build-system]
34
+ requires = ["hatchling>=1.33.0"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/datadouble_files"]
@@ -0,0 +1,98 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The files engine adapter for Datadouble.
5
+
6
+ It copies a spec's ``files`` (decision 97)::
7
+
8
+ files:
9
+ connection:
10
+ root: /srv/uploads # the tree, as Datadouble sees it
11
+ accept_inconsistent: true # no filesystem snapshot: copy each file as it is
12
+ select: # find tests for each top-level directory
13
+ avatars: -mtime -30
14
+ documents: -size -10M
15
+ exclude: [tmp, cache]
16
+ paths_from: # and the files the chosen rows name
17
+ table: customer_documents
18
+ path: documents/{customer_id}/{file_name}
19
+ cleanup: # shell, run in the copy's root
20
+ - find . -name '*.log' -delete
21
+ image: vendor/exiftool:13 # the image cleanup runs in
22
+
23
+ Each top-level directory is a table whose rows are its files, keyed by their
24
+ path from the root. Every top-level directory must be selected or excluded.
25
+ """
26
+
27
+ from collections.abc import Generator, Mapping
28
+ from contextlib import contextmanager
29
+ from pathlib import Path
30
+
31
+ from pydantic import BaseModel, ConfigDict, JsonValue
32
+
33
+ from datadouble.engine import EngineError, ServerPlan, SourceSession, Tooling, WorkingDatabases
34
+ from datadouble.names import EngineName
35
+ from datadouble.planner import Capabilities
36
+ from datadouble.runtime import identity
37
+ from datadouble.settings import NoSettings, parse_settings
38
+ from datadouble.spec import ImageFormat
39
+ from datadouble_files.source import FilesSource
40
+ from datadouble_files.tree import ENGINE
41
+ from datadouble_files.working import DEFAULT_IMAGE, FilesWorking
42
+
43
+
44
+ class FilesConnection(BaseModel):
45
+ """The ``files.connection`` settings."""
46
+
47
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
48
+
49
+ root: str
50
+ accept_inconsistent: bool = False
51
+
52
+
53
+ class FilesEngine:
54
+ """Implements :class:`datadouble.engine.EngineAdapter` for file trees."""
55
+
56
+ @property
57
+ def name(self) -> EngineName:
58
+ """``files``."""
59
+ return ENGINE
60
+
61
+ @property
62
+ def owner(self) -> str:
63
+ """Whoever runs Datadouble: copies are plain files, served by no server."""
64
+ return identity()
65
+
66
+ def capabilities(self) -> Capabilities:
67
+ """Physical images and hooks (the cleanup commands); every directory is accounted for."""
68
+ return Capabilities(
69
+ formats=(ImageFormat.PHYSICAL,),
70
+ expressions=False,
71
+ nested=False,
72
+ hooks=True,
73
+ complete=True,
74
+ )
75
+
76
+ @contextmanager
77
+ def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
78
+ """Open the tree."""
79
+ settings = parse_settings(FilesConnection, connection, "files connection")
80
+ yield FilesSource(Path(settings.root), accept_inconsistent=settings.accept_inconsistent)
81
+
82
+ def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases: # noqa: ARG002 - one layout version
83
+ """Copies under ``scratch``; cleanup runs in ``tooling.image`` or a Debian image."""
84
+ parse_settings(NoSettings, tooling.server, "files server")
85
+ return FilesWorking(tooling.runtime, tooling.image or DEFAULT_IMAGE, scratch)
86
+
87
+ def server(self, image: Path, server_image: str | None) -> ServerPlan:
88
+ """A file tree has no server; replicate it as a volume."""
89
+ message = (
90
+ f"{image.name}: a file tree has no server to start, in {server_image or 'any'} image;"
91
+ " its copies are its files"
92
+ )
93
+ raise EngineError(message)
94
+
95
+
96
+ def engine() -> FilesEngine:
97
+ """The entry point named in ``datadouble.engines``."""
98
+ return FilesEngine()
File without changes
@@ -0,0 +1,123 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The source side: the tree's catalog, and the copy of the chosen files.
5
+
6
+ A file tree has no transactions. A consistent copy would need a filesystem
7
+ snapshot (btrfs, ZFS or LVM), which this version does not take, so the
8
+ extract runs only when the spec accepts an inconsistent copy
9
+ (``accept_inconsistent: true``), and the manifest says so: each file is
10
+ copied as it is when read.
11
+ """
12
+
13
+ import datetime as dt
14
+ import shutil
15
+ import time
16
+ from collections.abc import Generator, Iterable, Mapping
17
+ from contextlib import contextmanager
18
+ from pathlib import Path
19
+
20
+ from pydantic import BaseModel, ConfigDict
21
+
22
+ from datadouble.catalog import Catalog
23
+ from datadouble.engine import EngineError, ExtractResult, Snapshot, TableCount, Tooling, outermost
24
+ from datadouble.names import ColumnName, TableName
25
+ from datadouble.planner import Plan
26
+ from datadouble.subset import Condition, KeyTuple
27
+ from datadouble_files.tree import PATH, catalog, chosen
28
+
29
+ TREE = "tree"
30
+ """The directory of an extract, working copy or image that holds the files."""
31
+ VERSION = "1"
32
+ """The version of the tree's layout, which images record as their server version."""
33
+ INCONSISTENT = "none: each file as it was when copied"
34
+
35
+
36
+ class Extracted(BaseModel):
37
+ """What an extract holds, for ``load``."""
38
+
39
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
40
+
41
+ tables: tuple[TableName, ...]
42
+
43
+
44
+ class FilesSnapshot:
45
+ """Reads of the live tree; not a snapshot, as the spec accepted."""
46
+
47
+ def __init__(self, root: Path, as_of: dt.datetime) -> None:
48
+ """Read ``root``; ``as_of`` is bound where find tests say ``:as_of``."""
49
+ self.root = root
50
+ self.as_of = as_of
51
+ self.opened = time.monotonic()
52
+
53
+ def project(
54
+ self, table: TableName, condition: Condition, columns: tuple[ColumnName, ...]
55
+ ) -> Iterable[KeyTuple]:
56
+ """The chosen files' paths; files have no other key."""
57
+ if columns != (PATH,):
58
+ message = f"files are chosen by path, not {', '.join(columns)}"
59
+ raise EngineError(message)
60
+ return {(path,) for path in chosen(self.root, table, condition, self.as_of)}
61
+
62
+ def extract(
63
+ self,
64
+ plan: Plan,
65
+ selections: Mapping[TableName, Condition],
66
+ directory: Path,
67
+ tooling: Tooling, # noqa: ARG002 - the copy needs no containers
68
+ ) -> ExtractResult:
69
+ """Copy the chosen files, keeping their paths and times."""
70
+ current = catalog(self.root)
71
+ if current.fingerprint() != plan.catalog_fingerprint:
72
+ message = "the tree's top-level directories changed since planning; plan again"
73
+ raise EngineError(message)
74
+ counts: list[TableCount] = []
75
+ for table in plan.extracted():
76
+ paths = sorted(chosen(self.root, table, selections[table], self.as_of))
77
+ for path in paths:
78
+ target = directory / TREE / path
79
+ target.parent.mkdir(parents=True, exist_ok=True)
80
+ shutil.copy2(self.root / path, target)
81
+ (directory / TREE / table.name).mkdir(parents=True, exist_ok=True)
82
+ counts.append(TableCount(table=table, rows=len(paths)))
83
+ index = Extracted(tables=plan.extracted())
84
+ (directory / "index.json").write_text(index.model_dump_json(indent=2), "utf-8")
85
+ return ExtractResult(
86
+ server_version=VERSION,
87
+ snapshot=INCONSISTENT,
88
+ snapshot_seconds=round(time.monotonic() - self.opened, 3),
89
+ counts=tuple(counts),
90
+ )
91
+
92
+
93
+ class FilesSource:
94
+ """A tree on a path Datadouble can read."""
95
+
96
+ def __init__(self, root: Path, *, accept_inconsistent: bool) -> None:
97
+ """Read the tree at ``root``."""
98
+ self.root = root
99
+ self.accept_inconsistent = accept_inconsistent
100
+
101
+ def server_version(self) -> str:
102
+ """The adapter's own format version: a directory has no server."""
103
+ return VERSION
104
+
105
+ def namespaces(self) -> tuple[str, ...]:
106
+ """The outermost namespaces of the catalog's tables."""
107
+ return outermost(self.catalog())
108
+
109
+ def catalog(self) -> Catalog:
110
+ """The top-level directories."""
111
+ return catalog(self.root)
112
+
113
+ @contextmanager
114
+ def snapshot(self, as_of: dt.datetime) -> Generator[Snapshot]:
115
+ """Reads of the live tree, if the spec accepts an inconsistent copy."""
116
+ if not self.accept_inconsistent:
117
+ message = (
118
+ "a consistent copy of a file tree needs a filesystem snapshot, which this"
119
+ " version does not take; set `accept_inconsistent: true` in the files"
120
+ " connection to copy each file as it is when read"
121
+ )
122
+ raise EngineError(message)
123
+ yield FilesSnapshot(self.root, as_of)
@@ -0,0 +1,186 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """A file tree as tables: the catalog, and the files a condition chooses.
5
+
6
+ Each top-level directory is a table in the ``files`` namespace. Its rows are
7
+ the regular files under it, keyed by ``path``, the file's path from the
8
+ tree's root (``documents/42/lease.pdf``). Seeds and assertions are ``find``
9
+ tests, run with GNU find on the directory: ``-mtime -30 -size -10M``. Tests
10
+ that act (``-exec``, ``-delete``, the printing ones) or follow symbolic links
11
+ are refused, and only regular files are ever chosen, so nothing outside the
12
+ tree is read.
13
+ """
14
+
15
+ import datetime as dt
16
+ import os
17
+ import shlex
18
+ from collections.abc import Iterable, Iterator
19
+ from pathlib import Path, PurePosixPath
20
+ from typing import assert_never
21
+
22
+ from datadouble.catalog import Catalog, Column, ColumnKind, Table
23
+ from datadouble.engine import EngineError
24
+ from datadouble.names import ColumnName, EngineName, TableName
25
+ from datadouble.programs import locate, run_program
26
+ from datadouble.subset import (
27
+ AllOf,
28
+ AllRows,
29
+ AnyNull,
30
+ AnyOf,
31
+ Condition,
32
+ NoRows,
33
+ Predicate,
34
+ SelectedBy,
35
+ ValuesIn,
36
+ )
37
+
38
+ ENGINE = EngineName("files")
39
+ AS_OF = ":as_of"
40
+ NAMESPACE = "files"
41
+ PATH = ColumnName("path")
42
+ CONTENT = ColumnName("content")
43
+ _REFUSED = frozenset(
44
+ {
45
+ "-exec",
46
+ "-execdir",
47
+ "-ok",
48
+ "-okdir",
49
+ "-delete",
50
+ "-fls",
51
+ "-fprint",
52
+ "-fprint0",
53
+ "-fprintf",
54
+ "-ls",
55
+ "-print",
56
+ "-print0",
57
+ "-printf",
58
+ "-quit",
59
+ "-follow",
60
+ "-files0-from",
61
+ }
62
+ )
63
+ _COLUMNS = (
64
+ Column(name=PATH, type="path", kind=ColumnKind.TEXT, nullable=False),
65
+ Column(name=ColumnName("size"), type="bytes", kind=ColumnKind.INTEGER, nullable=False),
66
+ Column(name=CONTENT, type="bytes", kind=ColumnKind.TEXT, nullable=False),
67
+ )
68
+ """Every table's columns: ``content`` is what the PII scan reads, the text in each file."""
69
+
70
+
71
+ def table_name(directory: str) -> TableName:
72
+ """The table of a top-level directory."""
73
+ return TableName.of(NAMESPACE, directory)
74
+
75
+
76
+ def catalog(root: Path) -> Catalog:
77
+ """One table per top-level directory; fails if the root holds files of its own."""
78
+ if not root.is_dir():
79
+ message = f"the files root {root} is not a directory"
80
+ raise EngineError(message)
81
+ entries = sorted(os.scandir(root), key=lambda entry: entry.name)
82
+ loose = [entry.name for entry in entries if not entry.is_dir(follow_symlinks=False)]
83
+ if loose:
84
+ message = (
85
+ f"the files root holds {len(loose)} entries that are not directories; every file"
86
+ " must be in a top-level directory, which is its table"
87
+ )
88
+ raise EngineError(message)
89
+ tables = tuple(
90
+ Table(name=table_name(entry.name), columns=_COLUMNS, primary_key=(PATH,))
91
+ for entry in entries
92
+ )
93
+ return Catalog(engine=ENGINE, tables=tables)
94
+
95
+
96
+ def find_tests(text: str, as_of: dt.datetime) -> list[str]:
97
+ """``find`` tests from a seed or assertion; refuses actions and symbolic-link following.
98
+
99
+ The word ``:as_of`` stands for the plan's anchor time, as in ``-newermt :as_of``.
100
+ """
101
+ try:
102
+ words = [as_of.isoformat() if word == AS_OF else word for word in shlex.split(text)]
103
+ except ValueError as error:
104
+ message = f"cannot read the find tests {text!r}: {error}"
105
+ raise EngineError(message) from None
106
+ refused = sorted({word for word in words if word in _REFUSED})
107
+ if refused:
108
+ message = f"find tests may only test files; {', '.join(refused)} is not allowed"
109
+ raise EngineError(message)
110
+ return words
111
+
112
+
113
+ def find(directory: Path, words: list[str]) -> set[str]:
114
+ """The regular files under ``directory`` the tests choose, relative to it."""
115
+ program = locate("find", "DATADOUBLE_FIND")
116
+ if program is None:
117
+ message = "GNU find was not found"
118
+ raise EngineError(message)
119
+ chosen = ["(", *words, ")"] if words else []
120
+ done = run_program(
121
+ program, [str(directory), "-mindepth", "1", *chosen, "-type", "f", "-printf", "%P\\0"]
122
+ )
123
+ if done.status != 0:
124
+ detail = done.stderr.strip().splitlines()[-1:] or [f"status {done.status}"]
125
+ message = f"find failed: {detail[0]}"
126
+ raise EngineError(message)
127
+ return {path for path in done.stdout.split("\0") if path}
128
+
129
+
130
+ def relative(path: str) -> PurePosixPath | None:
131
+ """A path from ``paths_from`` as a path in the tree, or None if it leaves the tree."""
132
+ parts = PurePosixPath(path.lstrip("/")).parts
133
+ if not parts or any(part in {"..", ""} for part in parts):
134
+ return None
135
+ return PurePosixPath(*(part for part in parts if part != "."))
136
+
137
+
138
+ def chosen(root: Path, table: TableName, condition: Condition, as_of: dt.datetime) -> set[str]:
139
+ """The paths, from the root, of the files in ``table`` the condition chooses."""
140
+ directory = root / table.name
141
+ match condition:
142
+ case AllRows():
143
+ return {f"{table.name}/{path}" for path in find(directory, [])}
144
+ case NoRows() | AnyNull():
145
+ # Every file has a path: none is null.
146
+ return set()
147
+ case Predicate(text):
148
+ return {f"{table.name}/{path}" for path in find(directory, find_tests(text, as_of))}
149
+ case ValuesIn(columns, values):
150
+ if columns != (PATH,):
151
+ message = f"files are chosen by path, not {', '.join(columns)}"
152
+ raise EngineError(message)
153
+ return _listed(root, table, (str(row[0]) for row in values))
154
+ case AnyOf(parts) | AllOf(parts):
155
+ sets = [chosen(root, table, part, as_of) for part in parts]
156
+ if not sets:
157
+ return set()
158
+ first, *rest = sets
159
+ return first.union(*rest) if isinstance(condition, AnyOf) else first.intersection(*rest)
160
+ case SelectedBy():
161
+ message = "file trees have no references; use the keys strategy"
162
+ raise EngineError(message)
163
+ case _:
164
+ assert_never(condition)
165
+
166
+
167
+ def _listed(root: Path, table: TableName, paths: Iterable[str]) -> set[str]:
168
+ """The listed paths that are regular files in ``table``; others are skipped."""
169
+ found: set[str] = set()
170
+ for path in paths:
171
+ inside = relative(path)
172
+ if inside is None or inside.parts[0] != table.name:
173
+ continue
174
+ file = root / inside
175
+ if file.is_file() and not file.is_symlink():
176
+ found.add(str(inside))
177
+ return found
178
+
179
+
180
+ def files_in(root: Path) -> Iterator[tuple[str, Path]]:
181
+ """Every regular file under ``root``, with its path from the root."""
182
+ for directory, _, names in os.walk(root):
183
+ for name in sorted(names):
184
+ file = Path(directory) / name
185
+ if file.is_file() and not file.is_symlink():
186
+ yield str(file.relative_to(root)), file
@@ -0,0 +1,178 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The scratch side: working copies, cleanup, images and restores.
5
+
6
+ A working copy is the group's directories from the extract. ``transform``
7
+ copies it and runs the cleanup commands (``after_transform`` hooks) in the
8
+ copy's root, in a container from the files' image, so an interrupted
9
+ transform leaves the loaded copy untouched; column rules do not apply to
10
+ files. The image is the tree itself (``physical``).
11
+
12
+ Verification reads the copy as text: ``content`` yields every run of
13
+ printable characters in each file, which finds personal data in text files
14
+ and in the metadata binary files carry, such as a photo's EXIF fields.
15
+ """
16
+
17
+ import datetime as dt
18
+ import re
19
+ import shlex
20
+ from collections import Counter
21
+ from collections.abc import Generator, Iterable, Iterator
22
+ from contextlib import contextmanager
23
+ from pathlib import Path
24
+
25
+ from datadouble.catalog import Requirement
26
+ from datadouble.engine import EngineError, RestoredImage, TableCount, Transformation, one_extract
27
+ from datadouble.files import copy_tree
28
+ from datadouble.names import ColumnRef, TableName
29
+ from datadouble.planner import Plan, PlannedGroup
30
+ from datadouble.runtime import Container, ContainerRuntime
31
+ from datadouble.spec import Hook, ImageFormat, TransformHook
32
+ from datadouble.subset import Edge
33
+ from datadouble_files.source import TREE, VERSION, Extracted
34
+ from datadouble_files.tree import CONTENT, PATH, files_in, find, find_tests
35
+
36
+ DEFAULT_IMAGE = (
37
+ "debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2"
38
+ )
39
+ """The image cleanup commands run in when the spec names none."""
40
+ _PRINTABLE = re.compile(rb"[\x20-\x7e]{6,}")
41
+ _EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
42
+
43
+
44
+ def _copy(source: Path, destination: Path) -> None:
45
+ problem = copy_tree(source, destination)
46
+ if problem:
47
+ message = f"cannot copy {source.name}: {problem}"
48
+ raise EngineError(message)
49
+
50
+
51
+ def _counts(tree: Path, tables: Iterable[TableName]) -> tuple[TableCount, ...]:
52
+ found = Counter(path.split("/", 1)[0] for path, _ in files_in(tree))
53
+ return tuple(TableCount(table=table, rows=found[table.name]) for table in tables)
54
+
55
+
56
+ def text_runs(file: Path) -> Iterator[str]:
57
+ """The runs of six or more printable ASCII characters in a file."""
58
+ for run in _PRINTABLE.findall(file.read_bytes()):
59
+ yield run.decode("ascii")
60
+
61
+
62
+ class FilesRestored:
63
+ """A tree open for checks: a restored image, or a working copy."""
64
+
65
+ def __init__(self, tree: Path) -> None:
66
+ """Check the tree at ``tree``."""
67
+ self.tree = tree
68
+
69
+ def counts(self, tables: Iterable[TableName]) -> dict[TableName, int]:
70
+ """Files per top-level directory."""
71
+ return {count.table: count.rows for count in _counts(self.tree, tables)}
72
+
73
+ def orphans(self, edge: Edge) -> int:
74
+ """File trees have no references to check."""
75
+ message = f"{edge.name}: file trees have no references"
76
+ raise EngineError(message)
77
+
78
+ def text_values(self, column: ColumnRef) -> Iterator[str]:
79
+ """The paths, or the text in the files, of one top-level directory."""
80
+ directory = self.tree / column.table.name
81
+ for path, file in files_in(directory):
82
+ if column.column == PATH:
83
+ yield f"{column.table.name}/{path}"
84
+ elif column.column == CONTENT:
85
+ yield from text_runs(file)
86
+
87
+ def failing_rows(self, query: str) -> int:
88
+ """Files the find tests in ``query`` choose anywhere in the tree."""
89
+ return len(find(self.tree, find_tests(query, _EPOCH)))
90
+
91
+
92
+ class FilesWorking:
93
+ """Working copies and images under one scratch directory."""
94
+
95
+ def __init__(self, runtime: ContainerRuntime, image: str, scratch: Path) -> None:
96
+ """Run cleanup commands with ``runtime`` in ``image``."""
97
+ self.runtime = runtime
98
+ self.image = image
99
+ self.scratch = scratch
100
+
101
+ def server_version(self) -> str:
102
+ """The tree layout's version; there is no server."""
103
+ return VERSION
104
+
105
+ def close(self) -> None:
106
+ """Nothing to stop: it runs no servers."""
107
+
108
+ def available(self) -> tuple[Requirement, ...]:
109
+ """Nothing yet: this adapter reports no requirements of its sources."""
110
+ return ()
111
+
112
+ def _commands(self, commands: Iterable[str], tree: Path, owner: Path) -> None:
113
+ for number, command in enumerate(commands, 1):
114
+ script = f"cd {shlex.quote(str(tree))} && {command}"
115
+ container = Container(
116
+ image=self.image, command=("sh", "-c", script), owner=owner, mounts=(tree,)
117
+ )
118
+ done = self.runtime.run(container)
119
+ if done.status != 0:
120
+ # The output can name files, which can hold personal data.
121
+ message = f"cleanup command {number} failed with status {done.status}"
122
+ raise EngineError(message)
123
+
124
+ def load(
125
+ self,
126
+ plan: Plan, # noqa: ARG002 - the protocol passes the plan; copying needs only the group
127
+ group: PlannedGroup,
128
+ extracts: tuple[Path, ...],
129
+ directory: Path,
130
+ hooks: tuple[Hook, ...],
131
+ ) -> tuple[TableCount, ...]:
132
+ """Copy the group's directories from the extract; run ``before_load`` commands."""
133
+ extract = one_extract(extracts)
134
+ Extracted.model_validate_json((extract / "index.json").read_bytes())
135
+ tree = directory / TREE
136
+ tree.mkdir(parents=True)
137
+ for table in group.tables:
138
+ if (extract / TREE / table.name).is_dir():
139
+ _copy(extract / TREE / table.name, tree / table.name)
140
+ self._commands((hook.sql for hook in hooks), tree, directory)
141
+ return _counts(tree, group.tables)
142
+
143
+ def transform(
144
+ self,
145
+ group: PlannedGroup,
146
+ source: Path,
147
+ directory: Path,
148
+ transformation: Transformation,
149
+ ) -> tuple[TableCount, ...]:
150
+ """Copy the working copy and run the cleanup commands in the copy."""
151
+ if transformation.rules:
152
+ message = "files take no column rules; clean them with `cleanup` commands"
153
+ raise EngineError(message)
154
+ directory.parent.mkdir(parents=True, exist_ok=True)
155
+ _copy(source, directory)
156
+ tree = directory / TREE
157
+ hooks: tuple[TransformHook, ...] = transformation.hooks
158
+ self._commands((hook.sql for hook in hooks), tree, directory)
159
+ return _counts(tree, group.tables)
160
+
161
+ def package(self, source: Path, image_format: ImageFormat, directory: Path) -> None:
162
+ """The image is the tree."""
163
+ if image_format is not ImageFormat.PHYSICAL:
164
+ message = "file trees have only physical images"
165
+ raise EngineError(message)
166
+ _copy(source / TREE, directory / TREE)
167
+
168
+ @contextmanager
169
+ def restore(
170
+ self, image: Path, image_format: ImageFormat, directory: Path
171
+ ) -> Generator[RestoredImage]:
172
+ """Copy an image's tree into scratch space for checks."""
173
+ if image_format is not ImageFormat.PHYSICAL:
174
+ message = "file trees have only physical images"
175
+ raise EngineError(message)
176
+ directory.mkdir(parents=True, exist_ok=True)
177
+ _copy(image / TREE, directory / TREE)
178
+ yield FilesRestored(directory / TREE)
@@ -0,0 +1,202 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """A spec's files beside a PostgreSQL source, in the Compose postgres service.
5
+
6
+ The tree is generated for each test: avatars and documents keyed by customer
7
+ ID, with fake personal data in a photo's metadata and in one document.
8
+ """
9
+
10
+ import json
11
+ from collections.abc import Generator
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+ from psycopg import sql
16
+
17
+ from datadouble.catalog import CatalogLock
18
+ from datadouble.planner import PlanError, PlanOptions
19
+ from datadouble.registry import Registry, installed
20
+ from datadouble.run import Run, RunOptions, RunResult, Stage
21
+ from datadouble.spec import parse_spec
22
+ from datadouble.storage import filesystem_store
23
+ from datadouble_conformance.engine import runtime_for_tests
24
+ from datadouble_files import FilesEngine
25
+ from datadouble_postgres import PostgresEngine
26
+ from test_conformance import PostgresScratch, scratch
27
+
28
+ pytestmark = pytest.mark.integration
29
+
30
+ PLANTED = "Reach me at jane.roe@realmail.net"
31
+ ENGINES = ("postgres-", "files-")
32
+ TEMPLATE = "{table: customer_document, path: 'documents/{customer_id}/{file_name}'}"
33
+ URL = (
34
+ "{table: customer_document, path: '{url}',"
35
+ " match: '^https://cdn[.]example[.]com/uploads/([^?]+)'}"
36
+ )
37
+
38
+ SPEC = """
39
+ name: uploads
40
+ sources:
41
+ app:
42
+ engine: postgres
43
+ connection: CONNECTION
44
+ subset:
45
+ seeds:
46
+ customer: "id <= 3"
47
+ follow:
48
+ down: ["customer -> customer_document"]
49
+ unselected: none
50
+ files:
51
+ connection:
52
+ root: ROOT
53
+ accept_inconsistent: true
54
+ select:
55
+ avatars: "-name '1.jpg'"
56
+ documents: -false
57
+ exclude: [EXCLUDED]
58
+ paths_from: PATHS_FROM
59
+ cleanup: CLEANUP
60
+ store:
61
+ - filesystem:
62
+ path: STORE
63
+ """
64
+
65
+
66
+ def jpeg(text: str) -> bytes:
67
+ """A JPEG with an EXIF segment holding ``text``, as cameras and apps write them."""
68
+ exif = b"Exif\x00\x00II*\x00" + text.encode() + b"\x00"
69
+ segment = b"\xff\xe1" + (len(exif) + 2).to_bytes(2, "big") + exif
70
+ return b"\xff\xd8" + segment + b"\xff\xd9"
71
+
72
+
73
+ def make_tree(root: Path) -> Path:
74
+ """Avatars and documents for customers 1 to 5, a temporary directory and a cache."""
75
+ for customer in range(1, 6):
76
+ (root / "avatars").mkdir(parents=True, exist_ok=True)
77
+ (root / "avatars" / f"{customer}.jpg").write_bytes(jpeg(f"Customer {customer}"))
78
+ folder = root / "documents" / str(customer)
79
+ folder.mkdir(parents=True)
80
+ (folder / "lease.txt").write_text(f"Lease for unit {customer}\n", "utf-8")
81
+ (root / "documents" / "3" / "contact.txt").write_text(PLANTED + "\n", "utf-8")
82
+ (root / "tmp").mkdir()
83
+ (root / "tmp" / "upload.part").write_text("partial", "utf-8")
84
+ (root / "cache").mkdir()
85
+ (root / "documents" / "1" / "render.log").write_text("rendered", "utf-8")
86
+ return root
87
+
88
+
89
+ @pytest.fixture
90
+ def source() -> Generator[PostgresScratch]:
91
+ with scratch() as made:
92
+ assert isinstance(made, PostgresScratch)
93
+ made.execute(sql.SQL("CREATE TABLE customer (id integer PRIMARY KEY)"))
94
+ # Documents are stored by URL, as an app serving them from a CDN would.
95
+ made.execute(
96
+ sql.SQL(
97
+ "CREATE TABLE customer_document (id serial PRIMARY KEY,"
98
+ " customer_id integer NOT NULL REFERENCES customer, file_name text NOT NULL,"
99
+ " url text)"
100
+ )
101
+ )
102
+ made.execute(sql.SQL("INSERT INTO customer SELECT generate_series(1, 5)"))
103
+ made.execute(
104
+ sql.SQL(
105
+ "INSERT INTO customer_document (customer_id, file_name)"
106
+ " SELECT n, 'lease.txt' FROM generate_series(1, 5) n"
107
+ " UNION ALL VALUES (3, 'contact.txt'), (2, '../../../etc/passwd'),"
108
+ " (1, 'render.log'), (2, 'missing.txt')"
109
+ )
110
+ )
111
+ made.execute(
112
+ sql.SQL(
113
+ "UPDATE customer_document SET url = 'https://cdn.example.com/uploads/documents/'"
114
+ " || customer_id || '/' || file_name || '?v=' || id"
115
+ )
116
+ )
117
+ made.execute(sql.SQL("UPDATE customer_document SET url = 'mailto:x' WHERE id = 2"))
118
+ yield made
119
+
120
+
121
+ def build(
122
+ source: PostgresScratch,
123
+ tmp_path: Path,
124
+ *,
125
+ excluded: str = "tmp, cache",
126
+ paths_from: str = TEMPLATE,
127
+ cleanup: tuple[str, ...] = ("find . -name '*.log' -delete",),
128
+ stages: tuple[Stage, ...] = tuple(Stage),
129
+ ) -> RunResult:
130
+ root = tmp_path / "uploads"
131
+ if not root.exists():
132
+ make_tree(root)
133
+ text = (
134
+ SPEC.replace("CONNECTION", json.dumps(dict(source.connection)))
135
+ .replace("ROOT", str(root))
136
+ .replace("EXCLUDED", excluded)
137
+ .replace("PATHS_FROM", paths_from)
138
+ .replace("CLEANUP", json.dumps(list(cleanup)))
139
+ .replace("STORE", str(tmp_path / "store"))
140
+ )
141
+ spec = parse_spec(text + f"runtime: {json.dumps(runtime_for_tests())}\n")
142
+ with PostgresEngine().connect(source.connection) as session:
143
+ lock = CatalogLock.of(session.catalog())
144
+ registry = Registry(
145
+ engines={"postgres": PostgresEngine, "files": FilesEngine},
146
+ stores={"filesystem": filesystem_store},
147
+ runtimes=installed().runtimes,
148
+ )
149
+ options = RunOptions(stages=stages, work=tmp_path / "work", plan=PlanOptions())
150
+ return Run(spec, lock, registry, options).execute()
151
+
152
+
153
+ def _engine(key: str) -> str:
154
+ """The engine a stored file belongs to: ``.../uploads/all/files-1/...`` is ``files``."""
155
+ return next(part.split("-")[0] for part in Path(key).parts if part.startswith(ENGINES))
156
+
157
+
158
+ def copied(result: RunResult) -> list[str]:
159
+ tree = Path(result.work) / "files" / "extract" / "data" / "files" / "tree"
160
+ return sorted(str(path.relative_to(tree)) for path in tree.rglob("*") if path.is_file())
161
+
162
+
163
+ def test_files_follow_the_chosen_rows(source: PostgresScratch, tmp_path: Path) -> None:
164
+ """Only the subset's files are copied, cleaned, and checked for personal data."""
165
+ result = build(source, tmp_path)
166
+ # Customers 1 to 3 and the avatar the seed selects; the path outside the
167
+ # tree and the missing file are skipped.
168
+ assert copied(result) == [
169
+ "avatars/1.jpg",
170
+ "documents/1/lease.txt",
171
+ "documents/1/render.log",
172
+ "documents/2/lease.txt",
173
+ "documents/3/contact.txt",
174
+ "documents/3/lease.txt",
175
+ ]
176
+ cleaned = Path(result.work) / "files" / "transform" / "all" / "db" / "tree"
177
+ assert not (cleaned / "documents" / "1" / "render.log").exists()
178
+ # The planted document fails the files' PII scan; the database's image passes.
179
+ by_engine = {s.identity.engine: s.verification.passed for s in result.images}
180
+ assert by_engine == {"postgres": True, "files": False}
181
+ failing = [c for r in result.verification for c in r.checks() if not c.passed]
182
+ assert any(c.name == "files.documents.content" for c in failing), failing
183
+ assert {_engine(key) for key in result.stored} == {"postgres"}
184
+
185
+
186
+ def test_cleanup_makes_the_files_pass(source: PostgresScratch, tmp_path: Path) -> None:
187
+ """Paths can come from URLs; a value the pattern does not match is reported."""
188
+ result = build(source, tmp_path, cleanup=("rm documents/3/contact.txt",), paths_from=URL)
189
+ assert "documents/3/contact.txt" in copied(result)
190
+ assert "documents/2/lease.txt" not in copied(result)
191
+ assert [w for w in result.warnings if "did not match" in w]
192
+ assert not result.failed(), result.verification
193
+ assert {s.identity.engine for s in result.images} == {"postgres", "files"}
194
+ assert {_engine(key) for key in result.stored} == {"postgres", "files"}
195
+
196
+
197
+ def test_every_top_level_directory_is_accounted_for(
198
+ source: PostgresScratch, tmp_path: Path
199
+ ) -> None:
200
+ with pytest.raises(PlanError) as caught:
201
+ build(source, tmp_path, excluded="tmp", stages=(Stage.PLAN,))
202
+ assert caught.value.problems == ("files.cache is neither selected nor excluded",)
@@ -0,0 +1,280 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The files adapter's parts that need no containers: trees, selection and checks."""
5
+
6
+ import datetime as dt
7
+ import shutil
8
+ from contextlib import AbstractContextManager
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ from datadouble.catalog import ColumnKind
15
+ from datadouble.engine import EngineError, Tooling, Transformation
16
+ from datadouble.names import ColumnName, ColumnRef, TableName
17
+ from datadouble.planner import PlannedRule, PlanOptions, SourceCatalog, plan
18
+ from datadouble.programs import Completed
19
+ from datadouble.runtime import Container, Server
20
+ from datadouble.spec import (
21
+ FILES_SOURCE,
22
+ ImageFormat,
23
+ NullOptions,
24
+ NullRule,
25
+ TransformHook,
26
+ parse_spec,
27
+ )
28
+ from datadouble.subset import (
29
+ AllOf,
30
+ AllRows,
31
+ AnyNull,
32
+ AnyOf,
33
+ Condition,
34
+ Edge,
35
+ NoRows,
36
+ Predicate,
37
+ SelectedBy,
38
+ ValuesIn,
39
+ )
40
+ from datadouble_files import FilesEngine, engine
41
+ from datadouble_files.source import FilesSnapshot, FilesSource
42
+ from datadouble_files.tree import CONTENT, PATH, catalog, chosen, find_tests, relative, table_name
43
+ from datadouble_files.working import FilesRestored, FilesWorking, text_runs
44
+
45
+ AS_OF = dt.datetime(2026, 1, 2, tzinfo=dt.UTC)
46
+ DOCS = table_name("documents")
47
+
48
+
49
+ def tree(root: Path) -> Path:
50
+ """A small tree: two documents, an avatar with text in its bytes, and a log."""
51
+ (root / "documents" / "1").mkdir(parents=True)
52
+ (root / "documents" / "1" / "a.txt").write_text("hello world\n", "utf-8")
53
+ (root / "documents" / "2.txt").write_text("call me at 617-222-3344\n", "utf-8")
54
+ (root / "avatars").mkdir()
55
+ (root / "avatars" / "1.jpg").write_bytes(b"\xff\xd8\x00Artist: Ann Example\x00\xff\xd9")
56
+ (root / "tmp").mkdir()
57
+ (root / "tmp" / "x.log").write_text("log", "utf-8")
58
+ (root / "documents" / "link.txt").symlink_to(root / "tmp" / "x.log")
59
+ return root
60
+
61
+
62
+ def test_catalog_has_a_table_per_top_level_directory(tmp_path: Path) -> None:
63
+ found = catalog(tree(tmp_path))
64
+ assert [str(t.name) for t in found.tables] == ["files.avatars", "files.documents", "files.tmp"]
65
+ assert [c.name for c in found.tables[0].columns] == ["path", "size", "content"]
66
+ (tmp_path / "loose.txt").write_text("x", "utf-8")
67
+ with pytest.raises(EngineError, match="1 entries that are not directories"):
68
+ catalog(tmp_path)
69
+ with pytest.raises(EngineError, match="is not a directory"):
70
+ catalog(tmp_path / "missing")
71
+
72
+
73
+ def test_find_tests_choose_regular_files(tmp_path: Path) -> None:
74
+ root = tree(tmp_path)
75
+ assert chosen(root, DOCS, AllRows(), AS_OF) == {"documents/1/a.txt", "documents/2.txt"}
76
+ assert chosen(root, DOCS, Predicate("-name '2*'"), AS_OF) == {"documents/2.txt"}
77
+ assert chosen(root, DOCS, Predicate("-newermt :as_of"), AS_OF) == {
78
+ "documents/1/a.txt",
79
+ "documents/2.txt",
80
+ }
81
+ assert chosen(root, DOCS, NoRows(), AS_OF) == set()
82
+ assert chosen(root, DOCS, AnyNull((PATH,)), AS_OF) == set()
83
+ for refused in ("-delete", "-exec rm {} ;", "-follow", "-fprint /tmp/x"):
84
+ with pytest.raises(EngineError, match="is not allowed"):
85
+ find_tests(refused, AS_OF)
86
+ with pytest.raises(EngineError, match="cannot read the find tests"):
87
+ find_tests("-name 'open", AS_OF)
88
+ with pytest.raises(EngineError, match="find failed"):
89
+ chosen(root, DOCS, Predicate("-bogus"), AS_OF)
90
+ with pytest.raises(EngineError, match="keys strategy"):
91
+ chosen(root, DOCS, SelectedBy((PATH,), DOCS, (PATH,)), AS_OF)
92
+
93
+
94
+ def test_listed_paths_stay_in_their_table(tmp_path: Path) -> None:
95
+ root = tree(tmp_path)
96
+ listed = ValuesIn(
97
+ (PATH,),
98
+ frozenset(
99
+ {
100
+ ("documents/2.txt",),
101
+ ("/documents/1/a.txt",),
102
+ ("./documents/1/./a.txt",),
103
+ ("../documents/2.txt",),
104
+ ("avatars/1.jpg",),
105
+ ("documents/missing.txt",),
106
+ ("documents/link.txt",),
107
+ ("",),
108
+ }
109
+ ),
110
+ )
111
+ assert chosen(root, DOCS, listed, AS_OF) == {"documents/1/a.txt", "documents/2.txt"}
112
+ both = AllOf((listed, Predicate("-name '2*'")))
113
+ assert chosen(root, DOCS, both, AS_OF) == {"documents/2.txt"}
114
+ assert chosen(root, DOCS, AnyOf(()), AS_OF) == set()
115
+ assert chosen(root, DOCS, AnyOf((NoRows(), both)), AS_OF) == {"documents/2.txt"}
116
+ assert relative("a/../b") is None
117
+ with pytest.raises(EngineError, match="chosen by path, not size"):
118
+ chosen(root, DOCS, ValuesIn((ColumnName("size"),), frozenset()), AS_OF)
119
+
120
+
121
+ def test_snapshots_need_consent(tmp_path: Path) -> None:
122
+ source = FilesSource(tree(tmp_path), accept_inconsistent=False)
123
+ assert source.server_version() == "1"
124
+ assert source.catalog().tables
125
+ # Every table of a tree sits in the one `files` namespace.
126
+ assert source.namespaces() == ("files",)
127
+ with pytest.raises(EngineError, match="accept_inconsistent: true"), source.snapshot(AS_OF):
128
+ pass
129
+ with FilesSource(tmp_path, accept_inconsistent=True).snapshot(AS_OF) as accepted:
130
+ assert set(accepted.project(DOCS, NoRows(), (PATH,))) == set()
131
+ snapshot = FilesSnapshot(tmp_path, AS_OF)
132
+ assert set(snapshot.project(DOCS, Predicate("-name '2*'"), (PATH,))) == {("documents/2.txt",)}
133
+ with pytest.raises(EngineError, match="chosen by path"):
134
+ snapshot.project(DOCS, AllRows(), (ColumnName("size"),))
135
+
136
+
137
+ def test_restored_trees_read_as_text(tmp_path: Path) -> None:
138
+ root = tree(tmp_path)
139
+ restored = FilesRestored(root)
140
+ assert restored.counts([DOCS, table_name("avatars")]) == {DOCS: 2, table_name("avatars"): 1}
141
+ content = ColumnRef(table=table_name("avatars"), column=CONTENT)
142
+ assert list(restored.text_values(content)) == ["Artist: Ann Example"]
143
+ paths = ColumnRef(table=DOCS, column=PATH)
144
+ assert sorted(restored.text_values(paths)) == ["documents/1/a.txt", "documents/2.txt"]
145
+ assert list(restored.text_values(ColumnRef(table=DOCS, column=ColumnName("size")))) == []
146
+ assert restored.failing_rows("-name '*.log'") == 1
147
+ assert list(text_runs(root / "documents" / "2.txt")) == ["call me at 617-222-3344\n"[:-1]]
148
+ edge = Edge(name="x", child=DOCS, columns=(PATH,), parent=DOCS, parent_columns=(PATH,))
149
+ with pytest.raises(EngineError, match="no references"):
150
+ restored.orphans(edge)
151
+
152
+
153
+ @dataclass
154
+ class _Runtime:
155
+ """A container runtime that records commands and fails the ones that say so."""
156
+
157
+ commands: list[str] = field(default_factory=list[str])
158
+
159
+ def run(self, container: Container) -> Completed:
160
+ self.commands.append(container.command[-1])
161
+ return Completed(1 if "fail" in container.command[-1] else 0, "", "")
162
+
163
+ def serve(self, container: Container) -> AbstractContextManager[Server]:
164
+ raise NotImplementedError
165
+
166
+ def release(self, owner: Path) -> None:
167
+ raise NotImplementedError
168
+
169
+
170
+ def test_working_copies(tmp_path: Path) -> None:
171
+ root = tree(tmp_path / "source")
172
+ extract = tmp_path / "extract"
173
+ (extract / "tree").mkdir(parents=True)
174
+ (extract / "index.json").write_text('{"tables": []}', "utf-8")
175
+ shutil.copytree(root / "documents", extract / "tree" / "documents", symlinks=True)
176
+ runtime = _Runtime()
177
+ working = FilesWorking(runtime, "img", tmp_path / "scratch")
178
+ assert working.server_version() == "1"
179
+ assert working.available() == ()
180
+ planned = plan(
181
+ parse_spec(
182
+ "name: t\nsources: {files: {engine: files}}\nstrict: {data: off}\nexclude: [tmp]\n"
183
+ "subset: {seeds: {documents: '-type f', avatars: '-type f'}}"
184
+ ),
185
+ (SourceCatalog(name=FILES_SOURCE, catalog=catalog(root), server_version="1"),),
186
+ None,
187
+ FilesEngine().capabilities(),
188
+ PlanOptions(now=AS_OF),
189
+ )
190
+ group = planned.groups[0]
191
+ counts = working.load(planned, group, (extract,), tmp_path / "loaded", ())
192
+ assert {c.table: c.rows for c in counts} == {DOCS: 2, table_name("avatars"): 0}
193
+ hook = TransformHook(sql="rm -f documents/2.txt")
194
+ transformation = Transformation((), lambda _r, _v: {}, (hook,))
195
+ working.transform(group, tmp_path / "loaded", tmp_path / "clean", transformation)
196
+ assert runtime.commands[-1].endswith("&& rm -f documents/2.txt")
197
+ failing = Transformation((), lambda _r, _v: {}, (TransformHook(sql="fail"),))
198
+ with pytest.raises(EngineError, match="cleanup command 1 failed with status 1"):
199
+ working.transform(group, tmp_path / "loaded", tmp_path / "bad", failing)
200
+ rule = PlannedRule(
201
+ column=ColumnRef(table=DOCS, column=CONTENT),
202
+ kind=ColumnKind.TEXT,
203
+ type="bytes",
204
+ rule=NullRule(null=NullOptions()),
205
+ )
206
+ with pytest.raises(EngineError, match="no column rules"):
207
+ working.transform(
208
+ group,
209
+ tmp_path / "loaded",
210
+ tmp_path / "r",
211
+ Transformation((rule,), lambda _r, _v: {}, ()),
212
+ )
213
+ with pytest.raises(EngineError, match="cannot copy"):
214
+ working.transform(group, tmp_path / "nowhere", tmp_path / "n", transformation)
215
+ image = tmp_path / "image"
216
+ image.mkdir()
217
+ working.package(tmp_path / "clean", ImageFormat.PHYSICAL, image)
218
+ with working.restore(image, ImageFormat.PHYSICAL, tmp_path / "restored") as restored:
219
+ assert restored.counts([DOCS]) == {DOCS: 2}
220
+ for image_format in (ImageFormat.LOGICAL,):
221
+ with pytest.raises(EngineError, match="only physical images"):
222
+ working.package(tmp_path / "clean", image_format, tmp_path)
223
+ with (
224
+ pytest.raises(EngineError, match="only physical images"),
225
+ working.restore(image, image_format, tmp_path / "r2"),
226
+ ):
227
+ pass
228
+
229
+
230
+ def test_the_engine(tmp_path: Path) -> None:
231
+ files = FilesEngine()
232
+ assert (files.name, engine().name) == ("files", "files")
233
+ assert files.capabilities().complete
234
+ assert files.owner
235
+ with files.connect({"root": str(tree(tmp_path)), "accept_inconsistent": True}) as session:
236
+ assert session.catalog().tables
237
+ working = files.working(tmp_path, Tooling(runtime=_Runtime()), "1")
238
+ assert isinstance(working, FilesWorking)
239
+ with pytest.raises(EngineError, match="no server to start"):
240
+ files.server(tmp_path, None)
241
+
242
+
243
+ def test_extract_copies_the_chosen_files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
244
+ root = tree(tmp_path / "source")
245
+ planned = plan(
246
+ parse_spec(
247
+ "name: t\nsources: {files: {engine: files}}\nstrict: {data: off}\nexclude: [tmp]\n"
248
+ "subset: {seeds: {documents: \"-name '2*'\", avatars: '-type f'}}"
249
+ ),
250
+ (SourceCatalog(name=FILES_SOURCE, catalog=catalog(root), server_version="1"),),
251
+ None,
252
+ FilesEngine().capabilities(),
253
+ PlanOptions(now=AS_OF),
254
+ )
255
+ selections: dict[TableName, Condition] = {
256
+ DOCS: AnyOf(
257
+ (Predicate("-name '2*'"), ValuesIn((PATH,), frozenset({("documents/1/a.txt",)})))
258
+ ),
259
+ table_name("avatars"): AllRows(),
260
+ }
261
+ snapshot = FilesSnapshot(root, AS_OF)
262
+ result = snapshot.extract(
263
+ planned, selections, tmp_path / "extract", Tooling(runtime=_Runtime())
264
+ )
265
+ assert {str(c.table): c.rows for c in result.counts} == {
266
+ "files.avatars": 1,
267
+ "files.documents": 2,
268
+ }
269
+ copied = sorted(
270
+ str(p.relative_to(tmp_path / "extract" / "tree"))
271
+ for p in (tmp_path / "extract" / "tree").rglob("*")
272
+ if p.is_file()
273
+ )
274
+ assert copied == ["avatars/1.jpg", "documents/1/a.txt", "documents/2.txt"]
275
+ (root / "added").mkdir()
276
+ with pytest.raises(EngineError, match="changed since planning"):
277
+ snapshot.extract(planned, selections, tmp_path / "again", Tooling(runtime=_Runtime()))
278
+ monkeypatch.setenv("PATH", "")
279
+ with pytest.raises(EngineError, match="GNU find was not found"):
280
+ chosen(root, DOCS, AllRows(), AS_OF)